@testsprite/testsprite-cli 0.2.0 → 0.3.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 (55) hide show
  1. package/README.md +34 -26
  2. package/dist/commands/agent.d.ts +43 -0
  3. package/dist/commands/agent.js +200 -18
  4. package/dist/commands/auth.js +29 -27
  5. package/dist/commands/doctor.d.ts +49 -0
  6. package/dist/commands/doctor.js +211 -0
  7. package/dist/commands/init.d.ts +1 -1
  8. package/dist/commands/init.js +24 -14
  9. package/dist/commands/project.d.ts +50 -1
  10. package/dist/commands/project.js +252 -43
  11. package/dist/commands/test.d.ts +188 -1
  12. package/dist/commands/test.js +1088 -81
  13. package/dist/commands/usage.js +13 -12
  14. package/dist/index.js +33 -2
  15. package/dist/lib/agent-targets.d.ts +72 -6
  16. package/dist/lib/agent-targets.js +188 -6
  17. package/dist/lib/bundle.d.ts +34 -0
  18. package/dist/lib/bundle.js +44 -10
  19. package/dist/lib/client-factory.d.ts +25 -0
  20. package/dist/lib/client-factory.js +47 -0
  21. package/dist/lib/config.d.ts +2 -0
  22. package/dist/lib/config.js +11 -2
  23. package/dist/lib/credentials.js +10 -1
  24. package/dist/lib/dry-run/samples.d.ts +5 -0
  25. package/dist/lib/dry-run/samples.js +28 -0
  26. package/dist/lib/flaky.d.ts +80 -0
  27. package/dist/lib/flaky.js +76 -0
  28. package/dist/lib/http.d.ts +20 -0
  29. package/dist/lib/http.js +216 -132
  30. package/dist/lib/interrupt.d.ts +61 -0
  31. package/dist/lib/interrupt.js +97 -0
  32. package/dist/lib/junit-report.d.ts +58 -0
  33. package/dist/lib/junit-report.js +210 -0
  34. package/dist/lib/output.d.ts +16 -1
  35. package/dist/lib/output.js +24 -2
  36. package/dist/lib/pagination.d.ts +4 -3
  37. package/dist/lib/pagination.js +34 -6
  38. package/dist/lib/prompt.js +52 -8
  39. package/dist/lib/proxy.d.ts +29 -0
  40. package/dist/lib/proxy.js +30 -0
  41. package/dist/lib/render-error.js +3 -1
  42. package/dist/lib/skill-nudge.d.ts +2 -2
  43. package/dist/lib/skill-nudge.js +13 -4
  44. package/dist/lib/target-url.js +8 -1
  45. package/dist/lib/ticker.d.ts +11 -1
  46. package/dist/lib/ticker.js +33 -1
  47. package/dist/lib/update-check.d.ts +67 -0
  48. package/dist/lib/update-check.js +246 -0
  49. package/dist/version-guard.d.ts +33 -0
  50. package/dist/version-guard.js +39 -0
  51. package/dist/version.d.ts +1 -1
  52. package/dist/version.js +1 -1
  53. package/package.json +3 -2
  54. package/skills/testsprite-onboard.skill.md +21 -0
  55. package/skills/testsprite-verify.skill.md +33 -0
@@ -1,20 +1,20 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { readFileSync } from 'node:fs';
3
3
  import { Command } from 'commander';
4
- import { emitDryRunBanner, makeHttpClient, } from '../lib/client-factory.js';
4
+ import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, } from '../lib/client-factory.js';
5
5
  import { ApiError } from '../lib/errors.js';
6
- import { GLOBAL_OPTS_HINT, Output } from '../lib/output.js';
6
+ import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
7
7
  import { assertNotLocal } from '../lib/target-url.js';
8
8
  import { assertIdempotencyKey } from '../lib/validate.js';
9
9
  import { fetchSinglePage, paginate, validatePaginationFlags, } from '../lib/pagination.js';
