@testsprite/testsprite-cli 0.11.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 (99) hide show
  1. package/README.md +52 -44
  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 +470 -9
  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.d.ts +90 -0
  11. package/dist/commands/project-env.js +486 -0
  12. package/dist/commands/project.d.ts +15 -5
  13. package/dist/commands/project.js +88 -92
  14. package/dist/commands/schedule.d.ts +2 -0
  15. package/dist/commands/schedule.js +18 -10
  16. package/dist/commands/test.d.ts +102 -30
  17. package/dist/commands/test.js +1949 -419
  18. package/dist/commands/testlist.js +77 -21
  19. package/dist/commands/tunnel.d.ts +26 -3
  20. package/dist/commands/tunnel.js +211 -14
  21. package/dist/commands/usage.d.ts +3 -0
  22. package/dist/commands/usage.js +12 -5
  23. package/dist/index.js +47 -23
  24. package/dist/lib/agent-targets.d.ts +3 -3
  25. package/dist/lib/agent-targets.js +2 -2
  26. package/dist/lib/billing-refusal.d.ts +43 -0
  27. package/dist/lib/billing-refusal.js +171 -0
  28. package/dist/lib/bundle.d.ts +5 -0
  29. package/dist/lib/bundle.js +43 -13
  30. package/dist/lib/ci-linkage.d.ts +90 -0
  31. package/dist/lib/ci-linkage.js +181 -0
  32. package/dist/lib/client-factory.d.ts +4 -1
  33. package/dist/lib/client-factory.js +25 -2
  34. package/dist/lib/client-tag.d.ts +13 -0
  35. package/dist/lib/client-tag.js +44 -0
  36. package/dist/lib/config.d.ts +17 -0
  37. package/dist/lib/config.js +20 -1
  38. package/dist/lib/conflict-reason.d.ts +67 -2
  39. package/dist/lib/conflict-reason.js +148 -13
  40. package/dist/lib/credentials.js +56 -14
  41. package/dist/lib/cron.js +8 -1
  42. package/dist/lib/dry-run/samples.d.ts +13 -1
  43. package/dist/lib/dry-run/samples.js +51 -7
  44. package/dist/lib/errors.d.ts +62 -12
  45. package/dist/lib/errors.js +180 -25
  46. package/dist/lib/failing-fe-resolver.d.ts +1 -1
  47. package/dist/lib/failing-fe-resolver.js +3 -3
  48. package/dist/lib/gh-output.d.ts +26 -11
  49. package/dist/lib/gh-output.js +47 -15
  50. package/dist/lib/history-retention.d.ts +8 -0
  51. package/dist/lib/history-retention.js +24 -0
  52. package/dist/lib/http.d.ts +44 -19
  53. package/dist/lib/http.js +53 -26
  54. package/dist/lib/interrupt.d.ts +21 -13
  55. package/dist/lib/interrupt.js +32 -21
  56. package/dist/lib/junit-report.d.ts +11 -1
  57. package/dist/lib/junit-report.js +15 -3
  58. package/dist/lib/local-target.d.ts +33 -1
  59. package/dist/lib/local-target.js +78 -1
  60. package/dist/lib/output.d.ts +27 -1
  61. package/dist/lib/output.js +22 -3
  62. package/dist/lib/plan-poll.d.ts +11 -11
  63. package/dist/lib/plan-poll.js +12 -12
  64. package/dist/lib/plans.types.d.ts +9 -9
  65. package/dist/lib/plans.types.js +3 -3
  66. package/dist/lib/poll.d.ts +2 -2
  67. package/dist/lib/poll.js +9 -3
  68. package/dist/lib/render-error.d.ts +2 -0
  69. package/dist/lib/render-error.js +13 -0
  70. package/dist/lib/response-schemas.d.ts +54 -12
  71. package/dist/lib/response-schemas.js +106 -7
  72. package/dist/lib/runs.types.d.ts +92 -6
  73. package/dist/lib/secret-file.js +72 -14
  74. package/dist/lib/skill-nudge.d.ts +6 -1
  75. package/dist/lib/skill-nudge.js +32 -5
  76. package/dist/lib/target-url-preflight.d.ts +6 -4
  77. package/dist/lib/target-url-preflight.js +64 -51
  78. package/dist/lib/target-url.js +31 -12
  79. package/dist/lib/telemetry.d.ts +172 -3
  80. package/dist/lib/telemetry.js +276 -15
  81. package/dist/lib/ticker.js +93 -4
  82. package/dist/lib/tunnel-session.d.ts +13 -0
  83. package/dist/lib/tunnel-session.js +4 -1
  84. package/dist/lib/tunnel.types.d.ts +12 -2
  85. package/dist/lib/tunnel.types.js +2 -2
  86. package/dist/lib/version-notice.d.ts +20 -1
  87. package/dist/lib/version-notice.js +59 -12
  88. package/dist/lib/wait-exit.d.ts +8 -0
  89. package/dist/lib/wait-exit.js +76 -4
  90. package/dist/lib/workspace-status.d.ts +23 -0
  91. package/dist/lib/workspace-status.js +15 -0
  92. package/dist/version-guard.d.ts +7 -1
  93. package/dist/version-guard.js +19 -1
  94. package/dist/version.d.ts +1 -1
  95. package/dist/version.js +1 -1
  96. package/package.json +4 -4
  97. package/skills/testsprite-onboard.skill.md +4 -4
  98. package/skills/testsprite-verify.codex.md +59 -57
  99. package/skills/testsprite-verify.skill.md +53 -36
