@testsprite/testsprite-cli 0.1.1 → 0.2.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.
@@ -10,11 +10,12 @@
10
10
  * Hard constraint: orchestrate existing exported primitives; never fork them.
11
11
  */
12
12
  import { Command } from 'commander';
13
+ import { emitDeprecationNotice } from '../lib/deprecate.js';
13
14
  import { CLIError } from '../lib/errors.js';
14
15
  import { GLOBAL_OPTS_HINT, Output } from '../lib/output.js';
15
16
  import { runConfigure, runWhoami } from './auth.js';
16
17
  import { runInstall } from './agent.js';
17
- import { TARGETS } from '../lib/agent-targets.js';
18
+ import { TARGETS, DEFAULT_SKILLS } from '../lib/agent-targets.js';
18
19
  import { readProfile } from '../lib/credentials.js';
19
20
  /** Mirrors auth.ts's DEFAULT_API_URL (kept in sync; auth.ts owns the canonical value). */
20
21
  const DEFAULT_API_URL = 'https://api.testsprite.com';
@@ -38,6 +39,20 @@ function resolveReportedEndpoint(opts, deps) {
38
39
  }
39
40
  return opts.endpointUrl ?? envApiUrl ?? existing ?? DEFAULT_API_URL;
40
41
  }
42
+ /**
43
+ * Collapse the per-skill install actions into one representative action for the
44
+ * init summary. Precedence: a real change (updated) outranks a fresh install,
45
+ * which outranks a no-op. `blocked` never reaches here — runInstall throws first.
46
+ */
47
+ function aggregateInstallAction(actions) {
48
+ if (actions.some(a => a === 'updated' || a === 'section-updated'))
49
+ return 'updated';
50
+ if (actions.some(a => a === 'written' || a === 'section-installed'))
51
+ return 'installed';
52
+ if (actions.some(a => a === 'dry-run'))
53
+ return 'dry-run';
54
+ return 'skipped'; // all skipped / section-unchanged
55
+ }
41
56
  // ---------------------------------------------------------------------------
42
57
  // Helpers to split deps into the two primitive shapes
43
58
  // ---------------------------------------------------------------------------
