@testsprite/testsprite-cli 0.3.0 → 0.5.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 (63) hide show
  1. package/README.md +55 -29
  2. package/dist/commands/agent.js +17 -6
  3. package/dist/commands/auth.d.ts +51 -0
  4. package/dist/commands/auth.js +46 -2
  5. package/dist/commands/completion.d.ts +36 -0
  6. package/dist/commands/completion.js +111 -0
  7. package/dist/commands/doctor.js +56 -16
  8. package/dist/commands/init.d.ts +32 -1
  9. package/dist/commands/init.js +40 -10
  10. package/dist/commands/project.d.ts +102 -4
  11. package/dist/commands/project.js +250 -47
  12. package/dist/commands/test.d.ts +253 -11
  13. package/dist/commands/test.js +1822 -390
  14. package/dist/commands/usage.d.ts +56 -17
  15. package/dist/commands/usage.js +144 -29
  16. package/dist/index.js +172 -29
  17. package/dist/lib/browser.d.ts +6 -0
  18. package/dist/lib/browser.js +54 -0
  19. package/dist/lib/bundle.d.ts +32 -31
  20. package/dist/lib/bundle.js +144 -84
  21. package/dist/lib/client-factory.d.ts +29 -0
  22. package/dist/lib/client-factory.js +49 -1
  23. package/dist/lib/config.js +7 -3
  24. package/dist/lib/credentials.d.ts +17 -1
  25. package/dist/lib/credentials.js +175 -16
  26. package/dist/lib/dry-run/samples.js +51 -1
  27. package/dist/lib/errors.d.ts +33 -1
  28. package/dist/lib/errors.js +110 -19
  29. package/dist/lib/failing-fe-resolver.d.ts +15 -0
  30. package/dist/lib/failing-fe-resolver.js +49 -1
  31. package/dist/lib/flaky.d.ts +12 -1
  32. package/dist/lib/flaky.js +7 -12
  33. package/dist/lib/gh-output.d.ts +62 -0
  34. package/dist/lib/gh-output.js +99 -0
  35. package/dist/lib/http.d.ts +86 -16
  36. package/dist/lib/http.js +181 -11
  37. package/dist/lib/interrupt.d.ts +65 -10
  38. package/dist/lib/interrupt.js +94 -9
  39. package/dist/lib/org-render.d.ts +52 -0
  40. package/dist/lib/org-render.js +59 -0
  41. package/dist/lib/poll.d.ts +11 -0
  42. package/dist/lib/poll.js +71 -6
  43. package/dist/lib/render-error.d.ts +14 -0
  44. package/dist/lib/render-error.js +30 -0
  45. package/dist/lib/response-schemas.d.ts +83 -0
  46. package/dist/lib/response-schemas.js +272 -0
  47. package/dist/lib/runs.types.d.ts +62 -8
  48. package/dist/lib/skill-nudge.d.ts +17 -0
  49. package/dist/lib/skill-nudge.js +19 -0
  50. package/dist/lib/telemetry.d.ts +90 -0
  51. package/dist/lib/telemetry.js +171 -0
  52. package/dist/lib/text-table.d.ts +14 -0
  53. package/dist/lib/text-table.js +45 -0
  54. package/dist/lib/v3-advisory.d.ts +22 -0
  55. package/dist/lib/v3-advisory.js +32 -0
  56. package/dist/lib/version-notice.d.ts +37 -0
  57. package/dist/lib/version-notice.js +87 -0
  58. package/dist/version.d.ts +1 -1
  59. package/dist/version.js +1 -1
  60. package/package.json +16 -5
  61. package/schemas/plan.schema.json +61 -0
  62. package/skills/testsprite-verify.codex.md +8 -2
  63. package/skills/testsprite-verify.skill.md +18 -7
package/README.md CHANGED
@@ -69,7 +69,7 @@ TESTSPRITE_API_KEY=sk-... testsprite setup --from-env --yes --agent claude
69
69
 