@@ -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');
@@ -69,6 +69,38 @@ export declare function parseLocalPort(raw: string): number;
69
69
  * misunderstanding to correct immediately, not a request to forward.
70
70
  */
71
71
  export declare function normalizeLocalHost(raw: string | undefined): LoopbackHost;
72
+ /**
73
+ * `normalizeLocalHost` for a command whose alternative to `--local` is `--url`
74
+ * (`project create/update`, `project env create/update`) rather than
75
+ * `--target-url`, so the refusal names the flag that command actually has.
76
+ */
77
+ export declare function normalizeStoredLocalHost(raw: string | undefined): LoopbackHost;
78
+ /** The target `--local <port> [--local-host]` names on a project or environment write. */
79
+ export interface StoredLocalTarget {
80
+ host: LoopbackHost;
81
+ port: number;
82
+ }
83
+ /**
84
+ * Parse the `--local` / `--local-host` / `--url` trio a stored-target write
85
+ * takes. `--local` and `--url` are two spellings of one field, so both is a
86
+ * contradiction; `--local-host` only means something next to `--local`; the
87
+ * port is validated strictly because it becomes part of a URL runs are billed
88
+ * against. Returns the local target, or `undefined` when `--url` (or nothing)
89
+ * was given.
90
+ */
91
+ export declare function parseStoredLocalTarget(opts: {
92
+ local?: string;
93
+ localHost?: string;
94
+ url?: string;
95
+ }): StoredLocalTarget | undefined;
96
+ /**
97
+ * Refuse a stored-target write whose loopback port has nothing listening —
98
+ * the same check `project create --local` runs, so a typo in the port is
99
+ * caught before a row exists anywhere. `skipPreflight` is a pure no-op.
100
+ */
101
+ export declare function assertStoredLocalTargetListening(target: StoredLocalTarget, opts: {
102
+ skipPreflight?: boolean;
103
+ }, deps?: LocalPortProbeDeps): Promise<void>;
72
104
  /** `http://<host>:<port>`, with IPv6 bracketed as the URL grammar requires. */
73
105
  export declare function buildLocalTargetUrl(host: LoopbackHost, port: number): string;
