@testsprite/testsprite-cli 0.12.0 → 0.13.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 (91) hide show
  1. package/README.md +11 -4
  2. package/dist/commands/agent.js +16 -13
  3. package/dist/commands/auth.d.ts +19 -0
  4. package/dist/commands/auth.js +60 -24
  5. package/dist/commands/ci.d.ts +86 -1
  6. package/dist/commands/ci.js +436 -5
  7. package/dist/commands/doctor.d.ts +2 -0
  8. package/dist/commands/doctor.js +22 -9
  9. package/dist/commands/init.js +14 -11
  10. package/dist/commands/project-env.js +9 -9
  11. package/dist/commands/project.d.ts +5 -5
  12. package/dist/commands/project.js +42 -42
  13. package/dist/commands/schedule.d.ts +2 -0
  14. package/dist/commands/schedule.js +18 -10
  15. package/dist/commands/test.d.ts +73 -27
  16. package/dist/commands/test.js +1756 -413
  17. package/dist/commands/testlist.js +49 -19
  18. package/dist/commands/tunnel.d.ts +26 -3
  19. package/dist/commands/tunnel.js +211 -14
  20. package/dist/commands/usage.d.ts +3 -0
  21. package/dist/commands/usage.js +12 -5
  22. package/dist/index.js +34 -20
  23. package/dist/lib/agent-targets.d.ts +3 -3
  24. package/dist/lib/agent-targets.js +2 -2
  25. package/dist/lib/billing-refusal.d.ts +43 -0
  26. package/dist/lib/billing-refusal.js +171 -0
  27. package/dist/lib/bundle.d.ts +5 -0
  28. package/dist/lib/bundle.js +43 -13
  29. package/dist/lib/ci-linkage.d.ts +90 -0
  30. package/dist/lib/ci-linkage.js +181 -0
  31. package/dist/lib/client-factory.d.ts +4 -1
  32. package/dist/lib/client-factory.js +23 -2
  33. package/dist/lib/config.d.ts +17 -0
  34. package/dist/lib/config.js +20 -1
  35. package/dist/lib/conflict-reason.d.ts +27 -3
  36. package/dist/lib/conflict-reason.js +53 -4
  37. package/dist/lib/credentials.js +56 -14
  38. package/dist/lib/dry-run/samples.d.ts +13 -1
  39. package/dist/lib/dry-run/samples.js +51 -7
  40. package/dist/lib/errors.d.ts +18 -11
  41. package/dist/lib/errors.js +111 -13
  42. package/dist/lib/failing-fe-resolver.d.ts +1 -1
  43. package/dist/lib/failing-fe-resolver.js +3 -3
  44. package/dist/lib/gh-output.d.ts +1 -0
  45. package/dist/lib/gh-output.js +13 -4
  46. package/dist/lib/history-retention.d.ts +8 -0
  47. package/dist/lib/history-retention.js +24 -0
  48. package/dist/lib/http.d.ts +37 -19
  49. package/dist/lib/http.js +46 -24
  50. package/dist/lib/interrupt.d.ts +21 -13
  51. package/dist/lib/interrupt.js +32 -21
  52. package/dist/lib/junit-report.d.ts +11 -1
  53. package/dist/lib/junit-report.js +15 -3
  54. package/dist/lib/local-target.d.ts +1 -1
  55. package/dist/lib/local-target.js +1 -1
  56. package/dist/lib/plan-poll.d.ts +11 -11
  57. package/dist/lib/plan-poll.js +12 -12
  58. package/dist/lib/plans.types.d.ts +9 -9
  59. package/dist/lib/plans.types.js +3 -3
  60. package/dist/lib/poll.d.ts +2 -2
  61. package/dist/lib/poll.js +9 -3
  62. package/dist/lib/render-error.d.ts +2 -0
  63. package/dist/lib/render-error.js +13 -0
  64. package/dist/lib/response-schemas.d.ts +54 -12
  65. package/dist/lib/response-schemas.js +88 -7
  66. package/dist/lib/runs.types.d.ts +59 -10
  67. package/dist/lib/secret-file.js +72 -14
  68. package/dist/lib/skill-nudge.d.ts +6 -1
  69. package/dist/lib/skill-nudge.js +32 -5
  70. package/dist/lib/target-url-preflight.d.ts +6 -4
  71. package/dist/lib/target-url-preflight.js +64 -51
  72. package/dist/lib/target-url.js +6 -6
  73. package/dist/lib/telemetry.d.ts +4 -1
  74. package/dist/lib/telemetry.js +13 -13
  75. package/dist/lib/ticker.js +93 -4
  76. package/dist/lib/tunnel-session.d.ts +13 -0
  77. package/dist/lib/tunnel-session.js +4 -1
  78. package/dist/lib/tunnel.types.d.ts +12 -2
  79. package/dist/lib/tunnel.types.js +2 -2
  80. package/dist/lib/wait-exit.d.ts +8 -0
  81. package/dist/lib/wait-exit.js +76 -4
  82. package/dist/lib/workspace-status.d.ts +23 -0
  83. package/dist/lib/workspace-status.js +15 -0
  84. package/dist/version-guard.d.ts +7 -1
  85. package/dist/version-guard.js +19 -1
  86. package/dist/version.d.ts +1 -1
  87. package/dist/version.js +1 -1
  88. package/package.json +4 -4
  89. package/skills/testsprite-onboard.skill.md +4 -4
  90. package/skills/testsprite-verify.codex.md +59 -57
  91. package/skills/testsprite-verify.skill.md +53 -38