10
10
  export async function runList(opts, deps = {}) {
11
11
  const out = makeOutput(opts.output, deps);
12
- const client = makeClient(opts, deps);
13
12
  const paginationFlags = validatePaginationFlags({
14
13
  pageSize: opts.pageSize,
15
14
  startingToken: opts.startingToken,
16
15
  maxItems: opts.maxItems,
17
16
  });
17
+ const client = makeClient(opts, deps);
18
18
  // When the user explicitly passed a page-size flag and did NOT ask
19
19
  // for --max-items, treat that as a "give me one page and the cursor"
20
20
  // request — same shape AWS CLI ships. Otherwise auto-page.
@@ -49,7 +49,15 @@ export async function runCreate(opts, deps = {}) {
49
49
  // (exit 10 UNAVAILABLE) — fail fast with a clear exit 5 instead.
50
50
  assertIdempotencyKey(opts.idempotencyKey);
51
51
  // P1-3: client-side length checks matching server limits.
52
- if (opts.name !== undefined && opts.name.length > 200) {
52
+ // Whitespace-only / empty rejection (parity with `test create`'s requireString;
53
+ // a truthy `--name " "` otherwise creates a blank-named project on the backend).
54
+ if (opts.name === undefined || opts.name.trim().length === 0) {
55
+ throw localValidationError('--name is required and must not be empty or whitespace-only');
56
+ }
57
+ if (opts.password !== undefined && opts.password.trim().length === 0) {
58
+ throw localValidationError('--password must not be empty or whitespace-only');
59
+ }
60
+ if (opts.name.length > 200) {
53
61
  throw localValidationError('--name must be at most 200 characters');
54
62
  }
55
63
  if (opts.description !== undefined && opts.description.length > 2000) {
@@ -119,32 +127,34 @@ export async function runUpdate(opts, deps = {}) {
119
127
  // P1-2: validate idempotency key before sending as an HTTP header.
120
128
  assertIdempotencyKey(opts.idempotencyKey);
121
129
  // P1-3: client-side length checks matching server limits.
122
- if (opts.name !== undefined && opts.name.length > 200) {
123
- throw localValidationError('--name must be at most 200 characters');
130
+ // Reject a whitespace-only `--name` on update too (parity with create); name
131
+ // stays optional here, so only validate when the flag is supplied.
132
+ if (opts.name !== undefined && opts.name.trim().length === 0) {
133
+ throw localValidationError('--name must not be empty or whitespace-only');
124
134
  }
125
- if (opts.description !== undefined && opts.description.length > 2000) {
126
- throw localValidationError('--description must be at most 2000 characters');
135
+ if (opts.password !== undefined && opts.password.trim().length === 0) {
136
+ throw localValidationError('--password must not be empty or whitespace-only');
127
137
  }
128
- // Resolve password
129
- let password = opts.password;
130
- if (password === undefined && opts.passwordFile !== undefined) {
131
- password = readFileSync(opts.passwordFile, 'utf8').trim();
138
+ if (opts.name !== undefined && opts.name.length > 200) {
139
+ throw localValidationError('--name must be at most 200 characters');
132
140
  }
133
141
  // P2-7: guard --url against localhost/RFC1918/non-http(s).
134
142
  if (opts.targetUrl !== undefined) {
135
143
  assertNotLocal(opts.targetUrl);
136
144
  }
145
+ const passwordSupplied = opts.password !== undefined || opts.passwordFile !== undefined;
137
146
  const mutableFields = {
138
- name: opts.name,
139
- targetUrl: opts.targetUrl,
140
- username: opts.username,
141
- password,
142
- description: opts.description,
143
- instruction: opts.instruction,
147
+ name: opts.name !== undefined,
148
+ targetUrl: opts.targetUrl !== undefined,
149
+ username: opts.username !== undefined,
150
+ password: passwordSupplied,
151
+ instruction: opts.instruction !== undefined,
144
152
  };
145
- const presentFields = Object.entries(mutableFields).filter(([, v]) => v !== undefined);
146
- if (presentFields.length === 0) {
147
- throw localValidationError('At least one mutable flag is required: --name, --url, --username, --password/--password-file, --description, or --instruction.');
153
+ const presentFieldNames = Object.entries(mutableFields)
154
+ .filter(([, present]) => present)
155
+ .map(([field]) => field);
156
+ if (presentFieldNames.length === 0) {
157
+ throw localValidationError('At least one mutable flag is required: --name, --url, --username, --password/--password-file, or --instruction.');
148
158
  }
149
159
  if (opts.dryRun) {
150
160
  // DEV-247: emit the banner here (this path returns before makeClient() does).
@@ -156,17 +166,30 @@ export async function runUpdate(opts, deps = {}) {
156
166
  }
157
167
  const sample = {
158
168
  id: opts.projectId,
159
- updatedFields: presentFields.map(([k]) => k),
169
+ updatedFields: presentFieldNames,
160
170
  updatedAt: '2026-05-16T00:00:00.000Z',
161
171
  };
162
172
  out.print(sample, data => renderUpdateText(data));
163
173
  return sample;
164
174
  }
175
+ // Resolve password only on the real path. Dry-run must not touch the
176
+ // filesystem, even when --password-file is present.
177
+ let password = opts.password;
178
+ if (password === undefined && opts.passwordFile !== undefined) {
179
+ password = readFileSync(opts.passwordFile, 'utf8').trim();
180
+ }
165
181
  const idempotencyKey = opts.idempotencyKey ?? `cli-proj-update-${randomUUID()}`;
166
182
  if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
167
183
  stderr(`idempotency-key: ${idempotencyKey}`);
168
184
  }
169
- const body = Object.fromEntries(presentFields);
185
+ const bodyFields = {
186
+ name: opts.name,
187
+ targetUrl: opts.targetUrl,
188
+ username: opts.username,
189
+ password,
190
+ instruction: opts.instruction,
191
+ };
192
+ const body = Object.fromEntries(Object.entries(bodyFields).filter(([, v]) => v !== undefined));
170
193
  const client = makeClient(opts, deps);
171
194
  const updated = await client.patch(`/projects/${encodeURIComponent(opts.projectId)}`, {
172
195
  body,
@@ -175,6 +198,136 @@ export async function runUpdate(opts, deps = {}) {
175
198
  out.print(updated, data => renderUpdateText(data));
176
199
  return updated;
177
200
  }
201
+ // ---------------------------------------------------------------------------
202
+ // project credential — set the static backend credential
203
+ // ---------------------------------------------------------------------------
204
+ const CLI_AUTH_TYPES = ['public', 'Bearer token', 'API key', 'basic token'];
205
+ export async function runCredential(opts, deps = {}) {
206
+ const out = makeOutput(opts.output, deps);
207
+ const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
208
+ assertIdempotencyKey(opts.idempotencyKey);
209
+ if (!CLI_AUTH_TYPES.includes(opts.authType)) {
210
+ throw localValidationError(`--type must be one of: ${CLI_AUTH_TYPES.join(', ')}`);
211
+ }
212
+ // Resolve the credential value (flag or file). Required for every type
213
+ // except `public` (which clears it).
214
+ let credential = opts.credential;
215
+ if (credential === undefined && opts.credentialFile !== undefined) {
216
+ credential = readFileSync(opts.credentialFile, 'utf8').trim();
217
+ }
218
+ if (opts.authType !== 'public' && (credential === undefined || credential === '')) {
219
+ throw localValidationError('--credential (or --credential-file) is required unless --type is "public"');
220
+ }
221
+ const body = { authType: opts.authType };
222
+ if (opts.authType !== 'public' && credential !== undefined)
223
+ body.credential = credential;
224
+ const idempotencyKey = opts.idempotencyKey ?? `cli-proj-cred-${randomUUID()}`;
225
+ if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
226
+ stderr(`idempotency-key: ${idempotencyKey}`);
227
+ }
228
+ if (opts.dryRun) {
229
+ const sample = {
230
+ projectId: opts.projectId,
231
+ authType: opts.authType,
232
+ rewroteCount: 0,
233
+ };
234
+ out.print(sample, data => renderCredentialText(data));
235
+ return sample;
236
+ }
237
+ const client = makeClient(opts, deps);
238
+ const res = await client.put(`/projects/${encodeURIComponent(opts.projectId)}/credential`, { body, headers: { 'idempotency-key': idempotencyKey } });
239
+ out.print(res, data => renderCredentialText(data));
240
+ return res;
241
+ }
242
+ function renderCredentialText(r) {
243
+ return [
244
+ `projectId ${r.projectId}`,
245
+ `authType ${r.authType}`,
246
+ `rewroteCount ${r.rewroteCount}`,
247
+ ].join('\n');
248
+ }
249
+ // ---------------------------------------------------------------------------
250
+ // project auto-auth — configure the recurring-token (auto-refresh) login
251
+ // ---------------------------------------------------------------------------
252
+ const AUTO_AUTH_METHODS = ['password', 'refresh_token', 'aws_cognito_refresh'];
253
+ const AUTO_AUTH_INJECTS = ['bearer', 'header', 'cookie'];
254
+ export async function runAutoAuth(opts, deps = {}) {
255
+ const out = makeOutput(opts.output, deps);
256
+ const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
257
+ assertIdempotencyKey(opts.idempotencyKey);
258
+ if (!AUTO_AUTH_METHODS.includes(opts.method)) {
259
+ throw localValidationError(`--method must be one of: ${AUTO_AUTH_METHODS.join(', ')}`);
260
+ }
261
+ if (!AUTO_AUTH_INJECTS.includes(opts.inject)) {
262
+ throw localValidationError(`--inject must be one of: ${AUTO_AUTH_INJECTS.join(', ')}`);
263
+ }
264
+ // Resolve secrets from --*-file variants so they stay out of shell history.
265
+ const password = opts.password ??
266
+ (opts.passwordFile !== undefined ? readFileSync(opts.passwordFile, 'utf8').trim() : undefined);
267
+ const clientSecret = opts.clientSecret ??
268
+ (opts.clientSecretFile !== undefined
269
+ ? readFileSync(opts.clientSecretFile, 'utf8').trim()
270
+ : undefined);
271
+ const refreshToken = opts.refreshToken ??
272
+ (opts.refreshTokenFile !== undefined
273
+ ? readFileSync(opts.refreshTokenFile, 'utf8').trim()
274
+ : undefined);
275
+ const enabled = opts.disable !== true;
276
+ const body = { enabled, method: opts.method, inject: opts.inject };
277
+ const maybe = (k, v) => {
278
+ if (v !== undefined)
279
+ body[k] = v;
280
+ };
281
+ maybe('injectKey', opts.injectKey);
282
+ maybe('loginUrl', opts.loginUrl);
283
+ maybe('loginMethod', opts.loginMethod);
284
+ maybe('loginContentType', opts.loginContentType);
285
+ maybe('loginBodyTemplate', opts.loginBodyTemplate);
286
+ maybe('username', opts.username);
287
+ maybe('password', password);
288
+ maybe('tokenPath', opts.tokenPath);
289
+ maybe('tokenEndpoint', opts.tokenEndpoint);
290
+ maybe('clientId', opts.clientId);
291
+ maybe('clientSecret', clientSecret);
292
+ maybe('refreshToken', refreshToken);
293
+ maybe('scope', opts.scope);
294
+ maybe('region', opts.region);
295
+ const idempotencyKey = opts.idempotencyKey ?? `cli-proj-autoauth-${randomUUID()}`;
296
+ if (opts.idempotencyKey === undefined && (opts.output === 'json' || opts.verbose || opts.debug)) {
297
+ stderr(`idempotency-key: ${idempotencyKey}`);
298
+ }
299
+ if (opts.dryRun) {
300
+ const sample = {
301
+ projectId: opts.projectId,
302
+ enabled,
303
+ method: opts.method,
304
+ inject: opts.inject,
305
+ };
306
+ out.print(sample, data => renderAutoAuthText(data));
307
+ return sample;
308
+ }
309
+ const client = makeClient(opts, deps);
310
+ const res = await client.put(`/projects/${encodeURIComponent(opts.projectId)}/auto-auth`, { body, headers: { 'idempotency-key': idempotencyKey } });
311
+ out.print(res, data => renderAutoAuthText(data));
312
+ return res;
313
+ }
314
+ function renderAutoAuthText(r) {
315
+ const lines = [
316
+ `projectId ${r.projectId}`,
317
+ `enabled ${r.enabled}`,
318
+ `method ${r.method}`,
319
+ `inject ${r.inject}`,
320
+ ];
321
+ if (r.lastRefreshError) {
322
+ lines.push(`lastRefreshError ${r.lastRefreshError}`);
323
+ }
324
+ // A disabled result after a write means the trial login failed — call it out
325
+ // so the user doesn't assume auto-auth is live.
326
+ if (!r.enabled) {
327
+ lines.push('note auto-auth was stored but is DISABLED — the trial login failed. Fix the credentials (e.g. a valid refresh token) and re-run.');
328
+ }
329
+ return lines.join('\n');
330
+ }
178
331
  export function createProjectCommand(deps = {}) {
179
332
  const project = new Command('project').description('Manage TestSprite projects');
180
333
  project
@@ -255,7 +408,6 @@ export function createProjectCommand(deps = {}) {
255
408
  .option('--username <user>', 'new auth username')
256
409
  .option('--password <pw>', 'new auth password')
257
410
  .option('--password-file <path>', 'read new password from file')
258
- .option('--description <text>', 'new description')
259
411
  .option('--instruction <text>', 'new FE plan-gen instruction hint')
260
412
  .option('--idempotency-key <token>', 'opaque idempotency token. Defaults to a UUIDv4 minted per invocation.')
261
413
  .addHelpText('after', GLOBAL_OPTS_HINT)
@@ -268,11 +420,85 @@ export function createProjectCommand(deps = {}) {
268
420
  username: cmdOpts.username,
269
421
  password: cmdOpts.password,
270
422
  passwordFile: cmdOpts.passwordFile,
271
- description: cmdOpts.description,
272
423
  instruction: cmdOpts.instruction,
273
424
  idempotencyKey: cmdOpts.idempotencyKey,
274
425
  }, deps);
275
426
  });
427
+ project
428
+ .command('credential <project-id>')
429
+ .description('Set the static backend credential injected into every backend test\n' +
430
+ '(Bearer token / API key / Basic token / public). Free tier.')
431
+ .requiredOption('--type <type>', 'public | "Bearer token" | "API key" | "basic token"')
432
+ .option('--credential <value>', 'credential value (required unless --type public)')
433
+ .option('--credential-file <path>', 'read the credential value from a file')
434
+ .option('--idempotency-key <token>', 'opaque idempotency token. Defaults to a UUIDv4 minted per invocation.')
435
+ .addHelpText('after', GLOBAL_OPTS_HINT)
436
+ .action(async (projectId, cmdOpts, command) => {
437
+ await runCredential({
438
+ ...resolveCommonOptions(command),
439
+ projectId,
440
+ authType: cmdOpts.type,
441
+ credential: cmdOpts.credential,
442
+ credentialFile: cmdOpts.credentialFile,
443
+ idempotencyKey: cmdOpts.idempotencyKey,
444
+ }, deps);
445
+ });
446
+ project
447
+ .command('auto-auth <project-id>')
448
+ .description('Configure the recurring-token (auto-refresh login) for backend tests (Pro).\n' +
449
+ 'A fresh token is fetched on each run and injected into every backend test.')
450
+ .requiredOption('--method <method>', 'password | refresh_token | aws_cognito_refresh')
451
+ .requiredOption('--inject <where>', 'bearer | header | cookie')
452
+ .option('--disable', 'turn auto-auth off (keeps stored config)')
453
+ .option('--inject-key <name>', 'header/cookie name when --inject is header/cookie')
454
+ // password method
455
+ .option('--login-url <url>', 'login endpoint (method=password)')
456
+ .option('--login-method <verb>', 'POST | PUT (method=password)')
457
+ .option('--login-content-type <ct>', 'application/json | application/x-www-form-urlencoded')
458
+ .option('--login-body-template <tpl>', 'login body template with {{username}}/{{password}}')
459
+ .option('--username <user>', 'login username (method=password)')
460
+ .option('--password <pw>', 'login password (method=password)')
461
+ .option('--password-file <path>', 'read login password from a file')
462
+ .option('--token-path <jsonpath>', 'JSONPath to the token in the login response')
463
+ // refresh_token method
464
+ .option('--token-endpoint <url>', 'OAuth token endpoint (method=refresh_token)')
465
+ .option('--client-id <id>', 'OAuth client id')
466
+ .option('--client-secret <secret>', 'OAuth client secret')
467
+ .option('--client-secret-file <path>', 'read OAuth client secret from a file')
468
+ .option('--refresh-token <token>', 'OAuth/Cognito refresh token')
469
+ .option('--refresh-token-file <path>', 'read the refresh token from a file')
470
+ .option('--scope <scope>', 'OAuth scope')
471
+ // aws_cognito_refresh method
472
+ .option('--region <region>', "AWS region (method=aws_cognito_refresh, e.g. 'us-east-1')")
473
+ .option('--idempotency-key <token>', 'opaque idempotency token. Defaults to a UUIDv4 minted per invocation.')
474
+ .addHelpText('after', GLOBAL_OPTS_HINT)
475
+ .action(async (projectId, cmdOpts, command) => {
476
+ await runAutoAuth({
477
+ ...resolveCommonOptions(command),
478
+ projectId,
479
+ disable: cmdOpts.disable,
480
+ method: cmdOpts.method,
481
+ inject: cmdOpts.inject,
482
+ injectKey: cmdOpts.injectKey,
483
+ loginUrl: cmdOpts.loginUrl,
484
+ loginMethod: cmdOpts.loginMethod,
485
+ loginContentType: cmdOpts.loginContentType,
486
+ loginBodyTemplate: cmdOpts.loginBodyTemplate,
487
+ username: cmdOpts.username,
488
+ password: cmdOpts.password,
489
+ passwordFile: cmdOpts.passwordFile,
490
+ tokenPath: cmdOpts.tokenPath,
491
+ tokenEndpoint: cmdOpts.tokenEndpoint,
492
+ clientId: cmdOpts.clientId,
493
+ clientSecret: cmdOpts.clientSecret,
494
+ clientSecretFile: cmdOpts.clientSecretFile,
495
+ refreshToken: cmdOpts.refreshToken,
496
+ refreshTokenFile: cmdOpts.refreshTokenFile,
497
+ scope: cmdOpts.scope,
498
+ region: cmdOpts.region,
499
+ idempotencyKey: cmdOpts.idempotencyKey,
500
+ }, deps);
501
+ });
276
502
  return project;
277
503
  }
278
504
  function parseFlag(raw, flagName) {
@@ -295,13 +521,9 @@ function parseFlag(raw, flagName) {
295
521
  function resolveCommonOptions(command) {
296
522
  const globals = command.optsWithGlobals();
297
523
  // P2-8: validate --output before allowing silent fallback to 'text'.
298
- const rawOutput = globals.output;
299
- if (rawOutput !== undefined && rawOutput !== 'json' && rawOutput !== 'text') {
300
- throw localValidationError('--output must be one of: json, text');
301
- }
302
524
  return {
303
525
  profile: globals.profile ?? 'default',
304
- output: globals.output ?? 'text',
526
+ output: resolveOutputMode(globals.output),
305
527
  endpointUrl: globals.endpointUrl,
306
528
  debug: globals.debug ?? false,
307
529
  verbose: globals.verbose ?? false,
@@ -309,19 +531,6 @@ function resolveCommonOptions(command) {
309
531
  requestTimeoutMs: parseRequestTimeoutFlag(globals.requestTimeout),
310
532
  };
311
533
  }
312
- /**
313
- * Parse the `--request-timeout <seconds>` flag value into milliseconds.
314
- * Returns `undefined` when the flag was not supplied (factory falls back to
315
- * the env var / default). Silently clamps out-of-range values.
316
- */
317
- function parseRequestTimeoutFlag(raw) {
318
- if (raw === undefined)
319
- return undefined;
320
- const n = Number(raw);
321
- if (!Number.isFinite(n) || n <= 0)
322
- return undefined;
323
- return Math.round(n * 1000); // seconds → milliseconds
324
- }
325
534
  function makeClient(opts, deps) {
326
535
  return makeHttpClient(opts, {
327
536
  env: deps.env,
@@ -1,10 +1,12 @@
1
1
  import { Command } from 'commander';
2
2
  import { type CommonOptions as FactoryCommonOptions } from '../lib/client-factory.js';
3
3
  import { type WriteBundleResult } from '../lib/bundle.js';
4
+ import { type JUnitReportFormat } from '../lib/junit-report.js';
4
5
  import { ApiError } from '../lib/errors.js';
5
6
  import type { FetchImpl } from '../lib/http.js';
6
7
  import { type Page } from '../lib/pagination.js';
7
8
  import type { RunResponse, TriggerRunResponse, RerunResponse, BatchRerunResponse, ListRunsResponse, RunSource, BatchRunFreshResponse } from '../lib/runs.types.js';
9
+ import { type FlakyReport } from '../lib/flaky.js';
8
10
  /**
9
11
  * `details` debug block per the CLI OpenAPI `Test` schema
10
12
  * (M2.1 amendment). `processingStatus` / `testStatus` are the
@@ -102,6 +104,19 @@ export interface CliTestStep {
102
104
  * that don't emit the field still type-check.
103
105
  */
104
106
  outcomeContributesToFailure?: boolean | null;
107
+ /**
108
+ * Per-step failure text, carried from `RunStepDto.error` on the run-scoped
109
+ * endpoint (`GET /runs/{id}?includeSteps=true`). Only present on `--run-id`
110
+ * responses; the cumulative `/tests/{id}/steps` rows do not carry it, so the
111
+ * field stays optional (additive, non-breaking for existing consumers).
112
+ */
113
+ error?: string | null;
114
+ /**
115
+ * Wire step kind from `RunStepDto.type` on the run-scoped endpoint. Same
116
+ * availability rules as `error`. Named `stepType` to avoid colliding with
117
+ * the free-form `action` label above.
118
+ */
119
+ stepType?: 'action' | 'assertion';
105
120
  }
106
121
  /**
107
122
  * §6.5 failureKind enum (M2.1 piece 4 widened from six to nine values).
@@ -300,6 +315,12 @@ export interface CliCreateTestResponse {
300
315
  type: 'frontend' | 'backend';
301
316
  codeVersion: string;
302
317
  createdAt: string;
318
+ /**
319
+ * Non-fatal advisories from the backend (e.g. the BE auth guardrail
320
+ * flagging a hardcoded credential). Rendered on stderr; the create
321
+ * still succeeded.
322
+ */
323
+ warnings?: string[];
303
324
  }
304
325
  export declare const CLI_CREATE_PRIORITIES: readonly ["p0", "p1", "p2", "p3"];
305
326
  export type CliCreatePriority = (typeof CLI_CREATE_PRIORITIES)[number];
@@ -847,6 +868,12 @@ export interface CliPutTestCodeResponse {
847
868
  testId: string;
848
869
  codeVersion: string;
849
870
  updatedAt: string;
871
+ /**
872
+ * Non-fatal advisories (e.g. the BE auth guardrail flagging a hardcoded
873
+ * credential in the replaced code). Rendered on stderr; the update still
874
+ * succeeded.
875
+ */
876
+ warnings?: string[];
850
877
  }
851
878
  type CodePutLanguage = CliTestCode['language'];
852
879
  interface CodePutOptions extends CommonOptions {
@@ -934,6 +961,102 @@ interface StepsOptions extends CommonOptions {
934
961
  */
935
962
  runId?: string;
936
963
  }
964
+ export interface DiffOptions extends CommonOptions {
965
+ runA: string;
966
+ runB: string;
967
+ }
968
+ /** One step whose status flipped between the two compared runs. */
969
+ export interface CliDiffStep {
970
+ stepIndex: number;
971
+ statusA: string;
972
+ statusB: string;
973
+ /** First divergent failing side's error text, when the wire carried one. */
974
+ errorA?: string | null;
975
+ errorB?: string | null;
976
+ }
977
+ export interface CliRunDiff {
978
+ runA: {
979
+ runId: string;
980
+ testId: string;
981
+ status: string;
982
+ failureKind: string | null;
983
+ failedStepIndex: number | null;
984
+ codeVersion: string | null;
985
+ };
986
+ runB: {
987
+ runId: string;
988
+ testId: string;
989
+ status: string;
990
+ failureKind: string | null;
991
+ failedStepIndex: number | null;
992
+ codeVersion: string | null;
993
+ };
994
+ verdictChanged: boolean;
995
+ failedStepIndexChanged: boolean;
996
+ failureKindChanged: boolean;
997
+ codeVersionChanged: boolean;
998
+ /** True when the two runs belong to DIFFERENT tests (deltas may be meaningless). */
999
+ crossTest: boolean;
1000
+ changedSteps: CliDiffStep[];
1001
+ }
1002
+ /**
1003
+ * `test diff <runA> <runB>` (issue #124): isolate what regressed between two
1004
+ * runs, the first question when CI goes red ("what changed since the last
1005
+ * green run?"). Pure client-side composition of the existing per-run read
1006
+ * (`GET /runs/{id}?includeSteps=true`); the endpoint accepts any two run-ids,
1007
+ * so a cross-test pair is a WARNING, not an error. Exit 0 when the verdicts
1008
+ * match, exit 1 when they differ, so the command is CI-scriptable.
1009
+ */
1010
+ export declare function runDiff(opts: DiffOptions, deps?: TestDeps): Promise<CliRunDiff>;
1011
+ export interface LintOptions extends CommonOptions {
1012
+ planFrom?: string;
1013
+ planFromDir?: string;
1014
+ plans?: string;
1015
+ steps?: string;
1016
+ }
1017
+ export interface CliLintIssue {
1018
+ file: string;
1019
+ field: string;
1020
+ reason: string;
1021
+ }
1022
+ export interface CliLintReport {
1023
+ checked: number;
1024
+ valid: number;
1025
+ issues: CliLintIssue[];
1026
+ }
1027
+ /**
1028
+ * `test lint` (issue #98): validate plan/steps files fully OFFLINE with the
1029
+ * SAME validators the create paths run, but collecting EVERY problem instead
1030
+ * of dying on the first one, and without any network write. The create-batch
1031
+ * reader is first-error-fatal and only reachable through a command that POSTs,
1032
+ * so authoring a 12-plan directory meant one error per paid round-trip. Zero
1033
+ * network, zero credentials: exit 0 when everything is valid, 5 otherwise, so
1034
+ * it drops into a pre-commit hook or CI step before `create-batch`.
1035
+ */
1036
+ export declare function runLint(opts: LintOptions, deps?: TestDeps): Promise<CliLintReport>;
1037
+ export interface ScaffoldOptions extends CommonOptions {
1038
+ scaffoldType: 'frontend' | 'backend';
1039
+ out?: string;
1040
+ force: boolean;
1041
+ }
1042
+ /** JSON payload `test scaffold --type backend` prints under --output json. */
1043
+ export interface CliBackendScaffold {
1044
+ type: 'backend';
1045
+ language: 'python';
1046
+ code: string;
1047
+ }
1048
+ /**
1049
+ * `test scaffold` — emit a schema-correct starter test definition so a first
1050
+ * test never starts from hand-copied JSON. Pure-local: no network, no
1051
+ * credentials, no filesystem reads. The frontend template is a `CliPlanInput`
1052
+ * (the exact shape `--plan-from` ingests; sourceRef: CliPlanInput /
1053
+ * PLAN_STEP_TYPES above), so `scaffold | create --plan-from -`-style flows
1054
+ * validate out of the box. The backend template is the minimal `requests`
1055
+ * script the onboarding skill mandates: define a test function with a
1056
+ * concrete status assertion, then CALL it (a defined-but-never-called test
1057
+ * would pass without asserting anything).
1058
+ */
1059
+ export declare function runScaffold(opts: ScaffoldOptions, deps?: TestDeps): Promise<CliPlanInput | CliBackendScaffold>;
937
1060
  export declare function runSteps(opts: StepsOptions, deps?: TestDeps): Promise<Page<CliTestStep>>;
938
1061
  interface ResultOptions extends CommonOptions {
939
1062
  testId: string;
@@ -1134,6 +1257,12 @@ interface RunTestRerunOptions extends CommonOptions {
1134
1257
  * filters. Client-side only.
1135
1258
  */
1136
1259
  nameFilter?: string;
1260
+ /** --report junit: write a JUnit XML sidecar after batch --wait completes. */
1261
+ report?: JUnitReportFormat;
1262
+ /** --report-file: destination path for the JUnit XML artifact. */
1263
+ reportFile?: string;
1264
+ /** --report-suite-name: optional override for the JUnit <testsuite name=...>. */
1265
+ reportSuiteName?: string;
1137
1266
  }
1138
1267
  /**
1139
1268
  * Decide whether a testId-scoped result belongs to THIS run (vs a stale
@@ -1154,6 +1283,35 @@ export declare function backendResultIsForThisRun(result: CliLatestResult, runId
1154
1283
  * 7 on timeout.
1155
1284
  */
1156
1285
  export declare function runTestRun(opts: RunTestRunOptions, deps?: TestDeps): Promise<TriggerRunResponse | RunResponse>;
1286
+ /** One row of the `test wait <run-id...>` multi-run payload. */
1287
+ export interface CliMultiWaitResult {
1288
+ runId: string;
1289
+ /** Terminal run status, or 'timeout', or 'error:<CODE>' when the poll failed. */
1290
+ status: string;
1291
+ /** Test the run belongs to, when the poll observed it. */
1292
+ testId?: string;
1293
+ }
1294
+ export interface RunTestWaitManyOptions extends CommonOptions {
1295
+ runIds: string[];
1296
+ timeoutSeconds: number;
1297
+ maxConcurrency: number;
1298
+ }
1299
+ /**
1300
+ * `test wait <run-id...>` with two or more ids: attach to N already-dispatched
1301
+ * runs in ONE invocation. This closes the loop the CLI itself opens: every
1302
+ * batch/closure timeout prints one `testsprite test wait <runId>` hint PER
1303
+ * member, which previously meant N sequential blocking invocations. The runs
1304
+ * are polled concurrently under a bounded pool with ONE shared deadline
1305
+ * (`--timeout` bounds the whole invocation, not each member), each member's
1306
+ * poll is total (a transient error on one run never discards the others), and
1307
+ * the exit code is the worst status across members: auth errors escalate to
1308
+ * exit 3, any timeout or poll error exits 7, any non-passed terminal exits 1.
1309
+ * Distinct from a run journal (issue #80): no persistence, just N known ids.
1310
+ */
1311
+ export declare function runTestWaitMany(opts: RunTestWaitManyOptions, deps?: TestDeps): Promise<{
1312
+ results: CliMultiWaitResult[];
1313
+ summary: Record<string, number>;
1314
+ }>;
1157
1315
  /**
1158
1316
  * `test wait <run-id>` — M3.3 piece-3.
1159
1317
  *
@@ -1162,7 +1320,7 @@ export declare function runTestRun(opts: RunTestRunOptions, deps?: TestDeps): Pr
1162
1320
  */
1163
1321
  export declare function runTestWait(opts: RunTestWaitOptions, deps?: TestDeps): Promise<RunResponse>;
1164
1322
  interface RunTestRunAllOptions extends CommonOptions {
1165
- /** projectId to run all BE tests in. */
1323
+ /** projectId to run all tests in. */
1166
1324
  projectId: string;
1167
1325
  /** --filter <substr>: only run tests whose name contains this substring (case-insensitive). */
1168
1326
  nameFilter?: string;
@@ -1174,6 +1332,12 @@ interface RunTestRunAllOptions extends CommonOptions {
1174
1332
  maxConcurrency: number;
1175
1333
  /** Caller-supplied idempotency token; auto-minted if absent. */
1176
1334
  idempotencyKey?: string;
1335
+ /** --report junit: write a JUnit XML sidecar after batch --wait completes. */
1336
+ report?: JUnitReportFormat;
1337
+ /** --report-file: destination path for the JUnit XML artifact. */
1338
+ reportFile?: string;
1339
+ /** --report-suite-name: optional override for the JUnit <testsuite name=...>. */
1340
+ reportSuiteName?: string;
1177
1341
  }
1178
1342
  /**
1179
1343
  * `test run --all --project <id>` — M4 piece-2.
@@ -1215,6 +1379,7 @@ export interface ArtifactGetResult {
1215
1379
  /** Set when bundle was written to disk. */
1216
1380
  bundle?: WriteBundleResult;
1217
1381
  }
1382
+ export declare function resolveDefaultArtifactDir(runId: string, cwd?: string): string;
1218
1383
  /**
1219
1384
  * Validate that the parent directory of `resolvedDir` exists and is a
1220
1385
  * directory. Surfaces `VALIDATION_ERROR` (exit 5) — matches the convention
@@ -1238,6 +1403,28 @@ export declare function assertOutDirParentExists(resolvedDir: string): Promise<v
1238
1403
  */
1239
1404
  export declare function runArtifactGet(opts: ArtifactGetOptions, deps?: TestDeps): Promise<ArtifactGetResult>;
1240
1405
  export declare function createTestCommand(deps?: TestDeps): Command;
1406
+ interface RunTestFlakyOptions extends CommonOptions {
1407
+ testId: string;
1408
+ /** Number of replays to run (1..MAX_FLAKY_RUNS). */
1409
+ runs: number;
1410
+ /** Stop at the first non-passing attempt. */
1411
+ untilFail: boolean;
1412
+ /** Per-attempt polling deadline in seconds. */
1413
+ timeoutSeconds: number;
1414
+ }
1415
+ /**
1416
+ * `test flaky <test-id>` — replay a test N times and report a stability score.
1417
+ *
1418
+ * Each attempt is a `POST /tests/{id}/runs/rerun` with auto-heal OFF (a strict
1419
+ * verbatim replay) followed by `pollRunUntilTerminal`. Frontend replays are
1420
+ * free verbatim script replays; backend replays re-run the dependency closure
1421
+ * (a one-line credit advisory is printed). The pure scoring lives in
1422
+ * `lib/flaky.ts`; this function is the I/O orchestrator.
1423
+ *
1424
+ * Exit code: 0 when every observed attempt passed (stable), else 1 — so CI can
1425
+ * gate a merge on flakiness.
1426
+ */
1427
+ export declare function runFlaky(opts: RunTestFlakyOptions, deps?: TestDeps): Promise<FlakyReport | undefined>;
1241
1428
  /**
1242
1429
  * D4 (dogfood CoderCup 2026-06-05): under `--wait` the user opts into a
1243
1430
  * long-running operation bounded by `--timeout`. The default 120s per-request