@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,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
@@ -56,7 +56,7 @@ export async function pollRunUntilTerminal(client, runId, options) {
56
56
  }
57
57
  }
58
58
  async function pollLoop(client, runId, options) {
59
- const { timeoutSeconds, onTick, onTransition, resolveAlternate } = options;
59
+ const { timeoutSeconds, resolveAlternate } = options;
60
60
  const shutdownSignal = options.shutdown?.signal;
61
61
  const rawSleep = options.sleep ?? defaultSleep;
62
62
  // Every sleep site (retryAfterSeconds, backoff schedule, not_yet_visible,
@@ -65,6 +65,68 @@ async function pollLoop(client, runId, options) {
65
65
  const sleep = (ms) => sleepUnlessInterrupted(rawSleep, ms, shutdownSignal);
66
66
  const startMs = Date.now();
67
67
  const deadlineMs = startMs + timeoutSeconds * 1000;
68
+ // Hoisted ONCE per poll *session* rather than re-minted every iteration.
69
+ // The abort target here — deadlineMs + a transport cushion — is a fixed
70
+ // absolute instant that does not change from one iteration to the next
71
+ // (remainingMs shrinks, but remainingMs + TRANSPORT_CUSHION_MS measured
72
+ // from "now" always lands on the same deadlineMs + cushion point). Minting
73
+ // a fresh AbortController + setTimeout + `AbortSignal.any` composite every
74
+ // iteration was therefore pure churn with no behavioral purpose: on a
75
+ // `--wait` fan-out over many concurrent runIds, each polling for many
76
+ // iterations, this created thousands of composite signals per invocation.
77
+ // Every `AbortSignal.any` call registers an internal dependency listener
78
+ // on the long-lived `shutdownSignal`, tracked via a WeakRef +
79
+ // FinalizationRegistry so the listener can be reclaimed once the derived
80
+ // signal is garbage-collected without leaking on the long-lived source —
81
+ // but under a high allocation rate with no macrotask yield between
82
+ // iterations (`TestDeps.sleep` in tests resolves via a bare microtask),
83
+ // V8 can fall behind on running that reclamation incrementally, and the
84
+ // eventual cleanup pass then has to walk a large backlog in one go
85
+ // (`JSFinalizationRegistry::Cleanup` → `KeepDuringJob` →
86
+ // `OrderedHashSet::Add`), pegging the CPU for minutes. One controller,
87
+ // one timer, and one composed signal — created once, reused for every
88
+ // iteration and every retry, cleared once when the session ends —
89
+ // removes that per-iteration scaling factor entirely; the deadline
90
+ // semantics are unchanged, since the abort target was already the same
91
+ // absolute instant on every iteration.
92
+ const TRANSPORT_CUSHION_MS = 2000;
93
+ const deadlineController = new AbortController();
94
+ const deadlineTimer = setTimeout(() => deadlineController.abort(), deadlineMs - startMs + TRANSPORT_CUSHION_MS);
95
+ const sessionSignal = shutdownSignal != null
96
+ ? AbortSignal.any([deadlineController.signal, shutdownSignal])
97
+ : deadlineController.signal;
98
+ // Same hoisting rationale for the `resolveAlternate` abort target
99
+ // (deadlineMs, no cushion — also a fixed absolute instant). Allocated
100
+ // lazily so callers that never pass `resolveAlternate` pay nothing for it.
101
+ let altAbort;
102
+ let altTimer;
103
+ let altSignal;
104
+ if (resolveAlternate) {
105
+ altAbort = new AbortController();
106
+ const controller = altAbort;
107
+ altTimer = setTimeout(() => controller.abort(), deadlineMs - startMs);
108
+ altSignal =
109
+ shutdownSignal != null ? AbortSignal.any([altAbort.signal, shutdownSignal]) : altAbort.signal;
110
+ }
111
+ try {
112
+ return await pollIterations(client, runId, options, {
113
+ startMs,
114
+ deadlineMs,
115
+ sessionSignal,
116
+ altSignal,
117
+ sleep,
118
+ });
119
+ }
120
+ finally {
121
+ clearTimeout(deadlineTimer);
122
+ if (altTimer !== undefined)
123
+ clearTimeout(altTimer);
124
+ }
125
+ }
126
+ async function pollIterations(client, runId, options, ctx) {
127
+ const { timeoutSeconds, onTick, onTransition, resolveAlternate } = options;
128
+ const shutdownSignal = options.shutdown?.signal;
129
+ const { startMs, deadlineMs, sessionSignal, altSignal, sleep } = ctx;
68
130
  // Track whether the server supports ?waitSeconds. Start optimistic.
69
131
  let useBackoff = false;
70
132
  let backoffIndex = 0;
@@ -82,36 +144,20 @@ async function pollLoop(client, runId, options) {
82
144
  }
83
145
  const remainingMs = deadlineMs - now;
84
146
  const remainingSeconds = Math.ceil(remainingMs / 1000);
85
- // Mint a per-iteration AbortController. The signal fires at the remaining
86
- // deadline plus a small transport cushion (2 s) so a hung fetch does not
87
- // block the CLI past --timeout.
88
- const TRANSPORT_CUSHION_MS = 2000;
89
- const abortController = new AbortController();
90
- const abortTimer = setTimeout(() => {
91
- abortController.abort();
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;
100
147
  let run;
101
148
  try {
102
149
  if (useBackoff) {
103
- run = await client.getRun(runId, { signal: iterationSignal });
150
+ run = await client.getRun(runId, { signal: sessionSignal });
104
151
  }
105
152
  else {
106
153
  const waitSeconds = Math.min(remainingSeconds, LONG_POLL_WAIT_SECONDS);
107
- run = await client.getRun(runId, { waitSeconds, signal: iterationSignal });
154
+ run = await client.getRun(runId, { waitSeconds, signal: sessionSignal });
108
155
  }
109
156
  // Successful GET resets the consecutive-error counter.
110
157
  consecutiveErrors = 0;
111
158
  notYetVisibleRetries = 0;
112
159
  }
113
160
  catch (err) {
114
- clearTimeout(abortTimer);
115
161
  // Interrupt classification precedes the timeout mapping: the composed
116
162
  // signal makes the fetch reject on Ctrl-C, and that abort must surface
117
163
  // as the InterruptError — not as a spurious TimeoutError.
@@ -119,8 +165,8 @@ async function pollLoop(client, runId, options) {
119
165
  throw err;
120
166
  if (shutdownSignal?.aborted)
121
167
  throw shutdownSignal.reason;
122
- // An AbortError from our per-iteration controller means the deadline
123
- // passed while the fetch was in flight — surface as TimeoutError.
168
+ // An AbortError from the session controller means the deadline passed
169
+ // while the fetch was in flight — surface as TimeoutError.
124
170
  if (isAbortError(err)) {
125
171
  throw new TimeoutError(runId, timeoutSeconds);
126
172
  }
@@ -170,8 +216,6 @@ async function pollLoop(client, runId, options) {
170
216
  // Everything else propagates.
171
217
  throw err;
172
218
  }
173
- // fetch completed — cancel the per-iteration abort timer.
174
- clearTimeout(abortTimer);
175
219
  const elapsedMs = Date.now() - startMs;
176
220
  onTick?.(run, elapsedMs);
177
221
  if (isTerminalStatus(run.status)) {
@@ -188,21 +232,13 @@ async function pollLoop(client, runId, options) {
188
232
  if (altRemainingMs <= 0) {
189
233
  throw new TimeoutError(runId, timeoutSeconds);
190
234
  }
191
- const altAbort = new AbortController();
192
- const altTimer = setTimeout(() => altAbort.abort(), altRemainingMs);
193
235
  // The alternate lookup aborts on interrupt too; its errors are swallowed
194
236
  // 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 = null;
200
- try {
201
- alternate = await resolveAlternate(run, elapsedMs, altSignal);
202
- }
203
- finally {
204
- clearTimeout(altTimer);
205
- }
237
+ // surfaces the InterruptError on the next iteration. `altSignal` is the
238
+ // hoisted per-session signal (allocated once, above, whenever
239
+ // `resolveAlternate` is present) — reused across every non-terminal
240
+ // tick rather than re-composed each time.
241
+ const alternate = await resolveAlternate(run, elapsedMs, altSignal);
206
242
  // Enforce the hard cap: reject a terminal alternate that only arrived
207
243
  // at/after the deadline, same as the run-row long-poll path below.
208
244
  if (Date.now() >= deadlineMs) {
@@ -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,282 @@
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. Three-state wire contract (pinned): **absent** — an older
96
+ // backend that predates this field, and cannot have produced a V3-native/
97
+ // unmirrored entity either (that capability and this field ship together)
98
+ // — the CLI computes its own legacy V2-shaped link. **Present + string** —
99
+ // the backend built a correct link (it alone knows which store answered
100
+ // and this environment's portal origin) — use it verbatim. **Present +
101
+ // `null`** — the backend deliberately has no correct link to offer (e.g. a
102
+ // V3-native entity with no DynamoDB mirror row for the client's V2-shaped
103
+ // guess to land on) — suppress the link entirely; a client-side guess here
104
+ // would be exactly the dead link the server declined to emit. The backend
105
+ // always includes the key going forward (typed `string | null`, never
106
+ // omitted when it has an opinion) — an earlier revision of this comment
107
+ // described the backend as omitting the key on "no correct link", which
108
+ // was the actual production defect this contract closes: the client's
109
+ // absent-branch fallback was firing on real V3-native no-link responses
110
+ // and printing the dead legacy URL this whole feature exists to remove.
111
+ //
112
+ // The `undefined` default (NOT `null`, unlike every field above) is load-bearing
113
+ // and measured: valibot applies a default only when the key is absent, and
114
+ // skips the assignment entirely when that default is `undefined` — so an
115
+ // omitted field stays an ABSENT key, which is exactly what
116
+ // `withRunDashboardUrl`'s `'dashboardUrl' in run` test (via the shared
117
+ // `resolveDashboardUrl` helper) reads to decide "old backend, compute the
118
+ // link myself". Aligning this with the `nullish(..., null)` fields above
119
+ // would materialize the key on every response and silently kill that
120
+ // fallback. A wire `null` is preserved as null here (nullable passes it
121
+ // through untouched) and normalized at the consumer, not in the schema.
122
+ // Locked by tests in response-schemas.test.ts.
123
+ dashboardUrl: v.nullish(v.string(), undefined),
124
+ // Absence means "steps not requested" and drives command branching, so no
125
+ // default is applied (rule 3, optional branch).
126
+ steps: v.optional(v.nullable(v.array(RUN_STEP_DTO_SCHEMA))),
127
+ });
128
+ // ---------------------------------------------------------------------------
129
+ // POST /tests/{testId}/runs
130
+ // ---------------------------------------------------------------------------
131
+ /** Mirrors `TriggerRunResponse` (runs.types.ts): `POST /tests/{testId}/runs`. */
132
+ export const TRIGGER_RUN_RESPONSE_SCHEMA = v.looseObject({
133
+ runId: v.string(),
134
+ status: openWireLiteral(),
135
+ enqueuedAt: v.string(),
136
+ codeVersion: v.string(),
137
+ targetUrl: v.string(),
138
+ });
139
+ // ---------------------------------------------------------------------------
140
+ // POST /tests/{testId}/runs/rerun
141
+ // ---------------------------------------------------------------------------
142
+ /** Mirrors `RerunClosureMember` (runs.types.ts): one BE closure member. */
143
+ const RERUN_CLOSURE_MEMBER_SCHEMA = v.looseObject({
144
+ testId: v.string(),
145
+ runId: v.string(),
146
+ role: openWireLiteral(),
147
+ });
148
+ /** Mirrors `RerunClosure` (runs.types.ts): BE closure breakdown. */
149
+ const RERUN_CLOSURE_SCHEMA = v.looseObject({
150
+ members: v.array(RERUN_CLOSURE_MEMBER_SCHEMA),
151
+ addedProducers: v.array(v.string()),
152
+ addedTeardowns: v.array(v.string()),
153
+ clearedCaptured: v.number(),
154
+ });
155
+ /**
156
+ * Mirrors `RerunAdvisory` (runs.types.ts): a server-side note that a
157
+ * requested option was forwarded to the execution engine but is not yet
158
+ * honored there. Present only on a V3-routed rerun that explicitly opted
159
+ * out of auto-heal — absent everywhere else, so this schema is only ever
160
+ * used inside an `v.optional(v.array(...))` wrapper.
161
+ */
162
+ const RERUN_ADVISORY_SCHEMA = v.looseObject({
163
+ feature: v.string(),
164
+ message: v.string(),
165
+ });
166
+ /** Mirrors `RerunResponse` (runs.types.ts): `POST /tests/{testId}/runs/rerun`. */
167
+ export const RERUN_RESPONSE_SCHEMA = v.looseObject({
168
+ runId: v.string(),
169
+ status: openWireLiteral(),
170
+ enqueuedAt: v.string(),
171
+ codeVersion: v.string(),
172
+ autoHeal: v.boolean(),
173
+ // FE reruns omit `closure`; the CLI's `!!closure` truthy check relies on
174
+ // absent staying absent, so optional with no default (rule 3).
175
+ closure: v.optional(v.nullable(RERUN_CLOSURE_SCHEMA)),
176
+ // Absent on every response except a V3-routed rerun with an explicit
177
+ // autoHeal:false opt-out (rule 3: optional, no default, so presence/absence
178
+ // survives validation byte-identically). Older backends that predate the
179
+ // field simply omit it — never fails validation.
180
+ advisories: v.optional(v.array(RERUN_ADVISORY_SCHEMA)),
181
+ });
182
+ // ---------------------------------------------------------------------------
183
+ // POST /tests/batch/rerun
184
+ // ---------------------------------------------------------------------------
185
+ /** Mirrors `BatchRerunResponse` (runs.types.ts): `POST /tests/batch/rerun`. */
186
+ export const BATCH_RERUN_RESPONSE_SCHEMA = v.looseObject({
187
+ // Mirrors BatchRerunAccepted (runs.types.ts).
188
+ accepted: v.array(v.looseObject({ testId: v.string(), runId: v.string(), enqueuedAt: v.string() })),
189
+ // Mirrors BatchRerunDeferred (runs.types.ts).
190
+ deferred: v.array(v.looseObject({ testId: v.string(), reason: v.string() })),
191
+ // Mirrors BatchRerunConflict (runs.types.ts).
192
+ conflicts: v.array(v.looseObject({ testId: v.string(), currentRunId: v.string() })),
193
+ // Mirrors BatchRerunClosure / BatchRerunClosureByProject (runs.types.ts).
194
+ closure: v.looseObject({
195
+ byProject: v.array(v.looseObject({
196
+ projectId: v.string(),
197
+ testIds: v.array(v.string()),
198
+ addedProducers: v.array(v.string()),
199
+ addedTeardowns: v.array(v.string()),
200
+ clearedCaptured: v.number(),
201
+ })),
202
+ }),
203
+ // Optional on the wire for back-compat with older backends (D2-CLI).
204
+ notFound: v.optional(v.array(v.string())),
205
+ // Absent on every response except a V3-routed batch containing at least
206
+ // one FE test with an explicit autoHeal:false opt-out. Same resilience
207
+ // rule as RERUN_RESPONSE_SCHEMA.advisories above.
208
+ advisories: v.optional(v.array(RERUN_ADVISORY_SCHEMA)),
209
+ });
210
+ // ---------------------------------------------------------------------------
211
+ // POST /tests/batch/run
212
+ // ---------------------------------------------------------------------------
213
+ /** Mirrors `BatchRunFreshResponse` (runs.types.ts): `POST /tests/batch/run`. */
214
+ export const BATCH_RUN_FRESH_RESPONSE_SCHEMA = v.looseObject({
215
+ // Mirrors BatchRunFreshAccepted (runs.types.ts); dashboardUrl is
216
+ // client-synthesized, tolerated as optional.
217
+ accepted: v.array(v.looseObject({
218
+ testId: v.string(),
219
+ runId: v.string(),
220
+ enqueuedAt: v.string(),
221
+ dashboardUrl: v.optional(v.string()),
222
+ })),
223
+ conflicts: v.array(v.looseObject({ testId: v.string() })),
224
+ deferred: v.array(v.looseObject({ testId: v.string() })),
225
+ skippedFrontend: v.array(v.string()),
226
+ skippedIntegration: v.array(v.looseObject({ testId: v.string() })),
227
+ });
228
+ // ---------------------------------------------------------------------------
229
+ // GET /tests/{testId}/runs
230
+ // ---------------------------------------------------------------------------
231
+ /** Mirrors `RunHistoryItem` (runs.types.ts): one run-history row. */
232
+ const RUN_HISTORY_ITEM_SCHEMA = v.looseObject({
233
+ runId: v.string(),
234
+ status: openWireLiteral(),
235
+ source: openWireLiteral(),
236
+ isRerun: v.boolean(),
237
+ createdFrom: v.nullish(v.string(), null),
238
+ createdAt: v.string(),
239
+ startedAt: v.nullish(v.string(), null),
240
+ finishedAt: v.nullish(v.string(), null),
241
+ // Nullable on the wire (`RunHistoryRow.codeVersion` is `[string, 'null']`).
242
+ codeVersion: v.nullish(v.string(), null),
243
+ failureKind: v.nullish(v.string(), null),
244
+ // G1b fields: optional on the wire for back-compat with older backends.
245
+ targetUrl: v.optional(v.nullable(v.string())),
246
+ targetUrlSource: v.optional(v.nullable(openWireLiteral())),
247
+ });
248
+ /** Mirrors `ListRunsResponse` (runs.types.ts): `GET /tests/{testId}/runs`. */
249
+ export const LIST_RUNS_RESPONSE_SCHEMA = v.looseObject({
250
+ runs: v.array(RUN_HISTORY_ITEM_SCHEMA),
251
+ nextCursor: v.nullish(v.string(), null),
252
+ // Mirrors RunHistoryMeta (runs.types.ts): every field optional, and the
253
+ // history command reads `resp.meta.note` / `resp.meta.portalUrl` directly,
254
+ // so the container itself stays required like the interface declares.
255
+ meta: v.looseObject({
256
+ testKind: v.optional(openWireLiteral()),
257
+ historyStartsAt: v.optional(v.string()),
258
+ note: v.optional(v.string()),
259
+ portalUrl: v.optional(v.string()),
260
+ }),
261
+ });
262
+ /** Mirrors `CliOrgSummary` (lib/org-render.ts): one `Me.organizations[]` entry. */
263
+ const ORG_SUMMARY_SCHEMA = v.looseObject({
264
+ id: v.string(),
265
+ name: v.string(),
266
+ role: v.string(),
267
+ isPersonal: v.boolean(),
268
+ });
269
+ /** Mirrors `CliOrgBinding` (lib/org-render.ts): `Me.org`. */
270
+ const ORG_BINDING_SCHEMA = v.looseObject({
271
+ id: v.string(),
272
+ name: v.nullable(v.string()),
273
+ role: v.string(),
274
+ });
275
+ /** Mirrors `MeIdentity` (commands/doctor.ts): `GET /api/cli/v1/me` core. */
276
+ export const ME_IDENTITY_SCHEMA = v.looseObject({
277
+ userId: v.optional(v.string()),
278
+ keyId: v.optional(v.string()),
279
+ organizations: v.optional(v.array(ORG_SUMMARY_SCHEMA)),
280
+ org: v.optional(ORG_BINDING_SCHEMA),
281
+ });
282
+ //# sourceMappingURL=response-schemas.js.map