@@ -3,6 +3,7 @@ import { rename, stat, unlink } from 'node:fs/promises';
3
3
  import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
4
4
  import { randomUUID } from 'node:crypto';
5
5
  import { localValidationError, TransportError } from './errors.js';
6
+ import { isNonDispatchedStatus } from './gh-output.js';
6
7
  /**
7
8
  * Duration in seconds between two ISO timestamps, or `undefined` when either is
8
9
  * missing / unparseable / negative (clock skew). Kept ≥ 0.
@@ -84,7 +85,7 @@ export function escapeXml(text) {
84
85
  function classifyJUnitOutcome(status, error) {
85
86
  if (status === 'passed')
86
87
  return 'passed';
87
- if (status === 'skipped')
88
+ if (isNonDispatchedStatus(status))
88
89
  return 'skipped';
89
90
  if (status === 'error' || error?.exitCode === 3)
90
91
  return 'error';
@@ -136,13 +137,13 @@ function renderTestcase(result, classname) {
136
137
  lines.push(` <error message="${message}" type="${type}">${body}</error>`);
137
138
  }
138
139
  else if (outcome === 'skipped') {
139
- lines.push(` <skipped/>`);
140
+ lines.push(` <skipped message="${escapeXml(result.skipReason ?? failureMessage(result))}"/>`);
140
141
  }
141
142
  lines.push(' </testcase>');
142
143
  return lines.join('\n');
143
144
  }
144
145
  /**
145
- * Build a JUnit XML document from batch poll results. Per-`testcase` `time` is
146
+ * Build a JUnit XML document from batch results, including skipped members. Per-`testcase` `time` is
146
147
  * the run's wall-clock duration (from `startedAt`/`finishedAt`); the `testsuite`
147
148
  * `time` is their sum. `time` falls back to `0` for a run with no timing.
148
149
  */
@@ -176,6 +177,17 @@ export function buildJUnitReport(opts) {
176
177
  '',
177
178
  ].join('\n');
178
179
  }
