@testsprite/testsprite-cli 0.14.0 → 0.16.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 (61) hide show
  1. package/README.md +27 -17
  2. package/dist/commands/agent.js +7 -2
  3. package/dist/commands/auth.js +7 -3
  4. package/dist/commands/ci.d.ts +66 -17
  5. package/dist/commands/ci.js +486 -122
  6. package/dist/commands/completion.js +2 -1
  7. package/dist/commands/doctor.d.ts +3 -0
  8. package/dist/commands/doctor.js +52 -10
  9. package/dist/commands/init.js +25 -5
  10. package/dist/commands/project-env.js +39 -17
  11. package/dist/commands/project-sign-in.js +9 -4
  12. package/dist/commands/project.js +43 -22
  13. package/dist/commands/schedule.js +24 -15
  14. package/dist/commands/test.d.ts +105 -36
  15. package/dist/commands/test.js +1494 -847
  16. package/dist/commands/testlist.js +13 -3
  17. package/dist/commands/tunnel.js +23 -25
  18. package/dist/commands/usage.js +1 -0
  19. package/dist/index.js +14 -7
  20. package/dist/lib/agent-targets.d.ts +8 -3
  21. package/dist/lib/agent-targets.js +15 -4
  22. package/dist/lib/ci-run.d.ts +11 -0
  23. package/dist/lib/ci-run.js +34 -0
  24. package/dist/lib/client-factory.d.ts +23 -0
  25. package/dist/lib/client-factory.js +7 -6
  26. package/dist/lib/config.d.ts +1 -0
  27. package/dist/lib/config.js +1 -1
  28. package/dist/lib/conflict-reason.d.ts +24 -3
  29. package/dist/lib/conflict-reason.js +33 -2
  30. package/dist/lib/credentials.d.ts +0 -1
  31. package/dist/lib/credentials.js +51 -14
  32. package/dist/lib/deprecate.d.ts +22 -0
  33. package/dist/lib/deprecate.js +26 -0
  34. package/dist/lib/dry-run/samples.js +56 -5
  35. package/dist/lib/environment-tunnel.d.ts +2 -1
  36. package/dist/lib/environment-tunnel.js +1 -4
  37. package/dist/lib/first-suite-hint.d.ts +55 -0
  38. package/dist/lib/first-suite-hint.js +101 -0
  39. package/dist/lib/gh-output.d.ts +62 -4
  40. package/dist/lib/gh-output.js +149 -7
  41. package/dist/lib/github-context.d.ts +21 -0
  42. package/dist/lib/github-context.js +153 -0
  43. package/dist/lib/http.d.ts +10 -1
  44. package/dist/lib/http.js +29 -3
  45. package/dist/lib/junit-report.d.ts +3 -0
  46. package/dist/lib/junit-report.js +8 -1
  47. package/dist/lib/output.d.ts +11 -1
  48. package/dist/lib/output.js +17 -2
  49. package/dist/lib/plans.types.d.ts +1 -1
  50. package/dist/lib/response-schemas.d.ts +5 -1
  51. package/dist/lib/response-schemas.js +57 -0
  52. package/dist/lib/runs.types.d.ts +122 -0
  53. package/dist/lib/telemetry.d.ts +26 -2
  54. package/dist/lib/telemetry.js +47 -4
  55. package/dist/version.d.ts +1 -1
  56. package/dist/version.js +1 -1
  57. package/package.json +3 -3
  58. package/schemas/plan.schema.json +2 -2
  59. package/skills/testsprite-ci.skill.md +154 -0
  60. package/skills/testsprite-verify.codex.md +7 -7
  61. package/skills/testsprite-verify.skill.md +24 -21
@@ -910,7 +910,17 @@ export function createTestListCommand(deps = {}) {
910
910
  });
911
911
  testlist
912
912
  .command('run <list-id>')
913
- .description('Run a test list (dispatch its cases and return pollable run ids). Loopback environments open a tunnel automatically and wait.')
913
+ .summary('Run a test list')
914
+ .description("Run a test list (dispatch its cases and return pollable run ids). Environments come from the list's --project-env mapping; loopback ones open one tunnel and wait (backend cases are skipped).\n" +
915
+ '\nExit codes:\n' +
916
+ ' 0 dispatched (or all passed with --wait)\n' +
917
+ ' 1 a run failed / blocked / cancelled\n' +
918
+ ' 3 auth error\n' +
919
+ ' 4 a --case id is not in the list\n' +
920
+ ' 6 nothing dispatched: every case conflicted (already running, or cannot run here)\n' +
921
+ ' 7 timeout, or some cases were rate-deferred (retry the printed ids)\n' +
922
+ ' 12 insufficient credits (non-retriable; top up)\n' +
923
+ ' 13 feature gated / workspace paused')
914
924
  .option('--case <test-id>', 'run only this case (repeatable; default: every case in the list)', collectRepeatable, [])
915
925
  .option('--wait', 'poll every dispatched run until terminal or --timeout', false)
916
926
  .option('--no-wait', 'detach without opening an automatic environment tunnel')
