@testsprite/testsprite-cli 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +26 -1
  2. package/dist/commands/agent.js +17 -6
  3. package/dist/commands/auth.d.ts +46 -0
  4. package/dist/commands/auth.js +37 -2
  5. package/dist/commands/completion.d.ts +36 -0
  6. package/dist/commands/completion.js +111 -0
  7. package/dist/commands/doctor.js +20 -2
  8. package/dist/commands/init.d.ts +32 -1
  9. package/dist/commands/init.js +40 -10
  10. package/dist/commands/project.d.ts +77 -3
  11. package/dist/commands/project.js +176 -43
  12. package/dist/commands/test.d.ts +160 -10
  13. package/dist/commands/test.js +1261 -303
  14. package/dist/commands/usage.d.ts +56 -17
  15. package/dist/commands/usage.js +144 -29
  16. package/dist/index.js +132 -26
  17. package/dist/lib/browser.d.ts +6 -0
  18. package/dist/lib/browser.js +54 -0
  19. package/dist/lib/bundle.d.ts +32 -31
  20. package/dist/lib/bundle.js +125 -83
  21. package/dist/lib/client-factory.d.ts +23 -0
  22. package/dist/lib/client-factory.js +33 -1
  23. package/dist/lib/config.js +7 -3
  24. package/dist/lib/credentials.d.ts +17 -1
  25. package/dist/lib/credentials.js +175 -16
  26. package/dist/lib/dry-run/samples.js +15 -1
  27. package/dist/lib/errors.d.ts +6 -1
  28. package/dist/lib/errors.js +70 -19
  29. package/dist/lib/flaky.d.ts +12 -1
  30. package/dist/lib/flaky.js +7 -12
  31. package/dist/lib/gh-output.d.ts +62 -0
  32. package/dist/lib/gh-output.js +99 -0
  33. package/dist/lib/http.d.ts +33 -15
  34. package/dist/lib/http.js +68 -6
  35. package/dist/lib/org-render.d.ts +52 -0
  36. package/dist/lib/org-render.js +59 -0
  37. package/dist/lib/poll.js +1 -1
  38. package/dist/lib/render-error.d.ts +14 -0
  39. package/dist/lib/render-error.js +30 -0
  40. package/dist/lib/response-schemas.d.ts +83 -0
  41. package/dist/lib/response-schemas.js +272 -0
  42. package/dist/lib/runs.types.d.ts +53 -8
  43. package/dist/lib/skill-nudge.d.ts +17 -0
  44. package/dist/lib/skill-nudge.js +19 -0
  45. package/dist/lib/telemetry.d.ts +90 -0
  46. package/dist/lib/telemetry.js +171 -0
  47. package/dist/lib/text-table.d.ts +14 -0
  48. package/dist/lib/text-table.js +45 -0
  49. package/dist/lib/v3-advisory.d.ts +10 -1
  50. package/dist/lib/v3-advisory.js +12 -4
  51. package/dist/version.d.ts +1 -1
  52. package/dist/version.js +1 -1
  53. package/package.json +16 -5
  54. package/schemas/plan.schema.json +61 -0
  55. package/skills/testsprite-verify.codex.md +2 -2
  56. package/skills/testsprite-verify.skill.md +3 -3