74
106
  /**
@@ -81,7 +113,7 @@ export declare function probeLocalPort(host: string, port: number, deps?: LocalP
81
113
  /**
82
114
  * Run {@link probeLocalPort} and either throw (refuse) or no-op (ok / skipped).
83
115
  *
84
- * 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
85
117
  * measured 1,003 blocked-with-URL CLI runs, 55.5% of the third-party-tunnel
86
118
  * ones blocked, every one of them charged, because the run row and its credit
87
119
  * spend happen before the Lambda ever discovers the target is dead. A dev
@@ -73,6 +73,83 @@ export function normalizeLocalHost(raw) {
73
73
  }
74
74
  return match;
75
75
  }
76
+ /**
77
+ * `normalizeLocalHost` for a command whose alternative to `--local` is `--url`
78
+ * (`project create/update`, `project env create/update`) rather than
79
+ * `--target-url`, so the refusal names the flag that command actually has.
80
+ */
81
+ export function normalizeStoredLocalHost(raw) {
82
+ try {
83
+ return normalizeLocalHost(raw);
84
+ }
85
+ catch (err) {
86
+ if (err instanceof ApiError && typeof err.details?.reason === 'string') {
87
+ throw localValidationError('local-host', err.details.reason.replace('--target-url', '--url'), err.details.accepted);
88
+ }
89
+ throw err;
90
+ }
91
+ }
92
+ /**
93
+ * Parse the `--local` / `--local-host` / `--url` trio a stored-target write
94
+ * takes. `--local` and `--url` are two spellings of one field, so both is a
95
+ * contradiction; `--local-host` only means something next to `--local`; the
96
+ * port is validated strictly because it becomes part of a URL runs are billed
97
+ * against. Returns the local target, or `undefined` when `--url` (or nothing)
98
+ * was given.
99
+ */
100
+ export function parseStoredLocalTarget(opts) {
101
+ if (opts.local !== undefined && opts.url !== undefined) {
102
+ throw flagPairError('--local and --url are mutually exclusive');
103
+ }
104
+ if (opts.localHost !== undefined && opts.local === undefined) {
105
+ throw flagPairError('--local-host requires --local');
106
+ }
107
+ if (opts.local === undefined)
108
+ return undefined;
109
+ if (!/^\d+$/.test(opts.local)) {
110
+ throw flagPairError('--local must be a port number between 1 and 65535');
111
+ }
112
+ return { host: normalizeStoredLocalHost(opts.localHost), port: parseLocalPort(opts.local) };
113
+ }
114
+ function flagPairError(message) {
115
+ return ApiError.fromEnvelope({
116
+ error: {
117
+ code: 'VALIDATION_ERROR',
118
+ message: 'Invalid request.',
119
+ nextAction: message,
120
+ requestId: 'local',
121
+ details: { reason: 'missing_required_flag' },
122
+ },
123
+ });
124
+ }
125
+ /**
126
+ * Refuse a stored-target write whose loopback port has nothing listening —
127
+ * the same check `project create --local` runs, so a typo in the port is
128
+ * caught before a row exists anywhere. `skipPreflight` is a pure no-op.
129
+ */
130
+ export async function assertStoredLocalTargetListening(target, opts, deps = {}) {
131
+ if (opts.skipPreflight)
132
+ return;
133
+ const outcome = await probeLocalPort(target.host, target.port, deps);
134
+ if (outcome.verdict === 'refuse') {
135
+ const targetUrl = buildLocalTargetUrl(target.host, target.port);
136
+ throw ApiError.fromEnvelope({
137
+ error: {
138
+ code: 'VALIDATION_ERROR',
139
+ message: `Nothing is listening on ${targetUrl}. Start your app first, or pass --skip-preflight.`,
140
+ nextAction: 'Verify --local and --local-host match the app you want to test.',
141
+ requestId: 'local',
142
+ details: {
143
+ field: 'local',
144
+ reason: 'local-port-not-listening',
145
+ host: target.host,
146
+ port: target.port,
147
+ probeReason: outcome.reason,
148
+ },
149
+ },
150
+ });
151
+ }
152
+ }
76
153
  /** `http://<host>:<port>`, with IPv6 bracketed as the URL grammar requires. */