@@ -921,8 +931,8 @@ export function createTestListCommand(deps = {}) {
921
931
  .option('--report <format>', 'with --wait: write a JUnit XML sidecar after polling (accepted: junit)')
922
932
  .option('--report-file <path>', 'output path for --report (atomic write)')
923
933
  .option('--report-suite-name <name>', 'JUnit <testsuite name=...> override (default: testsprite:testlist:<listId>)')
924
- .option('--gh-output', 'with --wait: emit GitHub-native output (::error:: annotations for failed/timed-out members, ::warning:: for never-dispatched ones; job-summary table when $GITHUB_STEP_SUMMARY is set). Auto-enabled when GITHUB_ACTIONS=true')
925
- .option('--summary-file <path>', 'with --wait: also write the reduced machine summary JSON {total, passed, failed, skipped, timedOut, runs[]} to this file')
934
+ .option('--gh-output', 'with --wait: emit GitHub annotations (::error:: failed/timed-out, ::warning:: never dispatched) and a job-summary table when $GITHUB_STEP_SUMMARY is set; auto-enabled when GITHUB_ACTIONS=true')
935
+ .option('--summary-file <path>', 'with --wait: also write summary JSON {total, passed, failed, skipped, timedOut, runs[]} to this file')
926
936
  .addHelpText('after', GLOBAL_OPTS_HINT)
927
937
  .action(async (listId, cmdOpts, command) => {
928
938
  const wait = cmdOpts.wait === true;
@@ -35,8 +35,8 @@ function assertTunnelClientId(clientId) {
35
35
  throw ApiError.fromEnvelope({
36
36
  error: {
37
37
  code: 'VALIDATION_ERROR',
38
- message: "Tunnel client id must be a UUID (see 'testsprite tunnel status'/'tunnel start' output).",
39
- nextAction: "Run 'testsprite tunnel start' to get a tunnel client id.",
38
+ message: "Tunnel client id must be a UUID (see 'testsprite tunnel list').",
39
+ nextAction: "Run 'testsprite tunnel list' to see your tunnel client ids, or 'testsprite tunnel start' to open one.",
40
40
  requestId: 'local',
41
41
  details: { field: 'clientId', reason: 'must be a UUID' },
42
42
  },
@@ -551,18 +551,14 @@ export async function runTunnelStop(opts, deps = {}) {
551
551
  export function createTunnelCommand(deps = {}) {
552
552
  const tunnel = new Command('tunnel')
553
553
  .description('Open a tunnel so TestSprite can reach an app on this machine')
554
- .addHelpText('after', '\nFrontend runs automatically open and close a tunnel when the selected environment URL\n' +
555
- 'is on this machine. Use these commands when you want one tunnel to serve several runs, or to check on\n' +
556
- 'one that a run reported as down.\n' +
557
- '\nA tunnel lives only as long as `tunnel start` is running — there is no background\n' +
558
- 'daemon, because the credential that authorises an inbound network path into this machine\n' +
559
- 'is never written to disk.\n' +
554
+ .addHelpText('after', '\nFrontend runs open and close a tunnel automatically when the environment URL is on this\n' +
555
+ 'machine. Use these commands to share one tunnel across several runs or to check one a run\n' +
556
+ 'reported as down. A tunnel lives only as long as `tunnel start` runs: there is no background\n' +
557
+ 'daemon, because its credential is never written to disk.\n' +
560
558
  '\nExamples:\n' +
561
- ' testsprite tunnel start # hold a tunnel open (Ctrl-C to stop)\n' +
562
- ' testsprite test run <id> --env <name> --tunnel-client <id>\n' +
563
- ' testsprite tunnel list\n' +
564
- ' testsprite tunnel status <id>\n' +
565
- ' testsprite tunnel stop <id>\n' +
559
+ ' testsprite tunnel start # hold a tunnel open (Ctrl-C to stop)\n' +
560
+ ' testsprite test run <test-id> --env <name> --tunnel-client <client-id>\n' +
561
+ ' testsprite test run <test-id> --local 3000 --tunnel-client <client-id>\n' +
566
562
  ' testsprite tunnel stop --all --confirm\n');
567
563
  tunnel
568
564
  .command('start')
@@ -570,14 +566,13 @@ export function createTunnelCommand(deps = {}) {
570
566
  // where an embedded newline breaks out of the indented column. The detail
571
567
  // belongs in this command's own help, below.
572
568
  .description('Open a tunnel and hold it until you stop the command (Ctrl-C)')
573
- .option('--ttl <seconds>', 'requested lifetime of the tunnel credential (60–28800). The server clamps this, and the ' +
574
- 'credential is deleted when the command exits regardless — the lifetime only matters if ' +
575
- 'this process is killed without cleaning up.')
576
- .addHelpText('after', '\nPrints the client id to stderr as soon as it is minted, before connecting; pass it\n' +
577
- 'to `test run <id> --env <name> --tunnel-client <id>` for an environment on this machine.\n' +
578
- 'Frontend runs normally open their own tunnel automatically for a loopback environment URL.\n' +
579
- '\nDev servers can take a minute per page through the tunnel. For a heavy dev server,\n' +
580
- "test a built server: `npm run build`, then your framework's preview/start command.\n" +
569
+ .summary('Open a tunnel and hold it until Ctrl-C')
570
+ .option('--ttl <seconds>', 'requested credential lifetime (60–28800), clamped by the server; the credential is deleted ' +
571
+ 'on exit regardless, so this only matters if the process is killed')
572
+ .addHelpText('after', '\nPrints the client id to stderr as soon as it is minted; pass it to\n' +
573
+ '`test run <test-id> --env <name> --tunnel-client <client-id>` for an environment on this machine.\n' +
574
+ '\nDev servers can take a minute per page through the tunnel; for a heavy one, test a built\n' +
575
+ "server (`npm run build`, then your framework's preview/start command).\n" +
581
576
  '\nExit codes:\n' +
582
577
  ' 0 you stopped it (Ctrl-C is the normal way to end this command)\n' +
583
578
  ' 3 auth error — the key needs the `run:tunnel` scope; mint a new key\n' +
@@ -594,8 +589,7 @@ export function createTunnelCommand(deps = {}) {
594
589
  tunnel
595
590
  .command('list')
596
591
  .description('List live tunnel bindings for this account')
597
- .addHelpText('after', '\nShows each tunnel client id, connection status, creation time and expiry.\n' +
598
- 'Includes tunnels automatically opened for environments on this machine.\n' +
592
+ .addHelpText('after', '\nShows each tunnel client id, status, creation time and expiry, including tunnels opened automatically.\n' +
599
593
  '\nExit codes:\n' +
600
594
  ' 0 listed (possibly empty)\n' +
601
595
  ' 3 auth error — the key needs the `run:tunnel` scope\n' +
@@ -607,6 +601,7 @@ export function createTunnelCommand(deps = {}) {
607
601
  });
608
602
  tunnel
609
603
  .command('status <client-id>')
604
+ .summary('Report whether a tunnel client is connected')
610
605
  .description('Report whether a tunnel client of yours is connected')
611
606
  .addHelpText('after', '\n`offline` means the API answered and said nothing is connected with that id. A failure\n' +
612
607
  'to reach TestSprite is reported as its own error, never as `offline`.\n' +
@@ -614,6 +609,7 @@ export function createTunnelCommand(deps = {}) {
614
609
  '\nExit codes:\n' +
615
610
  ' 0 answered (the answer may be `offline`)\n' +
616
611
  ' 4 no such tunnel for this account\n' +
612
+ ' 5 client id is not a UUID\n' +
617
613
  ' 10 could not reach TestSprite to ask\n')
618
614
  .addHelpText('after', GLOBAL_OPTS_HINT)
619
615
  .action(async (clientId, _cmdOpts, command) => {
@@ -621,19 +617,21 @@ export function createTunnelCommand(deps = {}) {
621
617
  });
622
618
  tunnel
623
619
  .command('stop [client-id]')
620
+ .summary('Stop one tunnel, or all with --all')
624
621
  .description('Destroy one tunnel credential or stop every live tunnel')
625
622
  .option('--all', 'stop every live tunnel on this account', false)
626
623
  .option('--confirm', 'required with --all for this destructive operation', false)
627
624
  .addHelpText('after', '\nStopping one that is already gone succeeds. Revoking the credential\n' +
628
625
  'also makes a running `tunnel start` exit within ~15 s.\n' +
629
626
  'A run that automatically opened this tunnel loses access to its environment when you stop it.\n' +
630
- 'Stopping all requires --confirm; --dry-run previews sample ids without it.\n' +
627
+ 'Stopping all requires --confirm and also revokes tunnels used by other terminals and CI jobs;\n' +
628
+ '--dry-run previews sample ids without it.\n' +
631
629
  '\nExit codes:\n' +
632
630
  ' 0 stopped (or already absent), including an empty --all result\n' +
633
631
  ' 1 at least one tunnel could not be stopped\n' +
634
632
  ' 3 auth error — the key needs the `run:tunnel` scope\n' +
635
633
  ' 4 server too old to list tunnels (with --all)\n' +
636
- ' 5 invalid arguments or --all without --confirm\n' +
634
+ ' 5 invalid arguments (e.g. a client id that is not a UUID) or --all without --confirm\n' +
637
635
  ' 10 could not reach TestSprite\n')
638
636
  .addHelpText('after', GLOBAL_OPTS_HINT)
639
637
  .action(async (clientId, cmdOpts, command) => {
@@ -241,6 +241,7 @@ function renderUsage(u, portalBase) {
241
241
  export function createUsageCommand(deps = {}) {
242
242
  const cmd = new Command('usage')
243
243
  .alias('credits')
244
+ .summary('Show credit balance and plan info')
244
245
  .description('Show credit balance and plan/entitlement info (proactive pre-flight before a large test run)')
245
246
  .addHelpText('after', GLOBAL_OPTS_HINT)
246
247
  .addHelpText('after', '\nExamples:\n' +
package/dist/index.js CHANGED
@@ -40,13 +40,12 @@ program
40
40
  .version(VERSION)
41
41
  .option('--output <mode>', 'Output format (json|text)', 'text')
42
42
  .option('--profile <name>', 'Configuration profile to use')
43
- .option('--endpoint-url <url>', 'Override the API endpoint host')
44
- .option('--verbose', 'Emit human-readable HTTP retry / backoff / polling-mode transitions to stderr. Less noisy than --debug; useful for diagnosing hangs without the full trace.')
43
+ .option('--endpoint-url <url>', 'API base URL (a full http(s) URL)')
44
+ .option('--verbose', 'Log HTTP retry / backoff / polling transitions to stderr (lighter than --debug)')
45
45
  .option('--debug', 'Print HTTP method/path, request id, latency, retry decisions to stderr')
46
- .option('--dry-run', 'Skip the network and credentials; emit a canned sample matching the OpenAPI contract. Useful for learning the CLI surface without an API key. Note: file inputs you pass (--plan-from/--plans/--steps) are still read and validated locally; only --code-file uses a placeholder.')
47
- .option('--request-timeout <seconds>', 'Client-side per-request timeout in seconds (default: 120). Aborts any single fetch that does not complete within this deadline. ' +
48
- 'Override via TESTSPRITE_REQUEST_TIMEOUT_MS env var (milliseconds). ' +
49
- 'Range: 1–600. Does not affect the --timeout polling ceiling for `test run/wait`.');
46
+ .option('--dry-run', 'Skip the network and credentials; emit a canned sample matching the OpenAPI contract. Exception: run commands (`test run`, `test rerun`, `test create --run`, `testlist run`) with credentials and no explicit target may make read-only GETs to preview an automatic tunnel target; nothing is created or started. File inputs (--plan-from/--plans/--steps) are still read locally; --code-file uses a placeholder.')
47
+ .option('--request-timeout <seconds>', 'Per-request timeout in seconds (default 120; range 1–600, values outside are clamped). ' +
48
+ 'Does not affect the --timeout polling ceiling for `test run/wait`.');
50
49
  // `setup` is the primary onboarding command, listed FIRST in --help so a coding
51
50
  // agent reaches it before anything else. `init` is kept as a hidden, deprecated
52
51
  // alias (invisible to --help; still works for existing scripts/agents).
@@ -75,7 +74,11 @@ program.addCommand(createTestCommand({
75
74
  },
76
75
  }));
77
76
  program.addCommand(createTestListCommand());
78
- program.addCommand(createCiCommand({}));
77
+ program.addCommand(createCiCommand({
78
+ onWaitTimeout: context => {
79
+ waitTimeoutTelemetry = context;
80
+ },
81
+ }));
79
82
  program.addCommand(createScheduleCommand({}));
80
83
  program.addCommand(createTunnelCommand({}));
81
84
  program.addCommand(createAgentCommand({}));
@@ -161,6 +164,10 @@ function unknownRootCommandMaskedByHelp(args) {
161
164
  return undefined;
162
165
  return args.slice(1).some(arg => arg === '--help' || arg === '-h') ? first : undefined;
163
166
  }
167
+ program.addHelpText('after', '\nEnvironment:\n' +
168
+ ' TESTSPRITE_API_KEY (overrides stored credentials), TESTSPRITE_NO_UPDATE_NOTIFIER (disables\n' +
169
+ ' the version check); TESTSPRITE_API_URL, TESTSPRITE_PROFILE and TESTSPRITE_REQUEST_TIMEOUT_MS\n' +
170
+ ' (milliseconds) mirror --endpoint-url, --profile and --request-timeout.');
164
171
  program.addHelpText('beforeAll', context => {
165
172
  if (context.command !== program)
166
173
  return '';
@@ -65,7 +65,12 @@ export interface SkillSpec {
65
65
  * `testsprite-onboard` codex contribution — a single always-on line. Kept here
66
66
  * (not in a `*.codex.md` asset) because it is one line; see {@link CodexContribution}.
67
67
  */
68
- export declare const ONBOARD_CODEX_LINE = "**First-time setup:** if this repo has no TestSprite tests yet, seed a *broad* first suite across its main user flows \u2014 not just one test \u2014 each with a concrete, observable assertion, before reporting setup as done.";
68
+ export declare const ONBOARD_CODEX_LINE = "**First-time setup:** if this repo has no TestSprite tests yet, seed a *broad* first suite across its main user flows \u2014 not just one test \u2014 each with a concrete, observable assertion, before reporting setup as done. Try `testsprite test plan generate --project <id>` then `test plan accept` first; author plans by hand only if generation is unavailable.";
69
+ /**
70
+ * `testsprite-ci` codex contribution — one always-on line; the full onboarding
71
+ * flow lives in the own-file body and the docs.
72
+ */
73
+ export declare const CI_CODEX_LINE = "**CI gate:** to run TestSprite on every pull request, use `testsprite ci init github --project <id> --env <name>`, finish the `REPLACE ME` step for how PRs deploy (platform-deployed previews \u2192 `on: deployment_status`; the workflow deploys \u2192 keep `pull_request`), set the `TESTSPRITE_API_KEY` secret, then prove it on one real, non-draft pull request. If the GitHub App already gates the project, ask before adding a second gate.";
69
74
  /**
70
75
  * The skill registry. Each entry owns its name, description (drift-guarded by a
71
76
  * byte-identity unit test against a template doc), own-file body asset, and codex
@@ -77,9 +82,9 @@ export declare const SKILLS: Record<string, SkillSpec>;
77
82
  /**
78
83
  * Skills installed by `setup` and by `agent install` when no `--skill` subset is
79
84
  * given. Order is significant for the codex aggregate (verify first, then the
80
- * onboard line as a short addendum).
85
+ * onboard and ci lines as short addenda).
81
86
  */
82
- export declare const DEFAULT_SKILLS: readonly ["testsprite-verify", "testsprite-onboard"];
87
+ export declare const DEFAULT_SKILLS: readonly ["testsprite-verify", "testsprite-onboard", "testsprite-ci"];
83
88
  /** @deprecated The canonical skill name. New code: iterate {@link SKILLS}. */
84
89
  export declare const SKILL_NAME = "testsprite-verify";
85
90
  /**
@@ -5,7 +5,12 @@ import { VERSION } from '../version.js';
5
5
  * `testsprite-onboard` codex contribution — a single always-on line. Kept here
6
6
  * (not in a `*.codex.md` asset) because it is one line; see {@link CodexContribution}.
7
7
  */
8
- export const ONBOARD_CODEX_LINE = '**First-time setup:** if this repo has no TestSprite tests yet, seed a *broad* first suite across its main user flows — not just one test — each with a concrete, observable assertion, before reporting setup as done.';
8
+ export const ONBOARD_CODEX_LINE = '**First-time setup:** if this repo has no TestSprite tests yet, seed a *broad* first suite across its main user flows — not just one test — each with a concrete, observable assertion, before reporting setup as done. Try `testsprite test plan generate --project <id>` then `test plan accept` first; author plans by hand only if generation is unavailable.';
9
+ /**
10
+ * `testsprite-ci` codex contribution — one always-on line; the full onboarding
11
+ * flow lives in the own-file body and the docs.
12
+ */
13
+ export const CI_CODEX_LINE = '**CI gate:** to run TestSprite on every pull request, use `testsprite ci init github --project <id> --env <name>`, finish the `REPLACE ME` step for how PRs deploy (platform-deployed previews → `on: deployment_status`; the workflow deploys → keep `pull_request`), set the `TESTSPRITE_API_KEY` secret, then prove it on one real, non-draft pull request. If the GitHub App already gates the project, ask before adding a second gate.';
9
14
  /**
10
15
  * The skill registry. Each entry owns its name, description (drift-guarded by a
11
16
  * byte-identity unit test against a template doc), own-file body asset, and codex
@@ -22,17 +27,23 @@ export const SKILLS = {
22
27
  },
23
28
  'testsprite-onboard': {
24
29
  name: 'testsprite-onboard',
25
- description: 'Stand up a complete, runnable TestSprite test suite for the current repo at first use — create a project (with a target URL and auth), derive a coherent set of tests from the codebase, batch-create them, and smoke-run a few to a green verdict so the user immediately has something worth running. Use ONLY when a repo has no TestSprite tests yet (a fresh project), right after `testsprite setup`, or when the user asks to "set up / bootstrap / seed tests". This is first-run setup, NOT change verification — once a project already has tests, use the testsprite-verify skill instead.',
30
+ description: 'Stand up a complete, runnable TestSprite test suite for the current repo at first use — create a project (with a target URL and auth), generate a coherent set of tests (or derive and batch-create them from the codebase), and smoke-run a few to a green verdict so the user has something worth running. Use ONLY when a repo has no TestSprite tests yet (a fresh project), right after `testsprite setup`, or when the user asks to "set up / bootstrap / seed tests". This is first-run setup, NOT change verification — once a project already has tests, use the testsprite-verify skill instead.',
26
31
  bodyFile: 'testsprite-onboard.skill.md',
27
32
  codex: { kind: 'line', text: ONBOARD_CODEX_LINE },
28
33
  },
34
+ 'testsprite-ci': {
35
+ name: 'testsprite-ci',
36
+ description: 'Gate pull requests with TestSprite in CI — work out how the repo deploys pull-request previews (platform-deployed → `on: deployment_status`; deployed in the workflow → `on: pull_request`), pick the environment the gate signs in with, generate the workflow with `testsprite ci init github`, finish its placeholder step, set the `TESTSPRITE_API_KEY` secret, and prove the gate on one real pull request. Use when the user asks to add TestSprite to CI or GitHub Actions, run the tests on every PR, or block merges on them. NOT for seeding a first suite (testsprite-onboard) or checking one change (testsprite-verify).',
37
+ bodyFile: 'testsprite-ci.skill.md',
38
+ codex: { kind: 'line', text: CI_CODEX_LINE },
39
+ },
29
40
  };
30
41
  /**
31
42
  * Skills installed by `setup` and by `agent install` when no `--skill` subset is
32
43
  * given. Order is significant for the codex aggregate (verify first, then the
33
- * onboard line as a short addendum).
44
+ * onboard and ci lines as short addenda).
34
45
  */
35
- export const DEFAULT_SKILLS = ['testsprite-verify', 'testsprite-onboard'];
46
+ export const DEFAULT_SKILLS = ['testsprite-verify', 'testsprite-onboard', 'testsprite-ci'];
36
47
  // ---------------------------------------------------------------------------
37
48
  // Back-compat single-skill exports (= the canonical `testsprite-verify` skill)
38
49
  // ---------------------------------------------------------------------------
@@ -0,0 +1,11 @@
1
+ import type { CiSummary } from './gh-output.js';
2
+ import type { RunConflict } from './conflict-reason.js';
3
+ import { type WaitMemberResult } from './wait-exit.js';
4
+ /** CI owns non-dispatch policy; operational poll failures retain their typed exit. */
5
+ export declare function resolveCiRunFailure(summary: CiSummary, accepted: readonly WaitMemberResult[], opts: {
6
+ timeoutSeconds: number;
7
+ allowEmpty?: boolean;
8
+ failOnSkipped?: boolean;
9
+ },
10
+ /** The batch's `conflicts[]`, with their reasons, when the caller has them. */
11
+ conflicts?: readonly RunConflict[]): Error | null;
@@ -0,0 +1,34 @@
1
+ import { CLIError } from './errors.js';
2
+ import { resolveWaitFailure } from './wait-exit.js';
3
+ /** CI owns non-dispatch policy; operational poll failures retain their typed exit. */
4
+ export function resolveCiRunFailure(summary, accepted, opts,
5
+ /** The batch's `conflicts[]`, with their reasons, when the caller has them. */
6
+ conflicts = []) {
7
+ const missing = summary.runs.filter(row => row.status === 'not_found');
8
+ if (missing.length > 0) {
9
+ return new CLIError(`Tests not found: ${missing.map(row => row.testId).join(', ')}`, 4);
10
+ }
11
+ const failure = resolveWaitFailure(accepted, opts);
12
+ if (failure)
13
+ return failure;
14
+ if (accepted.length === 0) {
15
+ // `--allow-empty` covers an empty selection: no tests, a filter that
16
+ // matched nothing, or runs already in flight elsewhere. A batch the
17
+ // backend REFUSED — an unknown environment, an un-runnable one, a
18
+ // view-only mirror, a billing hold — is not empty, and reading it as
19
+ // green is the false-green shape a gate exists to prevent.
20
+ const refused = conflicts.filter(c => c.reason !== undefined && c.reason !== 'in_flight' && c.reason !== 'not_found');
21
+ if (refused.length > 0) {
22
+ const first = refused[0];
23
+ return new CLIError(`No tests were dispatched: ${refused.length} refused (${first.reason}${first.message ? `: ${first.message}` : ''}).`, 5);
24
+ }
25
+ if (!opts.allowEmpty) {
26
+ return new CLIError('No tests were dispatched. Pass --allow-empty to allow an empty CI run.', 5);
27
+ }
28
+ }
29
+ if (summary.skipped > 0 && opts.failOnSkipped) {
30
+ return new CLIError(`${summary.skipped} tests were skipped (--fail-on-skipped).`, 1);
31
+ }
32
+ return null;
33
+ }
34
+ //# sourceMappingURL=ci-run.js.map
@@ -1,3 +1,19 @@
1
+ /**
2
+ * Shared `HttpClient` factory used by every M2 command. Two reasons for
3
+ * the extraction:
4
+ *
5
+ * 1. Three command files (`auth`, `project`, `test`) had byte-equivalent
6
+ * `makeClient` helpers — drift between them would silently change
7
+ * behavior depending on which command you called.
8
+ * 2. P6's `--dry-run` branch needs to bypass `loadConfig` (so it works
9
+ * with no `~/.testsprite/credentials`) and substitute a canned-fetch
10
+ * impl. Doing that once here is safer than three near-copies.
11
+ *
12
+ * The factory is intentionally narrow: it only takes the HTTP-relevant
13
+ * deps. Per-command deps (auth's `prompt`, test's `rawStdout`) stay
14
+ * with the command.
15
+ */
16
+ import { type Config } from './config.js';
1
17
  import type { DebugEvent, FetchImpl, HttpClientOptions } from './http.js';
2
18
  import { HttpClient } from './http.js';
3
19
  import { type ShutdownHandle } from './interrupt.js';
@@ -48,6 +64,13 @@ export interface ClientFactoryDeps {
48
64
  * in-flight request; tests inject their own controller's signal.
49
65
  */
50
66
  shutdownSignal?: AbortSignal;
67
+ /**
68
+ * Pre-resolved config. When supplied, the factory skips its own `loadConfig`
69
+ * call entirely. Callers that already resolved config (e.g. doctor, which
70
+ * must survive an unreadable credentials file) pass it through so the client
71
+ * never re-reads — and re-fails on — the file.
72
+ */
73
+ config?: Config;
51
74
  /** Defaults to `globalShutdown` so disarmed signals can see in-flight requests. */
52
75
  shutdown?: Pick<ShutdownHandle, 'runCriticalOperation'>;
53
76
  }
@@ -242,12 +242,13 @@ function resolveHttpClientOptions(opts, deps) {
242
242
  };
243
243
  }
244
244
  const credentialsPath = deps.credentialsPath ?? defaultCredentialsPath();
245
- const config = loadConfig({
246
- profile: opts.profile,
247
- endpointUrl: opts.endpointUrl,
248
- env,
249
- credentialsPath,
250
- });
245
+ const config = deps.config ??
246
+ loadConfig({
247
+ profile: opts.profile,
248
+ endpointUrl: opts.endpointUrl,
249
+ env,
250
+ credentialsPath,
251
+ });
251
252
  // Catch a malformed endpoint (from --endpoint-url / TESTSPRITE_API_URL /
252
253
  // credentials) before the auth check so a config typo surfaces as a clear
253
254
  // VALIDATION_ERROR rather than an opaque URL throw or a retried "fetch failed".
@@ -9,6 +9,7 @@ export interface LoadConfigOptions {
9
9
  env?: NodeJS.ProcessEnv;
10
10
  credentialsPath?: string;
11
11
  }
12
+ export declare const DEFAULT_API_URL = "https://api.testsprite.com";
12
13
  /** Treat empty / whitespace-only env values as unset for `??` resolution chains. */
13
14
  export declare function normalizeEnvVar(value: string | undefined): string | undefined;
14
15
  export declare function defaultConfigPath(): string;
@@ -1,7 +1,7 @@
1
1
  import { homedir } from 'node:os';
2
2
  import { join } from 'node:path';
3
3
  import { DEFAULT_PROFILE, defaultCredentialsPath, readProfile } from './credentials.js';
4
- const DEFAULT_API_URL = 'https://api.testsprite.com';
4
+ export const DEFAULT_API_URL = 'https://api.testsprite.com';
5
5
  /** Treat empty / whitespace-only env values as unset for `??` resolution chains. */
6
6
  export function normalizeEnvVar(value) {
7
7
  return value?.trim() || undefined;
@@ -17,10 +17,19 @@
17
17
  import { ApiError } from './errors.js';
18
18
  export type ConflictReason = 'in_flight' | 'mcp_view_only' | 'local_address' | 'not_found' | 'insufficient_credits' | 'paused'
19
19
  /** Deprecated spelling of `paused`, still sent by older backends. */
20
- | 'billing_hold' | 'error';
20
+ | 'billing_hold'
21
+ /**
22
+ * A backend consumer needs a variable no test case in the project captures.
23
+ * Like `producer_in_flight`, its `currentRunId` is the result the server
24
+ * seeded BLOCKED for this request, which becomes the test case's latest
25
+ * status: never dispatched, never charged.
26
+ */
27
+ | 'no_producer'
28
+ /** A backend consumer whose producer is running in another run. */
29
+ | 'producer_in_flight' | 'error';
21
30
  /** A conflict entry on a run response. `message` carries actionable detail for
22
- * `local_address` / `insufficient_credits` / `paused` / `error` (the
23
- * backend's nextAction). */
31
+ * `local_address` / `insufficient_credits` / `paused` / `no_producer` /
32
+ * `producer_in_flight` / `error` (the backend's nextAction). */
24
33
  export interface RunConflict {
25
34
  testId: string;
26
35
  currentRunId?: string;
@@ -42,6 +51,18 @@ export declare function describeConflict(c: RunConflict): string;
42
51
  * reason-aware summary instead of a misleading blanket "in flight".
43
52
  */
44
53
  export declare function allConflictsInFlight(conflicts: readonly RunConflict[]): boolean;
54
+ /**
55
+ * A backend consumer blocked before dispatch on a missing or busy producer.
56
+ * The CLI reports it as a refusal (exit 6), as a single `test run` does,
57
+ * rather than polling the result the server seeded for it.
58
+ */
59
+ export declare function isProducerBlock(c: RunConflict): boolean;
60
+ /**
61
+ * The retry advice for a set of refused test cases. A `no_producer` test case
62
+ * needs a producer, not a wait, so it gets its own line; every other reason
63
+ * keeps the caller's wait hint, given the ids it applies to.
64
+ */
65
+ export declare function conflictNextAction(conflicts: readonly RunConflict[], waitHint: (ids: readonly string[]) => string): string;
45
66
  /**
46
67
  * One-line summary of a conflict set grouped by reason, e.g.
47
68
  * `2 already in flight, 1 environment not runnable`. Used where a single line
@@ -34,6 +34,10 @@ export function describeConflict(c) {
34
34
  case 'paused':
35
35
  case 'billing_hold':
36
36
  return c.message || 'workspace paused';
37
+ case 'no_producer':
38
+ return c.message || 'no test case captures a variable it needs';
39
+ case 'producer_in_flight':
40
+ return c.message || 'its producer is running in another run';
37
41
  case 'error':
38
42
  return c.message || 'dispatch failed';
39
43
  case 'in_flight':
@@ -49,6 +53,8 @@ const CONFLICT_LABELS = {
49
53
  insufficient_credits: 'insufficient credits',
50
54
  paused: 'workspace paused',
51
55
  billing_hold: 'workspace paused',
56
+ no_producer: 'no producer for its variables',
57
+ producer_in_flight: 'producer running in another run',
52
58
  error: 'dispatch error',
53
59
  };
54
60
  /**
@@ -71,6 +77,30 @@ function countByReason(conflicts) {
71
77
  }
72
78
  return counts;
73
79
  }
80
+ /**
81
+ * A backend consumer blocked before dispatch on a missing or busy producer.
82
+ * The CLI reports it as a refusal (exit 6), as a single `test run` does,
83
+ * rather than polling the result the server seeded for it.
84
+ */
85
+ export function isProducerBlock(c) {
86
+ return c.reason === 'no_producer' || c.reason === 'producer_in_flight';
87
+ }
88
+ /**
89
+ * The retry advice for a set of refused test cases. A `no_producer` test case
90
+ * needs a producer, not a wait, so it gets its own line; every other reason
91
+ * keeps the caller's wait hint, given the ids it applies to.
92
+ */
93
+ export function conflictNextAction(conflicts, waitHint) {
94
+ const missing = conflicts.filter(c => c.reason === 'no_producer').map(c => c.testId);
95
+ const waiting = conflicts.filter(c => c.reason !== 'no_producer').map(c => c.testId);
96
+ const lines = [
97
+ waiting.length > 0 ? waitHint(waiting) : '',
98
+ missing.length > 0
99
+ ? `Add or accept a test case that captures the missing variable (or supply it from the environment), then retry: ${missing.join(' ')}`
100
+ : '',
101
+ ];
102
+ return lines.filter(Boolean).join('\n');
103
+ }
74
104
  /**
75
105
  * One-line summary of a conflict set grouped by reason, e.g.
76
106
  * `2 already in flight, 1 environment not runnable`. Used where a single line
@@ -78,9 +108,10 @@ function countByReason(conflicts) {
78
108
  */
79
109
  export function summarizeConflicts(conflicts) {
80
110
  // A future/unknown reason the loose wire schema admits (describeConflict covers
81
- // it via its default arm) must not render as "N undefined" here.
111
+ // it via its default arm) must not render as "N undefined" here. Callers wrap
112
+ // this in "not dispatched (…)", so the fallback must not say that again.
82
113
  return [...countByReason(conflicts).entries()]
83
- .map(([reason, n]) => `${n} ${CONFLICT_LABELS[reason] ?? 'not dispatched'}`)
114
+ .map(([reason, n]) => `${n} ${CONFLICT_LABELS[reason] ?? 'other'}`)
84
115
  .join(', ');
85
116
  }
86
117
  /**
@@ -22,7 +22,6 @@ type CredentialsWritePermissionError = NodeJS.ErrnoException & {
22
22
  export declare function isCredentialsWritePermissionError(error: unknown): error is CredentialsWritePermissionError;
23
23
  interface RestrictiveModeOptions {
24
24
  platform?: NodeJS.Platform;
25
- env?: NodeJS.ProcessEnv;
26
25
  spawnSync?: (command: string, args: readonly string[], options: {
27
26
  shell: false;
28
27
  stdio: 'ignore';
@@ -63,6 +63,8 @@ const CREDENTIALS_LOCK_WAIT_MS = 5_000;
63
63
  // problem and is surfaced as such.
64
64
  const CREDENTIALS_LOCK_TRANSIENT_WAIT_MS = 1_000;
65
65
  const CREDENTIALS_LOCK_STALE_MS = 30_000;
66
+ // How long a transient Windows error on replacing the credentials file is retried.
67
+ const CREDENTIALS_RENAME_TRANSIENT_WAIT_MS = 2_000;
66
68
  export function parseCredentials(content) {
67
69
  const result = {};
68
70
  let currentEntry = null;
@@ -181,27 +183,43 @@ export function ensureRestrictiveMode(path, options = {}) {
181
183
  chmodSync(path, 0o600);
182
184
  }
183
185
  /**
184
- * Restrict a Windows credentials file to the current user using icacls.
186
+ * Restrict a Windows credentials file to the file owner using icacls.
185
187
  * The command is invoked with an args array so credential paths are never shell-interpreted.
188
+ *
189
+ * Uses /reset to clear any broken inheritance state, followed by
190
+ * /inheritance:r /grant:r *S-1-3-4:F which decouples the file from parent ACLs
191
+ * and grants Full Control to the OWNER RIGHTS SID (S-1-3-4). This avoids
192
+ * dependency on resolving %USERNAME% (which fails on Microsoft Account or
193
+ * domain-joined machines).
186
194
  */
187
195
  function ensureWindowsRestrictiveAcl(path, options) {
188
- const username = (options.env ?? process.env).USERNAME?.trim();
189
- if (!username) {
190
- warnWindowsAcl('could not determine the Windows username; credentials file permissions were not tightened', options);
191
- return;
192
- }
193
196
  const run = options.spawnSync ?? spawnSync;
194
- const result = run('icacls', [path, '/inheritance:r', '/grant:r', `${username}:F`], {
197
+ const icaclsOptions = {
195
198
  shell: false,
196
199
  stdio: 'ignore',
197
200
  windowsHide: true,
198
- });
199
- if (result.error) {
200
- warnWindowsAcl(`icacls failed while tightening credentials file permissions: ${result.error.message}`, options);
201
+ };
202
+ const resetResult = run('icacls', [path, '/reset'], icaclsOptions);
203
+ if (resetResult.error) {
204
+ warnWindowsAcl(`icacls failed while resetting credentials file permissions: ${resetResult.error.message}`, options);
201
205
  return;
202
206
  }
203
- if (result.status !== 0) {
204
- warnWindowsAcl(`icacls exited with status ${result.status ?? 'unknown'}; credentials file permissions may be too broad`, options);
207
+ if (resetResult.status !== 0) {
208
+ warnWindowsAcl(`icacls /reset exited with status ${resetResult.status ?? 'unknown'}; credentials file permissions may be too broad`, options);
209
+ return;
210
+ }
211
+ // The trailing :F is load-bearing, not incidental: after /inheritance:r the
212
+ // file carries exactly this one ACE, and Full Control is what leaves
213
+ // WRITE_DAC with the owner — which is what makes a later `icacls /reset`
214
+ // possible at all. Tightening this to :R would leave the file unrepairable
215
+ // without taking ownership.
216
+ const grantResult = run('icacls', [path, '/inheritance:r', '/grant:r', '*S-1-3-4:F'], icaclsOptions);
217
+ if (grantResult.error) {
218
+ warnWindowsAcl(`icacls failed while tightening credentials file permissions: ${grantResult.error.message}`, options);
219
+ return;
220
+ }
221
+ if (grantResult.status !== 0) {
222
+ warnWindowsAcl(`icacls exited with status ${grantResult.status ?? 'unknown'}; credentials file permissions may be too broad`, options);
205
223
  }
206
224
  }
207
225
  /** Emit an explicit warning when Windows ACL tightening cannot be completed. */
@@ -238,8 +256,7 @@ function writeCredentialsAtomic(path, file) {
238
256
  try {
239
257
  // eslint-disable-next-line security/detect-non-literal-fs-filename -- `tmp` is `${path}.tmp.${pid}`, derived from the same internal credentials-file path; same baselined risk profile as the other fs calls in this file.
240
258
  writeFileSync(tmp, serializeCredentials(file), { mode: 0o600, encoding: 'utf8' });
241
- // eslint-disable-next-line security/detect-non-literal-fs-filename -- both operands derive from the internal credentials-file path (see above).
242
- renameSync(tmp, path);
259
+ renameCredentialsFile(tmp, path);
243
260
  }
244
261
  catch (error) {
245
262
  try {
@@ -259,6 +276,26 @@ function writeCredentialsAtomic(path, file) {
259
276
  }
260
277
  ensureRestrictiveMode(path);
261
278
  }
279
+ /**
280
+ * Replace the credentials file with the temp file. On Windows a transient
281
+ * EPERM/EBUSY/EACCES (another program briefly holding the file) is retried for a
282
+ * short window; anything else, or an error that persists, is thrown.
283
+ */
284
+ function renameCredentialsFile(tmp, path) {
285
+ const deadline = Date.now() + CREDENTIALS_RENAME_TRANSIENT_WAIT_MS;
286
+ while (true) {
287
+ try {
288
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- both operands derive from the internal credentials-file path (see writeCredentialsAtomic).
289
+ renameSync(tmp, path);
290
+ return;
291
+ }
292
+ catch (error) {
293
+ if (!isWindowsLockContention(error) || Date.now() >= deadline)
294
+ throw error;
295
+ sleepSync(CREDENTIALS_LOCK_RETRY_MS);
296
+ }
297
+ }
298
+ }
262
299
  function acquireCredentialsLock(path) {
263
300
  const lockPath = `${path}.lock`;
264
301
  const deadline = Date.now() + CREDENTIALS_LOCK_WAIT_MS;