180
+ /**
181
+ * The summary's non-dispatched rows (deferred / conflict / not-found) as
182
+ * skipped JUnit results. Accepted rows carry run statuses and never match
183
+ * `isNonDispatchedStatus`, so the filter alone separates the two without
184
+ * relying on row order.
185
+ */
186
+ export function skippedJUnitResultsFromSummary(summary) {
187
+ return summary.runs
188
+ .filter(row => isNonDispatchedStatus(row.status))
189
+ .map(row => ({ testId: row.testId, status: 'skipped', skipReason: row.error ?? row.status }));
190
+ }
179
191
  async function assertReportFileParent(rawPath) {
180
192
  if (typeof rawPath !== 'string' || rawPath.length === 0) {
181
193
  throw localValidationError('report-file', 'must be a non-empty file path');
@@ -113,7 +113,7 @@ export declare function probeLocalPort(host: string, port: number, deps?: LocalP
113
113
  /**
114
114
  * Run {@link probeLocalPort} and either throw (refuse) or no-op (ok / skipped).
115
115
  *
116
- * Call this BEFORE minting a tunnel. That ordering is the feature: DEV-243
116
+ * Call this BEFORE minting a tunnel. That ordering is the feature: telemetry
117
117
  * measured 1,003 blocked-with-URL CLI runs, 55.5% of the third-party-tunnel
118
118
  * ones blocked, every one of them charged, because the run row and its credit
119
119
  * spend happen before the Lambda ever discovers the target is dead. A dev
@@ -226,7 +226,7 @@ const SKIP_HINT = 'Skip this check with --skip-preflight.';
226
226
  /**
227
227
  * Run {@link probeLocalPort} and either throw (refuse) or no-op (ok / skipped).
228
228
  *
229
- * Call this BEFORE minting a tunnel. That ordering is the feature: DEV-243
229
+ * Call this BEFORE minting a tunnel. That ordering is the feature: telemetry
230
230
  * measured 1,003 blocked-with-URL CLI runs, 55.5% of the third-party-tunnel
231
231
  * ones blocked, every one of them charged, because the run row and its credit
232
232
  * spend happen before the Lambda ever discovers the target is dead. A dev
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Generation-ladder driver for `test plan generate` (DEV-384 V3-B).
2
+ * Generation-ladder driver for `test plan generate`.
3
3
  *
4
4
  * This is a NEW loop, deliberately not a reuse of `poll.ts`: the run poller
5
5
  * is hard-typed to runs (its `RunClient` contract, `isTerminalStatus` check,
@@ -14,7 +14,7 @@
14
14
  * - **The shutdown handle is armed here** for the whole ladder (first POST
15
15
  * included). Arm/disarm lives inside the run poller, not for free in the
16
16
  * harness — without arming, Ctrl-C during a generate wait would hard-kill
17
- * the process instead of running the honest-detach UX (DEV-331).
17
+ * the process instead of running the honest-detach UX.
18
18
  * - Long-poll preferred (`?waitSeconds = min(remaining, 25)`), with a
19
19
  * plain-GET + fixed-sleep fallback when the server rejects `waitSeconds`
20
20
  * with VALIDATION_ERROR (older deployment).
@@ -27,7 +27,7 @@
27
27
  * a single `.any()` per session (it still calls it); only http.ts
28
28
  * eliminated it outright (`composeAbortSignals`). This module composes
29
29
  * explicitly, like http.ts — don't go hunting for a poll.ts replacement
30
- * that isn't there (DEV-384 review F12).
30
+ * that isn't there.
31
31
  * A hung fetch can never overrun `--timeout` and an interrupt aborts the
32
32
  * in-flight request instantly.
33
33
  * - Every sleep is clamped to the remaining deadline and bails on interrupt.
@@ -102,7 +102,7 @@ export interface PlanLadderOptions {
102
102
  /** Injectable sleep (tests use an instant fake). */
103
103
  sleep?: (ms: number) => Promise<void>;
104
104
  /**
105
- * Graceful-detach coordinator (DEV-331). The ladder arms it for its whole
105
+ * Graceful-detach coordinator. The ladder arms it for its whole
106
106
  * duration; a SIGINT/SIGTERM surfaces as `InterruptError` out of this
107
107
  * function and the caller renders the honest detach.
108
108
  */
@@ -133,11 +133,11 @@ export interface PlanLadderResult {
133
133
  /** How many trigger POSTs were accepted (stages this invocation started). */
134
134
  acceptedPosts: number;
135
135
  /**
136
- * DEV-1008 — `skippedCategories` from the accepted trigger that carried it
137
- * (the proposals rung), or `null` when no accepted trigger did. Read from
138
- * the LAST such trigger, not `firstTrigger`: on a fresh backend project
139
- * the first accepted POST starts strategy, and the field rides only on
140
- * the proposals POST that follows.
136
+ * `skippedCategories` from the accepted trigger that carried it (the
137
+ * proposals rung), or `null` when no accepted trigger did. Read from the
138
+ * LAST such trigger, not `firstTrigger`: on a fresh backend project the
139
+ * first accepted POST starts strategy, and the field rides only on the
140
+ * proposals POST that follows.
141
141
  */
142
142
  skippedCategories: number | null;
143
143
  }
@@ -151,8 +151,8 @@ export declare const MAX_ACCEPTED_TRIGGER_POSTS: 3;
151
151
  /**
152
152
  * Companion cap on TOTAL trigger POSTs (attaches included), so an
153
153
  * attach-dominated pathological sequence also fails fast instead of
154
- * silently burning the whole `--timeout` (DEV-384 review): the accepted
155
- * rungs + headroom for an attach per rung.
154
+ * silently burning the whole `--timeout`: the accepted rungs + headroom for
155
+ * an attach per rung.
156
156
  */
157
157
  export declare const MAX_TRIGGER_POSTS_TOTAL: number;
158
158
  /**
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Generation-ladder driver for `test plan generate` (DEV-384 V3-B).
2
+ * Generation-ladder driver for `test plan generate`.
3
3
  *
4
4
  * This is a NEW loop, deliberately not a reuse of `poll.ts`: the run poller
5
5
  * is hard-typed to runs (its `RunClient` contract, `isTerminalStatus` check,
@@ -14,7 +14,7 @@
14
14
  * - **The shutdown handle is armed here** for the whole ladder (first POST
15
15
  * included). Arm/disarm lives inside the run poller, not for free in the
16
16
  * harness — without arming, Ctrl-C during a generate wait would hard-kill
17
- * the process instead of running the honest-detach UX (DEV-331).
17
+ * the process instead of running the honest-detach UX.
18
18
  * - Long-poll preferred (`?waitSeconds = min(remaining, 25)`), with a
19
19
  * plain-GET + fixed-sleep fallback when the server rejects `waitSeconds`
20
20
  * with VALIDATION_ERROR (older deployment).
@@ -27,7 +27,7 @@
27
27
  * a single `.any()` per session (it still calls it); only http.ts
28
28
  * eliminated it outright (`composeAbortSignals`). This module composes
29
29
  * explicitly, like http.ts — don't go hunting for a poll.ts replacement
30
- * that isn't there (DEV-384 review F12).
30
+ * that isn't there.
31
31
  * A hung fetch can never overrun `--timeout` and an interrupt aborts the
32
32
  * in-flight request instantly.
33
33
  * - Every sleep is clamped to the remaining deadline and bails on interrupt.
@@ -98,8 +98,8 @@ export const MAX_ACCEPTED_TRIGGER_POSTS = PLAN_GENERATION_STAGES.length;
98
98
  /**
99
99
  * Companion cap on TOTAL trigger POSTs (attaches included), so an
100
100
  * attach-dominated pathological sequence also fails fast instead of
101
- * silently burning the whole `--timeout` (DEV-384 review): the accepted
102
- * rungs + headroom for an attach per rung.
101
+ * silently burning the whole `--timeout`: the accepted rungs + headroom for
102
+ * an attach per rung.
103
103
  */
104
104
  export const MAX_TRIGGER_POSTS_TOTAL = PLAN_GENERATION_STAGES.length * 2;
105
105
  /**
@@ -206,10 +206,10 @@ async function ladderLoop(client, projectId, options) {
206
206
  }
207
207
  };
208
208
  const doTrigger = async () => {
209
- // Fresh idempotency namespace per POST attempt — ATTACHES INCLUDED
210
- // (DEV-384 review): a 409's key is never committed server-side, but
211
- // reusing it would silently depend on that; a fresh key never can.
212
- // Transport-level retries inside one POST still share the header.
209
+ // Fresh idempotency namespace per POST attempt — ATTACHES INCLUDED: a
210
+ // 409's key is never committed server-side, but reusing it would
211
+ // silently depend on that; a fresh key never can. Transport-level
212
+ // retries inside one POST still share the header.
213
213
  const key = state.triggerPosts === 0
214
214
  ? options.idempotencyKey
215
215
  : `${options.idempotencyKey}:post${state.triggerPosts + 1}`;
@@ -312,8 +312,8 @@ async function ladderLoop(client, projectId, options) {
312
312
  if (isActiveGenerationStatus(status)) {
313
313
  state.observedActiveSinceTrigger = true;
314
314
  // Seeing the proposals stage RUN arms billing guard #1 regardless of
315
- // who started it (DEV-384 review — the 409-attach path has no trigger
316
- // response to arm it from).
315
+ // who started it — the 409-attach path has no trigger response to
316
+ // arm it from.
317
317
  if (status === 'proposing')
318
318
  state.proposalsObserved = true;
319
319
  state.consecutiveIdleGaps = 0;
@@ -341,7 +341,7 @@ async function ladderLoop(client, projectId, options) {
341
341
  // waitSeconds hold for an ACTIVE generation status (`getPlans` guards
342
342
  // its wait loop with `waitSeconds && isActiveGenerationStatus(...)`),
343
343
  // so an idle read returns immediately and an unpaced loop here would
344
- // hammer the facade (DEV-384 review F13).
344
+ // hammer the facade.
345
345
  //
346
346
  // Billing guard #1: once the proposals rung is known to have started —
347
347
  // our own trigger said so (`stagesRemaining: []`) OR we watched it run
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Wire types for the DEV-384 plan-generation surface:
2
+ * Wire types for the plan-generation surface:
3
3
  *
4
4
  * `POST /api/cli/v1/projects/{id}/plans/generate` — start the next missing
5
5
  * pipeline stage (202)
@@ -9,8 +9,8 @@
9
9
  * `POST /api/cli/v1/projects/{id}/plans/accept` — staged proposals → real
10
10
  * test cases
11
11
  *
12
- * These mirror the backend facade's `cli-plans.types.ts` (V3-A) shape-for-
13
- * shape. The generation `status` is FACADE-SYNTHESIZED — no such enum exists
12
+ * These mirror the backend facade's `cli-plans.types.ts` shape-for-shape.
13
+ * The generation `status` is FACADE-SYNTHESIZED — no such enum exists
14
14
  * on the V3 pipeline itself (design-doc v3.1 §7, DR-31) — so the CLI treats
15
15
  * it as the complete truth and never tries to derive state from anything
16
16
  * else.
@@ -108,12 +108,12 @@ export interface CliGeneratePlansResponse {
108
108
  stagesRemaining: CliGenerationStage[];
109
109
  enqueuedAt: string;
110
110
  /**
111
- * DEV-1008 — `stage: proposals` on a backend project only. Strategy
112
- * categories the proposals stage was NOT asked for because they carry no
113
- * endpoint to attach a test case to (cross-cutting themes such as
114
- * authorization or pagination). Absent when nothing was skipped and on
115
- * every other stage. The stage is charged flat, so this is the only
116
- * signal that the plan covers fewer categories than the strategy lists.
111
+ * `stage: proposals` on a backend project only. Strategy categories the
112
+ * proposals stage was NOT asked for because they carry no endpoint to
113
+ * attach a test case to (cross-cutting themes such as authorization or
114
+ * pagination). Absent when nothing was skipped and on every other stage.
115
+ * The stage is charged flat, so this is the only signal that the plan
116
+ * covers fewer categories than the strategy lists.
117
117
  */
118
118
  skippedCategories?: number;
119
119
  }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Wire types for the DEV-384 plan-generation surface:
2
+ * Wire types for the plan-generation surface:
3
3
  *
4
4
  * `POST /api/cli/v1/projects/{id}/plans/generate` — start the next missing
5
5
  * pipeline stage (202)
@@ -9,8 +9,8 @@
9
9
  * `POST /api/cli/v1/projects/{id}/plans/accept` — staged proposals → real
10
10
  * test cases
11
11
  *
12
- * These mirror the backend facade's `cli-plans.types.ts` (V3-A) shape-for-
13
- * shape. The generation `status` is FACADE-SYNTHESIZED — no such enum exists
12
+ * These mirror the backend facade's `cli-plans.types.ts` shape-for-shape.
13
+ * The generation `status` is FACADE-SYNTHESIZED — no such enum exists
14
14
  * on the V3 pipeline itself (design-doc v3.1 §7, DR-31) — so the CLI treats
15
15
  * it as the complete truth and never tries to derive state from anything
16
16
  * else.
@@ -61,7 +61,7 @@ export interface PollOptions {
61
61
  * Lets the caller resolve a terminal `RunResponse` from an alternate
62
62
  * source when the run-surface row itself will never finalize.
63
63
  *
64
- * The motivating case (dogfood L1888): backend-test run rows are written
64
+ * The motivating case: backend-test run rows are written
65
65
  * `queued` then orphaned server-side (`finalizeRun` is FE-only), so the
66
66
  * run-row poll would always hit `--timeout` → exit 7 even on a passing BE
67
67
  * test. The handler supplies a fallback that reads the testId-scoped
@@ -78,7 +78,7 @@ export interface PollOptions {
78
78
  */
79
79
  resolveAlternate?: (run: RunResponse, elapsedMs: number, signal: AbortSignal) => Promise<RunResponse | null>;
80
80
  /**
81
- * Graceful-detach coordinator (DEV-331 piece 1). While the poll runs, the
81
+ * Graceful-detach coordinator. While the poll runs, the
82
82
  * scope is armed: a SIGINT/SIGTERM aborts `shutdown.signal` with an
83
83
  * `InterruptError` instead of killing the process, and this loop surfaces
84
84
  * it immediately — the in-flight long-poll fetch aborts (composed into the
package/dist/lib/poll.js CHANGED
@@ -46,13 +46,19 @@ const BACKOFF_SCHEDULE_MS = [2000, 4000, 8000, 15000];
46
46
  * and unrecoverable server errors.
47
47
  */
48
48
  export async function pollRunUntilTerminal(client, runId, options) {
49
- // Arm the graceful-detach scope for the duration of the poll (DEV-331):
49
+ // Arm the graceful-detach scope for the duration of the poll:
50
50
  // while armed, a termination signal aborts instead of hard-killing the
51
51
  // process, and the wait-path catch blocks own the honest detach UX.
52
52
  const disarm = options.shutdown?.arm();
53
53
  try {
54
54
  return await pollLoop(client, runId, options);
55
55
  }
56
+ catch (err) {
57
+ if (err instanceof InterruptError && options.shutdown?.signal.aborted) {
58
+ err.runWaitContext = true;
59
+ }
60
+ throw err;
61
+ }
56
62
  finally {
57
63
  disarm?.();
58
64
  }
@@ -225,11 +231,11 @@ async function pollIterations(client, runId, options, ctx) {
225
231
  }
226
232
  // Non-terminal run tick. Give the caller a chance to resolve a terminal
227
233
  // verdict from an alternate source (e.g. the backend testId-scoped
228
- // result when the run-surface row never finalizes — dogfood L1888).
234
+ // result when the run-surface row never finalizes).
229
235
  if (resolveAlternate) {
230
236
  // Bound the alternate lookup by the REMAINING --timeout (not the much
231
237
  // larger per-request HTTP timeout) so a stalled fallback read can't
232
- // overrun the user's deadline (codex round-2).
238
+ // overrun the user's deadline.
233
239
  const altRemainingMs = deadlineMs - Date.now();
234
240
  if (altRemainingMs <= 0) {
235
241
  throw new TimeoutError(runId, timeoutSeconds);
@@ -39,4 +39,6 @@ export declare function renderCommanderError(pendingMsg: string | null, fallback
39
39
  * shape change must never crash the CLI's error path.
40
40
  */
41
41
  export declare function renderAmbiguousOrgCandidates(candidates: unknown): string[];
42
+ /** Text-mode recovery handles for the account's tunnel binding limit. */
43
+ export declare function renderTunnelBindingLimitIds(details: unknown): string[];
42
44
  export declare function rephraseUnknownOption(raw: string): string | null;
@@ -80,6 +80,19 @@ export function renderAmbiguousOrgCandidates(candidates) {
80
80
  lines.push(' hint: re-run with --project <id> to disambiguate.');
81
81
  return lines;
82
82
  }
83
+ /** Text-mode recovery handles for the account's tunnel binding limit. */
84
+ export function renderTunnelBindingLimitIds(details) {
85
+ if (!Array.isArray(details))
86
+ return [];
87
+ const ids = details.filter((value) => typeof value === 'string');
88
+ if (ids.length === 0)
89
+ return [];
90
+ const lines = ids.slice(0, 20).map(id => ` tunnel: ${id}`);
91
+ if (ids.length > 20)
92
+ lines.push(` … and ${ids.length - 20} more`);
93
+ lines.push(' hint: testsprite tunnel list · testsprite tunnel stop <client-id> · testsprite tunnel stop --all --confirm');
94
+ return lines;
95
+ }
83
96
  export function rephraseUnknownOption(raw) {
84
97
  // Commander emits: "error: unknown option '--foo'"
85
98
  const match = /unknown option\s+'--([^']+)'/.exec(raw);
@@ -1,14 +1,15 @@
1
1
  /**
2
- * Valibot schemas for the run-path wire shapes (issue #102).
2
+ * Valibot schemas for the API wire shapes (issue #102, extended by #277).
3
3
  *
4
4
  * `requestWithMeta` used to return `(await response.json()) as T` with zero
5
5
  * runtime validation, so a drifted or partial server response surfaced as
6
6
  * `undefined` output or an opaque TypeError deep inside a command. These
7
7
  * schemas are wired (opt-in, via `RequestOptions.schema`) into the typed
8
- * HttpClient helpers only: `triggerRun`, `triggerRunWithMeta`, `triggerRerun`,
8
+ * HttpClient helpers `triggerRun`, `triggerRunWithMeta`, `triggerRerun`,
9
9
  * `triggerBatchRerun`, `triggerBatchRunFresh`, `getRun`, `listTestRuns`,
10
- * `cancelRun`.
11
- * The generic `get`/`post`/`put`/`patch`/`delete` paths stay schema-free.
10
+ * `cancelRun`, and — for the account surfaces below — the `client.get` call
11
+ * sites that own a `/me` or usage read. Every other generic
12
+ * `get`/`post`/`put`/`patch`/`delete` caller stays schema-free and opt-in.
12
13
  *
13
14
  * Resilience rules (additive server changes must never hard-fail the CLI):
14
15
  *
@@ -33,9 +34,11 @@
33
34
  * interface it mirrors, so schema/interface drift fails `tsc` in this file.
34
35
  */
35
36
  import * as v from 'valibot';
37
+ import type { MeResponse } from '../commands/auth.js';
38
+ import type { UsageResponse } from '../commands/usage.js';
36
39
  import type { BatchRerunResponse, BatchRunFreshResponse, CancelRunResponse, ListRunsResponse, RerunResponse, RunResponse, TriggerRunResponse } from './runs.types.js';
37
40
  import type { CliTestListRunResponse } from './testlist.types.js';
38
- import type { TunnelMintResponse, TunnelStatusResponse } from './tunnel.types.js';
41
+ import type { TunnelListResponse, TunnelMintResponse, TunnelStatusResponse } from './tunnel.types.js';
39
42
  /** Mirrors `RunResponse` (runs.types.ts): `GET /api/cli/v1/runs/{runId}`. */
40
43
  export declare const RUN_RESPONSE_SCHEMA: v.GenericSchema<unknown, RunResponse>;
41
44
  /** Mirrors `CancelRunResponse` (runs.types.ts): the run envelope plus cancel metadata. */
@@ -57,17 +60,23 @@ export declare const TESTLIST_RUN_RESPONSE_SCHEMA: v.GenericSchema<unknown, CliT
57
60
  /** Mirrors `ListRunsResponse` (runs.types.ts): `GET /tests/{testId}/runs`. */
58
61
  export declare const LIST_RUNS_RESPONSE_SCHEMA: v.GenericSchema<unknown, ListRunsResponse>;
59
62
  /**
60
- * Minimal `/me` identity core shared by its consumers. `doctor` reads a
61
- * two-field optional projection (`MeIdentity` in commands/doctor.ts) while
62
- * `auth whoami` reads the full `MeResponse` (commands/auth.ts); this schema
63
- * validates the common identity core so it can guard either caller, and
64
- * `looseObject` lets the full projection (scopes, env, email, ...) pass
65
- * through untouched. Not wired into any typed helper yet: `/me` callers use
66
- * the generic `get`, which stays schema-free in this change.
63
+ * Minimal `/me` identity core, as read by `doctor`'s connectivity check.
64
+ *
65
+ * `doctor` deliberately treats every field as optional: the check only needs
66
+ * "the key was accepted", and it decorates the detail line with the userId
67
+ * *when present* (`me.userId ? ...`). Fixture evidence for keeping it fully
68
+ * optional rather than reusing {@link ME_RESPONSE_SCHEMA}: `OK_ME` in
69
+ * `commands/doctor.test.ts` is `{ userId, keyId }` with no `scopes`/`env`, and
70
+ * a connectivity probe must not fail on a partial identity projection.
71
+ *
72
+ * `commands/doctor.ts` aliases its `MeIdentity` to this type so the two cannot
73
+ * drift (they already had: `v3Enabled` existed on the command side only).
67
74
  */
68
75
  export interface MeIdentityWire {
69
76
  userId?: string;
70
77
  keyId?: string;
78
+ /** Authoritative per-user V3 routing bit; older backends omit it. */
79
+ v3Enabled?: boolean;
71
80
  /**
72
81
  * Account-wide organization membership list (mirrors `CliOrgSummary` in
73
82
  * `lib/org-render.ts`). Optional/absent-safe: omitted on a server-side
@@ -92,6 +101,37 @@ export interface MeIdentityWire {
92
101
  }
93
102
  /** Mirrors `MeIdentity` (commands/doctor.ts): `GET /api/cli/v1/me` core. */
94
103
  export declare const ME_IDENTITY_SCHEMA: v.GenericSchema<unknown, MeIdentityWire>;
104
+ /**
105
+ * Mirrors `MeResponse` (commands/auth.ts): the full `GET /me` projection read
106
+ * by `auth whoami` (and, through it, `init`).
107
+ *
108
+ * `scopes` is required and array-typed on purpose — this is the shape drift
109
+ * that actually bites today. `runWhoami` renders `m.scopes.join(', ')` and
110
+ * computes `missingScopes` via `m.scopes.includes(...)` with no guard, so a
111
+ * `/me` body without `scopes` crashes with a raw `TypeError` (exit 1) instead
112
+ * of a typed envelope. Every `/me` fixture in the suite supplies it
113
+ * (`auth.test.ts`, `init.test.ts`, `usage.test.ts`, `cli.subprocess.test.ts`,
114
+ * `test/mock-backend/fixtures.ts`), so requiring it matches observed wire
115
+ * reality; `email` / `displayName` / `v3Enabled` are the genuinely absent-safe
116
+ * ones and stay `v.optional` with no default (rule 3, optional branch).
117
+ *
118
+ * `init` calls this through `runWhoami` inside a try/catch that falls back to
119
+ * a placeholder identity, so a drifted `/me` degrades the setup summary
120
+ * instead of failing the whole `init`.
121
+ */
122
+ export declare const ME_RESPONSE_SCHEMA: v.GenericSchema<unknown, MeResponse>;
123
+ /**
124
+ * Mirrors `UsageResponse` (commands/usage.ts): the credits/plan projection the
125
+ * `usage` command reads off the same `GET /me` body.
126
+ *
127
+ * `renderUsage` prints `userId`/`keyId`/`env` unconditionally as its "identity
128
+ * block", so those three are required; `credits`, `subPlan` and
129
+ * `creditsPerRun` are forward-compat fields the backend does not send today
130
+ * (see the BACKEND FOLLOW-UP note in usage.ts) and every renderer branch is
131
+ * gated on `!== undefined`, so they stay optional with no default. `scopes`
132
+ * rides along as an unknown extra key and is preserved by `looseObject`.
133
+ */
134
+ export declare const USAGE_RESPONSE_SCHEMA: v.GenericSchema<unknown, UsageResponse>;
95
135
  /**
96
136
  * Mirrors `TunnelMintResponse` (tunnel.types.ts): `POST /tunnel`.
97
137
  *
@@ -104,3 +144,5 @@ export declare const ME_IDENTITY_SCHEMA: v.GenericSchema<unknown, MeIdentityWire
104
144
  export declare const TUNNEL_MINT_RESPONSE_SCHEMA: v.GenericSchema<unknown, TunnelMintResponse>;
105
145
  /** Mirrors `TunnelStatusResponse` (tunnel.types.ts): `GET /tunnel/{clientId}`. */
106
146
  export declare const TUNNEL_STATUS_RESPONSE_SCHEMA: v.GenericSchema<unknown, TunnelStatusResponse>;
147
+ /** Mirrors `TunnelListResponse`: a server may add status values or omit creation time. */
148
+ export declare const TUNNEL_LIST_RESPONSE_SCHEMA: v.GenericSchema<unknown, TunnelListResponse>;
@@ -1,14 +1,15 @@
1
1
  /**
2
- * Valibot schemas for the run-path wire shapes (issue #102).
2
+ * Valibot schemas for the API wire shapes (issue #102, extended by #277).
3
3
  *
4
4
  * `requestWithMeta` used to return `(await response.json()) as T` with zero
5
5
  * runtime validation, so a drifted or partial server response surfaced as
6
6
  * `undefined` output or an opaque TypeError deep inside a command. These
7
7
  * schemas are wired (opt-in, via `RequestOptions.schema`) into the typed
8
- * HttpClient helpers only: `triggerRun`, `triggerRunWithMeta`, `triggerRerun`,
8
+ * HttpClient helpers `triggerRun`, `triggerRunWithMeta`, `triggerRerun`,
9
9
  * `triggerBatchRerun`, `triggerBatchRunFresh`, `getRun`, `listTestRuns`,
10
- * `cancelRun`.
11
- * The generic `get`/`post`/`put`/`patch`/`delete` paths stay schema-free.
10
+ * `cancelRun`, and — for the account surfaces below — the `client.get` call
11
+ * sites that own a `/me` or usage read. Every other generic
12
+ * `get`/`post`/`put`/`patch`/`delete` caller stays schema-free and opt-in.
12
13
  *
13
14
  * Resilience rules (additive server changes must never hard-fail the CLI):
14
15
  *
@@ -175,6 +176,12 @@ export const TRIGGER_RUN_RESPONSE_SCHEMA = v.looseObject({
175
176
  enqueuedAt: v.string(),
176
177
  codeVersion: v.string(),
177
178
  targetUrl: v.string(),
179
+ // Optional with NO default (rule 3). The default must stay
180
+ // absent: `undefined` here means "this backend predates the field and
181
+ // stripped what we sent", which is precisely what the opt-out advisory
182
+ // keys on. Defaulting it to `false` would make an old backend look like
183
+ // it had honoured `--no-auto-heal`.
184
+ autoHeal: v.optional(v.boolean()),
178
185
  // The run's environment — optional with no default (rule 3, optional branch).
179
186
  environment: OPTIONAL_ENVIRONMENT_SCHEMA,
180
187
  // Server-built portal links (backend ≥ the run-links change). Optional
@@ -239,8 +246,15 @@ export const BATCH_RERUN_RESPONSE_SCHEMA = v.looseObject({
239
246
  accepted: v.array(v.looseObject({ testId: v.string(), runId: v.string(), enqueuedAt: v.string() })),
240
247
  // Mirrors BatchRerunDeferred (runs.types.ts).
241
248
  deferred: v.array(v.looseObject({ testId: v.string(), reason: v.string() })),
242
- // Mirrors BatchRerunConflict (runs.types.ts).
243
- conflicts: v.array(v.looseObject({ testId: v.string(), currentRunId: v.string() })),
249
+ // Mirrors BatchRerunConflict (runs.types.ts). `currentRunId` is optional,
250
+ // as in the two schemas below: a refusal only carries a run id when there
251
+ // is a run to point at.
252
+ conflicts: v.array(v.looseObject({
253
+ testId: v.string(),
254
+ currentRunId: v.optional(v.string()),
255
+ reason: v.optional(v.string()),
256
+ message: v.optional(v.string()),
257
+ })),
244
258
  // Mirrors BatchRerunClosure / BatchRerunClosureByProject (runs.types.ts).
245
259
  closure: v.looseObject({
246
260
  byProject: v.array(v.looseObject({
@@ -263,6 +277,8 @@ export const BATCH_RERUN_RESPONSE_SCHEMA = v.looseObject({
263
277
  // ---------------------------------------------------------------------------
264
278
  /** Mirrors `BatchRunFreshResponse` (runs.types.ts): `POST /tests/batch/run`. */
265
279
  export const BATCH_RUN_FRESH_RESPONSE_SCHEMA = v.looseObject({
280
+ // See TRIGGER_RUN_RESPONSE_SCHEMA; absence carries the same meaning.
281
+ autoHeal: v.optional(v.boolean()),
266
282
  // Mirrors BatchRunFreshAccepted (runs.types.ts); dashboardUrl is
267
283
  // client-synthesized, tolerated as optional.
268
284
  accepted: v.array(v.looseObject({
@@ -285,6 +301,8 @@ export const BATCH_RUN_FRESH_RESPONSE_SCHEMA = v.looseObject({
285
301
  // keeps computing its legacy template for an older backend / the V2 engine;
286
302
  // `null` passes through as a present key meaning "no correct page".
287
303
  dashboardUrl: v.nullish(v.string(), undefined),
304
+ // An exact echo confirms that the backend read the target URL override.
305
+ targetUrl: v.optional(v.string()),
288
306
  });
289
307
  /**
290
308
  * `POST /api/cli/v1/testlist/{listId}/run`. Mirrors the batch-run-fresh shape so
@@ -337,6 +355,10 @@ export const LIST_RUNS_RESPONSE_SCHEMA = v.looseObject({
337
355
  historyStartsAt: v.optional(v.string()),
338
356
  note: v.optional(v.string()),
339
357
  portalUrl: v.optional(v.string()),
358
+ tier: v.optional(v.string()),
359
+ retentionDays: v.optional(v.nullable(v.number())),
360
+ hiddenCount: v.optional(v.number()),
361
+ billingUrl: v.optional(v.string()),
340
362
  }),
341
363
  });
342
364
  /** Mirrors `CliOrgSummary` (lib/org-render.ts): one `Me.organizations[]` entry. */
@@ -356,11 +378,61 @@ const ORG_BINDING_SCHEMA = v.looseObject({
356
378
  export const ME_IDENTITY_SCHEMA = v.looseObject({
357
379
  userId: v.optional(v.string()),
358
380
  keyId: v.optional(v.string()),
381
+ v3Enabled: v.optional(v.boolean()),
359
382
  organizations: v.optional(v.array(ORG_SUMMARY_SCHEMA)),
360
383
  org: v.optional(ORG_BINDING_SCHEMA),
361
384
  });
385
+ /**
386
+ * Mirrors `MeResponse` (commands/auth.ts): the full `GET /me` projection read
387
+ * by `auth whoami` (and, through it, `init`).
388
+ *
389
+ * `scopes` is required and array-typed on purpose — this is the shape drift
390
+ * that actually bites today. `runWhoami` renders `m.scopes.join(', ')` and
391
+ * computes `missingScopes` via `m.scopes.includes(...)` with no guard, so a
392
+ * `/me` body without `scopes` crashes with a raw `TypeError` (exit 1) instead
393
+ * of a typed envelope. Every `/me` fixture in the suite supplies it
394
+ * (`auth.test.ts`, `init.test.ts`, `usage.test.ts`, `cli.subprocess.test.ts`,
395
+ * `test/mock-backend/fixtures.ts`), so requiring it matches observed wire
396
+ * reality; `email` / `displayName` / `v3Enabled` are the genuinely absent-safe
397
+ * ones and stay `v.optional` with no default (rule 3, optional branch).
398
+ *
399
+ * `init` calls this through `runWhoami` inside a try/catch that falls back to
400
+ * a placeholder identity, so a drifted `/me` degrades the setup summary
401
+ * instead of failing the whole `init`.
402
+ */
403
+ export const ME_RESPONSE_SCHEMA = v.looseObject({
404
+ userId: v.string(),
405
+ keyId: v.string(),
406
+ scopes: v.array(v.string()),
407
+ env: openWireLiteral(),
408
+ email: v.optional(v.string()),
409
+ displayName: v.optional(v.string()),
410
+ v3Enabled: v.optional(v.boolean()),
411
+ });
412
+ // ---------------------------------------------------------------------------
413
+ // GET /me (usage projection)
414
+ // ---------------------------------------------------------------------------
415
+ /**
416
+ * Mirrors `UsageResponse` (commands/usage.ts): the credits/plan projection the
417
+ * `usage` command reads off the same `GET /me` body.
418
+ *
419
+ * `renderUsage` prints `userId`/`keyId`/`env` unconditionally as its "identity
420
+ * block", so those three are required; `credits`, `subPlan` and
421
+ * `creditsPerRun` are forward-compat fields the backend does not send today
422
+ * (see the BACKEND FOLLOW-UP note in usage.ts) and every renderer branch is
423
+ * gated on `!== undefined`, so they stay optional with no default. `scopes`
424
+ * rides along as an unknown extra key and is preserved by `looseObject`.
425
+ */
426
+ export const USAGE_RESPONSE_SCHEMA = v.looseObject({
427
+ userId: v.string(),
428
+ keyId: v.string(),
429
+ env: openWireLiteral(),
430
+ credits: v.optional(v.number()),
431
+ subPlan: v.optional(v.string()),
432
+ creditsPerRun: v.optional(v.number()),
433
+ });
362
434
  // ---------------------------------------------------------------------------
363
- // /tunnel — DEV-747 piece 1 facade
435
+ // /tunnel facade
364
436
  // ---------------------------------------------------------------------------
365
437
  /**
366
438
  * Mirrors `TunnelMintResponse` (tunnel.types.ts): `POST /tunnel`.
@@ -385,4 +457,13 @@ export const TUNNEL_STATUS_RESPONSE_SCHEMA = v.looseObject({
385
457
  status: openWireLiteral(),
386
458
  expiresAt: v.string(),
387
459
  });
460
+ /** Mirrors `TunnelListResponse`: a server may add status values or omit creation time. */
461
+ export const TUNNEL_LIST_RESPONSE_SCHEMA = v.looseObject({
462
+ tunnels: v.array(v.looseObject({
463
+ clientId: v.string(),
464
+ status: openWireLiteral(),
465
+ expiresAt: v.string(),
466
+ createdAt: v.optional(v.nullable(v.string())),
467
+ })),
468
+ });
388
469
  //# sourceMappingURL=response-schemas.js.map