@testsprite/testsprite-cli 0.3.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 (63) hide show
  1. package/README.md +55 -29
  2. package/dist/commands/agent.js +17 -6
  3. package/dist/commands/auth.d.ts +51 -0
  4. package/dist/commands/auth.js +46 -2
  5. package/dist/commands/completion.d.ts +36 -0
  6. package/dist/commands/completion.js +111 -0
  7. package/dist/commands/doctor.js +56 -16
  8. package/dist/commands/init.d.ts +32 -1
  9. package/dist/commands/init.js +40 -10
  10. package/dist/commands/project.d.ts +102 -4
  11. package/dist/commands/project.js +250 -47
  12. package/dist/commands/test.d.ts +253 -11
  13. package/dist/commands/test.js +1822 -390
  14. package/dist/commands/usage.d.ts +56 -17
  15. package/dist/commands/usage.js +144 -29
  16. package/dist/index.js +172 -29
  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 +144 -84
  21. package/dist/lib/client-factory.d.ts +29 -0
  22. package/dist/lib/client-factory.js +49 -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 +51 -1
  27. package/dist/lib/errors.d.ts +33 -1
  28. package/dist/lib/errors.js +110 -19
  29. package/dist/lib/failing-fe-resolver.d.ts +15 -0
  30. package/dist/lib/failing-fe-resolver.js +49 -1
  31. package/dist/lib/flaky.d.ts +12 -1
  32. package/dist/lib/flaky.js +7 -12
  33. package/dist/lib/gh-output.d.ts +62 -0
  34. package/dist/lib/gh-output.js +99 -0
  35. package/dist/lib/http.d.ts +86 -16
  36. package/dist/lib/http.js +181 -11
  37. package/dist/lib/interrupt.d.ts +65 -10
  38. package/dist/lib/interrupt.js +94 -9
  39. package/dist/lib/org-render.d.ts +52 -0
  40. package/dist/lib/org-render.js +59 -0
  41. package/dist/lib/poll.d.ts +11 -0
  42. package/dist/lib/poll.js +71 -6
  43. package/dist/lib/render-error.d.ts +14 -0
  44. package/dist/lib/render-error.js +30 -0
  45. package/dist/lib/response-schemas.d.ts +83 -0
  46. package/dist/lib/response-schemas.js +272 -0
  47. package/dist/lib/runs.types.d.ts +62 -8
  48. package/dist/lib/skill-nudge.d.ts +17 -0
  49. package/dist/lib/skill-nudge.js +19 -0
  50. package/dist/lib/telemetry.d.ts +90 -0
  51. package/dist/lib/telemetry.js +171 -0
  52. package/dist/lib/text-table.d.ts +14 -0
  53. package/dist/lib/text-table.js +45 -0
  54. package/dist/lib/v3-advisory.d.ts +22 -0
  55. package/dist/lib/v3-advisory.js +32 -0
  56. package/dist/lib/version-notice.d.ts +37 -0
  57. package/dist/lib/version-notice.js +87 -0
  58. package/dist/version.d.ts +1 -1
  59. package/dist/version.js +1 -1
  60. package/package.json +16 -5
  61. package/schemas/plan.schema.json +61 -0
  62. package/skills/testsprite-verify.codex.md +8 -2
  63. package/skills/testsprite-verify.skill.md +18 -7
@@ -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
@@ -20,6 +20,7 @@
20
20
  * 5xx → single retry honoring Retry-After, second 5xx throws (exit 9).
21
21
  * Deadline exceeded → throw `TimeoutError`.
22
22
  */
23
+ import type { ShutdownHandle } from './interrupt.js';
23
24
  import type { RunResponse } from './runs.types.js';
24
25
  /**
25
26
  * Minimal interface that `pollRunUntilTerminal` requires from the HTTP client.
@@ -75,6 +76,16 @@ export interface PollOptions {
75
76
  * user's deadline (the per-request HTTP timeout is much larger).
76
77
  */
77
78
  resolveAlternate?: (run: RunResponse, elapsedMs: number, signal: AbortSignal) => Promise<RunResponse | null>;