@@ -0,0 +1,99 @@
1
+ /**
2
+ * CI-native output layer for the batch run path (issue #99, reshaped from
3
+ * the withdrawn top-level `ci` command per the #264 review).
4
+ *
5
+ * `test run --all --wait` presents its result in the formats CI consumes:
6
+ * (a) a stable machine summary `{total, passed, failed, timedOut, runs[]}`
7
+ * written to `--summary-file <path>` when requested,
8
+ * (b) a Markdown results table appended to `$GITHUB_STEP_SUMMARY` when
9
+ * running under GitHub Actions,
10
+ * (c) one `::error::` workflow-command line per non-passed run so failures
11
+ * annotate the PR checks tab.
12
+ * Activation: `GITHUB_ACTIONS=true` in the environment, or the explicit
13
+ * `--gh-output` flag (which forces the annotations even off-Actions, so the
14
+ * behavior is previewable locally). All writes are best-effort: a broken
15
+ * summary file must never mask the batch gate's exit code.
16
+ */
17
+ /**
18
+ * Reduce the batch command's JSON payload into the CI summary. The parse is
19
+ * defensive: it reads the same `accepted[]` rows the automation contract
20
+ * documents, and anything unparseable (dry-run envelope, partial output
21
+ * after a timeout) reduces to an empty run list rather than a crash.
22
+ */
23
+ export function summarizeAcceptedPayload(capturedJson) {
24
+ let parsed;
25
+ try {
26
+ parsed = JSON.parse(capturedJson);
27
+ }
28
+ catch {
29
+ // Not JSON at all (dry-run banner path or truncated output): no rows.
30
+ parsed = undefined;
31
+ }
32
+ // `JSON.parse('null')` and non-object payloads are valid JSON but carry no
33
+ // batch envelope — treat them like unparseable input instead of crashing.
34
+ const payload = parsed !== null && typeof parsed === 'object' ? parsed : {};
35
+ const rows = Array.isArray(payload.accepted)
36
+ ? payload.accepted
37
+ .filter((entry) => entry !== null && typeof entry === 'object')
38
+ .map(row => {
39
+ const errorMessage = row.error !== null && typeof row.error === 'object'
40
+ ? row.error.message
41
+ : undefined;
42
+ return {
43
+ testId: String(row.testId ?? ''),
44
+ ...(typeof row.runId === 'string' ? { runId: row.runId } : {}),
45
+ status: String(row.status ?? 'unknown'),
46
+ ...(typeof row.dashboardUrl === 'string' ? { dashboardUrl: row.dashboardUrl } : {}),
47
+ ...(typeof errorMessage === 'string' ? { error: errorMessage } : {}),
48
+ };
49
+ })
50
+ : [];
51
+ const passed = rows.filter(row => row.status === 'passed').length;
52
+ const timedOut = rows.filter(row => row.status === 'timeout').length;
53
+ const failed = rows.length - passed - timedOut;
54
+ return { total: rows.length, passed, failed, timedOut, runs: rows };
55
+ }
56
+ /** Markdown table for the GitHub job summary. */
57
+ export function renderJobSummaryMarkdown(summary) {
58
+ return [
59
+ '## TestSprite results',
60
+ '',
61
+ `**${summary.passed}/${summary.total} passed** (${summary.failed} failed, ${summary.timedOut} timed out)`,
62
+ '',
63
+ '| Test | Status | Run |',
64
+ '| --- | --- | --- |',
65
+ ...summary.runs.map(row => `| ${row.testId} | ${row.status} | ${row.dashboardUrl ? `[dashboard](${row.dashboardUrl})` : (row.runId ?? '')} |`),
66
+ '',
67
+ ].join('\n');
68
+ }
69
+ /**
70
+ * Emit the GitHub-native surfaces. Self-gating on the standard env vars:
71
+ * `$GITHUB_STEP_SUMMARY` (a file path Actions provides) receives the Markdown
72
+ * table; `GITHUB_ACTIONS=true` enables one `::error::` workflow command per
73
+ * non-passed run on stdout (Actions parses workflow commands from stdout).
74
+ * `force` (the `--gh-output` flag) emits the annotations even off-Actions;
75
+ * the step summary still requires the env-provided file path to exist.
76
+ * Both writes are best-effort: a broken summary file must not mask the gate.
77
+ */
78
+ export function emitGithubOutputs(summary, env, sinks, opts = {}) {
79
+ const summaryPath = env.GITHUB_STEP_SUMMARY;
80
+ if (typeof summaryPath === 'string' && summaryPath.length > 0) {
81
+ try {
82
+ sinks.appendFile(summaryPath, renderJobSummaryMarkdown(summary));
83
+ }
84
+ catch {
85
+ sinks.stderr('[run] could not append to GITHUB_STEP_SUMMARY; continuing');
86
+ }
87
+ }
88
+ if (env.GITHUB_ACTIONS === 'true' || opts.force === true) {
89
+ const annotate = sinks.annotations ?? sinks.stdout;
90
+ for (const row of summary.runs) {
91
+ if (row.status === 'passed')
92
+ continue;
93
+ const detail = row.error !== undefined ? ` ${row.error}` : '';
94
+ const link = row.dashboardUrl !== undefined ? ` ${row.dashboardUrl}` : '';
95
+ annotate(`::error title=TestSprite ${row.testId}::status=${row.status}${detail}${link}`);
96
+ }
97
+ }
98
+ }
99
+ //# sourceMappingURL=gh-output.js.map
@@ -1,3 +1,4 @@
1
+ import * as v from 'valibot';
1
2
  import type { ErrorCode } from './errors.js';
2
3
  import { ApiError } from './errors.js';
3
4
  import type { TriggerRunBody, TriggerRunResponse, RunResponse, RerunRequest, RerunResponse, BatchRerunRequest, BatchRerunResponse, BatchRunFreshRequest, BatchRunFreshResponse, ListRunsQuery, ListRunsResponse, CancelRunResponse } from './runs.types.js';
@@ -87,10 +88,26 @@ export interface HttpClientOptions {
87
88
  */
88
89
  shutdownSignal?: AbortSignal;
89
90
  }
