@testsprite/testsprite-cli 0.4.0 → 0.6.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 +27 -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 +200 -10
  13. package/dist/commands/test.js +1636 -351
  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 +84 -0
  32. package/dist/lib/gh-output.js +202 -0
  33. package/dist/lib/http.d.ts +33 -15
  34. package/dist/lib/http.js +141 -7
  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 +72 -36
  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 +282 -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 +30 -1
  50. package/dist/lib/v3-advisory.js +35 -4
  51. package/dist/version.d.ts +1 -1
  52. package/dist/version.js +1 -1
  53. package/package.json +17 -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,202 @@
1
+ /**
2
+ * CI-native output layer for the run path (issue #99, reshaped from
3
+ * the withdrawn top-level `ci` command per the #264 review). Covers both a
4
+ * single `test run <test-id> --wait` and the `test run --all --wait` batch.
5
+ *
6
+ * A `--wait` run presents its result in the formats CI consumes:
7
+ * (a) a stable machine summary `{total, passed, failed, timedOut, runs[]}`
8
+ * written to `--summary-file <path>` when requested,
9
+ * (b) a Markdown results table appended to `$GITHUB_STEP_SUMMARY` when
10
+ * running under GitHub Actions,
11
+ * (c) one `::error::` workflow-command line per non-passed run so failures
12
+ * annotate the PR checks tab.
13
+ * Activation: `GITHUB_ACTIONS=true` in the environment, or the explicit
14
+ * `--gh-output` flag (which forces the annotations even off-Actions, so the
15
+ * behavior is previewable locally). All writes are best-effort: a broken
16
+ * summary file must never mask the batch gate's exit code.
17
+ */
18
+ /**
19
+ * Reduce a non-dispatched bucket (`deferred` / `conflicts` / `notFound`) into
20
+ * CI rows. Items are either bare testId strings (`notFound`) or
21
+ * `{ testId, currentRunId? }` objects; both shapes are handled. `note` becomes
22
+ * the row's error text so the annotation explains why the item did not run.
23
+ */
24
+ function bucketRows(bucket, status, note) {
25
+ if (!Array.isArray(bucket))
26
+ return [];
27
+ return bucket.map(item => {
28
+ const rec = item !== null && typeof item === 'object' ? item : undefined;
29
+ const testId = typeof item === 'string' ? item : typeof rec?.testId === 'string' ? rec.testId : '';
30
+ const currentRunId = typeof rec?.currentRunId === 'string' ? rec.currentRunId : undefined;
31
+ return {
32
+ testId,
33
+ status,
34
+ ...(currentRunId ? { runId: currentRunId } : {}),
35
+ error: note,
36
+ };
37
+ });
38
+ }
39
+ /**
40
+ * Reduce the batch command's JSON payload into the CI summary. The parse is
41
+ * defensive: it reads the same `accepted[]` rows the automation contract
42
+ * documents, and anything unparseable (dry-run envelope, partial output
43
+ * after a timeout) reduces to an empty run list rather than a crash.
44
+ *
45
+ * Non-dispatched work (`deferred` / `conflicts` / `notFound`) is folded in as
46
+ * non-passed rows: those buckets already force a non-zero exit (deferred /
47
+ * timeout → 7, all-conflict → 6) but were previously absent from the summary,
48
+ * so a partial batch like `1 accepted passed + 1 deferred` read as "1/1 passed"
49
+ * with no annotation. (`skippedFrontend` / `skippedIntegration` are NOT folded
50
+ * in — they exit 0 and are the Action layer's allow-partial concern.)
51
+ */
52
+ export function summarizeAcceptedPayload(capturedJson) {
53
+ let parsed;
54
+ try {
55
+ parsed = JSON.parse(capturedJson);
56
+ }
57
+ catch {
58
+ // Not JSON at all (dry-run banner path or truncated output): no rows.
59
+ parsed = undefined;
60
+ }
61
+ // `JSON.parse('null')` and non-object payloads are valid JSON but carry no
62
+ // batch envelope — treat them like unparseable input instead of crashing.
63
+ const payload = parsed !== null && typeof parsed === 'object' ? parsed : {};
64
+ const acceptedRows = Array.isArray(payload.accepted)
65
+ ? payload.accepted
66
+ .filter((entry) => entry !== null && typeof entry === 'object')
67
+ .map(row => {
68
+ const errorMessage = row.error !== null && typeof row.error === 'object'
69
+ ? row.error.message
70
+ : undefined;
71
+ return {
72
+ testId: String(row.testId ?? ''),
73
+ ...(typeof row.runId === 'string' ? { runId: row.runId } : {}),
74
+ status: String(row.status ?? 'unknown'),
75
+ ...(typeof row.dashboardUrl === 'string' ? { dashboardUrl: row.dashboardUrl } : {}),
76
+ ...(typeof errorMessage === 'string' ? { error: errorMessage } : {}),
77
+ };
78
+ })
79
+ : [];
80
+ const rows = [
81
+ ...acceptedRows,
82
+ ...bucketRows(payload.deferred, 'deferred', 'rate-deferred (not dispatched)'),
83
+ ...bucketRows(payload.conflicts, 'conflict', 'already in flight (not dispatched)'),
84
+ ...bucketRows(payload.notFound, 'not_found', 'no replayable run (not dispatched)'),
85
+ ];
86
+ const passed = rows.filter(row => row.status === 'passed').length;
87
+ const timedOut = rows.filter(row => row.status === 'timeout').length;
88
+ const failed = rows.length - passed - timedOut;
89
+ return { total: rows.length, passed, failed, timedOut, runs: rows };
90
+ }
91
+ /**
92
+ * Reduce a single `test run <test-id> --wait` result into the same CI summary
93
+ * shape as the batch path, so `--gh-output` / `--summary-file` behave
94
+ * identically for a one-test CI job. Unlike the batch envelope, a single
95
+ * RunResponse carries `error` as a raw string (not `{ message }`) and
96
+ * `dashboardUrl` as `string | null`; both are normalized here.
97
+ */
98
+ export function summarizeSingleRun(run) {
99
+ const row = {
100
+ testId: String(run.testId ?? ''),
101
+ ...(typeof run.runId === 'string' ? { runId: run.runId } : {}),
102
+ status: String(run.status ?? 'unknown'),
103
+ ...(typeof run.dashboardUrl === 'string' ? { dashboardUrl: run.dashboardUrl } : {}),
104
+ ...(typeof run.error === 'string' && run.error.length > 0 ? { error: run.error } : {}),
105
+ };
106
+ const passed = row.status === 'passed' ? 1 : 0;
107
+ const timedOut = row.status === 'timeout' ? 1 : 0;
108
+ const failed = 1 - passed - timedOut;
109
+ return { total: 1, passed, failed, timedOut, runs: [row] };
110
+ }
111
+ /**
112
+ * Escape a value for a Markdown table cell. A raw `|` would break the column
113
+ * layout and a CR/LF would inject extra Markdown lines (rows are newline-joined)
114
+ * — the same injection class the annotation escaping guards against, on the
115
+ * step-summary surface.
116
+ */
117
+ function escapeTableCell(value) {
118
+ return value.replace(/\|/g, '\\|').replace(/[\r\n]+/g, ' ');
119
+ }
120
+ /**
121
+ * Escape a URL for a Markdown `[text](url)` link: a literal `)` closes the link
122
+ * early and whitespace / `|` / CR-LF break the link or the surrounding cell.
123
+ */
124
+ function escapeMarkdownUrl(url) {
125
+ return url
126
+ .replace(/[\r\n]+/g, '')
127
+ .replace(/ /g, '%20')
128
+ .replace(/\(/g, '%28')
129
+ .replace(/\)/g, '%29')
130
+ .replace(/\|/g, '%7C');
131
+ }
132
+ /** Markdown table for the GitHub job summary. */
133
+ export function renderJobSummaryMarkdown(summary) {
134
+ return [
135
+ '## TestSprite results',
136
+ '',
137
+ `**${summary.passed}/${summary.total} passed** (${summary.failed} failed, ${summary.timedOut} timed out)`,
138
+ '',
139
+ '| Test | Status | Run |',
140
+ '| --- | --- | --- |',
141
+ ...summary.runs.map(row => {
142
+ const run = row.dashboardUrl
143
+ ? `[dashboard](${escapeMarkdownUrl(row.dashboardUrl)})`
144
+ : escapeTableCell(row.runId ?? '');
145
+ return `| ${escapeTableCell(row.testId)} | ${escapeTableCell(row.status)} | ${run} |`;
146
+ }),
147
+ '',
148
+ ].join('\n');
149
+ }
150
+ /**
151
+ * Escape a value destined for the DATA half of a workflow command (the text
152
+ * after `::`). Per GitHub's rules, `%`, CR and LF are percent-encoded so a raw
153
+ * multiline run error can never introduce a newline that starts a second
154
+ * `::command::` line in the Actions output stream (`%` first, so the encodings
155
+ * we add are not themselves re-encoded).
156
+ */
157
+ function escapeCommandData(value) {
158
+ return value.replace(/%/g, '%25').replace(/\r/g, '%0D').replace(/\n/g, '%0A');
159
+ }
160
+ /**
161
+ * Escape a value destined for a command PROPERTY (e.g. `title=...`). Beyond the
162
+ * data rules, `:` and `,` are encoded so the value cannot terminate the
163
+ * property list or the command header.
164
+ */
165
+ function escapeCommandProperty(value) {
166
+ return escapeCommandData(value).replace(/:/g, '%3A').replace(/,/g, '%2C');
167
+ }
168
+ /**
169
+ * Emit the GitHub-native surfaces. Self-gating on the standard env vars:
170
+ * `$GITHUB_STEP_SUMMARY` (a file path Actions provides) receives the Markdown
171
+ * table; `GITHUB_ACTIONS=true` enables one `::error::` workflow command per
172
+ * non-passed run on stdout (Actions parses workflow commands from stdout).
173
+ * `force` (the `--gh-output` flag) emits the annotations even off-Actions;
174
+ * the step summary still requires the env-provided file path to exist.
175
+ * Both writes are best-effort: a broken summary file must not mask the gate.
176
+ */
177
+ export function emitGithubOutputs(summary, env, sinks, opts = {}) {
178
+ const summaryPath = env.GITHUB_STEP_SUMMARY;
179
+ if (typeof summaryPath === 'string' && summaryPath.length > 0) {
180
+ try {
181
+ sinks.appendFile(summaryPath, renderJobSummaryMarkdown(summary));
182
+ }
183
+ catch {
184
+ sinks.stderr('[run] could not append to GITHUB_STEP_SUMMARY; continuing');
185
+ }
186
+ }
187
+ if (env.GITHUB_ACTIONS === 'true' || opts.force === true) {
188
+ const annotate = sinks.annotations ?? sinks.stdout;
189
+ for (const row of summary.runs) {
190
+ if (row.status === 'passed')
191
+ continue;
192
+ const detail = row.error !== undefined ? ` ${row.error}` : '';
193
+ const link = row.dashboardUrl !== undefined ? ` ${row.dashboardUrl}` : '';
194
+ // Escape both halves: a raw multiline run error (or a testId) must not be
195
+ // able to smuggle a second workflow command into the Actions stream.
196
+ const title = `TestSprite ${escapeCommandProperty(row.testId)}`;
197
+ const message = escapeCommandData(`status=${row.status}${detail}${link}`);
198
+ annotate(`::error title=${title}::${message}`);
199
+ }
200
+ }
201
+ }
202
+ //# 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
@@ -328,7 +345,17 @@ export class HttpClient {
328
345
  // letting a long-poll drain its window before the interrupt surfaces.
329
346
  if (this.shutdownSignal != null)
330
347
  composedSignals.push(this.shutdownSignal);
331
- const effectiveSignal = composedSignals.length > 1 ? AbortSignal.any(composedSignals) : timeoutSignal;
348
+ // Composed via `composeAbortSignals` (manual listeners), NOT the native
349
+ // `AbortSignal.any` — see that function's doc comment. `this.shutdownSignal`
350
+ // is process-lifetime (`globalShutdown.signal`, `client-factory.ts`) and is
351
+ // pushed into `composedSignals` on essentially every request, so
352
+ // `AbortSignal.any` here was measured to register ~330K dependent-signal
353
+ // trackings against that one long-lived signal over a single request-heavy
354
+ // test file — the same `FinalizationRegistry` backlog mechanism already
355
+ // fixed once in `poll.ts`, just recreated per-request instead of
356
+ // per-poll-iteration. `cleanupAbortComposition` MUST be called once the
357
+ // request settles (below, alongside `requestTimeout.clear()`).
358
+ const { signal: effectiveSignal, cleanup: cleanupAbortComposition } = composeAbortSignals(composedSignals);
332
359
  try {
333
360
  try {
334
361
  response = await this.fetchImpl(url, {
@@ -372,7 +399,9 @@ export class HttpClient {
372
399
  errorCode: 'TRANSPORT',
373
400
  durationMs: Date.now() - startedAt,
374
401
  });
375
- const decision = transportRetryDecision(attempt, this.random);
402
+ const decision = allowTransportRetry
403
+ ? transportRetryDecision(attempt, this.random)
404
+ : { retry: false, delayMs: 0 };
376
405
  if (!decision.retry)
377
406
  throw new TransportError(message, requestId);
378
407
  this.transition(`Network error on ${shortPath(path)} — retrying in ${Math.round(decision.delayMs / 1000)}s (attempt ${attempt})`);
@@ -404,8 +433,9 @@ export class HttpClient {
404
433
  requestId,
405
434
  durationMs,
406
435
  });
436
+ let raw;
407
437
  try {
408
- return { body: (await response.json()), requestId, status: response.status };
438
+ raw = await response.json();
409
439
  }
410
440
  catch (err) {
411
441
  // Interrupt passthrough (see the fetch catch above).
@@ -421,6 +451,30 @@ export class HttpClient {
421
451
  // and break the --output json envelope contract.
422
452
  throw malformedResponseError(response, requestId, err);
423
453
  }
454
+ if (options.schema !== undefined) {
455
+ const parsed = v.safeParse(options.schema, raw);
456
+ if (!parsed.success) {
457
+ const issues = parsed.issues.slice(0, MAX_SCHEMA_ISSUES_IN_DETAILS).map(issue => ({
458
+ path: v.getDotPath(issue) ?? '(root)',
459
+ message: issue.message,
460
+ }));
461
+ // Shape drift is a server-side contract break: surface a typed
462
+ // INTERNAL envelope (requestId + the first mismatched paths,
463
+ // never the body) instead of letting a blind cast poison
464
+ // downstream output with undefined fields or a raw TypeError.
465
+ throw ApiError.fromEnvelope({
466
+ error: {
467
+ code: 'INTERNAL',
468
+ message: `Response shape mismatch from ${shortPath(path)}.`,
469
+ nextAction: 'Retry; if it persists, report this requestId (the server returned an unexpected shape).',
470
+ requestId,
471
+ details: { issues },
472
+ },
473
+ }, response.status);
474
+ }
475
+ return { body: parsed.output, requestId, status: response.status };
476
+ }
477
+ return { body: raw, requestId, status: response.status };
424
478
  }
425
479
  let rawBody;
426
480
  try {
@@ -450,7 +504,9 @@ export class HttpClient {
450
504
  errorCode: 'TRANSPORT',
451
505
  durationMs,
452
506
  });
453
- const decision = transportRetryDecision(attempt, this.random);
507
+ const decision = allowTransportRetry
508
+ ? transportRetryDecision(attempt, this.random)
509
+ : { retry: false, delayMs: 0 };
454
510
  if (!decision.retry) {
455
511
  throw new TransportError(`HTTP ${response.status} from ${url}`, requestId);
456
512
  }
@@ -518,6 +574,11 @@ export class HttpClient {
518
574
  }
519
575
  finally {
520
576
  requestTimeout.clear();
577
+ // Remove the manually-added abort listeners now, synchronously —
578
+ // see `composeAbortSignals`. Runs on every path out of the try
579
+ // (return, throw, or `continue` into the next attempt), so nothing
580
+ // outlives the request it was created for.
581
+ cleanupAbortComposition();
521
582
  }
522
583
  }
523
584
  }
@@ -612,6 +673,63 @@ export function buildUrl(baseUrl, path, query) {
612
673
  function newRequestId() {
613
674
  return `cli_${randomUUID()}`;
614
675
  }
676
+ /**
677
+ * Compose multiple `AbortSignal`s into one — abort on whichever fires first —
678
+ * WITHOUT using the native `AbortSignal.any`.
679
+ *
680
+ * `AbortSignal.any` builds a persistent "dependent signal" relationship: the
681
+ * signal it returns is tracked (via a `WeakRef` + `FinalizationRegistry`)
682
+ * against EVERY source signal passed in, including any long-lived one. Every
683
+ * outgoing request here composes `this.shutdownSignal` — process-lifetime
684
+ * (`globalShutdown.signal`, wired by `client-factory.ts` on essentially every
685
+ * command invocation) — into `composedSignals`, so each request added one
686
+ * more tracked dependent against that single long-lived signal, reclaimed
687
+ * only whenever V8 next got around to running ITS `FinalizationRegistry`
688
+ * cleanup pass. Under a request-heavy path (retries, a wide closure/batch
689
+ * fan-out, RATE_LIMITED backoff) this reproduces — per HTTP request instead
690
+ * of per poll-iteration — the exact backlog mechanism already fixed once in
691
+ * `poll.ts` (`JSFinalizationRegistry::Cleanup` → `KeepDuringJob` →
692
+ * `OrderedHashSet::Add` pegging the CPU once the deferred backlog is finally
693
+ * walked). Measured directly: the RATE_LIMITED closure-fanout scenario in
694
+ * `test.rerun.spec.ts` alone drives ~330K `AbortSignal.any` calls against the
695
+ * one process-lifetime `globalShutdown.signal` over the life of that single
696
+ * test file.
697
+ *
698
+ * This performs the identical "first one wins, propagate its `.reason`"
699
+ * composition with a plain `AbortController` and ordinary
700
+ * `addEventListener`/`removeEventListener` — no dependent-signal tracking, no
701
+ * `WeakRef`, no GC-deferred cleanup. The caller MUST invoke the returned
702
+ * `cleanup()` once the request settles (success, error, or retry) so the
703
+ * listeners are removed immediately rather than left for a cleanup pass that,
704
+ * for this composition, no longer exists.
705
+ */
706
+ function composeAbortSignals(signals) {
707
+ if (signals.length <= 1) {
708
+ return { signal: signals[0], cleanup: () => { } };
709
+ }
710
+ // Mirror AbortSignal.any's already-aborted short-circuit: if a source is
711
+ // already aborted at composition time, propagate its reason immediately —
712
+ // no listeners are ever added, so cleanup is a no-op.
713
+ const alreadyAborted = signals.find(s => s.aborted);
714
+ const controller = new AbortController();
715
+ if (alreadyAborted) {
716
+ controller.abort(alreadyAborted.reason);
717
+ return { signal: controller.signal, cleanup: () => { } };
718
+ }
719
+ const removers = [];
720
+ for (const source of signals) {
721
+ const onAbort = () => controller.abort(source.reason);
722
+ source.addEventListener('abort', onAbort, { once: true });
723
+ removers.push(() => source.removeEventListener('abort', onAbort));
724
+ }
725
+ return {
726
+ signal: controller.signal,
727
+ cleanup: () => {
728
+ for (const remove of removers)
729
+ remove();
730
+ },
731
+ };
732
+ }
615
733
  function createRequestTimeout(timeoutMs) {
616
734
  const controller = new AbortController();
617
735
  const timer = setTimeout(() => {
@@ -713,6 +831,18 @@ function transportRetryDecision(attempt, random) {
713
831
  return { retry: false, delayMs: 0 };
714
832
  return { retry: true, delayMs: backoffDelay(attempt, random) };
715
833
  }
834
+ function canRetryTransport(method, options) {
835
+ return isIdempotentMethod(method) || hasIdempotencyKey(options.headers);
836
+ }
837
+ function isIdempotentMethod(method) {
838
+ const normalized = method.toUpperCase();
839
+ return normalized === 'GET' || normalized === 'HEAD';
840
+ }
841
+ function hasIdempotencyKey(headers) {
842
+ if (!headers)
843
+ return false;
844
+ return Object.keys(headers).some(name => name.toLowerCase() === 'idempotency-key');
845
+ }
716
846
  function apiRetryDecision(code, attempt, retryAfterSec, random, retryOnConflict = true, retryOnRateLimit = true) {
717
847
  switch (code) {
718
848
  // M3.2 piece-1 / piece-2: `PRECONDITION_FAILED` (etag mismatch),
@@ -726,6 +856,9 @@ function apiRetryDecision(code, attempt, retryAfterSec, random, retryOnConflict
726
856
  // case below and retries normally.
727
857
  // FEATURE_GATED is non-retriable: a paid-feature gate can't self-heal with
728
858
  // retries — the caller must upgrade their plan first.
859
+ // AMBIGUOUS_ORG is non-retriable: unlike a generic CONFLICT (mid-mutation
860
+ // snapshot race), this is a permanent id collision across the caller's
861
+ // organizations — retrying resolves the exact same ambiguity again.
729
862
  case 'AUTH_REQUIRED':
730
863
  case 'AUTH_INVALID':
731
864
  case 'AUTH_FORBIDDEN':
@@ -738,6 +871,7 @@ function apiRetryDecision(code, attempt, retryAfterSec, random, retryOnConflict
738
871
  case 'INSUFFICIENT_CREDITS':
739
872
  case 'FEATURE_GATED':
740
873
  case 'CLIENT_TOO_OLD':
874
+ case 'AMBIGUOUS_ORG':
741
875
  // CLIENT_TOO_OLD: retrying re-sends the same too-old client — it can only
742
876
  // self-heal by upgrading, so fail fast with the upgrade guidance.
743
877
  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;