79
+ /**
80
+ * Graceful-detach coordinator (DEV-331 piece 1). While the poll runs, the
81
+ * scope is armed: a SIGINT/SIGTERM aborts `shutdown.signal` with an
82
+ * `InterruptError` instead of killing the process, and this loop surfaces
83
+ * it immediately — the in-flight long-poll fetch aborts (composed into the
84
+ * per-iteration signal) and every backoff/retry sleep bails early. The
85
+ * caller's catch block renders the honest partial + re-attach hint.
86
+ * Absent (tests, non-wait callers): behavior is unchanged.
87
+ */
88
+ shutdown?: ShutdownHandle;
78
89
  }
79
90
  /**
80
91
  * Poll `GET /api/cli/v1/runs/{runId}` until the run reaches a terminal
package/dist/lib/poll.js CHANGED
@@ -20,7 +20,7 @@
20
20
  * 5xx → single retry honoring Retry-After, second 5xx throws (exit 9).
21
21
  * Deadline exceeded → throw `TimeoutError`.
22
22
  */
23
- import { ApiError } from './errors.js';
23
+ import { ApiError, InterruptError } from './errors.js';
24
24
  import { isTerminalStatus } from './runs.types.js';
25
25
  /** Thrown when the polling deadline is hit. */
26
26
  export class TimeoutError extends Error {
@@ -44,8 +44,25 @@ const BACKOFF_SCHEDULE_MS = [2000, 4000, 8000, 15000];
44
44
  * and unrecoverable server errors.
45
45
  */
46
46
  export async function pollRunUntilTerminal(client, runId, options) {
47
+ // Arm the graceful-detach scope for the duration of the poll (DEV-331):
48
+ // while armed, a termination signal aborts instead of hard-killing the
49
+ // process, and the wait-path catch blocks own the honest detach UX.
50
+ const disarm = options.shutdown?.arm();
51
+ try {
52
+ return await pollLoop(client, runId, options);
53
+ }
54
+ finally {
55
+ disarm?.();
56
+ }
57
+ }
58
+ async function pollLoop(client, runId, options) {
47
59
  const { timeoutSeconds, onTick, onTransition, resolveAlternate } = options;
48
- const sleep = options.sleep ?? defaultSleep;
60
+ const shutdownSignal = options.shutdown?.signal;
61
+ const rawSleep = options.sleep ?? defaultSleep;
62
+ // Every sleep site (retryAfterSeconds, backoff schedule, not_yet_visible,
63
+ // 5xx retry) bails immediately on interrupt — a Ctrl-C must not sit out a
64
+ // 15s backoff before it is noticed.
65
+ const sleep = (ms) => sleepUnlessInterrupted(rawSleep, ms, shutdownSignal);
49
66
  const startMs = Date.now();
50
67
  const deadlineMs = startMs + timeoutSeconds * 1000;
51
68
  // Track whether the server supports ?waitSeconds. Start optimistic.
@@ -55,6 +72,10 @@ export async function pollRunUntilTerminal(client, runId, options) {
55
72
  // 404 not_yet_visible retry budget (one soft retry per event).
56
73
  let notYetVisibleRetries = 0;
57
74
  while (true) {
75
+ // Interrupt outranks the deadline: a Ctrl-C that raced the timeout must
76
+ // surface as the honest detach, not as a generic TimeoutError.
77
+ if (shutdownSignal?.aborted)
78
+ throw shutdownSignal.reason;
58
79
  const now = Date.now();
59
80
  if (now >= deadlineMs) {
60
81
  throw new TimeoutError(runId, timeoutSeconds);
@@ -69,14 +90,21 @@ export async function pollRunUntilTerminal(client, runId, options) {
69
90
  const abortTimer = setTimeout(() => {
70
91
  abortController.abort();
71
92
  }, remainingMs + TRANSPORT_CUSHION_MS);
93
+ // Compose the interrupt into the per-iteration signal: a `--wait` can sit
94
+ // inside one <=25s long-poll fetch (and the auto-raised per-request
95
+ // timeout means even longer for slow backends) — checking the flag
96
+ // between iterations is not enough, the in-flight fetch must abort.
97
+ const iterationSignal = shutdownSignal != null
98
+ ? AbortSignal.any([abortController.signal, shutdownSignal])
99
+ : abortController.signal;
72
100
  let run;
73
101
  try {
74
102
  if (useBackoff) {
75
- run = await client.getRun(runId, { signal: abortController.signal });
103
+ run = await client.getRun(runId, { signal: iterationSignal });
76
104
  }
77
105
  else {
78
106
  const waitSeconds = Math.min(remainingSeconds, LONG_POLL_WAIT_SECONDS);
79
- run = await client.getRun(runId, { waitSeconds, signal: abortController.signal });
107
+ run = await client.getRun(runId, { waitSeconds, signal: iterationSignal });
80
108
  }
81
109
  // Successful GET resets the consecutive-error counter.
82
110
  consecutiveErrors = 0;
@@ -84,6 +112,13 @@ export async function pollRunUntilTerminal(client, runId, options) {
84
112
  }
85
113
  catch (err) {
86
114
  clearTimeout(abortTimer);
115
+ // Interrupt classification precedes the timeout mapping: the composed
116
+ // signal makes the fetch reject on Ctrl-C, and that abort must surface
117
+ // as the InterruptError — not as a spurious TimeoutError.
118
+ if (err instanceof InterruptError)
119
+ throw err;
120
+ if (shutdownSignal?.aborted)
121
+ throw shutdownSignal.reason;
87
122
  // An AbortError from our per-iteration controller means the deadline
88
123
  // passed while the fetch was in flight — surface as TimeoutError.
89
124
  if (isAbortError(err)) {
@@ -155,9 +190,15 @@ export async function pollRunUntilTerminal(client, runId, options) {
155
190
  }
156
191
  const altAbort = new AbortController();
157
192
  const altTimer = setTimeout(() => altAbort.abort(), altRemainingMs);
158
- let alternate = null;
193
+ // The alternate lookup aborts on interrupt too; its errors are swallowed
194
+ // by the fallback (best-effort), so the loop-top interrupt check above
195
+ // surfaces the InterruptError on the next iteration.
196
+ const altSignal = shutdownSignal != null
197
+ ? AbortSignal.any([altAbort.signal, shutdownSignal])
198
+ : altAbort.signal;
199
+ let alternate;
159
200
  try {
160
- alternate = await resolveAlternate(run, elapsedMs, altAbort.signal);
201
+ alternate = await resolveAlternate(run, elapsedMs, altSignal);
161
202
  }
162
203
  finally {
163
204
  clearTimeout(altTimer);
@@ -205,6 +246,30 @@ function backoffScheduleDelay(index) {
205
246
  function defaultSleep(ms) {
206
247
  return new Promise(resolve => setTimeout(resolve, ms));
207
248
  }
249
+ /**
250
+ * Race a sleep against the shutdown signal: rejects with the signal's
251
+ * `InterruptError` reason the moment it fires, so no backoff/retry wait can
252
+ * delay the honest-detach UX. Wraps the injected `sleep` (tests keep their
253
+ * deterministic fakes); the underlying timer is left to fire harmlessly —
254
+ * the interrupt path exits the process long before it matters.
255
+ */
256
+ function sleepUnlessInterrupted(sleep, ms, signal) {
257
+ if (signal == null)
258
+ return sleep(ms);
259
+ if (signal.aborted)
260
+ return Promise.reject(signal.reason);
261
+ return new Promise((resolve, reject) => {
262
+ const onAbort = () => reject(signal.reason);
263
+ signal.addEventListener('abort', onAbort, { once: true });
264
+ sleep(ms).then(() => {
265
+ signal.removeEventListener('abort', onAbort);
266
+ resolve();
267
+ }, err => {
268
+ signal.removeEventListener('abort', onAbort);
269
+ reject(err instanceof Error ? err : new Error(String(err)));
270
+ });
271
+ });
272
+ }
208
273
  /**
209
274
  * Detects an AbortError thrown when an AbortSignal fires.
210
275
  * Works for native fetch AbortErrors as well as `AbortController.abort()`
@@ -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>;
@@ -0,0 +1,272 @@
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
+ /**
36
+ * Compile-time literal union, runtime open string.
37
+ *
38
+ * Keeps `InferOutput` aligned with the union declared in `runs.types.ts`
39
+ * while accepting any string on the wire, per resilience rule 2 above.
40
+ * `v.custom` is valibot's documented escape hatch for exactly this
41
+ * "caller-asserted type, custom runtime check" pattern.
42
+ */
43
+ function openWireLiteral() {
44
+ return v.custom(value => typeof value === 'string');
45
+ }
46
+ // ---------------------------------------------------------------------------
47
+ // GET /runs/{runId}
48
+ // ---------------------------------------------------------------------------
49
+ /** Mirrors `RunStepSummary` (runs.types.ts): per-run step counters. */
50
+ const RUN_STEP_SUMMARY_SCHEMA = v.looseObject({
51
+ total: v.number(),
52
+ completed: v.number(),
53
+ passedCount: v.number(),
54
+ failedCount: v.number(),
55
+ });
56
+ /** Mirrors `RunStepDto` (runs.types.ts): one `?includeSteps=true` step row. */
57
+ const RUN_STEP_DTO_SCHEMA = v.looseObject({
58
+ stepIndex: v.string(),
59
+ type: openWireLiteral(),
60
+ action: v.string(),
61
+ status: v.nullish(openWireLiteral(), null),
62
+ description: v.nullish(v.string(), null),
63
+ error: v.nullish(v.string(), null),
64
+ screenshotUrl: v.nullish(v.string(), null),
65
+ htmlSnapshotUrl: v.nullish(v.string(), null),
66
+ createdAt: v.string(),
67
+ });
68
+ /** Mirrors `RunResponse` (runs.types.ts): `GET /api/cli/v1/runs/{runId}`. */
69
+ export const RUN_RESPONSE_SCHEMA = v.looseObject({
70
+ runId: v.string(),
71
+ testId: v.string(),
72
+ projectId: v.string(),
73
+ userId: v.string(),
74
+ status: openWireLiteral(),
75
+ source: v.string(),
76
+ createdAt: v.string(),
77
+ startedAt: v.nullish(v.string(), null),
78
+ finishedAt: v.nullish(v.string(), null),
79
+ // Both are nullable on the wire (`RunEnvelope` declares
80
+ // `[string, 'null']`): `codeVersion` is null on pre-M3.1 rows and on tests
81
+ // with no stored code body, `targetUrl` is null for backend runs and for
82
+ // execution backends that record no URL. Renderers already omit the line
83
+ // when either is null (rule 3).
84
+ codeVersion: v.nullish(v.string(), null),
85
+ targetUrl: v.nullish(v.string(), null),
86
+ createdFrom: v.nullish(v.string(), null),
87
+ failedStepIndex: v.nullish(v.number(), null),
88
+ failureKind: v.nullish(v.string(), null),
89
+ // Loosened per fixture evidence (rule 3): several real poll bodies omit
90
+ // `error` entirely; consumers render it only when non-null.
91
+ error: v.nullish(v.string(), null),
92
+ videoUrl: v.nullish(v.string(), null),
93
+ stepSummary: RUN_STEP_SUMMARY_SCHEMA,
94
+ retryAfterSeconds: v.optional(v.number()),
95
+ // Portal link. Newer backends DO send this (they alone know which store
96
+ // answered the read and can resolve a non-prod portal origin); older ones
97
+ // omit it and the CLI computes its own. `nullish` rather than `optional`
98
+ // deliberately: the backend omits the field when no correct link exists, but
99
+ // a `null` from any other producer must not fail validation and take down
100
+ // `test wait` — the same trap that had to be un-sprung for a null
101
+ // `targetUrl`/`codeVersion`.
102
+ //
103
+ // The `undefined` default (NOT `null`, unlike every field above) is load-bearing
104
+ // and measured: valibot applies a default only when the key is absent, and
105
+ // skips the assignment entirely when that default is `undefined` — so an
106
+ // omitted field stays an ABSENT key, which is exactly what
107
+ // `withRunDashboardUrl`'s `'dashboardUrl' in run` test reads to decide
108
+ // "old backend, compute the link myself". Aligning this with the
109
+ // `nullish(..., null)` fields above would materialize the key on every
110
+ // response and silently kill that fallback. A wire `null` is preserved as
111
+ // null here (nullable passes it through untouched) and normalized at the
112
+ // consumer, not in the schema. Locked by tests in response-schemas.test.ts.
113
+ dashboardUrl: v.nullish(v.string(), undefined),
114
+ // Absence means "steps not requested" and drives command branching, so no
115
+ // default is applied (rule 3, optional branch).
116
+ steps: v.optional(v.nullable(v.array(RUN_STEP_DTO_SCHEMA))),
117
+ });
118
+ // ---------------------------------------------------------------------------
119
+ // POST /tests/{testId}/runs
120
+ // ---------------------------------------------------------------------------
121
+ /** Mirrors `TriggerRunResponse` (runs.types.ts): `POST /tests/{testId}/runs`. */
122
+ export const TRIGGER_RUN_RESPONSE_SCHEMA = v.looseObject({
123
+ runId: v.string(),
124
+ status: openWireLiteral(),
125
+ enqueuedAt: v.string(),
126
+ codeVersion: v.string(),
127
+ targetUrl: v.string(),
128
+ });
129
+ // ---------------------------------------------------------------------------
130
+ // POST /tests/{testId}/runs/rerun
131
+ // ---------------------------------------------------------------------------
132
+ /** Mirrors `RerunClosureMember` (runs.types.ts): one BE closure member. */
133
+ const RERUN_CLOSURE_MEMBER_SCHEMA = v.looseObject({
134
+ testId: v.string(),
135
+ runId: v.string(),
136
+ role: openWireLiteral(),
137
+ });
138
+ /** Mirrors `RerunClosure` (runs.types.ts): BE closure breakdown. */
139
+ const RERUN_CLOSURE_SCHEMA = v.looseObject({
140
+ members: v.array(RERUN_CLOSURE_MEMBER_SCHEMA),
141
+ addedProducers: v.array(v.string()),
142
+ addedTeardowns: v.array(v.string()),
143
+ clearedCaptured: v.number(),
144
+ });
145
+ /**
146
+ * Mirrors `RerunAdvisory` (runs.types.ts): a server-side note that a
147
+ * requested option was forwarded to the execution engine but is not yet
148
+ * honored there. Present only on a V3-routed rerun that explicitly opted
149
+ * out of auto-heal — absent everywhere else, so this schema is only ever
150
+ * used inside an `v.optional(v.array(...))` wrapper.
151
+ */
152
+ const RERUN_ADVISORY_SCHEMA = v.looseObject({
153
+ feature: v.string(),
154
+ message: v.string(),
155
+ });
156
+ /** Mirrors `RerunResponse` (runs.types.ts): `POST /tests/{testId}/runs/rerun`. */
157
+ export const RERUN_RESPONSE_SCHEMA = v.looseObject({
158
+ runId: v.string(),
159
+ status: openWireLiteral(),
160
+ enqueuedAt: v.string(),
161
+ codeVersion: v.string(),
162
+ autoHeal: v.boolean(),
163
+ // FE reruns omit `closure`; the CLI's `!!closure` truthy check relies on
164
+ // absent staying absent, so optional with no default (rule 3).
165
+ closure: v.optional(v.nullable(RERUN_CLOSURE_SCHEMA)),
166
+ // Absent on every response except a V3-routed rerun with an explicit
167
+ // autoHeal:false opt-out (rule 3: optional, no default, so presence/absence
168
+ // survives validation byte-identically). Older backends that predate the
169
+ // field simply omit it — never fails validation.
170
+ advisories: v.optional(v.array(RERUN_ADVISORY_SCHEMA)),
171
+ });
172
+ // ---------------------------------------------------------------------------
173
+ // POST /tests/batch/rerun
174
+ // ---------------------------------------------------------------------------
175
+ /** Mirrors `BatchRerunResponse` (runs.types.ts): `POST /tests/batch/rerun`. */
176
+ export const BATCH_RERUN_RESPONSE_SCHEMA = v.looseObject({
177
+ // Mirrors BatchRerunAccepted (runs.types.ts).
178
+ accepted: v.array(v.looseObject({ testId: v.string(), runId: v.string(), enqueuedAt: v.string() })),
179
+ // Mirrors BatchRerunDeferred (runs.types.ts).
180
+ deferred: v.array(v.looseObject({ testId: v.string(), reason: v.string() })),
181
+ // Mirrors BatchRerunConflict (runs.types.ts).
182
+ conflicts: v.array(v.looseObject({ testId: v.string(), currentRunId: v.string() })),
183
+ // Mirrors BatchRerunClosure / BatchRerunClosureByProject (runs.types.ts).
184
+ closure: v.looseObject({
185
+ byProject: v.array(v.looseObject({
186
+ projectId: v.string(),
187
+ testIds: v.array(v.string()),
188
+ addedProducers: v.array(v.string()),
189
+ addedTeardowns: v.array(v.string()),
190
+ clearedCaptured: v.number(),
191
+ })),
192
+ }),
193
+ // Optional on the wire for back-compat with older backends (D2-CLI).
194
+ notFound: v.optional(v.array(v.string())),
195
+ // Absent on every response except a V3-routed batch containing at least
196
+ // one FE test with an explicit autoHeal:false opt-out. Same resilience
197
+ // rule as RERUN_RESPONSE_SCHEMA.advisories above.
198
+ advisories: v.optional(v.array(RERUN_ADVISORY_SCHEMA)),
199
+ });
200
+ // ---------------------------------------------------------------------------
201
+ // POST /tests/batch/run
202
+ // ---------------------------------------------------------------------------
203
+ /** Mirrors `BatchRunFreshResponse` (runs.types.ts): `POST /tests/batch/run`. */
204
+ export const BATCH_RUN_FRESH_RESPONSE_SCHEMA = v.looseObject({
205
+ // Mirrors BatchRunFreshAccepted (runs.types.ts); dashboardUrl is
206
+ // client-synthesized, tolerated as optional.
207
+ accepted: v.array(v.looseObject({
208
+ testId: v.string(),
209
+ runId: v.string(),
210
+ enqueuedAt: v.string(),
211
+ dashboardUrl: v.optional(v.string()),
212
+ })),
213
+ conflicts: v.array(v.looseObject({ testId: v.string() })),
214
+ deferred: v.array(v.looseObject({ testId: v.string() })),
215
+ skippedFrontend: v.array(v.string()),
216
+ skippedIntegration: v.array(v.looseObject({ testId: v.string() })),
217
+ });
218
+ // ---------------------------------------------------------------------------
219
+ // GET /tests/{testId}/runs
220
+ // ---------------------------------------------------------------------------
221
+ /** Mirrors `RunHistoryItem` (runs.types.ts): one run-history row. */
222
+ const RUN_HISTORY_ITEM_SCHEMA = v.looseObject({
223
+ runId: v.string(),
224
+ status: openWireLiteral(),
225
+ source: openWireLiteral(),
226
+ isRerun: v.boolean(),
227
+ createdFrom: v.nullish(v.string(), null),
228
+ createdAt: v.string(),
229
+ startedAt: v.nullish(v.string(), null),
230
+ finishedAt: v.nullish(v.string(), null),
231
+ // Nullable on the wire (`RunHistoryRow.codeVersion` is `[string, 'null']`).
232
+ codeVersion: v.nullish(v.string(), null),
233
+ failureKind: v.nullish(v.string(), null),
234
+ // G1b fields: optional on the wire for back-compat with older backends.
235
+ targetUrl: v.optional(v.nullable(v.string())),
236
+ targetUrlSource: v.optional(v.nullable(openWireLiteral())),
237
+ });
238
+ /** Mirrors `ListRunsResponse` (runs.types.ts): `GET /tests/{testId}/runs`. */
239
+ export const LIST_RUNS_RESPONSE_SCHEMA = v.looseObject({
240
+ runs: v.array(RUN_HISTORY_ITEM_SCHEMA),
241
+ nextCursor: v.nullish(v.string(), null),
242
+ // Mirrors RunHistoryMeta (runs.types.ts): every field optional, and the
243
+ // history command reads `resp.meta.note` / `resp.meta.portalUrl` directly,
244
+ // so the container itself stays required like the interface declares.
245
+ meta: v.looseObject({
246
+ testKind: v.optional(openWireLiteral()),
247
+ historyStartsAt: v.optional(v.string()),
248
+ note: v.optional(v.string()),
249
+ portalUrl: v.optional(v.string()),
250
+ }),
251
+ });
252
+ /** Mirrors `CliOrgSummary` (lib/org-render.ts): one `Me.organizations[]` entry. */
253
+ const ORG_SUMMARY_SCHEMA = v.looseObject({
254
+ id: v.string(),
255
+ name: v.string(),
256
+ role: v.string(),
257
+ isPersonal: v.boolean(),
258
+ });
259
+ /** Mirrors `CliOrgBinding` (lib/org-render.ts): `Me.org`. */
260
+ const ORG_BINDING_SCHEMA = v.looseObject({
261
+ id: v.string(),
262
+ name: v.nullable(v.string()),
263
+ role: v.string(),
264
+ });
265
+ /** Mirrors `MeIdentity` (commands/doctor.ts): `GET /api/cli/v1/me` core. */
266
+ export const ME_IDENTITY_SCHEMA = v.looseObject({
267
+ userId: v.optional(v.string()),
268
+ keyId: v.optional(v.string()),
269
+ organizations: v.optional(v.array(ORG_SUMMARY_SCHEMA)),
270
+ org: v.optional(ORG_BINDING_SCHEMA),
271
+ });
272
+ //# sourceMappingURL=response-schemas.js.map