90
- export interface RequestOptions {
91
+ export interface RequestOptions<T = unknown> {
91
92
  query?: Record<string, string | number | boolean | undefined>;
92
93
  signal?: AbortSignal;
93
94
  requestId?: string;
95
+ /**
96
+ * Optional valibot schema for the parsed 2xx response body (issue #102).
97
+ *
98
+ * When present, `requestWithMeta` runs `v.safeParse` on the OK-path JSON:
99
+ * success returns the parsed output (unknown extra keys preserved via
100
+ * `looseObject`); failure throws an INTERNAL `ApiError` envelope naming the
101
+ * request path and the first {@link MAX_SCHEMA_ISSUES_IN_DETAILS} mismatched
102
+ * field paths (never the body itself). When absent, behavior is unchanged:
103
+ * the body is returned via the historical blind `as T` cast.
104
+ *
105
+ * Wired by the typed run helpers only (`triggerRun`, `triggerRunWithMeta`,
106
+ * `triggerRerun`, `triggerBatchRerun`, `triggerBatchRunFresh`, `getRun`,
107
+ * `listTestRuns`); generic `get`/`post`/... callers stay opt-in.
108
+ * sourceRef: response-schemas.ts.
109
+ */
110
+ schema?: v.GenericSchema<unknown, T>;
94
111
  /**
95
112
  * Optional JSON body for non-GET requests. Serialized with
96
113
  * `JSON.stringify`; `Content-Type: application/json` is auto-attached
@@ -158,21 +175,21 @@ export declare class HttpClient {
158
175
  * resolved client-side via the npm update-notice.)
159
176
  */
160
177
  private captureServerVersion;
161
- get<T>(path: string, options?: RequestOptions): Promise<T>;
162
- post<T>(path: string, options?: RequestOptions): Promise<T>;
163
- put<T>(path: string, options?: RequestOptions): Promise<T>;
164
- patch<T>(path: string, options?: RequestOptions): Promise<T>;
165
- delete<T>(path: string, options?: RequestOptions): Promise<T>;
178
+ get<T>(path: string, options?: RequestOptions<T>): Promise<T>;
179
+ post<T>(path: string, options?: RequestOptions<T>): Promise<T>;
180
+ put<T>(path: string, options?: RequestOptions<T>): Promise<T>;
181
+ patch<T>(path: string, options?: RequestOptions<T>): Promise<T>;
182
+ delete<T>(path: string, options?: RequestOptions<T>): Promise<T>;
166
183
  /**
167
184
  * Like `get` / `post` / etc. but returns the full `RequestResult` including
168
185
  * `requestId` and `status`, so callers can surface the requestId in
169
186
  * happy-path output (dogfood item 1).
170
187
  */
171
- getWithMeta<T>(path: string, options?: RequestOptions): Promise<RequestResult<T>>;
172
- postWithMeta<T>(path: string, options?: RequestOptions): Promise<RequestResult<T>>;
173
- putWithMeta<T>(path: string, options?: RequestOptions): Promise<RequestResult<T>>;
174
- patchWithMeta<T>(path: string, options?: RequestOptions): Promise<RequestResult<T>>;
175
- deleteWithMeta<T>(path: string, options?: RequestOptions): Promise<RequestResult<T>>;
188
+ getWithMeta<T>(path: string, options?: RequestOptions<T>): Promise<RequestResult<T>>;
189
+ postWithMeta<T>(path: string, options?: RequestOptions<T>): Promise<RequestResult<T>>;
190
+ putWithMeta<T>(path: string, options?: RequestOptions<T>): Promise<RequestResult<T>>;
191
+ patchWithMeta<T>(path: string, options?: RequestOptions<T>): Promise<RequestResult<T>>;
192
+ deleteWithMeta<T>(path: string, options?: RequestOptions<T>): Promise<RequestResult<T>>;
176
193
  /**
177
194
  * POST /api/cli/v1/tests/{testId}/runs
178
195
  * Trigger a run and return the queued-run envelope.
@@ -202,8 +219,9 @@ export declare class HttpClient {
202
219
  }): Promise<RequestResult<TriggerRunResponse>>;
203
220
  /**
204
221
  * POST /api/cli/v1/tests/{testId}/runs/rerun
205
- * Trigger a rerun (replay) for a single test. FE: verbatim script replay (no credits).
206
- * BE: dependency-closure re-run. Returns `runId` + optional `closure` (BE).
222
+ * Trigger a rerun (replay) for a single test. FE: verbatim script replay, billed at
223
+ * 0.5 credits (same as a fresh run; legacy V2 accounts: free). BE: dependency-closure
224
+ * re-run, billed at 0.2 credits. Returns `runId` + optional `closure` (BE).
207
225
  *
208
226
  * `retryOnConflict: false` — 409 on rerun means the test is already in-flight,
209
227
  * a persistent condition. Retrying would race against the running test.
@@ -285,7 +303,7 @@ export declare class HttpClient {
285
303
  * continue its own error handling (transport retry / envelope parse).
286
304
  */
287
305
  private rethrowIfAbort;
288
- requestWithMeta<T>(method: string, path: string, options?: RequestOptions): Promise<RequestResult<T>>;
306
+ requestWithMeta<T>(method: string, path: string, options?: RequestOptions<T>): Promise<RequestResult<T>>;
289
307
  private buildHeaders;
290
308
  /**
291
309
  * Retry-delay sleep that bails the moment the shutdown signal fires
@@ -302,7 +320,7 @@ export declare class HttpClient {
302
320
  * `client.request(...)` directly. New callers should use
303
321
  * `requestWithMeta` or the typed helpers (`get`, `post`, etc.).
304
322
  */
305
- request<T>(method: string, path: string, options?: RequestOptions): Promise<T>;
323
+ request<T>(method: string, path: string, options?: RequestOptions<T>): Promise<T>;
306
324
  }
307
325
  export declare function buildUrl(baseUrl: string, path: string, query?: Record<string, string | number | boolean | undefined>): string;
308
326
  /**
package/dist/lib/http.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { randomUUID } from 'node:crypto';
2
+ import * as v from 'valibot';
2
3
  import { ApiError, InterruptError, RequestTimeoutError, TransportError } from './errors.js';
3
4
  import { VERSION } from '../version.js';
5
+ import { BATCH_RERUN_RESPONSE_SCHEMA, BATCH_RUN_FRESH_RESPONSE_SCHEMA, LIST_RUNS_RESPONSE_SCHEMA, RERUN_RESPONSE_SCHEMA, RUN_RESPONSE_SCHEMA, TRIGGER_RUN_RESPONSE_SCHEMA, } from './response-schemas.js';
4
6
  /**
5
7
  * Default per-request timeout (120s). Comfortably covers every metadata/read
6
8
  * request and every <=25s long-poll request (`?waitSeconds` is capped at 25
@@ -39,6 +41,10 @@ const MAX_ATTEMPTS_INTERNAL = 2;
39
41
  const MAX_RATE_LIMITED_DELAY_MS = 60_000;
40
42
  const CONFLICT_DELAY_MS = 1000;
41
43
  const INTERNAL_DELAY_MS = 500;
44
+ // Cap on how many valibot issues a shape-mismatch INTERNAL envelope carries in
45
+ // `details.issues` (path + message each). Keeps the envelope readable and
46
+ // guarantees the response body itself is never echoed back to the operator.
47
+ const MAX_SCHEMA_ISSUES_IN_DETAILS = 3;
42
48
  export class HttpClient {
43
49
  baseUrl;
44
50
  apiKey;
@@ -128,6 +134,7 @@ export class HttpClient {
128
134
  body,
129
135
  headers: { 'idempotency-key': options.idempotencyKey },
130
136
  signal: options.signal,
137
+ schema: TRIGGER_RUN_RESPONSE_SCHEMA,
131
138
  // 409 on POST /runs means "another run is already in flight" — a
132
139
  // persistent condition, not a transient snapshot conflict. Retrying
133
140
  // would enqueue a second run once the first finishes.
@@ -151,6 +158,7 @@ export class HttpClient {
151
158
  body,
152
159
  headers: { 'idempotency-key': options.idempotencyKey },
153
160
  signal: options.signal,
161
+ schema: TRIGGER_RUN_RESPONSE_SCHEMA,
154
162
  retryOnConflict: false,
155
163
  // Default true: single `test run` / `test create --run` retain 429 retry.
156
164
  // Batch call site passes false to keep outer-loop as sole rate-limit owner.
@@ -159,8 +167,9 @@ export class HttpClient {
159
167
  }
160
168
  /**
161
169
  * POST /api/cli/v1/tests/{testId}/runs/rerun
162
- * Trigger a rerun (replay) for a single test. FE: verbatim script replay (no credits).
163
- * BE: dependency-closure re-run. Returns `runId` + optional `closure` (BE).
170
+ * Trigger a rerun (replay) for a single test. FE: verbatim script replay, billed at
171
+ * 0.5 credits (same as a fresh run; legacy V2 accounts: free). BE: dependency-closure
172
+ * re-run, billed at 0.2 credits. Returns `runId` + optional `closure` (BE).
164
173
  *
165
174
  * `retryOnConflict: false` — 409 on rerun means the test is already in-flight,
166
175
  * a persistent condition. Retrying would race against the running test.
@@ -170,6 +179,7 @@ export class HttpClient {
170
179
  body,
171
180
  headers: { 'idempotency-key': options.idempotencyKey },
172
181
  signal: options.signal,
182
+ schema: RERUN_RESPONSE_SCHEMA,
173
183
  retryOnConflict: false,
174
184
  }).then(r => r.body);
175
185
  }
@@ -185,6 +195,7 @@ export class HttpClient {
185
195
  body,
186
196
  headers: { 'idempotency-key': options.idempotencyKey },
187
197
  signal: options.signal,
198
+ schema: BATCH_RERUN_RESPONSE_SCHEMA,
188
199
  retryOnConflict: false,
189
200
  }).then(r => r.body);
190
201
  }
@@ -201,6 +212,7 @@ export class HttpClient {
201
212
  body,
202
213
  headers: { 'idempotency-key': options.idempotencyKey },
203
214
  signal: options.signal,
215
+ schema: BATCH_RUN_FRESH_RESPONSE_SCHEMA,
204
216
  retryOnConflict: false,
205
217
  }).then(r => r.body);
206
218
  }
@@ -222,7 +234,10 @@ export class HttpClient {
222
234
  q.source = query.source;
223
235
  if (query.since !== undefined)
224
236
  q.since = query.since;
225
- return this.get(`/tests/${encodeURIComponent(testId)}/runs`, { query: q });
237
+ return this.get(`/tests/${encodeURIComponent(testId)}/runs`, {
238
+ query: q,
239
+ schema: LIST_RUNS_RESPONSE_SCHEMA,
240
+ });
226
241
  }
227
242
  /**
228
243
  * GET /api/cli/v1/runs/{runId}
@@ -248,6 +263,7 @@ export class HttpClient {
248
263
  return this.get(`/runs/${encodeURIComponent(runId)}`, {
249
264
  query: Object.keys(query).length > 0 ? query : undefined,
250
265
  signal: options?.signal,
266
+ schema: RUN_RESPONSE_SCHEMA,
251
267
  });
252
268
  }
253
269
  /**
@@ -300,6 +316,7 @@ export class HttpClient {
300
316
  throw ApiError.authRequired();
301
317
  const url = buildUrl(this.baseUrl, path, options.query);
302
318
  const requestId = options.requestId ?? newRequestId();
319
+ const allowTransportRetry = canRetryTransport(method, options);
303
320
  let attempt = 0;
304
321
  while (true) {
305
322
  // Bail before issuing (or re-issuing after a retry sleep) a request the
@@ -372,7 +389,9 @@ export class HttpClient {
372
389
  errorCode: 'TRANSPORT',
373
390
  durationMs: Date.now() - startedAt,
374
391
  });
375
- const decision = transportRetryDecision(attempt, this.random);
392
+ const decision = allowTransportRetry
393
+ ? transportRetryDecision(attempt, this.random)
394
+ : { retry: false, delayMs: 0 };
376
395
  if (!decision.retry)
377
396
  throw new TransportError(message, requestId);
378
397
  this.transition(`Network error on ${shortPath(path)} — retrying in ${Math.round(decision.delayMs / 1000)}s (attempt ${attempt})`);
@@ -404,8 +423,9 @@ export class HttpClient {
404
423
  requestId,
405
424
  durationMs,
406
425
  });
426
+ let raw;
407
427
  try {
408
- return { body: (await response.json()), requestId, status: response.status };
428
+ raw = await response.json();
409
429
  }
410
430
  catch (err) {
411
431
  // Interrupt passthrough (see the fetch catch above).
@@ -421,6 +441,30 @@ export class HttpClient {
421
441
  // and break the --output json envelope contract.
422
442
  throw malformedResponseError(response, requestId, err);
423
443
  }
444
+ if (options.schema !== undefined) {
445
+ const parsed = v.safeParse(options.schema, raw);
446
+ if (!parsed.success) {
447
+ const issues = parsed.issues.slice(0, MAX_SCHEMA_ISSUES_IN_DETAILS).map(issue => ({
448
+ path: v.getDotPath(issue) ?? '(root)',
449
+ message: issue.message,
450
+ }));
451
+ // Shape drift is a server-side contract break: surface a typed
452
+ // INTERNAL envelope (requestId + the first mismatched paths,
453
+ // never the body) instead of letting a blind cast poison
454
+ // downstream output with undefined fields or a raw TypeError.
455
+ throw ApiError.fromEnvelope({
456
+ error: {
457
+ code: 'INTERNAL',
458
+ message: `Response shape mismatch from ${shortPath(path)}.`,
459
+ nextAction: 'Retry; if it persists, report this requestId (the server returned an unexpected shape).',
460
+ requestId,
461
+ details: { issues },
462
+ },
463
+ }, response.status);
464
+ }
465
+ return { body: parsed.output, requestId, status: response.status };
466
+ }
467
+ return { body: raw, requestId, status: response.status };
424
468
  }
425
469
  let rawBody;
426
470
  try {
@@ -450,7 +494,9 @@ export class HttpClient {
450
494
  errorCode: 'TRANSPORT',
451
495
  durationMs,
452
496
  });
453
- const decision = transportRetryDecision(attempt, this.random);
497
+ const decision = allowTransportRetry
498
+ ? transportRetryDecision(attempt, this.random)
499
+ : { retry: false, delayMs: 0 };
454
500
  if (!decision.retry) {
455
501
  throw new TransportError(`HTTP ${response.status} from ${url}`, requestId);
456
502
  }
@@ -713,6 +759,18 @@ function transportRetryDecision(attempt, random) {
713
759
  return { retry: false, delayMs: 0 };
714
760
  return { retry: true, delayMs: backoffDelay(attempt, random) };
715
761
  }
762
+ function canRetryTransport(method, options) {
763
+ return isIdempotentMethod(method) || hasIdempotencyKey(options.headers);
764
+ }
765
+ function isIdempotentMethod(method) {
766
+ const normalized = method.toUpperCase();
767
+ return normalized === 'GET' || normalized === 'HEAD';
768
+ }
769
+ function hasIdempotencyKey(headers) {
770
+ if (!headers)
771
+ return false;
772
+ return Object.keys(headers).some(name => name.toLowerCase() === 'idempotency-key');
773
+ }
716
774
  function apiRetryDecision(code, attempt, retryAfterSec, random, retryOnConflict = true, retryOnRateLimit = true) {
717
775
  switch (code) {
718
776
  // M3.2 piece-1 / piece-2: `PRECONDITION_FAILED` (etag mismatch),
@@ -726,6 +784,9 @@ function apiRetryDecision(code, attempt, retryAfterSec, random, retryOnConflict
726
784
  // case below and retries normally.
727
785
  // FEATURE_GATED is non-retriable: a paid-feature gate can't self-heal with
728
786
  // retries — the caller must upgrade their plan first.
787
+ // AMBIGUOUS_ORG is non-retriable: unlike a generic CONFLICT (mid-mutation
788
+ // snapshot race), this is a permanent id collision across the caller's
789
+ // organizations — retrying resolves the exact same ambiguity again.
729
790
  case 'AUTH_REQUIRED':
730
791
  case 'AUTH_INVALID':
731
792
  case 'AUTH_FORBIDDEN':
@@ -738,6 +799,7 @@ function apiRetryDecision(code, attempt, retryAfterSec, random, retryOnConflict
738
799
  case 'INSUFFICIENT_CREDITS':
739
800
  case 'FEATURE_GATED':
740
801
  case 'CLIENT_TOO_OLD':
802
+ case 'AMBIGUOUS_ORG':
741
803
  // CLIENT_TOO_OLD: retrying re-sends the same too-old client — it can only
742
804
  // self-heal by upgrading, so fail fast with the upgrade guidance.
743
805
  return { retry: false, delayMs: 0 };
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Shared org-attribution text rendering for `auth status`, `usage`, and
3
+ * `doctor` — every surface that reads `GET /me`.
4
+ *
5
+ * `organizations[]` (the caller's full account-wide membership list) and
6
+ * `org` (a membership key's own org binding, present only for a
7
+ * Postgres-backed `sk-member-…` key) are both optional/absent-safe on the `/me`
8
+ * response: older backends omit them entirely, and a lookup hiccup
9
+ * server-side omits `organizations` without failing the request. Callers
10
+ * render a line only when the corresponding formatter returns a non-undefined
11
+ * string — never an `undefined`/`null` literal.
12
+ */
13
+ /** One organization from `MeResponse.organizations[]`. */
14
+ export interface CliOrgSummary {
15
+ id: string;
16
+ name: string;
17
+ role: string;
18
+ isPersonal: boolean;
19
+ }
20
+ /** A membership key's own org binding, from `MeResponse.org`. */
21
+ export interface CliOrgBinding {
22
+ id: string;
23
+ /** `null` when best-effort name resolution failed or found no match server-side. */
24
+ name: string | null;
25
+ role: string;
26
+ }
27
+ /**
28
+ * One-line summary of the caller's full membership list, for an `orgs:`
29
+ * line. Returns `undefined` when the list is absent or empty so the caller
30
+ * can omit the line entirely.
31
+ */
32
+ export declare function formatOrgsSummary(organizations: readonly CliOrgSummary[] | undefined): string | undefined;
33
+ /**
34
+ * One-line summary of a membership key's own org binding, for an
35
+ * `org binding:` line. Returns `undefined` when no binding is present
36
+ * (legacy envelope key, or a backend that doesn't return it).
37
+ */
38
+ export declare function formatOrgBinding(org: CliOrgBinding | undefined): string | undefined;
39
+ /**
40
+ * Hint for a caller whose key can only reach their personal workspace while
41
+ * they are a member of at least one team workspace.
42
+ *
43
+ * A key is bound to exactly ONE membership — the workspace is chosen when the
44
+ * key is minted, not per command, which is why there is no `--org` flag to
45
+ * reach for. Without this line the failure mode is silent and baffling: the
46
+ * team's projects simply don't appear in `project list`, and addressing one by
47
+ * id 404s exactly like a typo would.
48
+ *
49
+ * Returns `undefined` when the key is already workspace-bound, or when the
50
+ * caller has no team workspace to be confused about.
51
+ */
52
+ export declare function formatPersonalScopeHint(organizations: readonly CliOrgSummary[] | undefined, org: CliOrgBinding | undefined): string | undefined;
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Shared org-attribution text rendering for `auth status`, `usage`, and
3
+ * `doctor` — every surface that reads `GET /me`.
4
+ *
5
+ * `organizations[]` (the caller's full account-wide membership list) and
6
+ * `org` (a membership key's own org binding, present only for a
7
+ * Postgres-backed `sk-member-…` key) are both optional/absent-safe on the `/me`
8
+ * response: older backends omit them entirely, and a lookup hiccup
9
+ * server-side omits `organizations` without failing the request. Callers
10
+ * render a line only when the corresponding formatter returns a non-undefined
11
+ * string — never an `undefined`/`null` literal.
12
+ */
13
+ /**
14
+ * One-line summary of the caller's full membership list, for an `orgs:`
15
+ * line. Returns `undefined` when the list is absent or empty so the caller
16
+ * can omit the line entirely.
17
+ */
18
+ export function formatOrgsSummary(organizations) {
19
+ if (!organizations || organizations.length === 0)
20
+ return undefined;
21
+ return organizations
22
+ .map(o => `${o.name} (${o.id}${o.isPersonal ? ', personal' : ''}, role: ${o.role})`)
23
+ .join('; ');
24
+ }
25
+ /**
26
+ * One-line summary of a membership key's own org binding, for an
27
+ * `org binding:` line. Returns `undefined` when no binding is present
28
+ * (legacy envelope key, or a backend that doesn't return it).
29
+ */
30
+ export function formatOrgBinding(org) {
31
+ if (!org)
32
+ return undefined;
33
+ const label = org.name ?? org.id;
34
+ return `${label} (${org.id}, role: ${org.role})`;
35
+ }
36
+ /**
37
+ * Hint for a caller whose key can only reach their personal workspace while
38
+ * they are a member of at least one team workspace.
39
+ *
40
+ * A key is bound to exactly ONE membership — the workspace is chosen when the
41
+ * key is minted, not per command, which is why there is no `--org` flag to
42
+ * reach for. Without this line the failure mode is silent and baffling: the
43
+ * team's projects simply don't appear in `project list`, and addressing one by
44
+ * id 404s exactly like a typo would.
45
+ *
46
+ * Returns `undefined` when the key is already workspace-bound, or when the
47
+ * caller has no team workspace to be confused about.
48
+ */
49
+ export function formatPersonalScopeHint(organizations, org) {
50
+ if (org)
51
+ return undefined;
52
+ const teams = (organizations ?? []).filter(o => !o.isPersonal);
53
+ if (teams.length === 0)
54
+ return undefined;
55
+ const names = teams.map(o => o.name).join(', ');
56
+ return (`this key is scoped to your personal workspace, so nothing in ${names} is reachable with it. ` +
57
+ `A key belongs to one workspace: mint one from that workspace's Settings → API Keys and use it here.`);
58
+ }
59
+ //# sourceMappingURL=org-render.js.map
package/dist/lib/poll.js CHANGED
@@ -196,7 +196,7 @@ async function pollLoop(client, runId, options) {
196
196
  const altSignal = shutdownSignal != null
197
197
  ? AbortSignal.any([altAbort.signal, shutdownSignal])
198
198
  : altAbort.signal;
199
- let alternate = null;
199
+ let alternate;
200
200
  try {
201
201
  alternate = await resolveAlternate(run, elapsedMs, altSignal);
202
202
  }
@@ -25,4 +25,18 @@ import type { OutputMode } from './output.js';
25
25
  * mode: the output mode resolved from --output (or argv fallback).
26
26
  */
27
27
  export declare function renderCommanderError(pendingMsg: string | null, fallbackMsg: string, mode: OutputMode): string;
28
+ /**
29
+ * Text-mode rendering for the `AMBIGUOUS_ORG` conflict (`details.candidates[]`
30
+ * — an array of `{ projectId, orgId }` pairs the same testId resolved to,
31
+ * across the caller's organizations). Renders one actionable `candidate:`
32
+ * line per well-formed entry, plus a trailing hint to disambiguate with
33
+ * `--project <id>`.
34
+ *
35
+ * Defensive by design: any entry missing `projectId`/`orgId` (or a
36
+ * malformed/empty/absent `candidates` value) is silently skipped rather than
37
+ * thrown — this is best-effort stderr decoration on top of an error that
38
+ * already renders correctly via the generic envelope, so a future server
39
+ * shape change must never crash the CLI's error path.
40
+ */
41
+ export declare function renderAmbiguousOrgCandidates(candidates: unknown): string[];
28
42
  export declare function rephraseUnknownOption(raw: string): string | null;
@@ -50,6 +50,36 @@ export function renderCommanderError(pendingMsg, fallbackMsg, mode) {
50
50
  // or rephrased by rephraseUnknownOption). Synthesize when null.
51
51
  return pendingMsg ?? `${rawMsg}\n`;
52
52
  }
53
+ /**
54
+ * Text-mode rendering for the `AMBIGUOUS_ORG` conflict (`details.candidates[]`
55
+ * — an array of `{ projectId, orgId }` pairs the same testId resolved to,
56
+ * across the caller's organizations). Renders one actionable `candidate:`
57
+ * line per well-formed entry, plus a trailing hint to disambiguate with
58
+ * `--project <id>`.
59
+ *
60
+ * Defensive by design: any entry missing `projectId`/`orgId` (or a
61
+ * malformed/empty/absent `candidates` value) is silently skipped rather than
62
+ * thrown — this is best-effort stderr decoration on top of an error that
63
+ * already renders correctly via the generic envelope, so a future server
64
+ * shape change must never crash the CLI's error path.
65
+ */
66
+ export function renderAmbiguousOrgCandidates(candidates) {
67
+ if (!Array.isArray(candidates))
68
+ return [];
69
+ const lines = [];
70
+ for (const candidate of candidates) {
71
+ if (candidate === null || typeof candidate !== 'object')
72
+ continue;
73
+ const { projectId, orgId } = candidate;
74
+ if (typeof projectId !== 'string' || typeof orgId !== 'string')
75
+ continue;
76
+ lines.push(` candidate: project ${projectId} (org ${orgId})`);
77
+ }
78
+ if (lines.length === 0)
79
+ return [];
80
+ lines.push(' hint: re-run with --project <id> to disambiguate.');
81
+ return lines;
82
+ }
53
83
  export function rephraseUnknownOption(raw) {
54
84
  // Commander emits: "error: unknown option '--foo'"
55
85
  const match = /unknown option\s+'--([^']+)'/.exec(raw);
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Valibot schemas for the run-path wire shapes (issue #102).
3
+ *
4
+ * `requestWithMeta` used to return `(await response.json()) as T` with zero
5
+ * runtime validation, so a drifted or partial server response surfaced as
6
+ * `undefined` output or an opaque TypeError deep inside a command. These
7
+ * schemas are wired (opt-in, via `RequestOptions.schema`) into the typed
8
+ * HttpClient helpers only: `triggerRun`, `triggerRunWithMeta`, `triggerRerun`,
9
+ * `triggerBatchRerun`, `triggerBatchRunFresh`, `getRun`, `listTestRuns`.
10
+ * The generic `get`/`post`/`put`/`patch`/`delete` paths stay schema-free.
11
+ *
12
+ * Resilience rules (additive server changes must never hard-fail the CLI):
13
+ *
14
+ * 1. Every object is `v.looseObject`: unknown extra keys pass validation AND
15
+ * are preserved in the output, so a new server field still reaches
16
+ * `--output json` consumers untouched.
17
+ * 2. Enum-ish string fields (`status`, `source`, `role`, step `type`, ...) are
18
+ * validated as open strings via {@link openWireLiteral}: the CLI already
19
+ * treats unknown values as open (e.g. `isTerminalStatus` returns false and
20
+ * the poll continues; renderers print the raw value), so a new server enum
21
+ * member must degrade gracefully, never reject the whole response.
22
+ * 3. REQUIRED-nullable interface fields use `v.nullish(inner, null)`: the wire
23
+ * may omit a nullable field entirely (real fixture evidence: the chained
24
+ * `test create --run` poll bodies in `test.test.ts` omit `error`), and
25
+ * every consumer already null-checks these, so absence normalizes to
26
+ * `null` instead of failing. OPTIONAL interface fields (`?`) use
27
+ * `v.optional` with NO default so presence/absence semantics that commands
28
+ * branch on (e.g. `RerunResponse.closure`, `RunResponse.steps`) survive
29
+ * validation byte-identically.
30
+ *
31
+ * Each schema is annotated `v.GenericSchema<unknown, T>` against the
32
+ * interface it mirrors, so schema/interface drift fails `tsc` in this file.
33
+ */
34
+ import * as v from 'valibot';
35
+ import type { BatchRerunResponse, BatchRunFreshResponse, ListRunsResponse, RerunResponse, RunResponse, TriggerRunResponse } from './runs.types.js';
36
+ /** Mirrors `RunResponse` (runs.types.ts): `GET /api/cli/v1/runs/{runId}`. */
37
+ export declare const RUN_RESPONSE_SCHEMA: v.GenericSchema<unknown, RunResponse>;
38
+ /** Mirrors `TriggerRunResponse` (runs.types.ts): `POST /tests/{testId}/runs`. */
39
+ export declare const TRIGGER_RUN_RESPONSE_SCHEMA: v.GenericSchema<unknown, TriggerRunResponse>;
40
+ /** Mirrors `RerunResponse` (runs.types.ts): `POST /tests/{testId}/runs/rerun`. */
41
+ export declare const RERUN_RESPONSE_SCHEMA: v.GenericSchema<unknown, RerunResponse>;
42
+ /** Mirrors `BatchRerunResponse` (runs.types.ts): `POST /tests/batch/rerun`. */
43
+ export declare const BATCH_RERUN_RESPONSE_SCHEMA: v.GenericSchema<unknown, BatchRerunResponse>;
44
+ /** Mirrors `BatchRunFreshResponse` (runs.types.ts): `POST /tests/batch/run`. */
45
+ export declare const BATCH_RUN_FRESH_RESPONSE_SCHEMA: v.GenericSchema<unknown, BatchRunFreshResponse>;
46
+ /** Mirrors `ListRunsResponse` (runs.types.ts): `GET /tests/{testId}/runs`. */
47
+ export declare const LIST_RUNS_RESPONSE_SCHEMA: v.GenericSchema<unknown, ListRunsResponse>;
48
+ /**
49
+ * Minimal `/me` identity core shared by its consumers. `doctor` reads a
50
+ * two-field optional projection (`MeIdentity` in commands/doctor.ts) while
51
+ * `auth whoami` reads the full `MeResponse` (commands/auth.ts); this schema
52
+ * validates the common identity core so it can guard either caller, and
53
+ * `looseObject` lets the full projection (scopes, env, email, ...) pass
54
+ * through untouched. Not wired into any typed helper yet: `/me` callers use
55
+ * the generic `get`, which stays schema-free in this change.
56
+ */
57
+ export interface MeIdentityWire {
58
+ userId?: string;
59
+ keyId?: string;
60
+ /**
61
+ * Account-wide organization membership list (mirrors `CliOrgSummary` in
62
+ * `lib/org-render.ts`). Optional/absent-safe: omitted on a server-side
63
+ * lookup failure or an older backend.
64
+ */
65
+ organizations?: Array<{
66
+ id: string;
67
+ name: string;
68
+ role: string;
69
+ isPersonal: boolean;
70
+ }>;
71
+ /**
72
+ * The calling key's own org binding (mirrors `CliOrgBinding`). Present
73
+ * only for a Postgres-backed membership key (`sk-member-…`); `name` is
74
+ * nullable (best-effort resolution).
75
+ */
76
+ org?: {
77
+ id: string;
78
+ name: string | null;
79
+ role: string;
80
+ };
81
+ }
82
+ /** Mirrors `MeIdentity` (commands/doctor.ts): `GET /api/cli/v1/me` core. */
83
+ export declare const ME_IDENTITY_SCHEMA: v.GenericSchema<unknown, MeIdentityWire>;