@testsprite/testsprite-cli 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +35 -26
  2. package/dist/commands/agent.d.ts +43 -0
  3. package/dist/commands/agent.js +200 -18
  4. package/dist/commands/auth.d.ts +5 -0
  5. package/dist/commands/auth.js +38 -27
  6. package/dist/commands/doctor.d.ts +49 -0
  7. package/dist/commands/doctor.js +233 -0
  8. package/dist/commands/init.d.ts +1 -1
  9. package/dist/commands/init.js +24 -14
  10. package/dist/commands/project.d.ts +75 -2
  11. package/dist/commands/project.js +326 -47
  12. package/dist/commands/test.d.ts +281 -2
  13. package/dist/commands/test.js +1658 -177
  14. package/dist/commands/usage.js +13 -12
  15. package/dist/index.js +71 -3
  16. package/dist/lib/agent-targets.d.ts +72 -6
  17. package/dist/lib/agent-targets.js +188 -6
  18. package/dist/lib/bundle.d.ts +34 -0
  19. package/dist/lib/bundle.js +63 -11
  20. package/dist/lib/client-factory.d.ts +31 -0
  21. package/dist/lib/client-factory.js +63 -0
  22. package/dist/lib/config.d.ts +2 -0
  23. package/dist/lib/config.js +11 -2
  24. package/dist/lib/credentials.js +10 -1
  25. package/dist/lib/dry-run/samples.d.ts +5 -0
  26. package/dist/lib/dry-run/samples.js +64 -0
  27. package/dist/lib/errors.d.ts +28 -1
  28. package/dist/lib/errors.js +40 -0
  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 +80 -0
  32. package/dist/lib/flaky.js +76 -0
  33. package/dist/lib/http.d.ts +73 -1
  34. package/dist/lib/http.js +327 -135
  35. package/dist/lib/interrupt.d.ts +116 -0
  36. package/dist/lib/interrupt.js +182 -0
  37. package/dist/lib/junit-report.d.ts +58 -0
  38. package/dist/lib/junit-report.js +210 -0
  39. package/dist/lib/output.d.ts +16 -1
  40. package/dist/lib/output.js +24 -2
  41. package/dist/lib/pagination.d.ts +4 -3
  42. package/dist/lib/pagination.js +34 -6
  43. package/dist/lib/poll.d.ts +11 -0
  44. package/dist/lib/poll.js +70 -5
  45. package/dist/lib/prompt.js +52 -8
  46. package/dist/lib/proxy.d.ts +29 -0
  47. package/dist/lib/proxy.js +30 -0
  48. package/dist/lib/render-error.js +3 -1
  49. package/dist/lib/runs.types.d.ts +9 -0
  50. package/dist/lib/skill-nudge.d.ts +2 -2
  51. package/dist/lib/skill-nudge.js +13 -4
  52. package/dist/lib/target-url.js +8 -1
  53. package/dist/lib/ticker.d.ts +11 -1
  54. package/dist/lib/ticker.js +33 -1
  55. package/dist/lib/update-check.d.ts +67 -0
  56. package/dist/lib/update-check.js +246 -0
  57. package/dist/lib/v3-advisory.d.ts +13 -0
  58. package/dist/lib/v3-advisory.js +24 -0
  59. package/dist/lib/version-notice.d.ts +37 -0
  60. package/dist/lib/version-notice.js +87 -0
  61. package/dist/version-guard.d.ts +33 -0
  62. package/dist/version-guard.js +39 -0
  63. package/dist/version.d.ts +1 -1
  64. package/dist/version.js +1 -1
  65. package/package.json +3 -2
  66. package/skills/testsprite-onboard.skill.md +21 -0
  67. package/skills/testsprite-verify.codex.md +6 -0
  68. package/skills/testsprite-verify.skill.md +48 -4
package/README.md CHANGED
@@ -17,7 +17,7 @@ AI ships code in minutes — verifying it hasn't. `testsprite` opens your live a
17
17
  <p>
18
18
  <a href="https://www.npmjs.com/package/@testsprite/testsprite-cli"><img src="https://img.shields.io/npm/v/@testsprite/testsprite-cli?color=19C379&label=npm" alt="npm version"></a>
19
19
  <a href="https://www.npmjs.com/package/@testsprite/testsprite-cli"><img src="https://img.shields.io/npm/dm/@testsprite/testsprite-cli?color=19C379&label=downloads" alt="npm downloads"></a>
20
- <a href="#quickstart"><img src="https://img.shields.io/badge/node-%3E%3D20-19C379" alt="Node >= 20"></a>
20
+ <a href="#quickstart"><img src="https://img.shields.io/badge/node-20.19%2B%20%7C%2022.13%2B%20%7C%2024%2B-19C379" alt="Node 20.19+, 22.13+, or 24+"></a>
21
21
  <a href="./LICENSE"><img src="https://img.shields.io/badge/license-Apache%202.0-0A0A0A" alt="License Apache 2.0"></a>
22
22
  <a href="https://github.com/TestSprite/testsprite-cli/actions/workflows/ci.yml"><img src="https://github.com/TestSprite/testsprite-cli/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