77
154
  export function buildLocalTargetUrl(host, port) {
78
155
  const authority = host.includes(':') ? `[${host}]` : host;
@@ -149,7 +226,7 @@ const SKIP_HINT = 'Skip this check with --skip-preflight.';
149
226
  /**
150
227
  * Run {@link probeLocalPort} and either throw (refuse) or no-op (ok / skipped).
151
228
  *
152
- * 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
153
230
  * measured 1,003 blocked-with-URL CLI runs, 55.5% of the third-party-tunnel
154
231
  * ones blocked, every one of them charged, because the run row and its credit
155
232
  * spend happen before the Lambda ever discovers the target is dead. A dev
@@ -21,6 +21,22 @@ export declare function isOutputMode(value: unknown): value is OutputMode;
21
21
  * helper so the validation is uniform.
22
22
  */
23
23
  export declare function resolveOutputMode(raw: unknown): OutputMode;
24
+ /**
25
+ * Input to {@link Output.error} — the same 5-key shape as the hand-built
26
+ * envelopes in `index.ts`'s ApiError / InterruptError / RequestTimeoutError
27
+ * catch branches (`{error:{code,message,nextAction,requestId,details}}`).
28
+ * Only `code` and `message` are required; the rest default to the
29
+ * client-local values (`''`, `'local'`, `{}`) so every `--output json` error
30
+ * — regardless of which catch branch produced it — renders the identical
31
+ * envelope shape.
32
+ */
33
+ export interface ErrorEnvelopeInput {
34
+ code: string;
35
+ message: string;
36
+ nextAction?: string;
37
+ requestId?: string;
38
+ details?: Record<string, unknown>;
39
+ }
24
40
  export interface OutputStreams {
25
41
  /**
26
42
  * Line-oriented stdout writer. Each call is one logical line; the
@@ -66,5 +82,15 @@ export declare class Output {
66
82
  * contract.
67
83
  */
68
84
  writeChunk(text: string): Promise<void>;
69
- error(message: string): void;
85
+ /**
86
+ * Render a terminal error. JSON mode always emits the SAME 5-key envelope
87
+ * shape as the ApiError / InterruptError / RequestTimeoutError branches
88
+ * hand-build in `index.ts`'s catch (`{error:{code,message,nextAction,
89
+ * requestId,details}}`) — before this, the only two callers of
90
+ * this method (the plain-CLIError and uncaught-exception catch branches)
91
+ * fell through to a bare `{"error":"<message>"}` string, breaking the
92
+ * envelope contract that machine consumers (`--output json` scripts/CI/
93
+ * agents) rely on for every other error path.
94
+ */
95
+ error(input: ErrorEnvelopeInput): void;
70
96
  }
@@ -66,12 +66,31 @@ export class Output {
66
66
  async writeChunk(text) {
67
67
  await this.rawStdoutWrite(text);
68
68
  }
69
- error(message) {
69
+ /**
70
+ * Render a terminal error. JSON mode always emits the SAME 5-key envelope
71
+ * shape as the ApiError / InterruptError / RequestTimeoutError branches
72
+ * hand-build in `index.ts`'s catch (`{error:{code,message,nextAction,
73
+ * requestId,details}}`) — before this, the only two callers of
74
+ * this method (the plain-CLIError and uncaught-exception catch branches)
75
+ * fell through to a bare `{"error":"<message>"}` string, breaking the
76
+ * envelope contract that machine consumers (`--output json` scripts/CI/
77
+ * agents) rely on for every other error path.
78
+ */
79
+ error(input) {
70
80
  if (this.mode === 'json') {
71
- this.stderrWrite(JSON.stringify({ error: message }, null, 2));
81
+ const envelope = {
82
+ error: {
83
+ code: input.code,
84
+ message: input.message,
85
+ nextAction: input.nextAction ?? '',
86
+ requestId: input.requestId ?? 'local',
87
+ details: input.details ?? {},
88
+ },
89
+ };
90
+ this.stderrWrite(JSON.stringify(envelope, null, 2));
72
91
  return;
73
92
  }
74
- this.stderrWrite(`Error: ${message}`);
93
+ this.stderrWrite(`Error: ${input.message}`);
75
94
  }
76
95
  }
77
96
  /**
@@ -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>;