@@ -47,7 +62,7 @@ function resolveReportedEndpoint(opts, deps) {
47
62
  * and runWhoami's identity block are replaced by the init summary.
48
63
  * stderr (advisory messages, errors) flows through.
49
64
  */
50
- function toAuthDeps(deps, apiKey) {
65
+ function toAuthDeps(deps, apiKey, commandTag) {
51
66
  return {
52
67
  env: deps.env,
53
68
  credentialsPath: deps.credentialsPath,
@@ -61,6 +76,10 @@ function toAuthDeps(deps, apiKey) {
61
76
  // If an explicit API key was provided, override the prompt so configure
62
77
  // never actually prompts the user.
63
78
  prompt: apiKey ? { secret: async (_q) => apiKey } : deps.prompt,
79
+ // Telemetry attribution for the configure-validate GET /me. Passed only for
80
+ // the configure step (see runInit) — never whoami — so each init run emits
81
+ // exactly one cli.initialized event on the backend.
82
+ commandTag,
64
83
  };
65
84
  }
66
85
  /**
@@ -135,7 +154,9 @@ export async function runInit(opts, deps = {}) {
135
154
  apiUrl: resolveReportedEndpoint(opts, deps),
136
155
  env: 'development',
137
156
  scopes: [],
138
- agent: agentTarget ? { target: agentTarget, action: 'dry-run' } : null,
157
+ agent: agentTarget
158
+ ? { target: agentTarget, action: 'dry-run', skills: [...DEFAULT_SKILLS] }
159
+ : null,
139
160
  status: 'initialized',
140
161
  };
141
162
  out.print(summary, renderInitText);
@@ -147,7 +168,11 @@ export async function runInit(opts, deps = {}) {
147
168
  // --api-key takes precedence over --from-env: when an explicit key is supplied,
148
169
  // force fromEnv=false so runConfigure uses the injected key (toAuthDeps wires it
149
170
  // as the prompt) instead of reading TESTSPRITE_API_KEY from the environment (codex).
150
- await runConfigure({ ...opts, fromEnv: opts.apiKey ? false : opts.fromEnv }, toAuthDeps(deps, opts.apiKey));
171
+ await runConfigure({ ...opts, fromEnv: opts.apiKey ? false : opts.fromEnv },
172
+ // commandTag:'init' tags ONLY this configure-validate GET /me with
173
+ // `X-CLI-Command: init` → counted as cli.initialized. The whoami banner call
174
+ // below builds deps WITHOUT a tag, so init emits exactly one cli.initialized.
175
+ toAuthDeps(deps, opts.apiKey, 'init'));
151
176
  // -------------------------------------------------------------------------
152
177
  // Step 2: Whoami banner — for identity display only; not used for validation
153
178
  // -------------------------------------------------------------------------
@@ -178,16 +203,19 @@ export async function runInit(opts, deps = {}) {
178
203
  // -------------------------------------------------------------------------
179
204
  let installedTarget = null;
180
205
  let installedAction = null;
206
+ let installedSkills = [];
181
207
  if (!opts.noAgent) {
182
- // Run install in JSON mode internally so we can reliably parse the action
208
+ // Run install in JSON mode internally so we can reliably parse the result
183
209
  // regardless of the outer --output flag. The stdout is captured here and
184
- // NOT forwarded — runInit owns the output surface.
185
- let capturedInstallResult = null;
210
+ // NOT forwarded — runInit owns the output surface. setup installs the full
211
+ // DEFAULT_SKILLS set (runInstall's default), so several InstallResults come
212
+ // back (one per own-file skill; one aggregate for codex).
213
+ let capturedInstallResults = [];
186
214
  const captureStdout = (line) => {
187
215
  try {
188
216
  const parsed = JSON.parse(line);
189
- if (Array.isArray(parsed) && parsed.length > 0 && parsed[0]) {
190
- capturedInstallResult = parsed[0];
217
+ if (Array.isArray(parsed) && parsed.length > 0) {
218
+ capturedInstallResults = parsed;
191
219
  }
192
220
  }
193
221
  catch {
@@ -199,13 +227,17 @@ export async function runInit(opts, deps = {}) {
199
227
  ...opts,
200
228
  output: 'json', // parse the result; final summary is ours to print
201
229
  target: [opts.agent],
230
+ // skills omitted → runInstall installs DEFAULT_SKILLS (verify + onboard)
202
231
  force: opts.force,
203
232
  dir: opts.dir,
204
233
  }, toAgentDeps(deps, captureStdout));
205
234
  installedTarget = opts.agent;
206
- installedAction = capturedInstallResult
207
- ? capturedInstallResult.action
208
- : 'installed';
235
+ installedAction =
236
+ capturedInstallResults.length > 0
237
+ ? aggregateInstallAction(capturedInstallResults.map(r => r.action))
238
+ : 'installed';
239
+ // De-dupe skills across results, preserving first-seen order.
240
+ installedSkills = [...new Set(capturedInstallResults.flatMap(r => r.skills ?? []))];
209
241
  }
210
242
  catch (installErr) {
211
243
  // Fix 6: credentials were already saved (Step 1+2 above succeeded).
@@ -221,7 +253,11 @@ export async function runInit(opts, deps = {}) {
221
253
  // -------------------------------------------------------------------------
222
254
  const agentSummary = opts.noAgent || installedTarget === null
223
255
  ? null
224
- : { target: installedTarget, action: installedAction ?? 'installed' };
256
+ : {
257
+ target: installedTarget,
258
+ action: installedAction ?? 'installed',
259
+ skills: installedSkills.length > 0 ? installedSkills : [...DEFAULT_SKILLS],
260
+ };
225
261
  const summary = {
226
262
  profile: opts.profile,
227
263
  // Resolved AFTER configure persists the profile → reflects the real endpoint
@@ -253,6 +289,9 @@ function renderInitText(data) {
253
289
  lines.push('');
254
290
  if (s.agent) {
255
291
  lines.push(` agent: ${s.agent.target} (${s.agent.action})`);
292
+ if (s.agent.skills && s.agent.skills.length > 0) {
293
+ lines.push(` skills: ${s.agent.skills.join(', ')}`);
294
+ }
256
295
  }
257
296
  else {
258
297
  lines.push(' agent: skipped (--no-agent)');
@@ -289,62 +328,96 @@ function parseRequestTimeoutFlag(raw) {
289
328
  return undefined;
290
329
  return Math.round(n * 1000);
291
330
  }
292
- export function createInitCommand(deps = {}) {
293
- const validTargets = Object.keys(TARGETS);
294
- const defaultAgent = 'claude';
295
- const cmd = new Command('init')
296
- .description('One-shot onboarding: configure an API key and install the coding-agent skill')
331
+ const SETUP_DESCRIPTION = 'Set up TestSprite: configure your API key and install the TestSprite agent skills for your coding agent';
332
+ /** Attach the onboarding flags shared by `setup` and the `init` alias. */
333
+ function addSetupOptions(cmd, validTargets, defaultAgent) {
334
+ return cmd
297
335
  .option('--api-key <key>', 'API key to configure (skips the interactive prompt)')
298
336
  .option('--from-env', 'Read TESTSPRITE_API_KEY from the environment instead of prompting', false)
299
337
  .option('--agent <target>', `Coding-agent target to install: ${validTargets.join(', ')} (default: ${defaultAgent})`, defaultAgent)
300
338
  .option('--no-agent', 'Skip the agent skill install (configure credentials only)')
301
339
  .option('--force', 'Overwrite an existing skill file (a .bak backup is kept)')
302
340
  .option('--dir <path>', 'Project root for the skill install (default: current directory)')
303
- .option('-y, --yes', 'Non-interactive: accept all defaults, never prompt')
341
+ .option('-y, --yes', 'Non-interactive: accept all defaults, never prompt');
342
+ }
343
+ /** Build {@link InitOptions} from raw Commander opts + globals. */
344
+ function buildSetupOptions(cmdOpts, command, defaultAgent) {
345
+ const common = resolveCommonOptions(command);
346
+ // Commander sets `agent: false` (boolean) when `--no-agent` is passed,
347
+ // because `--no-agent` is the negation of `--agent <target>`. Guard against
348
+ // this: if agent is falsy (false or empty string) default to the CLI default
349
+ // so runInstall never receives a non-string target.
350
+ const resolvedAgent = cmdOpts.agent && typeof cmdOpts.agent === 'string' ? cmdOpts.agent : defaultAgent;
351
+ const isNoAgent = cmdOpts.noAgent === true || cmdOpts.agent === false;
352
+ // Detect conflict when both --no-agent and --agent <target> appear in the raw
353
+ // args. Commander only populates `rawArgs` on the ROOT command passed to
354
+ // parseAsync; subcommands have an empty array. Walk up to the root so we
355
+ // always inspect the full argv.
356
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
357
+ let root = command;
358
+ while (root.parent)
359
+ root = root.parent;
360
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
361
+ const rawArgs = root.rawArgs ?? process.argv;
362
+ const rawArgConflict = rawArgs.some((a) => a === '--no-agent') &&
363
+ rawArgs.some((a) => a === '--agent' || a.startsWith('--agent='));
364
+ return {
365
+ ...common,
366
+ apiKey: cmdOpts.apiKey,
367
+ fromEnv: Boolean(cmdOpts.fromEnv),
368
+ agent: resolvedAgent,
369
+ noAgent: isNoAgent,
370
+ force: Boolean(cmdOpts.force),
371
+ dir: cmdOpts.dir,
372
+ yes: Boolean(cmdOpts.yes),
373
+ rawArgConflict,
374
+ };
375
+ }
376
+ /** Shared action for `setup` and the deprecated `init` alias. */
377
+ async function runSetupAction(cmdOpts, command, deps, defaultAgent) {
378
+ const opts = buildSetupOptions(cmdOpts, command, defaultAgent);
379
+ // When --yes is supplied without a key source, force isTTY=false so runInit
380
+ // emits exit 5 with a clear message rather than hanging on a prompt in a
381
+ // headless CI environment where a TTY fd happens to be open.
382
+ const effectiveDeps = {
383
+ ...deps,
384
+ ...(opts.yes && !opts.apiKey && !opts.fromEnv ? { isTTY: false } : {}),
385
+ };
386
+ await runInit(opts, effectiveDeps);
387
+ }
388
+ export function createSetupCommand(deps = {}) {
389
+ const validTargets = Object.keys(TARGETS);
390
+ const defaultAgent = 'claude';
391
+ return addSetupOptions(new Command('setup'), validTargets, defaultAgent)
392
+ .description(SETUP_DESCRIPTION)
304
393
  .addHelpText('after', GLOBAL_OPTS_HINT)
305
394
  .action(async (cmdOpts, command) => {
306
- const common = resolveCommonOptions(command);
307
- // Commander sets `agent: false` (boolean) when `--no-agent` is passed,
308
- // because `--no-agent` is the negation of `--agent <target>`. Guard
309
- // against this: if agent is falsy (false or empty string) default to
310
- // the CLI default so runInstall never receives a non-string target.
311
- const resolvedAgent = cmdOpts.agent && typeof cmdOpts.agent === 'string' ? cmdOpts.agent : defaultAgent;
312
- const isNoAgent = cmdOpts.noAgent === true || cmdOpts.agent === false;
313
- // Fix 5: detect conflict when both --no-agent and --agent <target> appear
314
- // in the raw args. Thread the flag into runInit so it can emit the [warn]
315
- // via deps.stderr (testable) instead of process.stderr directly.
316
- //
317
- // Commander only populates `rawArgs` on the ROOT command passed to
318
- // parseAsync; subcommands have an empty array. Walk up to the root
319
- // so we always inspect the full argv.
320
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
321
- let root = command;
322
- while (root.parent)
323
- root = root.parent;
324
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
325
- const rawArgs = root.rawArgs ?? process.argv;
326
- const rawArgConflict = rawArgs.some((a) => a === '--no-agent') &&
327
- rawArgs.some((a) => a === '--agent' || a.startsWith('--agent='));
328
- const opts = {
329
- ...common,
330
- apiKey: cmdOpts.apiKey,
331
- fromEnv: Boolean(cmdOpts.fromEnv),
332
- agent: resolvedAgent,
333
- noAgent: isNoAgent,
334
- force: Boolean(cmdOpts.force),
335
- dir: cmdOpts.dir,
336
- yes: Boolean(cmdOpts.yes),
337
- rawArgConflict,
338
- };
339
- // When --yes is supplied without a key source, force isTTY=false so
340
- // runInit emits exit 5 with a clear message rather than hanging on a
341
- // prompt in a headless CI environment where a TTY fd happens to be open.
342
- const effectiveDeps = {
343
- ...deps,
344
- ...(opts.yes && !opts.apiKey && !opts.fromEnv ? { isTTY: false } : {}),
345
- };
346
- await runInit(opts, effectiveDeps);
395
+ await runSetupAction(cmdOpts, command, deps, defaultAgent);
347
396
  });
348
- return cmd;
397
+ }
398
+ /**
399
+ * Hidden, deprecated `init` alias → runs `setup`. Kept so existing scripts and
400
+ * agents trained on the old command keep working; registered with
401
+ * `{ hidden: true }` in index.ts (invisible to `--help`) and prints a
402
+ * deprecation notice. (Setup consolidation.)
403
+ */
404
+ export function createDeprecatedInitCommand(deps = {}) {
405
+ const validTargets = Object.keys(TARGETS);
406
+ const defaultAgent = 'claude';
407
+ return addSetupOptions(new Command('init'), validTargets, defaultAgent)
408
+ .description('(deprecated) alias for `setup`')
409
+ .action(async (cmdOpts, command) => {
410
+ emitDeprecationNotice('init', 'setup', deps.stderr);
411
+ await runSetupAction(cmdOpts, command, deps, defaultAgent);
412
+ });
413
+ }
414
+ /**
415
+ * Entry for the hidden, deprecated `auth configure` alias. Per the setup
416
+ * consolidation, `auth configure` now runs FULL setup (configure + install)
417
+ * so an agent that reaches for the old command still ends up with the skill.
418
+ * `setup` is the ONLY path that writes credentials.
419
+ */
420
+ export async function runConfigureViaSetup(command, deps, fromEnv) {
421
+ await runSetupAction({ agent: 'claude', fromEnv }, command, deps, 'claude');
349
422
  }
350
423
  //# sourceMappingURL=init.js.map
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { readFileSync } from 'node:fs';
3
3
  import { Command } from 'commander';
4
- import { makeHttpClient, } from '../lib/client-factory.js';
4
+ import { emitDryRunBanner, makeHttpClient, } from '../lib/client-factory.js';
5
5
  import { ApiError } from '../lib/errors.js';
6
6
  import { GLOBAL_OPTS_HINT, Output } from '../lib/output.js';
7
7
  import { assertNotLocal } from '../lib/target-url.js';
@@ -64,6 +64,9 @@ export async function runCreate(opts, deps = {}) {
64
64
  throw localValidationError('--url is required for --type frontend');
65
65
  }
66
66
  if (opts.dryRun) {
67
+ // DEV-247: this path returns before makeClient() fires the banner, so emit it
68
+ // here — otherwise the canned sample can be mistaken for a live response.
69
+ emitDryRunBanner(stderr);
67
70
  const idempotencyKey = opts.idempotencyKey ?? `cli-proj-create-${randomUUID()}`;
68
71
  // P2-6: gate idempotency-key output behind --verbose/--debug/json (matches
69
72
  // test create convention). Suppress in plain text interactive mode to reduce
@@ -144,6 +147,8 @@ export async function runUpdate(opts, deps = {}) {
144
147
  throw localValidationError('At least one mutable flag is required: --name, --url, --username, --password/--password-file, --description, or --instruction.');
145
148
  }
146
149
  if (opts.dryRun) {
150
+ // DEV-247: emit the banner here (this path returns before makeClient() does).
151
+ emitDryRunBanner(stderr);
147
152
  const idempotencyKey = opts.idempotencyKey ?? `cli-proj-update-${randomUUID()}`;
148
153
  if (opts.idempotencyKey === undefined &&
149
154
  (opts.output === 'json' || opts.verbose || opts.debug)) {
@@ -110,11 +110,10 @@ export interface CliTestStep {
110
110
  * — agents must not switch on raw strings outside the enumerated set.
111
111
  */
112
112
  export type CliFailureKind = 'assertion' | 'assertion_blocked' | 'routing_404' | 'network_timeout' | 'network' | 'timeout' | 'browser_crash' | 'infra' | 'unknown' | null;
113
- export interface CliResultSummary {
114
- passed: number;
115
- failed: number;
116
- skipped: number;
117
- }
113
+ /** test VERDICT (the outcome of a completed run). */
114
+ export type CliVerdict = 'passed' | 'failed' | 'blocked';
115
+ /** execution LIFECYCLE (where the test is in its run lifecycle). */
116
+ export type CliExecutionStatus = 'draft' | 'ready' | 'queued' | 'running' | 'completed' | 'cancelled' | 'unknown';
118
117
  /** §6.5 LatestResult wire shape. All correlation fields are required. */
119
118
  export interface CliLatestResult {
120
119
  testId: string;
@@ -146,7 +145,20 @@ export interface CliLatestResult {
146
145
  targetUrlSource?: 'run' | 'project-default' | 'unresolved' | null;
147
146
  failedStepIndex: number | null;
148
147
  failureKind: CliFailureKind;
149
- summary: CliResultSummary;
148
+ /**
149
+ * the test VERDICT only (`passed | failed | blocked`), or `null`
150
+ * when the latest run produced no verdict yet (never run / queued / running /
151
+ * cancelled). Lifecycle lives in `executionStatus`; `status` above is the
152
+ * legacy conflated field, retained for back-compat.
153
+ */
154
+ verdict: CliVerdict | null;
155
+ /** the execution LIFECYCLE (terminal runs collapse to `completed`). */
156
+ executionStatus: CliExecutionStatus;
157
+ /**
158
+ * a human/agent-readable description of the latest run (replaces the
159
+ * former `{passed,failed,skipped}` count object).
160
+ */
161
+ summary: string;
150
162
  /**
151
163
  * §6.5.1 (M2.1 piece 3) — inline failure analysis. Present when the
152
164
  * caller passed `--include-analysis` (`?includeAnalysis=true` on
@@ -815,11 +827,14 @@ interface CodeGetOptions extends CommonOptions {
815
827
  * directly; presigned URLs are dereferenced via the same fetch impl
816
828
  * (without API-key headers — the URL is the bearer of authority).
817
829
  *
818
- * `--out <path>` redirects the same bytes into a file. We open the file
819
- * before issuing the network request so a permission/dir error fails
820
- * fast (exit 5 / VALIDATION_ERROR) without spending an API call. On
821
- * any error after open we tear down the sink so we don't leak a
822
- * half-written artifact.
830
+ * `--out <path>` redirects the same bytes into a file. We validate the
831
+ * path and open a sibling temp file before issuing the network request
832
+ * so a permission/dir error fails fast (exit 5 / VALIDATION_ERROR)
833
+ * without spending an API call. The temp file is renamed onto the real
834
+ * `--out` path only after a successful, complete write; on any error
835
+ * (or the "no code generated yet" branch, which writes nothing) the
836
+ * temp file is discarded and the user's pre-existing `--out` file, if
837
+ * any, is left untouched.
823
838
  */
824
839
  export declare function runCodeGet(opts: CodeGetOptions, deps?: TestDeps): Promise<CliTestCode>;
825
840
  /**