23
23
  </p>
@@ -54,14 +54,14 @@ If you find `testsprite` useful, a GitHub Star ⭐️ would be greatly appreciat
54
54
 
55
55
  ## Quickstart
56
56
 
57
- Requires **Node.js ≥ 20**. (No global install? `npx @testsprite/testsprite-cli` works too.)
57
+ Requires **Node.js 20.19+**, **22.13+**, or **24+**. (No global install? `npx @testsprite/testsprite-cli` works too.)
58
58
 
59
59
  ```bash
60
60
  npm install -g @testsprite/testsprite-cli
61
61
  testsprite setup
62
62
  ```
63
63
 
64
- `testsprite setup` prompts for your [API key](https://www.testsprite.com), verifies it, and installs the verification-loop skill for your coding agent (`claude`, `cursor`, `cline`, `antigravity`, `codex`, etc.) — one command, so your agent is wired to verify its own work. Non-interactive (CI / onboarding scripts):
64
+ `testsprite setup` prompts for your [API key](https://www.testsprite.com), verifies it, and installs the verification-loop skill for your coding agent (`claude`, `cursor`, `cline`, `windsurf`, `antigravity`, `codex`, etc.) — one command, so your agent is wired to verify its own work. Non-interactive (CI / onboarding scripts):
65
65
 
66
66
  ```bash
67
67
  TESTSPRITE_API_KEY=sk-... testsprite setup --from-env --yes --agent claude
@@ -69,6 +69,8 @@ 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. 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
+
72
74
  From there, the loop runs on its own — an example session, typed by the coding agent:
73
75
 
74
76
  ```bash
@@ -89,28 +91,35 @@ Prefer to configure each step by hand (or learn the surface offline with `--dry-
89
91
 
90
92
  ## Commands
91
93
 
92
- | Group | Command | What it does |
93
- | --------- | --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
94
- | **Setup** | `setup` | **Start here** — one command: configure your API key, verify it, and install the agent verification skill |
95
- | **Auth** | `auth status` | Resolve the active profile to its user, key, env, and scopes |
96
- | | `auth remove` | Remove the active profile from the credentials file |
97
- | **Read** | `project list` / `project get` | List projects / fetch one by id |
98
- | | `test list` / `test get` | List tests under a project / fetch one by id |
99
- | | `test code get` | Print (or write) the generated test source |
100
- | | `test steps` | List the latest run's steps with screenshot / DOM pointers |
101
- | | `test result` | Latest result; `--history` lists a test's prior runs |
102
- | | `test failure get` | The agent entry point: one self-contained latest-failure bundle |
103
- | | `test failure summary` | One-screen triage card (no media download) |
104
- | **Write** | `test create` / `test create-batch` | Create a test (or bulk-create from a plan file); `--produces` / `--needs` / `--category` wire BE dependency metadata |
105
- | | `test update` / `test delete` / `test delete-batch` | Edit metadata / soft-delete |
106
- | | `test code put` | Replace generated code (etag-guarded) |
107
- | | `test plan put` | Replace a frontend test's plan-steps |
108
- | | `project create` / `project update` | Manage projects |
109
- | **Run** | `test run` | Trigger a fresh run; `--wait` blocks until terminal; `--all --project <id>` runs all tests in a project in wave order |
110
- | | `test rerun` | Cheap replay of one/many tests (FE verbatim; BE with deps); `--all --project <id>` reruns all tests |
111
- | | `test wait` | Block on a `runId` until terminal |
112
- | | `test artifact get` | Download the failure bundle for a specific `runId` |
113
- | **Agent** | `agent install` / `agent list` | Add or list coding-agent targets (pure-local): `claude`, `codex`, `cursor`, `cline`, `antigravity` |
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 and BE dependency declarations (`--produces` / `--needs` / `--category`) / 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` / `project delete` | Manage projects; `delete` removes a project and everything under it (`--confirm` required, no restore window) |
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 cancel` | Cancel one or more in-flight runs (Ctrl-C during `--wait` only detaches — `cancel` is the real stop) |
121
+ | | `test artifact get` | Download the failure bundle for a specific `runId` |
122
+ | **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` |
114
123
 
115
124
  > 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).
116
125
 
@@ -173,7 +182,7 @@ That's the point of all of this: you no longer need the biggest, most expensive
173
182
 
174
183
  ## Contributing
175
184
 
176
- Contributions are welcome — the CLI is plain TypeScript/Node (≥ 20), tested with Vitest, built with `tsc`. Getting a dev loop running takes a minute:
185
+ Contributions are welcome — the CLI is plain TypeScript/Node (20.19+, 22.13+, or 24+), tested with Vitest, built with `tsc`. Getting a dev loop running takes a minute:
177
186
 
178
187
  ```bash
179
188
  git clone https://github.com/TestSprite/testsprite-cli.git
@@ -56,5 +56,48 @@ export interface ListResult {
56
56
  path: string;
57
57
  }
58
58
  export declare function runList(opts: CommonOptions, deps?: AgentDeps): Promise<void>;
59
+ /**
60
+ * Health of one installed skill artifact, as reported by `agent status`.
61
+ *
62
+ * Decision order (first match wins):
63
+ * - 'absent' : nothing at the landing path (codex: no managed section,
64
+ * including an AGENTS.md that exists without our sentinels).
65
+ * - 'corrupt' : codex only. Dangling or duplicated sentinels, the same
66
+ * classification `agent install` refuses on; status REPORTS it
67
+ * instead of refusing.
68
+ * - 'unmarked' : artifact present but carries no testsprite-skill marker
69
+ * (installed before markers existed), or the landing path is
70
+ * occupied by a non-regular file (never followed).
71
+ * - 'stale' : marker present, but its hash differs from the current
72
+ * canonical body: a re-install would change the content. Edits
73
+ * on top of an OLD install also read stale (older renders
74
+ * cannot be reproduced); the remedy is the same re-install.
75
+ * - 'modified' : marker hash matches the current body, but the artifact bytes
76
+ * differ from the canonical render carrying that same marker
77
+ * line: the user edited the artifact after install.
78
+ * - 'ok' : marker hash matches and the bytes equal the canonical render
79
+ * with the file's own marker line (a version-string-only lag
80
+ * with an unchanged body still reads ok).
81
+ *
82
+ * For the codex managed section, ONE marker names every aggregated skill
83
+ * ('+'-joined); skills not named by the marker report 'absent'.
84
+ */
85
+ export type SkillArtifactState = 'ok' | 'stale' | 'modified' | 'unmarked' | 'absent' | 'corrupt';
86
+ export interface StatusResult {
87
+ target: AgentTarget;
88
+ skill: string;
89
+ path: string;
90
+ state: SkillArtifactState;
91
+ }
92
+ interface StatusOptions extends CommonOptions {
93
+ dir?: string;
94
+ }
95
+ /**
96
+ * `agent status`: one row per (target × default skill), each classified per
97
+ * the {@link SkillArtifactState} contract. Exit contract: returns normally
98
+ * (exit 0) when every row is 'ok' or 'absent'; throws CLIError exit 1 when any
99
+ * row is stale/modified/unmarked/corrupt, so the command can gate CI.
100
+ */
101
+ export declare function runStatus(opts: StatusOptions, deps?: AgentDeps): Promise<void>;
59
102
  export declare function createAgentCommand(deps?: AgentDeps): Command;
60
103
  export {};
@@ -2,9 +2,9 @@ import path from 'node:path';
2
2
  import fs from 'node:fs/promises';
3
3
  import { Command } from 'commander';
4
4
  import { CLIError, localValidationError } from '../lib/errors.js';
5
- import { GLOBAL_OPTS_HINT, Output } from '../lib/output.js';
5
+ import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
6
6
  import { promptText } from '../lib/prompt.js';
7
- import { TARGETS, SKILLS, DEFAULT_SKILLS, pathFor, loadSkillBodyFor, buildCodexAggregate, renderForTarget, MANAGED_SECTION_BEGIN, MANAGED_SECTION_END, } from '../lib/agent-targets.js';
7
+ import { TARGETS, SKILLS, DEFAULT_SKILLS, MARKER_SKILL_SEPARATOR, pathFor, loadSkillBodyFor, bodyHash12, compactBodyFor, buildCodexAggregate, buildSkillMarker, parseSkillMarker, renderForTarget, renderOwnFileWithMarker, MANAGED_SECTION_BEGIN, MANAGED_SECTION_END, } from '../lib/agent-targets.js';
8
8
  // ---------------------------------------------------------------------------
9
9
  // Constants
10
10
  // ---------------------------------------------------------------------------
@@ -105,11 +105,15 @@ async function writeBackup(agentFs, abs, existing) {
105
105
  // Managed-section helpers (codex target)
106
106
  // ---------------------------------------------------------------------------
107
107
  /**
108
- * Build the section block to inject (sentinels + body + trailing newline).
108
+ * Build the section block to inject (sentinels + marker + body + trailing
109
+ * newline). The provenance marker line sits just inside the BEGIN sentinel so
110
+ * `agent status` can fingerprint the section. The same skill set + CLI version
111
+ * + body always produce byte-identical output, so the classifySection
112
+ * 'unchanged' fast-path keeps working across re-installs.
109
113
  * Uses \n throughout; the caller handles CRLF normalisation.
110
114
  */
111
- function buildSection(body) {
112
- return `${MANAGED_SECTION_BEGIN}\n${body.trimEnd()}\n${MANAGED_SECTION_END}\n`;
115
+ function buildSection(body, markerLine) {
116
+ return `${MANAGED_SECTION_BEGIN}\n${markerLine}\n${body.trimEnd()}\n${MANAGED_SECTION_END}\n`;
113
117
  }
114
118
  /**
115
119
  * Inspect an existing AGENTS.md and classify the managed-section state.
@@ -224,15 +228,18 @@ export async function runInstall(opts, deps = {}) {
224
228
  if (rawTargets.length === 0) {
225
229
  const isTTY = deps.isTTY ?? Boolean(process.stdin.isTTY);
226
230
  if (!isTTY) {
227
- throw localValidationError('target', `required; pass --target=claude (comma-separated or repeated for several). Supported: ${Object.keys(TARGETS).join(', ')}`);
231
+ stderrFn('[info] --target not specified; defaulting to claude. Pass --target=<target> to select a different agent.');
232
+ resolvedTargetStrings = ['claude'];
233
+ }
234
+ else {
235
+ const promptFn = deps.prompt ?? ((q) => promptText(q));
236
+ const answer = (await promptFn('Targets to install (comma-separated) [claude]: ')).trim();
237
+ const defaulted = answer || 'claude';
238
+ resolvedTargetStrings = defaulted
239
+ .split(',')
240
+ .map(s => s.trim())
241
+ .filter(Boolean);
228
242
  }
229
- const promptFn = deps.prompt ?? ((q) => promptText(q));
230
- const answer = (await promptFn('Targets to install (comma-separated) [claude]: ')).trim();
231
- const defaulted = answer || 'claude';
232
- resolvedTargetStrings = defaulted
233
- .split(',')
234
- .map(s => s.trim())
235
- .filter(Boolean);
236
243
  }
237
244
  else {
238
245
  resolvedTargetStrings = rawTargets;
@@ -286,10 +293,28 @@ export async function runInstall(opts, deps = {}) {
286
293
  }
287
294
  return b;
288
295
  };
296
+ // Budget-capped own-file targets (e.g. windsurf) render the compact per-skill
297
+ // body so the rule file isn't truncated by the agent. Cached separately; must
298
+ // match renderForTarget's default selection so written bytes equal the asserted
299
+ // render.
300
+ const compactBodyCache = new Map();
301
+ const compactBodyForSkill = (skill) => {
302
+ let b = compactBodyCache.get(skill);
303
+ if (b === undefined) {
304
+ b = compactBodyFor(skill);
305
+ compactBodyCache.set(skill, b);
306
+ }
307
+ return b;
308
+ };
309
+ const ownFileBodyFor = (t, skill) => TARGETS[t].compactBody ? compactBodyForSkill(skill) : bodyForSkill(skill);
289
310
  let codexSectionCache;
290
311
  const getCodexSection = () => {
291
312
  if (codexSectionCache === undefined) {
292
- codexSectionCache = buildSection(buildCodexAggregate(skills));
313
+ const aggregate = buildCodexAggregate(skills);
314
+ // ONE marker for the whole managed section: it names every aggregated
315
+ // skill ('+'-joined) and hashes the canonical aggregate body, so
316
+ // `agent status` can attribute and fingerprint the section per skill.
317
+ codexSectionCache = buildSection(aggregate, buildSkillMarker(skills.join(MARKER_SKILL_SEPARATOR), aggregate));
293
318
  }
294
319
  return codexSectionCache;
295
320
  };
@@ -457,8 +482,16 @@ export async function runInstall(opts, deps = {}) {
457
482
  if (abs !== root && !abs.startsWith(root + path.sep)) {
458
483
  throw new CLIError(`refusing to write outside --dir: ${relPath}`, 5);
459
484
  }
460
- const content = renderForTarget(t, skill, bodyForSkill(skill)).content;
485
+ const content = renderForTarget(t, skill, ownFileBodyFor(t, skill)).content;
461
486
  if (opts.dryRun) {
487
+ // Apply the SAME symlink fail-close guard as the real install path
488
+ // below (the codex managed-section branch already does this). Without
489
+ // it, dry-run reports success for a planted symlink that the real
490
+ // install would refuse with exit 5.
491
+ const dryRunSt = await inspectTargetPath(agentFs, root, relPath);
492
+ if (dryRunSt !== null && !dryRunSt.isFile) {
493
+ throw new CLIError(`${relPath} exists but is not a regular file — remove it and re-run.`, 5);
494
+ }
462
495
  const bytes = Buffer.byteLength(content, 'utf8');
463
496
  dryRunLines.push({ abs, bytes, note: '' });
464
497
  results.push({ target: t, path: relPath, action: 'dry-run', skills: [skill] });
@@ -563,6 +596,147 @@ export async function runList(opts, deps = {}) {
563
596
  return [header, ...rows].join('\n');
564
597
  });
565
598
  }
599
+ /**
600
+ * Classify one own-file artifact per the {@link SkillArtifactState} contract.
601
+ * Comparisons are byte-exact, matching the installer's own skipped/blocked
602
+ * comparison for own-file targets.
603
+ */
604
+ async function classifyOwnFileState(agentFs, abs, target, skill, bodyForSkill) {
605
+ const stat = await agentFs.lstat(abs);
606
+ if (stat === null)
607
+ return 'absent';
608
+ // Occupied by a directory or symlink: not something our installer wrote, and
609
+ // never followed (mirrors the installer's fail-closed stance on symlinks).
610
+ if (!stat.isFile)
611
+ return 'unmarked';
612
+ const existing = await agentFs.readFile(abs);
613
+ const marker = parseSkillMarker(existing);
614
+ if (marker === null)
615
+ return 'unmarked';
616
+ const canonicalBody = bodyForSkill(skill);
617
+ if (marker.hash12 !== bodyHash12(canonicalBody))
618
+ return 'stale';
619
+ // Hash matches the current body: pristine iff the file equals the canonical
620
+ // render carrying its own marker line, so a marker whose version string lags
621
+ // behind an unchanged body still reads ok.
622
+ const reRender = renderOwnFileWithMarker(target, skill, marker.line, canonicalBody);
623
+ return existing === reRender ? 'ok' : 'modified';
624
+ }
625
+ /**
626
+ * Classify the codex managed section per skill. The section is ONE artifact
627
+ * carrying ONE marker that names every aggregated skill, so a single
628
+ * inspection answers all skill rows; the returned function maps a skill name
629
+ * to its state. Comparisons are CRLF-insensitive on the section bytes.
630
+ */
631
+ async function classifyManagedSectionStates(agentFs, abs) {
632
+ const constantState = (state) => () => state;
633
+ const stat = await agentFs.lstat(abs);
634
+ if (stat === null)
635
+ return constantState('absent');
636
+ // Occupied by a directory or symlink: never followed (fail-closed).
637
+ if (!stat.isFile)
638
+ return constantState('unmarked');
639
+ const existing = await agentFs.readFile(abs);
640
+ // Current canonical section for the default skill set. classifySection's
641
+ // 'unchanged' answers the common all-defaults-fresh case; its
642
+ // corrupt/append classification is reused verbatim for status verdicts.
643
+ const defaultAggregate = buildCodexAggregate(DEFAULT_SKILLS);
644
+ const defaultSection = buildSection(defaultAggregate, buildSkillMarker(DEFAULT_SKILLS.join(MARKER_SKILL_SEPARATOR), defaultAggregate));
645
+ const sectionState = classifySection(existing, defaultSection);
646
+ if (sectionState.kind === 'corrupt')
647
+ return constantState('corrupt');
648
+ // No standalone sentinels anywhere: the managed section is not installed.
649
+ if (sectionState.kind === 'append')
650
+ return constantState('absent');
651
+ if (sectionState.kind === 'unchanged') {
652
+ // Byte-identical to today's default install.
653
+ return skill => (DEFAULT_SKILLS.includes(skill) ? 'ok' : 'absent');
654
+ }
655
+ if (sectionState.kind !== 'replace') {
656
+ // 'create' is unreachable when the file exists; treat defensively as absent.
657
+ return constantState('absent');
658
+ }
659
+ // Sentinels are present but the section differs from today's default
660
+ // canonical: slice the live section bytes out of the file and inspect its
661
+ // own marker (before/after are exact byte prefix/suffix around the section).
662
+ const sectionContent = existing.slice(sectionState.before.length, existing.length - sectionState.after.length);
663
+ const marker = parseSkillMarker(sectionContent);
664
+ if (marker === null)
665
+ return constantState('unmarked');
666
+ const installedSkills = marker.skill.split(MARKER_SKILL_SEPARATOR);
667
+ const coversSkill = (skill) => installedSkills.includes(skill);
668
+ // A marker naming a skill this CLI does not ship cannot be re-rendered;
669
+ // report the named skills stale (a re-install refreshes the section).
670
+ if (installedSkills.some(name => SKILLS[name] === undefined)) {
671
+ return skill => (coversSkill(skill) ? 'stale' : 'absent');
672
+ }
673
+ const canonicalAggregate = buildCodexAggregate(installedSkills);
674
+ if (marker.hash12 !== bodyHash12(canonicalAggregate)) {
675
+ return skill => (coversSkill(skill) ? 'stale' : 'absent');
676
+ }
677
+ // Hash matches the current aggregate: the section is pristine iff its bytes
678
+ // equal a re-render carrying its own marker line (version-string-only lag
679
+ // with an unchanged body still reads ok).
680
+ const pristine = sectionContent.replace(/\r\n/g, '\n') === buildSection(canonicalAggregate, marker.line);
681
+ return skill => (coversSkill(skill) ? (pristine ? 'ok' : 'modified') : 'absent');
682
+ }
683
+ /**
684
+ * `agent status`: one row per (target × default skill), each classified per
685
+ * the {@link SkillArtifactState} contract. Exit contract: returns normally
686
+ * (exit 0) when every row is 'ok' or 'absent'; throws CLIError exit 1 when any
687
+ * row is stale/modified/unmarked/corrupt, so the command can gate CI.
688
+ */
689
+ export async function runStatus(opts, deps = {}) {
690
+ const agentFs = deps.fs ?? defaultAgentFs;
691
+ const out = makeOutput(opts.output, deps);
692
+ // An explicit but empty --dir must not silently resolve to cwd
693
+ // (path.resolve('') === cwd).
694
+ if (opts.dir !== undefined && opts.dir.trim() === '') {
695
+ throw localValidationError('dir', 'must not be empty');
696
+ }
697
+ const dir = opts.dir !== undefined ? opts.dir.trim() : (deps.cwd ?? process.cwd());
698
+ const root = path.resolve(dir);
699
+ // Canonical own-file bodies, read once per skill (same lazy caching pattern
700
+ // as runInstall's bodyForSkill).
701
+ const skillBodyCache = new Map();
702
+ const bodyForSkill = (skill) => {
703
+ let cachedBody = skillBodyCache.get(skill);
704
+ if (cachedBody === undefined) {
705
+ cachedBody = loadSkillBodyFor(skill);
706
+ skillBodyCache.set(skill, cachedBody);
707
+ }
708
+ return cachedBody;
709
+ };
710
+ const results = [];
711
+ for (const [target, spec] of Object.entries(TARGETS)) {
712
+ if (spec.mode === 'managed-section') {
713
+ const stateFor = await classifyManagedSectionStates(agentFs, path.resolve(root, spec.path));
714
+ for (const skill of DEFAULT_SKILLS) {
715
+ results.push({ target, skill, path: spec.path, state: stateFor(skill) });
716
+ }
717
+ continue;
718
+ }
719
+ for (const skill of DEFAULT_SKILLS) {
720
+ const relPath = pathFor(target, skill);
721
+ results.push({
722
+ target,
723
+ skill,
724
+ path: relPath,
725
+ state: await classifyOwnFileState(agentFs, path.resolve(root, relPath), target, skill, bodyForSkill),
726
+ });
727
+ }
728
+ }
729
+ out.print(results, data => {
730
+ const items = data;
731
+ const header = `${'TARGET'.padEnd(14)} ${'SKILL'.padEnd(20)} ${'STATE'.padEnd(10)} PATH`;
732
+ const rows = items.map(row => `${row.target.padEnd(14)} ${row.skill.padEnd(20)} ${row.state.padEnd(10)} ${row.path}`);
733
+ return [header, ...rows].join('\n');
734
+ });
735
+ const needingAttention = results.filter(result => result.state !== 'ok' && result.state !== 'absent');
736
+ if (needingAttention.length > 0) {
737
+ throw new CLIError(`${needingAttention.length} skill artifact(s) need attention (stale/modified/unmarked/corrupt); re-run \`testsprite agent install\` (add --force for own-file targets) to refresh them.`, 1);
738
+ }
739
+ }
566
740
  // ---------------------------------------------------------------------------