70
70
  > **Pointing a coding agent (Claude Code, Cursor, Codex, Cline, …) at TestSprite?** Have it run `testsprite setup` first — that installs the verification skill, so the agent knows how to create, run, and triage tests on its own (instead of guessing from this README). New here? Start with the **[getting-started overview](https://docs.testsprite.com/cli/getting-started/overview)**.
71
71
 
72
- > **Privacy note:** interactive runs check the npm registry at most once per 24 h to offer a "new version available" notice — package name only, never your key or data; `TESTSPRITE_NO_UPDATE_NOTIFIER=1` disables it. Details in [DOCUMENTATION.md → Update notice](./DOCUMENTATION.md#update-notice).
72
+ > **Privacy note:** interactive runs check the npm registry at most once per 24 h to offer a "new version available" notice — package name only, never your key or data; `TESTSPRITE_NO_UPDATE_NOTIFIER=1` disables it. The backend also advertises its minimum supported CLI version — a below-floor CLI prints a one-line upgrade advisory on stderr, and a too-old client may be rejected with exit 14 (`CLIENT_TOO_OLD`). Details in [DOCUMENTATION.md → Update notice](./DOCUMENTATION.md#update-notice).
73
73
 
74
74
  From there, the loop runs on its own — an example session, typed by the coding agent:
75
75
 
@@ -87,38 +87,64 @@ testsprite test rerun test_3a9f21c7 --wait --output json
87
87
  # → exits 0: passed. The test now lives in your durable suite.
88
88
  ```
89
89
 
90
+ `./checkout-flow.plan.json` (the `--plan-from` argument above) is a JSON file describing the test in plain language — no browser code required. This is the exact, byte-identical output of `testsprite test create --plan-template` (also embedded verbatim in `test create --help`):
91
+
92
+ ```json
93
+ {
94
+ "$schema": "https://raw.githubusercontent.com/TestSprite/testsprite-cli/v0.4.0/schemas/plan.schema.json",
95
+ "projectId": "prj_abc123",
96
+ "type": "frontend",
97
+ "name": "Login rejects an empty password",
98
+ "planSteps": [
99
+ {
100
+ "type": "action",
101
+ "description": "Navigate to /login and submit the form with an empty password"
102
+ },
103
+ {
104
+ "type": "assertion",
105
+ "description": "Verify an inline error says the password is required"
106
+ }
107
+ ]
108
+ }
109
+ ```
110
+
111
+ Get this exact skeleton without hand-copying it (and without the risk of it drifting from your installed version — see below): `testsprite test create --plan-template`. Full field reference (including the `{{...}}`-placeholder caveat, size caps, and the `$schema` hook for live editor validation): [Plan file format](./DOCUMENTATION.md#plan-file-format).
112
+
113
+ > The `$schema` URL above is pinned to the CLI version that generated this doc (`v0.4.0`) — `--plan-template`'s live output always pins to **your installed version** instead, which is what actually resolves. If you're reading this on a later release, run the command yourself rather than trusting this snippet verbatim.
114
+
90
115
  Prefer to configure each step by hand (or learn the surface offline with `--dry-run` first)? See [Manual setup](./DOCUMENTATION.md#manual-setup) and [Install & verify](./DOCUMENTATION.md#install--verify).
91
116
 
92
117
  ## Commands
93
118
 
94
- | Group | Command | What it does |
95
- | --------- | --------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
96
- | **Setup** | `setup` | **Start here** — one command: configure your API key, verify it, and install the agent verification skill |
97
- | | `doctor` | Environment diagnostic — CLI/Node versions, profile, endpoint, credentials, connectivity, agent skill; exits non-zero on failure |
98
- | **Auth** | `auth status` | Resolve the active profile to its user, key, env, and scopes |
99
- | | `auth remove` | Remove the active profile from the credentials file |
100
- | | `usage` (alias `credits`) | Account pre-flight: identity, plus credit balance / plan info when the backend supplies them |
101
- | **Read** | `project list` / `project get` | List projects / fetch one by id |
102
- | | `test list` / `test get` | List tests under a project / fetch one by id |
103
- | | `test code get` | Print (or write) the generated test source |
104
- | | `test steps` | List the latest run's steps with screenshot / DOM pointers |
105
- | | `test result` | Latest result; `--history` lists a test's prior runs |
106
- | | `test failure get` | The agent entry point: one self-contained latest-failure bundle |
107
- | | `test failure summary` | One-screen triage card (no media download) |
108
- | | `test diff` | Compare two runs — verdict, failure kind, per-step status flips, code-version drift |
109
- | **Write** | `test scaffold` / `test lint` | Author plans locally: emit a schema-correct starter, validate plan files offline — no network, no credentials |
110
- | | `test create` / `test create-batch` | Create a test (or bulk-create from a plan file); `--produces` / `--needs` / `--category` wire BE dependency metadata |
111
- | | `test update` / `test delete` / `test delete-batch` | Edit metadata / permanently delete (no restore window; `--confirm` required) |
112
- | | `test code put` | Replace generated code (etag-guarded) |
113
- | | `test plan put` | Replace a frontend test's plan-steps |
114
- | | `project create` / `project update` | Manage projects |
115
- | | `project credential` / `project auto-auth` | Configure backend-test auth: a static injected credential, or auto-refresh login (Pro) |
116
- | **Run** | `test run` | Trigger a fresh run; `--wait` blocks until terminal; `--all --project <id>` runs all tests in a project in wave order |
117
- | | `test rerun` | Cheap replay of one/many tests (FE verbatim; BE with deps); `--all --project <id>` reruns all tests |
118
- | | `test flaky` | Replay a test several times (auto-heal off) and report a stability score |
119
- | | `test wait` | Block on one or more `runId`s until terminal |
120
- | | `test artifact get` | Download the failure bundle for a specific `runId` |
121
- | **Agent** | `agent install` / `agent list` / `agent status` | Add, list, or health-check coding-agent skills (pure-local): `claude`, `codex`, `cursor`, `cline`, `antigravity`, `kiro`, `windsurf`, `copilot` |
119
+ | Group | Command | What it does |
120
+ | --------- | ------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
121
+ | **Setup** | `setup` | **Start here** — one command: configure your API key, verify it, and install the agent verification skill |
122
+ | | `doctor` | Environment diagnostic — CLI/Node versions, profile, endpoint, credentials, connectivity, agent skill; exits non-zero on failure |
123
+ | **Auth** | `auth status` | Resolve the active profile to its user, key, env, and scopes |
124
+ | | `auth remove` | Remove the active profile from the credentials file |
125
+ | | `usage` (alias `credits`) | Account pre-flight: identity, plus credit balance / plan info when the backend supplies them |
126
+ | **Read** | `project list` / `project get` | List projects / fetch one by id |
127
+ | | `test list` / `test get` | List tests under a project / fetch one by id |
128
+ | | `test code get` | Print (or write) the generated test source |
129
+ | | `test steps` | List the latest run's steps with screenshot / DOM pointers |
130
+ | | `test result` | Latest result; `--history` lists a test's prior runs |
131
+ | | `test failure get` | The agent entry point: one self-contained latest-failure bundle |
132
+ | | `test failure summary` | One-screen triage card (no media download) |
133
+ | | `test diff` | Compare two runs — verdict, failure kind, per-step status flips, code-version drift |
134
+ | **Write** | `test scaffold` / `test lint` | Author plans locally: emit a schema-correct starter, validate plan files offline — no network, no credentials |
135
+ | | `test create` / `test create-batch` | Create a test (or bulk-create from a plan file); `--produces` / `--needs` / `--category` wire BE dependency metadata |
136
+ | | `test update` / `test delete` / `test delete-batch` | Edit metadata and BE dependency declarations (`--produces` / `--needs` / `--category`) / permanently delete (no restore window; `--confirm` required) |
137
+ | | `test code put` | Replace generated code (etag-guarded) |
138
+ | | `test plan put` | Replace a frontend test's plan-steps |
139
+ | | `project create` / `project update` / `project delete` | Manage projects; `delete` removes a project and everything under it (`--confirm` required, no restore window) |
140
+ | | `project credential` / `project auto-auth` | Configure backend-test auth: a static injected credential, or auto-refresh login (Pro) |
141
+ | **Run** | `test run` | Trigger a fresh run; `--wait` blocks until terminal; `--all --project <id>` runs all tests in a project in wave order |
142
+ | | `test rerun` | Replay one/many tests (FE verbatim; BE with deps); billed as a run (0.5 credits FE / 0.2 BE); `--all --project <id>` reruns all tests |
143
+ | | `test flaky` | Replay a test several times (auto-heal off) and report a stability score |
144
+ | | `test wait` | Block on one or more `runId`s until terminal |
145
+ | | `test cancel` | Cancel one or more in-flight runs (Ctrl-C during `--wait` only detaches — `cancel` is the real stop) |
146
+ | | `test artifact get` | Download the failure bundle for a specific `runId` |
147
+ | **Agent** | `agent install` / `agent list` / `agent status` | Add, list, or health-check coding-agent skills (pure-local): `claude`, `codex`, `cursor`, `cline`, `antigravity`, `kiro`, `windsurf`, `copilot` |
122
148
 
123
149
  > The earlier command names — `init`, `auth configure`, `auth whoami`, `auth logout` — still work as hidden, deprecated aliases (each prints a one-line notice pointing at the new name), so existing scripts keep running. `auth configure` now runs the full `setup` (it also installs the skill).
124
150
 
@@ -359,7 +359,7 @@ export async function runInstall(opts, deps = {}) {
359
359
  const bytes = Buffer.byteLength(section, 'utf8');
360
360
  let wouldBeContent = section;
361
361
  if (dryRunSt !== null) {
362
- let existing = null;
362
+ let existing;
363
363
  try {
364
364
  existing = await agentFs.readFile(abs);
365
365
  }
@@ -746,18 +746,29 @@ function collect(v, prev) {
746
746
  export function createAgentCommand(deps = {}) {
747
747
  const agent = new Command('agent').description('Install TestSprite guidance into coding-agent config (Claude Code, Cursor, Cline, Antigravity, Kiro, Windsurf, Copilot, Codex)');
748
748
  agent
749
- .command('install')
750
- .description('Write the TestSprite agent skills (verification loop + first-run onboarding) into a project for a coding agent')
751
- .option('--target <t>', 'Agent target(s): claude, cursor, cline, antigravity, kiro, windsurf, copilot, codex (comma-separated or repeated)', collect, [])
749
+ .command('install [targets...]')
750
+ .description('Write the TestSprite agent skills (verification loop + first-run onboarding) into a project for a coding agent. ' +
751
+ 'Target(s) may be given positionally (e.g. `agent install cursor codex`) and/or via --target; the two are merged.')
752
+ .option('--target <t>', 'Agent target(s): claude, cursor, cline, antigravity, kiro, windsurf, copilot, codex (comma-separated or repeated). Merged with any positional target(s).', collect, [])
752
753
  .option('--skill <name>', `Skill(s) to install: ${Object.keys(SKILLS).join(', ')} (comma-separated or repeated; default: all)`, collect, [])
753
754
  .option('--dir <path>', 'Project root to write into (default: cwd)')
754
755
  .option('--force', 'For own-file targets: overwrite existing file (a .bak backup is kept). ' +
755
756
  'For codex (managed-section): replaces the section unconditionally; user content outside the section is never destroyed.')
756
757
  .addHelpText('after', GLOBAL_OPTS_HINT)
757
- .action(async (cmdOpts, command) => {
758
+ .action(async (
759
+ // Positional targets: `agent install cursor` previously parsed
760
+ // as zero targets (Commander silently drops undeclared positionals),
761
+ // silently falling through to the non-TTY default-to-claude path — so
762
+ // 7 of the 8 documented one-liners installed the WRONG agent's skill
763
+ // with zero signal. Declaring `[targets...]` captures them; they are
764
+ // merged with `--target` (order: positional first, then flag values)
765
+ // and flow through runInstall's existing parse/validate/dedupe pipeline
766
+ // unchanged, so an unknown name (positional or flag) still rejects with
767
+ // exit 5 instead of silently defaulting.
768
+ positionalTargets, cmdOpts, command) => {
758
769
  await runInstall({
759
770
  ...resolveCommonOptions(command),
760
- target: cmdOpts.target,
771
+ target: [...positionalTargets, ...cmdOpts.target],
761
772
  skills: cmdOpts.skill,
762
773
  dir: cmdOpts.dir,
763
774
  force: Boolean(cmdOpts.force),
@@ -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 { CliOrgBinding, CliOrgSummary } from '../lib/org-render.js';
4
5
  export interface MeResponse {
5
6
  userId: string;
6
7
  keyId: string;
@@ -15,6 +16,45 @@ export interface MeResponse {
15
16
  email?: string;
16
17
  /** Human-readable display name for the bound account. Absent-safe (dogfood L1866). */
17
18
  displayName?: string;
19
+ /**
20
+ * Authoritative per-user V3 routing bit. Absent-safe: older backends omit it,
21
+ * so it is only rendered when present.
22
+ */
23
+ v3Enabled?: boolean;
24
+ /**
25
+ * Legacy per-user billing projections. Absent-safe; superseded by
26
+ * `activeOrg` when both are present. Declared so shared fixtures typed as
27
+ * `MeResponse` can carry them (the `usage` command has its own richer view).
28
+ */
29
+ credits?: number;
30
+ subPlan?: string;
31
+ creditsPerRun?: number;
32
+ /**
33
+ * The caller's organization (org-based billing subject). Absent-safe:
34
+ * rendered as a single `org:` line when present (V3-routed callers only).
35
+ */
36
+ activeOrg?: {
37
+ id: string;
38
+ name: string;
39
+ plan: string;
40
+ role: string;
41
+ remaining: number;
42
+ includedCredits: number;
43
+ seats: number;
44
+ };
45
+ /**
46
+ * Every organization the underlying user belongs to (account-wide
47
+ * membership list, personal org included). Independent of `org` below.
48
+ * Absent-safe: omitted on a server-side lookup failure or an older
49
+ * backend.
50
+ */
51
+ organizations?: CliOrgSummary[];
52
+ /**
53
+ * The calling key's own org binding. Present only when the request
54
+ * authenticated with a Postgres-backed membership key (`sk-member-…`);
55
+ * absent for a legacy envelope key, which has no binding to echo.
56
+ */
57
+ org?: CliOrgBinding;
18
58
  }
19
59
  export interface AuthDeps {
20
60
  env?: NodeJS.ProcessEnv;
@@ -40,6 +80,17 @@ export interface AuthDeps {
40
80
  type CommonOptions = FactoryCommonOptions;
41
81
  interface ConfigureOptions extends CommonOptions {
42
82
  fromEnv: boolean;
83
+ /**
84
+ * When true and the active profile already has a saved API key, skip the
85
+ * interactive key prompt and proceed directly to the skill-install step.
86
+ * A CI-safe flag: lets `setup` run idempotently without prompting on
87
+ * machines that already have credentials (e.g. re-running setup to
88
+ * refresh the agent skill without re-entering the key).
89
+ *
90
+ * Ignored when an explicit `--api-key` or `--from-env` key source is
91
+ * provided -- those paths always overwrite, regardless of existing state.
92
+ */
93
+ skipIfConfigured?: boolean;
43
94
  }
44
95
  export declare function runConfigure(opts: ConfigureOptions, deps?: AuthDeps): Promise<void>;
45
96
  export declare function runWhoami(opts: CommonOptions, deps?: AuthDeps): Promise<MeResponse>;
@@ -1,5 +1,5 @@
1
1
  import { Command } from 'commander';
2
- import { assertValidEndpointUrl, emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, } from '../lib/client-factory.js';
2
+ import { assertValidApiKey, assertValidEndpointUrl, emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, } from '../lib/client-factory.js';
3
3
  import { ApiError, CLIError } from '../lib/errors.js';
4
4
  import { facadeBaseUrl } from '../lib/facade.js';
5
5
  import { HttpClient } from '../lib/http.js';
@@ -8,6 +8,8 @@ import { loadConfig, normalizeEnvVar } from '../lib/config.js';
8
8
  import { emitDeprecationNotice } from '../lib/deprecate.js';
9
9
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
10
10
  import { promptSecret } from '../lib/prompt.js';
11
+ import { formatOrgBinding, formatOrgsSummary, formatPersonalScopeHint } from '../lib/org-render.js';
12
+ import { emitV3RoutingAdvisory, routingLabel } from '../lib/v3-advisory.js';
11
13
  const DEFAULT_API_URL = 'https://api.testsprite.com';
12
14
  const FROM_ENV_MISSING_KEY = 'TESTSPRITE_API_KEY is not set in the environment. Set it and re-run with --from-env, or omit --from-env to enter the key interactively.';
13
15
  export async function runConfigure(opts, deps = {}) {
@@ -60,9 +62,22 @@ export async function runConfigure(opts, deps = {}) {
60
62
  throw validationError('TESTSPRITE_API_KEY', FROM_ENV_MISSING_KEY);
61
63
  }
62
64
  else {
65
+ // --skip-if-configured: when a non-empty API key is already saved for
66
+ // this profile, skip the interactive prompt and return early. The
67
+ // key is NOT re-validated via GET /me on this path -- the caller
68
+ // (runInit) only reaches this when no explicit key source was given,
69
+ // and the subsequent whoami call in runInit will surface an expired
70
+ // key to the user anyway.
71
+ if (opts.skipIfConfigured && existingProfile?.apiKey) {
72
+ out.print({ profile: opts.profile, apiUrl, status: 'already_configured' }, data => {
73
+ const d = data;
74
+ return `Profile "${d.profile}" already configured. Endpoint: ${d.apiUrl}`;
75
+ });
76
+ return;
77
+ }
63
78
  const promptApi = deps.prompt ?? { secret: (q) => promptSecret(q) };
64
79
  prelude(`Configuring profile "${opts.profile}".\n`);
65
- // Only the API key is prompted — the endpoint defaults to prod (see above).
80
+ // Only the API key is prompted -- the endpoint defaults to prod (see above).
66
81
  apiKey = (await promptApi.secret('TestSprite API key: ')).trim();
67
82
  if (!apiKey)
68
83
  throw new CLIError('No API key provided.', 5);
@@ -76,6 +91,9 @@ export async function runConfigure(opts, deps = {}) {
76
91
  resolvedFromProfile !== DEFAULT_API_URL) {
77
92
  stderr(`[advisory] Inheriting api_url from existing profile: ${resolvedFromProfile}`);
78
93
  }
94
+ // Reject a malformed key up front — before any network — so `setup` fails
95
+ // fast with a VALIDATION_ERROR instead of a live ping or a raw Headers error.
96
+ assertValidApiKey(apiKey);
79
97
  // Verify the key is accepted before persisting. Build an HttpClient
80
98
  // directly (bypassing loadConfig) so we can test the candidate key+url
81
99
  // before it is written to disk. This ensures we never overwrite a
@@ -124,6 +142,7 @@ export async function runConfigure(opts, deps = {}) {
124
142
  export async function runWhoami(opts, deps = {}) {
125
143
  const out = makeOutput(opts.output, deps);
126
144
  const env = deps.env ?? process.env;
145
+ const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
127
146
  // Resolve the endpoint URL so it can be surfaced in text output.
128
147
  // Dry-run uses the flag/env/default chain without touching credentials.
129
148
  // Real path uses the same loadConfig the HttpClient factory uses so the
@@ -165,6 +184,26 @@ export async function runWhoami(opts, deps = {}) {
165
184
  `endpoint: ${resolvedEndpoint}`,
166
185
  `env: ${m.env}`,
167
186
  `scopes: ${m.scopes.join(', ')}`,
187
+ // Org context — confirms whose wallet a billable command will draw
188
+ // from, so it renders only for V3-routed callers (`v3Enabled` is the
189
+ // authoritative routing bit; field presence alone is not trusted).
190
+ ...(m.v3Enabled === true && m.activeOrg
191
+ ? [`org: ${m.activeOrg.name} (${m.activeOrg.plan}, ${m.activeOrg.role})`]
192
+ : []),
193
+ // Authoritative routing mode, rendered only when the backend supplies it.
194
+ ...(m.v3Enabled !== undefined ? [`routing: ${routingLabel(m.v3Enabled)}`] : []),
195
+ // Org attribution — account-wide membership list, rendered only when
196
+ // the backend supplies a non-empty list.
197
+ ...(formatOrgsSummary(m.organizations)
198
+ ? [`orgs: ${formatOrgsSummary(m.organizations)}`]
199
+ : []),
200
+ // The calling key's own org binding — membership keys only.
201
+ ...(formatOrgBinding(m.org) ? [`org binding: ${formatOrgBinding(m.org)}`] : []),
202
+ // A personal-scoped key held by someone who is also in a team: say so
203
+ // here rather than letting the team's projects just not show up.
204
+ ...(formatPersonalScopeHint(m.organizations, m.org)
205
+ ? [`note: ${formatPersonalScopeHint(m.organizations, m.org)}`]
206
+ : []),
168
207
  ];
169
208
  // C2: warn in text mode when key cannot write/run
170
209
  const missingScopes = ['write:tests', 'run:tests'].filter(s => !m.scopes.includes(s));
@@ -173,6 +212,11 @@ export async function runWhoami(opts, deps = {}) {
173
212
  }
174
213
  return lines.join('\n');
175
214
  });
215
+ // When V3 routing is on, warn (text mode only) about the still-open behavior
216
+ // gaps. JSON consumers read `v3Enabled` directly; stdout stays pure.
217
+ if (opts.output !== 'json' && me.v3Enabled === true) {
218
+ emitV3RoutingAdvisory(stderr);
219
+ }
176
220
  return me;
177
221
  }
178
222
  export async function runLogout(opts, deps = {}) {
@@ -0,0 +1,36 @@
1
+ /**
2
+ * `testsprite completion [bash|zsh|fish]` — emit a shell completion script.
3
+ *
4
+ * The command names, per-group subcommands, and global flags are NOT hardcoded:
5
+ * `index.ts` builds a {@link CompletionSpec} by walking the fully-assembled
6
+ * Commander program and passes it in, so the generated script can never drift
7
+ * from the real command tree. `renderCompletion` is a pure function of the spec,
8
+ * which keeps it unit-testable without a live program.
9
+ *
10
+ * Usage:
11
+ * bash: eval "$(testsprite completion bash)" (add to ~/.bashrc)
12
+ * zsh: testsprite completion zsh > ~/.zsh/_testsprite (on your fpath)
13
+ * fish: testsprite completion fish | source (add to config.fish)
14
+ */
15
+ import { Command } from 'commander';
16
+ export declare const SUPPORTED_SHELLS: readonly ["bash", "zsh", "fish"];
17
+ export type Shell = (typeof SUPPORTED_SHELLS)[number];
18
+ export interface CompletionSpec {
19
+ /** Binary name, e.g. "testsprite". */
20
+ program: string;
21
+ /** Top-level command names. */
22
+ commands: string[];
23
+ /** command name -> its subcommand names (only groups that have subcommands). */
24
+ subcommands: Record<string, string[]>;
25
+ /** Global long option flags (e.g. "--output"). */
26
+ globalFlags: string[];
27
+ }
28
+ export interface CompletionDeps {
29
+ env?: NodeJS.ProcessEnv;
30
+ stdout?: (line: string) => void;
31
+ }
32
+ export declare function isShell(value: string): value is Shell;
33
+ /** Best-effort shell detection from `$SHELL` (e.g. "/bin/zsh" -> "zsh"). */
34
+ export declare function detectShell(env: NodeJS.ProcessEnv): Shell | undefined;
35
+ export declare function renderCompletion(shell: Shell, spec: CompletionSpec): string;
36
+ export declare function createCompletionCommand(getSpec: () => CompletionSpec, deps?: CompletionDeps): Command;
@@ -0,0 +1,111 @@
1
+ /**
2
+ * `testsprite completion [bash|zsh|fish]` — emit a shell completion script.
3
+ *
4
+ * The command names, per-group subcommands, and global flags are NOT hardcoded:
5
+ * `index.ts` builds a {@link CompletionSpec} by walking the fully-assembled
6
+ * Commander program and passes it in, so the generated script can never drift
7
+ * from the real command tree. `renderCompletion` is a pure function of the spec,
8
+ * which keeps it unit-testable without a live program.
9
+ *
10
+ * Usage:
11
+ * bash: eval "$(testsprite completion bash)" (add to ~/.bashrc)
12
+ * zsh: testsprite completion zsh > ~/.zsh/_testsprite (on your fpath)
13
+ * fish: testsprite completion fish | source (add to config.fish)
14
+ */
15
+ import { Command } from 'commander';
16
+ import { localValidationError } from '../lib/errors.js';
17
+ export const SUPPORTED_SHELLS = ['bash', 'zsh', 'fish'];
18
+ export function isShell(value) {
19
+ return SUPPORTED_SHELLS.includes(value);
20
+ }
21
+ /** Best-effort shell detection from `$SHELL` (e.g. "/bin/zsh" -> "zsh"). */
22
+ export function detectShell(env) {
23
+ const shellPath = env.SHELL ?? '';
24
+ const rawBase = shellPath.split(/[/\\]/).pop() ?? '';
25
+ const base = rawBase.toLowerCase().replace(/\.exe$/, '');
26
+ return isShell(base) ? base : undefined;
27
+ }
28
+ export function renderCompletion(shell, spec) {
29
+ switch (shell) {
30
+ case 'bash':
31
+ return renderBash(spec);
32
+ case 'zsh':
33
+ return renderZsh(spec);
34
+ case 'fish':
35
+ return renderFish(spec);
36
+ }
37
+ }
38
+ function renderBash(spec) {
39
+ const fn = `_${spec.program}_completion`;
40
+ const lines = [
41
+ `# ${spec.program} bash completion. Enable with: eval "$(${spec.program} completion bash)"`,
42
+ `${fn}() {`,
43
+ ' local cur prev',
44
+ ' cur="${COMP_WORDS[COMP_CWORD]}"',
45
+ ' prev="${COMP_WORDS[COMP_CWORD-1]}"',
46
+ ` local commands="${spec.commands.join(' ')}"`,
47
+ ` local global_flags="${spec.globalFlags.join(' ')}"`,
48
+ ' case "$prev" in',
49
+ ...Object.entries(spec.subcommands).map(([group, subs]) => ` ${group}) COMPREPLY=( $(compgen -W "${subs.join(' ')}" -- "$cur") ); return;;`),
50
+ ' esac',
51
+ ' if [[ "$cur" == -* ]]; then',
52
+ ' COMPREPLY=( $(compgen -W "$global_flags" -- "$cur") ); return',
53
+ ' fi',
54
+ ' COMPREPLY=( $(compgen -W "$commands" -- "$cur") )',
55
+ '}',
56
+ `complete -F ${fn} ${spec.program}`,
57
+ ];
58
+ return lines.join('\n');
59
+ }
60
+ function renderZsh(spec) {
61
+ const fn = `_${spec.program}`;
62
+ const lines = [
63
+ `#compdef ${spec.program}`,
64
+ `# ${spec.program} zsh completion. Enable with: ${spec.program} completion zsh > "$fpath[1]/_${spec.program}"`,
65
+ `${fn}() {`,
66
+ ' local -a commands',
67
+ ` commands=(${spec.commands.join(' ')})`,
68
+ ' if (( CURRENT == 2 )); then',
69
+ " _describe 'command' commands",
70
+ ' return',
71
+ ' fi',
72
+ ' case "${words[2]}" in',
73
+ ...Object.entries(spec.subcommands).map(([group, subs]) => ` ${group}) local -a subs; subs=(${subs.join(' ')}); _describe 'subcommand' subs;;`),
74
+ ' esac',
75
+ '}',
76
+ `compdef ${fn} ${spec.program}`,
77
+ ];
78
+ return lines.join('\n');
79
+ }
80
+ function renderFish(spec) {
81
+ const lines = [
82
+ `# ${spec.program} fish completion. Enable with: ${spec.program} completion fish | source`,
83
+ `complete -c ${spec.program} -f`,
84
+ ...spec.commands.map(command => `complete -c ${spec.program} -n '__fish_use_subcommand' -a '${command}'`),
85
+ ...Object.entries(spec.subcommands).flatMap(([group, subs]) => subs.map(sub => `complete -c ${spec.program} -n '__fish_seen_subcommand_from ${group}' -a '${sub}'`)),
86
+ ...spec.globalFlags.map(flag => `complete -c ${spec.program} -l ${flag.replace(/^--/, '')}`),
87
+ ];
88
+ return lines.join('\n');
89
+ }
90
+ export function createCompletionCommand(getSpec, deps = {}) {
91
+ return new Command('completion')
92
+ .description('Print a shell completion script (bash|zsh|fish)')
93
+ .argument('[shell]', 'Shell to generate for (bash|zsh|fish); auto-detected from $SHELL when omitted')
94
+ .addHelpText('after', '\nExamples:\n' +
95
+ ' eval "$(testsprite completion bash)" # bash, current session\n' +
96
+ ' testsprite completion zsh > ~/.zsh/_testsprite\n' +
97
+ ' testsprite completion fish | source # fish, current session')
98
+ .action((shellArg, _cmdOpts) => {
99
+ const env = deps.env ?? process.env;
100
+ const shell = shellArg ?? detectShell(env);
101
+ if (shell === undefined) {
102
+ throw localValidationError('shell', `could not detect the shell from $SHELL; pass one explicitly (${SUPPORTED_SHELLS.join(', ')})`, [...SUPPORTED_SHELLS]);
103
+ }
104
+ if (!isShell(shell)) {
105
+ throw localValidationError('shell', `unsupported shell "${shell}"; use one of: ${SUPPORTED_SHELLS.join(', ')}`, [...SUPPORTED_SHELLS]);
106
+ }
107
+ const write = deps.stdout ?? ((line) => process.stdout.write(`${line}\n`));
108
+ write(renderCompletion(shell, getSpec()));
109
+ });
110
+ }
111
+ //# sourceMappingURL=completion.js.map
@@ -18,8 +18,10 @@ import { Command } from 'commander';
18
18
  import { assertValidEndpointUrl, makeHttpClient, } from '../lib/client-factory.js';
19
19
  import { loadConfig } from '../lib/config.js';
20
20
  import { ApiError, CLIError, localValidationError } from '../lib/errors.js';
21
- import { GLOBAL_OPTS_HINT, Output } from '../lib/output.js';
21
+ import { formatOrgBinding, formatOrgsSummary, formatPersonalScopeHint } from '../lib/org-render.js';
22
+ import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
22
23
  import { isVerifySkillInstalled } from '../lib/skill-nudge.js';
24
+ import { emitV3RoutingAdvisory, routingLabel } from '../lib/v3-advisory.js';
23
25
  import { VERSION } from '../version.js';
24
26
  import { MIN_SUPPORTED_NODE_MAJOR, shouldRejectNodeVersion } from '../version-guard.js';
25
27
  export async function runDoctor(opts, deps = {}) {
@@ -35,22 +37,53 @@ export async function runDoctor(opts, deps = {}) {
35
37
  });
36
38
  const endpointCheck = checkEndpoint(config.apiUrl);
37
39
  const hasKey = Boolean(config.apiKey);
40
+ const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
41
+ const connectivity = await checkConnectivity(opts, deps, {
42
+ hasKey,
43
+ endpointOk: endpointCheck.status === 'ok',
44
+ });
38
45
  const checks = [
39
46
  { name: 'CLI version', status: 'ok', detail: VERSION },
40
47
  checkNodeVersion(nodeVersion),
41
48
  { name: 'Profile', status: 'ok', detail: config.profile },
42
49
  endpointCheck,
43
50
  checkCredentials(hasKey, config.profile, opts.dryRun ?? false),
44
- await checkConnectivity(opts, deps, {
45
- hasKey,
46
- endpointOk: endpointCheck.status === 'ok',
47
- }),
48
- checkSkill(cwd, deps),
51
+ connectivity.check,
49
52
  ];
53
+ // Informational routing line, only when the backend reported it (no new call).
54
+ if (connectivity.v3Enabled !== undefined) {
55
+ const label = routingLabel(connectivity.v3Enabled);
56
+ checks.push({
57
+ name: 'Routing',
58
+ status: 'ok',
59
+ detail: connectivity.v3Enabled === true
60
+ ? `${label} (V3 execution routing is ON)`
61
+ : `${label} (default routing)`,
62
+ });
63
+ }
64
+ // Org attribution lines — only when the backend reported them (no new call).
65
+ const orgsSummary = formatOrgsSummary(connectivity.organizations);
66
+ if (orgsSummary) {
67
+ checks.push({ name: 'Organizations', status: 'ok', detail: orgsSummary });
68
+ }
69
+ const orgBinding = formatOrgBinding(connectivity.org);
70
+ if (orgBinding) {
71
+ checks.push({ name: 'Org binding', status: 'ok', detail: orgBinding });
72
+ }
73
+ // Warn, not fail: the key works — it just cannot see the team's work, which
74
+ // otherwise looks like missing data rather than a scoping choice.
75
+ const personalScopeHint = formatPersonalScopeHint(connectivity.organizations, connectivity.org);
76
+ if (personalScopeHint) {
77
+ checks.push({ name: 'Workspace scope', status: 'warn', detail: personalScopeHint });
78
+ }
79
+ checks.push(checkSkill(cwd, deps));
50
80
  const failures = checks.filter(check => check.status === 'fail').length;
51
81
  const warnings = checks.filter(check => check.status === 'warn').length;
52
82
  const report = { checks, failures, warnings };
53
83
  out.print(report, () => renderDoctor(report));
84
+ if (connectivity.v3Enabled === true) {
85
+ emitV3RoutingAdvisory(stderr);
86
+ }
54
87
  if (failures > 0) {
55
88
  // Non-zero exit so `testsprite doctor && ...` gates a CI step or an agent
56
89
  // preflight. The full report already printed above; this line is the stderr
@@ -120,11 +153,11 @@ function checkSkill(cwd, deps) {
120
153
  async function checkConnectivity(opts, deps, ctx) {
121
154
  const name = 'Connectivity';
122
155
  if (opts.dryRun)
123
- return { name, status: 'warn', detail: 'skipped under --dry-run' };
156
+ return { check: { name, status: 'warn', detail: 'skipped under --dry-run' } };
124
157
  if (!ctx.hasKey)
125
- return { name, status: 'warn', detail: 'skipped; no API key to test with' };
158
+ return { check: { name, status: 'warn', detail: 'skipped; no API key to test with' } };
126
159
  if (!ctx.endpointOk)
127
- return { name, status: 'warn', detail: 'skipped; endpoint URL is invalid' };
160
+ return { check: { name, status: 'warn', detail: 'skipped; endpoint URL is invalid' } };
128
161
  try {
129
162
  const client = makeHttpClient(opts, {
130
163
  env: deps.env,
@@ -134,21 +167,28 @@ async function checkConnectivity(opts, deps, ctx) {
134
167
  });
135
168
  const me = await client.get('/me');
136
169
  const who = me.userId ? ` (userId ${me.userId})` : '';
137
- return { name, status: 'ok', detail: `reached GET /me, API key accepted${who}` };
170
+ return {
171
+ check: { name, status: 'ok', detail: `reached GET /me, API key accepted${who}` },
172
+ v3Enabled: me.v3Enabled,
173
+ organizations: me.organizations,
174
+ org: me.org,
175
+ };
138
176
  }
139
177
  catch (error) {
140
178
  if (error instanceof ApiError) {
141
179
  if (error.code === 'AUTH_REQUIRED' ||
142
180
  error.code === 'AUTH_INVALID' ||
143
181
  error.code === 'AUTH_FORBIDDEN') {
144
- return { name, status: 'fail', detail: `API key rejected (${error.code})` };
182
+ return { check: { name, status: 'fail', detail: `API key rejected (${error.code})` } };
145
183
  }
146
- return { name, status: 'fail', detail: `GET /me failed (${error.code})` };
184
+ return { check: { name, status: 'fail', detail: `GET /me failed (${error.code})` } };
147
185
  }
148
186
  return {
149
- name,
150
- status: 'fail',
151
- detail: `GET /me failed (${error instanceof Error ? error.message : String(error)})`,
187
+ check: {
188
+ name,
189
+ status: 'fail',
190
+ detail: `GET /me failed (${error instanceof Error ? error.message : String(error)})`,
191
+ },
152
192
  };
153
193
  }
154
194
  }
@@ -186,7 +226,7 @@ function resolveCommonOptions(command) {
186
226
  const globals = command.optsWithGlobals();
187
227
  return {
188
228
  profile: globals.profile ?? 'default',
189
- output: globals.output ?? 'text',
229
+ output: resolveOutputMode(globals.output),
190
230
  endpointUrl: globals.endpointUrl,
191
231
  debug: globals.debug ?? false,
192
232
  verbose: globals.verbose ?? false,