567
741
  // Command factory
568
742
  // ---------------------------------------------------------------------------
@@ -570,11 +744,11 @@ function collect(v, prev) {
570
744
  return prev.concat(v);
571
745
  }
572
746
  export function createAgentCommand(deps = {}) {
573
- const agent = new Command('agent').description('Install TestSprite guidance into coding-agent config (Claude Code, Cursor, Cline, Antigravity, Codex)');
747
+ const agent = new Command('agent').description('Install TestSprite guidance into coding-agent config (Claude Code, Cursor, Cline, Antigravity, Kiro, Windsurf, Copilot, Codex)');
574
748
  agent
575
749
  .command('install')
576
750
  .description('Write the TestSprite agent skills (verification loop + first-run onboarding) into a project for a coding agent')
577
- .option('--target <t>', 'Agent target(s): claude, cursor, cline, antigravity, codex (comma-separated or repeated)', collect, [])
751
+ .option('--target <t>', 'Agent target(s): claude, cursor, cline, antigravity, kiro, windsurf, copilot, codex (comma-separated or repeated)', collect, [])
578
752
  .option('--skill <name>', `Skill(s) to install: ${Object.keys(SKILLS).join(', ')} (comma-separated or repeated; default: all)`, collect, [])
579
753
  .option('--dir <path>', 'Project root to write into (default: cwd)')
580
754
  .option('--force', 'For own-file targets: overwrite existing file (a .bak backup is kept). ' +
@@ -596,6 +770,14 @@ export function createAgentCommand(deps = {}) {
596
770
  .action(async (_o, command) => {
597
771
  await runList(resolveCommonOptions(command), deps);
598
772
  });
773
+ agent
774
+ .command('status')
775
+ .description('Check installed TestSprite skill files against this CLI version: ok, stale, modified, unmarked, absent, or corrupt (exits 1 when anything needs attention, so it can gate CI)')
776
+ .option('--dir <path>', 'Project root to inspect (default: cwd)')
777
+ .addHelpText('after', GLOBAL_OPTS_HINT)
778
+ .action(async (cmdOpts, command) => {
779
+ await runStatus({ ...resolveCommonOptions(command), dir: cmdOpts.dir }, deps);
780
+ });
599
781
  return agent;
600
782
  }
601
783
  // ---------------------------------------------------------------------------
@@ -605,7 +787,7 @@ function resolveCommonOptions(command) {
605
787
  const globals = command.optsWithGlobals();
606
788
  return {
607
789
  profile: globals.profile ?? 'default',
608
- output: globals.output ?? 'text',
790
+ output: resolveOutputMode(globals.output),
609
791
  endpointUrl: globals.endpointUrl,
610
792
  debug: globals.debug ?? false,
611
793
  verbose: globals.verbose ?? false,
@@ -15,6 +15,11 @@ export interface MeResponse {
15
15
  email?: string;
16
16
  /** Human-readable display name for the bound account. Absent-safe (dogfood L1866). */
17
17
  displayName?: string;
18
+ /**
19
+ * Authoritative per-user V3 routing bit. Absent-safe: older backends omit it,
20
+ * so it is only rendered when present.
21
+ */
22
+ v3Enabled?: boolean;
18
23
  }
19
24
  export interface AuthDeps {
20
25
  env?: NodeJS.ProcessEnv;
@@ -1,32 +1,37 @@
1
1
  import { Command } from 'commander';
2
- import { emitDryRunBanner, makeHttpClient, } from '../lib/client-factory.js';
2
+ import { 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';
6
6
  import { defaultCredentialsPath, deleteProfile, readProfile, writeProfile, } from '../lib/credentials.js';
7
- import { loadConfig } from '../lib/config.js';
7
+ import { loadConfig, normalizeEnvVar } from '../lib/config.js';
8
8
  import { emitDeprecationNotice } from '../lib/deprecate.js';
9
- import { GLOBAL_OPTS_HINT, Output } from '../lib/output.js';
9
+ import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
10
10
  import { promptSecret } from '../lib/prompt.js';
11
+ import { emitV3RoutingAdvisory, routingLabel } from '../lib/v3-advisory.js';
11
12
  const DEFAULT_API_URL = 'https://api.testsprite.com';
12
13
  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
14
  export async function runConfigure(opts, deps = {}) {
14
15
  const env = deps.env ?? process.env;
15
16
  const credentialsPath = deps.credentialsPath ?? defaultCredentialsPath();
16
17
  const out = makeOutput(opts.output, deps);
17
- const prelude = deps.preludeWrite ?? ((chunk) => process.stdout.write(chunk));
18
+ // The "Configuring profile …" prelude is informational, not result data, so
19
+ // it defaults to stderr — stdout stays a pure result stream (the configured
20
+ // JSON/text), which matters under `--output json` (§8.1 stdout purity).
21
+ const prelude = deps.preludeWrite ?? ((chunk) => process.stderr.write(chunk));
18
22
  const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
19
23
  // Normalize the env endpoint: an empty / whitespace-only TESTSPRITE_API_URL is
20
24
  // treated as unset. Without this, `''` (e.g. `export TESTSPRITE_API_URL=` in a
21
25
  // shell profile) is non-nullish and would short-circuit the `??` chains below to
22
26
  // an empty endpoint instead of falling through to the profile / prod default.
23
- const envApiUrl = env.TESTSPRITE_API_URL?.trim() || undefined;
27
+ const envApiUrl = normalizeEnvVar(env.TESTSPRITE_API_URL);
24
28
  // Dry-run: do not prompt, do not read env, do not write credentials.
25
29
  // Print the canned success shape so an agent sees exactly the JSON it
26
30
  // would get on a real configure (modulo the endpoint string).
27
31
  if (opts.dryRun) {
28
- emitDryRunBanner(stderr);
29
32
  const apiUrl = opts.endpointUrl ?? envApiUrl ?? DEFAULT_API_URL;
33
+ assertValidEndpointUrl(apiUrl);
34
+ emitDryRunBanner(stderr);
30
35
  stderr(`[dry-run] would write credentials for profile="${opts.profile}" to ${credentialsPath}`);
31
36
  out.print({ profile: opts.profile, apiUrl, status: 'configured' }, data => {
32
37
  const d = data;
@@ -49,6 +54,7 @@ export async function runConfigure(opts, deps = {}) {
49
54
  // api_url doesn't silently validate a new key against the default endpoint.
50
55
  const resolvedFromProfile = existingProfile?.apiUrl;
51
56
  const apiUrl = opts.endpointUrl ?? envApiUrl ?? resolvedFromProfile ?? DEFAULT_API_URL;
57
+ assertValidEndpointUrl(apiUrl);
52
58
  if (opts.fromEnv) {
53
59
  apiKey = env.TESTSPRITE_API_KEY?.trim();
54
60
  if (!apiKey)
@@ -79,6 +85,7 @@ export async function runConfigure(opts, deps = {}) {
79
85
  baseUrl: facadeBaseUrl(apiUrl),
80
86
  apiKey,
81
87
  fetchImpl: deps.fetchImpl,
88
+ requestTimeoutMs: opts.requestTimeoutMs,
82
89
  });
83
90
  try {
84
91
  // Tag the validation call with the originating command (when provided) so
@@ -90,11 +97,20 @@ export async function runConfigure(opts, deps = {}) {
90
97
  catch (err) {
91
98
  const message = err instanceof Error ? err.message : String(err);
92
99
  stderr(`API key rejected by ${apiUrl}: ${message} — profile NOT updated`);
93
- const exitCode = err instanceof ApiError ? err.exitCode : 3;
94
- // Include the resolved endpoint in the thrown message so the user knows
95
- // which host rejected the key. This prevents the "invalid or revoked"
96
- // message from being ambiguous when the key is valid for a different env.
97
- throw new CLIError(`API key rejected by ${apiUrl}: ${message} — did you mean to set TESTSPRITE_API_URL?`, exitCode);
100
+ // When the verification call returned a typed API error (AUTH_INVALID,
101
+ // AUTH_FORBIDDEN, etc.), re-throw it directly so `index.ts` renders the
102
+ // full typed envelope under `--output json` (code, nextAction, requestId,
103
+ // details). Previously wrapping it in CLIError discarded those fields and
104
+ // emitted a bare `{"error":"...string..."}` — violating the JSON contract.
105
+ // Augment the message with the endpoint context so text-mode users still
106
+ // see which host rejected the key.
107
+ if (err instanceof ApiError) {
108
+ err.message = `API key rejected by ${apiUrl}: ${message} — did you mean to set TESTSPRITE_API_URL?`;
109
+ throw err;
110
+ }
111
+ // Non-ApiError (truly unexpected throws like a TypeError from a
112
+ // misconfigured fetchImpl). Exit 3 (auth family).
113
+ throw new CLIError(`API key rejected by ${apiUrl}: ${message} — did you mean to set TESTSPRITE_API_URL?`, 3);
98
114
  }
99
115
  writeProfile(opts.profile, { apiKey, apiUrl }, { path: credentialsPath });
100
116
  out.print({ profile: opts.profile, apiUrl, status: 'configured' }, data => {
@@ -109,13 +125,15 @@ export async function runConfigure(opts, deps = {}) {
109
125
  export async function runWhoami(opts, deps = {}) {
110
126
  const out = makeOutput(opts.output, deps);
111
127
  const env = deps.env ?? process.env;
128
+ const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
112
129
  // Resolve the endpoint URL so it can be surfaced in text output.
113
130
  // Dry-run uses the flag/env/default chain without touching credentials.
114
131
  // Real path uses the same loadConfig the HttpClient factory uses so the
115
132
  // displayed URL always matches where requests actually go (dogfood L1788).
116
133
  let resolvedEndpoint;
117
134
  if (opts.dryRun) {
118
- resolvedEndpoint = opts.endpointUrl ?? env.TESTSPRITE_API_URL ?? 'https://api.testsprite.com';
135
+ resolvedEndpoint =
136
+ opts.endpointUrl ?? normalizeEnvVar(env.TESTSPRITE_API_URL) ?? 'https://api.testsprite.com';
119
137
  }
120
138
  else {
121
139
  const credentialsPath = deps.credentialsPath ?? defaultCredentialsPath();
@@ -149,6 +167,8 @@ export async function runWhoami(opts, deps = {}) {
149
167
  `endpoint: ${resolvedEndpoint}`,
150
168
  `env: ${m.env}`,
151
169
  `scopes: ${m.scopes.join(', ')}`,
170
+ // Authoritative routing mode, rendered only when the backend supplies it.
171
+ ...(m.v3Enabled !== undefined ? [`routing: ${routingLabel(m.v3Enabled)}`] : []),
152
172
  ];
153
173
  // C2: warn in text mode when key cannot write/run
154
174
  const missingScopes = ['write:tests', 'run:tests'].filter(s => !m.scopes.includes(s));
@@ -157,6 +177,11 @@ export async function runWhoami(opts, deps = {}) {
157
177
  }
158
178
  return lines.join('\n');
159
179
  });
180
+ // When V3 routing is on, warn (text mode only) about the still-open behavior
181
+ // gaps. JSON consumers read `v3Enabled` directly; stdout stays pure.
182
+ if (opts.output !== 'json' && me.v3Enabled === true) {
183
+ emitV3RoutingAdvisory(stderr);
184
+ }
160
185
  return me;
161
186
  }
162
187
  export async function runLogout(opts, deps = {}) {
@@ -222,7 +247,7 @@ function resolveCommonOptions(command) {
222
247
  const globals = command.optsWithGlobals();
223
248
  return {
224
249
  profile: globals.profile ?? 'default',
225
- output: globals.output ?? 'text',
250
+ output: resolveOutputMode(globals.output),
226
251
  endpointUrl: globals.endpointUrl,
227
252
  debug: globals.debug ?? false,
228
253
  verbose: globals.verbose ?? false,
@@ -230,20 +255,6 @@ function resolveCommonOptions(command) {
230
255
  requestTimeoutMs: parseRequestTimeoutFlag(globals.requestTimeout),
231
256
  };
232
257
  }
233
- /**
234
- * Parse the `--request-timeout <seconds>` flag value into milliseconds.
235
- * Returns `undefined` when the flag was not supplied (factory falls back to
236
- * the env var / default). Silently clamps out-of-range values — the
237
- * factory applies the same clamp so there is no double-clamp risk.
238
- */
239
- function parseRequestTimeoutFlag(raw) {
240
- if (raw === undefined)
241
- return undefined;
242
- const n = Number(raw);
243
- if (!Number.isFinite(n) || n <= 0)
244
- return undefined;
245
- return Math.round(n * 1000); // seconds → milliseconds
246
- }
247
258
  function makeOutput(mode, deps) {
248
259
  return new Output(mode, { stdout: deps.stdout, stderr: deps.stderr });
249
260
  }