@testsprite/testsprite-cli 0.16.0 → 0.18.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 (206) hide show
  1. package/README.md +52 -147
  2. package/dist/commands/agent.d.ts +12 -4
  3. package/dist/commands/agent.js +48 -63
  4. package/dist/commands/auth.d.ts +6 -10
  5. package/dist/commands/auth.js +40 -56
  6. package/dist/commands/ci.d.ts +23 -100
  7. package/dist/commands/ci.js +293 -487
  8. package/dist/commands/conversation.d.ts +27 -0
  9. package/dist/commands/conversation.js +741 -0
  10. package/dist/commands/doctor.d.ts +5 -1
  11. package/dist/commands/doctor.js +129 -34
  12. package/dist/commands/init.d.ts +4 -45
  13. package/dist/commands/init.js +108 -66
  14. package/dist/commands/project-env.d.ts +62 -2
  15. package/dist/commands/project-env.js +434 -43
  16. package/dist/commands/project-sign-in.d.ts +0 -48
  17. package/dist/commands/project-sign-in.js +1 -229
  18. package/dist/commands/project.d.ts +19 -186
  19. package/dist/commands/project.js +108 -926
  20. package/dist/commands/result.d.ts +10 -0
  21. package/dist/commands/result.js +216 -0
  22. package/dist/commands/schedule.d.ts +0 -29
  23. package/dist/commands/schedule.js +28 -87
  24. package/dist/commands/test.d.ts +301 -1838
  25. package/dist/commands/test.js +1880 -13917
  26. package/dist/commands/testlist.d.ts +130 -5
  27. package/dist/commands/testlist.js +300 -342
  28. package/dist/commands/tunnel.d.ts +3 -3
  29. package/dist/commands/tunnel.js +23 -20
  30. package/dist/commands/usage.d.ts +12 -45
  31. package/dist/commands/usage.js +50 -131
  32. package/dist/index.js +191 -110
  33. package/dist/lib/agent-detect.js +9 -5
  34. package/dist/lib/agent-targets.d.ts +21 -2
  35. package/dist/lib/agent-targets.js +88 -11
  36. package/dist/lib/args.d.ts +13 -0
  37. package/dist/lib/args.js +49 -0
  38. package/dist/lib/basic-auth.d.ts +3 -0
  39. package/dist/lib/basic-auth.js +15 -0
  40. package/dist/lib/billing-refusal.js +4 -3
  41. package/dist/lib/ci-linkage.d.ts +4 -82
  42. package/dist/lib/ci-linkage.js +4 -157
  43. package/dist/lib/ci-run.js +1 -1
  44. package/dist/lib/client-factory.d.ts +12 -4
  45. package/dist/lib/client-factory.js +41 -30
  46. package/dist/lib/commit-signal.d.ts +65 -0
  47. package/dist/lib/commit-signal.js +305 -0
  48. package/dist/lib/concurrency-limiter.d.ts +6 -0
  49. package/dist/lib/concurrency-limiter.js +29 -0
  50. package/dist/lib/config.js +10 -5
  51. package/dist/lib/conflict-reason.d.ts +9 -3
  52. package/dist/lib/conflict-reason.js +6 -3
  53. package/dist/lib/conversation/answers.d.ts +9 -0
  54. package/dist/lib/conversation/answers.js +49 -0
  55. package/dist/lib/conversation/api.d.ts +75 -0
  56. package/dist/lib/conversation/api.js +151 -0
  57. package/dist/lib/conversation/change.d.ts +31 -0
  58. package/dist/lib/conversation/change.js +124 -0
  59. package/dist/lib/conversation/context.d.ts +29 -0
  60. package/dist/lib/conversation/context.js +82 -0
  61. package/dist/lib/conversation/environment.d.ts +16 -0
  62. package/dist/lib/conversation/environment.js +21 -0
  63. package/dist/lib/conversation/follow.d.ts +24 -0
  64. package/dist/lib/conversation/follow.js +42 -0
  65. package/dist/lib/conversation/render.d.ts +33 -0
  66. package/dist/lib/conversation/render.js +318 -0
  67. package/dist/lib/conversation/title.d.ts +2 -0
  68. package/dist/lib/conversation/title.js +18 -0
  69. package/dist/lib/conversation/types.d.ts +158 -0
  70. package/dist/lib/conversation/types.js +6 -0
  71. package/dist/lib/credentials.js +67 -11
  72. package/dist/lib/cron.d.ts +1 -1
  73. package/dist/lib/cron.js +2 -2
  74. package/dist/lib/dispatch-stop.d.ts +20 -0
  75. package/dist/lib/dispatch-stop.js +30 -0
  76. package/dist/lib/download.d.ts +100 -0
  77. package/dist/lib/download.js +408 -0
  78. package/dist/lib/dry-run/fetch.d.ts +10 -0
  79. package/dist/lib/dry-run/fetch.js +20 -0
  80. package/dist/lib/dry-run/samples.d.ts +6 -34
  81. package/dist/lib/dry-run/samples.js +375 -747
  82. package/dist/lib/environment-tunnel.d.ts +19 -30
  83. package/dist/lib/environment-tunnel.js +168 -202
  84. package/dist/lib/errors.d.ts +20 -4
  85. package/dist/lib/errors.js +36 -16
  86. package/dist/lib/facade.d.ts +7 -29
  87. package/dist/lib/facade.js +7 -36
  88. package/dist/lib/failing-fe-resolver.d.ts +13 -58
  89. package/dist/lib/failing-fe-resolver.js +47 -132
  90. package/dist/lib/first-suite-hint.d.ts +20 -30
  91. package/dist/lib/first-suite-hint.js +57 -72
  92. package/dist/lib/gh-output.d.ts +76 -21
  93. package/dist/lib/gh-output.js +171 -90
  94. package/dist/lib/git-utils.d.ts +56 -0
  95. package/dist/lib/git-utils.js +212 -0
  96. package/dist/lib/github-context.d.ts +2 -0
  97. package/dist/lib/github-context.js +40 -8
  98. package/dist/lib/history-retention.d.ts +6 -2
  99. package/dist/lib/history-retention.js +10 -7
  100. package/dist/lib/http.d.ts +58 -134
  101. package/dist/lib/http.js +354 -291
  102. package/dist/lib/interrupt.d.ts +14 -8
  103. package/dist/lib/interrupt.js +28 -10
  104. package/dist/lib/junit-report.d.ts +57 -4
  105. package/dist/lib/junit-report.js +202 -32
  106. package/dist/lib/local-target.d.ts +8 -7
  107. package/dist/lib/local-target.js +14 -13
  108. package/dist/lib/output.d.ts +2 -41
  109. package/dist/lib/output.js +13 -51
  110. package/dist/lib/pagination.d.ts +2 -5
  111. package/dist/lib/pagination.js +2 -5
  112. package/dist/lib/presigned-url.d.ts +22 -0
  113. package/dist/lib/presigned-url.js +90 -0
  114. package/dist/lib/prompt.js +36 -2
  115. package/dist/lib/proxy.js +2 -1
  116. package/dist/lib/redact.d.ts +2 -2
  117. package/dist/lib/redact.js +3 -4
  118. package/dist/lib/removed-commands.d.ts +18 -0
  119. package/dist/lib/removed-commands.js +170 -0
  120. package/dist/lib/render-error.d.ts +31 -6
  121. package/dist/lib/render-error.js +88 -25
  122. package/dist/lib/response-schemas.d.ts +38 -30
  123. package/dist/lib/response-schemas.js +207 -207
  124. package/dist/lib/result/api.d.ts +24 -0
  125. package/dist/lib/result/api.js +28 -0
  126. package/dist/lib/result/evidence.d.ts +73 -0
  127. package/dist/lib/result/evidence.js +422 -0
  128. package/dist/lib/result/render.d.ts +20 -0
  129. package/dist/lib/result/render.js +194 -0
  130. package/dist/lib/result/types.d.ts +122 -0
  131. package/dist/lib/result/types.js +19 -0
  132. package/dist/lib/run-output.d.ts +275 -0
  133. package/dist/lib/run-output.js +227 -0
  134. package/dist/lib/run-render.d.ts +101 -0
  135. package/dist/lib/run-render.js +183 -0
  136. package/dist/lib/run-wait.d.ts +192 -0
  137. package/dist/lib/run-wait.js +452 -0
  138. package/dist/lib/runs.types.d.ts +118 -367
  139. package/dist/lib/runs.types.js +0 -14
  140. package/dist/lib/secret-file.d.ts +1 -1
  141. package/dist/lib/secret-file.js +11 -2
  142. package/dist/lib/skill-nudge.d.ts +7 -27
  143. package/dist/lib/skill-nudge.js +9 -37
  144. package/dist/lib/target-path.d.ts +15 -0
  145. package/dist/lib/target-path.js +35 -0
  146. package/dist/lib/target-url-advisory.d.ts +19 -0
  147. package/dist/lib/target-url-advisory.js +31 -0
  148. package/dist/lib/target-url-preflight.d.ts +9 -0
  149. package/dist/lib/target-url-preflight.js +214 -106
  150. package/dist/lib/target-url.d.ts +8 -8
  151. package/dist/lib/target-url.js +14 -24
  152. package/dist/lib/telemetry.d.ts +35 -15
  153. package/dist/lib/telemetry.js +38 -9
  154. package/dist/lib/terminal-text.d.ts +41 -0
  155. package/dist/lib/terminal-text.js +127 -0
  156. package/dist/lib/testlist.types.d.ts +16 -8
  157. package/dist/lib/testlist.types.js +1 -1
  158. package/dist/lib/text-equality.d.ts +2 -0
  159. package/dist/lib/text-equality.js +5 -0
  160. package/dist/lib/text-file.d.ts +16 -0
  161. package/dist/lib/text-file.js +41 -0
  162. package/dist/lib/text-table.d.ts +46 -0
  163. package/dist/lib/text-table.js +72 -4
  164. package/dist/lib/ticker.d.ts +9 -2
  165. package/dist/lib/ticker.js +16 -3
  166. package/dist/lib/transport-failure.d.ts +22 -0
  167. package/dist/lib/transport-failure.js +126 -0
  168. package/dist/lib/tunnel-session.d.ts +8 -2
  169. package/dist/lib/tunnel-session.js +24 -11
  170. package/dist/lib/update-check.js +3 -2
  171. package/dist/lib/url-template.d.ts +43 -0
  172. package/dist/lib/url-template.js +151 -0
  173. package/dist/lib/validate.d.ts +0 -64
  174. package/dist/lib/validate.js +2 -131
  175. package/dist/lib/version-notice.js +4 -3
  176. package/dist/lib/wait-exit.d.ts +37 -2
  177. package/dist/lib/wait-exit.js +88 -30
  178. package/dist/lib/workspace-status.js +10 -2
  179. package/dist/version.d.ts +1 -1
  180. package/dist/version.js +1 -1
  181. package/package.json +2 -3
  182. package/skills/testsprite-ci.skill.md +52 -23
  183. package/skills/testsprite-onboard.skill.md +70 -153
  184. package/skills/testsprite-verify.codex.md +54 -58
  185. package/skills/testsprite-verify.skill.md +189 -358
  186. package/dist/lib/browser.d.ts +0 -6
  187. package/dist/lib/browser.js +0 -54
  188. package/dist/lib/bundle.d.ts +0 -234
  189. package/dist/lib/bundle.js +0 -781
  190. package/dist/lib/deprecate.d.ts +0 -32
  191. package/dist/lib/deprecate.js +0 -39
  192. package/dist/lib/flaky.d.ts +0 -91
  193. package/dist/lib/flaky.js +0 -71
  194. package/dist/lib/plan-poll.d.ts +0 -171
  195. package/dist/lib/plan-poll.js +0 -441
  196. package/dist/lib/plans.types.d.ts +0 -130
  197. package/dist/lib/plans.types.js +0 -31
  198. package/dist/lib/poll.d.ts +0 -100
  199. package/dist/lib/poll.js +0 -290
  200. package/dist/lib/rate-throttle.d.ts +0 -49
  201. package/dist/lib/rate-throttle.js +0 -75
  202. package/dist/lib/run-progress.d.ts +0 -41
  203. package/dist/lib/run-progress.js +0 -56
  204. package/dist/lib/v3-advisory.d.ts +0 -55
  205. package/dist/lib/v3-advisory.js +0 -74
  206. package/schemas/plan.schema.json +0 -61
@@ -1,20 +1,16 @@
1
1
  import { resolveEnvironmentRunTarget, type EnvironmentTunnelContext, type ResolvedRunTarget, type RunTargetTest } from '../lib/environment-tunnel.js';
2
2
  import { Command } from 'commander';
3
3
  import { type CommonOptions as FactoryCommonOptions } from '../lib/client-factory.js';
4
- import { type WriteBundleResult } from '../lib/bundle.js';
5
4
  import { type JUnitReportFormat, type JUnitTestResult } from '../lib/junit-report.js';
6
5
  import { ApiError, InterruptError } from '../lib/errors.js';
7
6
  import { type ShutdownHandle } from '../lib/interrupt.js';
8
7
  import type { FetchImpl } from '../lib/http.js';
9
- import { type DeprecationEntry } from '../lib/deprecate.js';
10
8
  import { type Page } from '../lib/pagination.js';
11
9
  import { type WaitTimeoutTelemetry } from '../lib/telemetry.js';
12
- import type { CliGetPlansResponse, CliGenerationStage } from '../lib/plans.types.js';
13
- import type { RunResponse, RunStatus, TriggerRunResponse, RerunResponse, BatchRerunResponse, ListRunsResponse, RunSource, BatchRunFreshResponse, CancelRunResponse, CiGithubTrigger, RunEnvironmentRef } from '../lib/runs.types.js';
14
- import { type LoopbackHost } from '../lib/local-target.js';
10
+ import { type RunCounts, type RunReceipt, type RunResult } from '../lib/run-output.js';
11
+ import type { ProjectRunResponse, RunStatus, CancelRunResponse, CiGithubTrigger } from '../lib/runs.types.js';
15
12
  import { type TunnelClientHandle } from '../lib/tunnel-session.js';
16
13
  import { type TunnelClientOptions } from '../vendor/tunnel-client/index.js';
17
- import { type FlakyReport } from '../lib/flaky.js';
18
14
  /**
19
15
  * `details` debug block per the CLI OpenAPI `Test` schema
20
16
  * (M2.1 amendment). `processingStatus` / `testStatus` are the
@@ -24,322 +20,44 @@ import { type FlakyReport } from '../lib/flaky.js';
24
20
  * already parse it. All three are debug-only — automation depends on
25
21
  * the typed top-level `status` field.
26
22
  */
27
- export interface CliTestStatusDetails {
28
- processingStatus: string | null;
29
- testStatus: string | null;
30
- rawStatus: string;
31
- }
32
23
  /**
33
- * Public Test shape per the CLI OpenAPI `Test` schema.
34
- * `details` is optional debug context — automation must depend only on
35
- * the typed top-level fields. `createdFrom` takes one of the three
36
- * documented values (`portal` | `mcp` | `cli`); anything else is a
37
- * contract violation worth surfacing rather than silently coercing.
24
+ * A test case as `test list` / `test get` show it: the case's own fields and
25
+ * nothing of its results, which `result list --test` reads. Fields a backend may
26
+ * leave out stay optional; JSON output preserves the wire objects unchanged.
38
27
  */
39
28
  export interface CliTest {
40
29
  id: string;
41
30
  projectId: string;
42
- /**
43
- * §6.2 / M2.1 piece 4 — human-friendly project name. `null` when
44
- * project lookup wasn't possible (record missing, ownership
45
- * boundary, or pre-M2.1 backend that never populated the field).
46
- * Optional on the wire so older facades that don't ship the field
47
- * still type-check; the renderer falls back to `projectId` when
48
- * absent.
49
- */
31
+ /** Human-friendly project name; `null` when the lookup was not possible. */
50
32
  projectName?: string | null;
51
- name: string;
33
+ /** The display id the Test Cases table shows (`CHECKOUT-004`); `null` on rows written before slugs. */
34
+ slug?: string | null;
35
+ title: string;
36
+ description?: string | null;
52
37
  type: 'frontend' | 'backend';
53
- /**
54
- * Assembled integration test (backend). Absent on older backends — treated
55
- * as false. Listed as `backend/int` so it is not mistaken for a plain test.
56
- */
38
+ /** Assembled integration test (backend). Listed as `backend/int` so it is not mistaken for a plain test. */
57
39
  isIntegration?: boolean;
58
- createdFrom: 'portal' | 'mcp' | 'cli';
59
- status: CliPublicStatus;
60
- statusByEnvironment?: Array<{
61
- environmentId: string | null;
62
- environmentName: string | null;
63
- status: CliPublicStatus;
64
- }>;
65
- headlineEnvironment?: {
66
- id: string | null;
67
- name: string | null;
68
- } | null;
69
- createdAt: string;
70
- updatedAt: string;
71
- /**
72
- * M3.4 — number of FE plan steps, or `null` for BE tests and rows
73
- * without plan steps. Optional on the wire so pre-M3.4 facades that
74
- * don't ship it still type-check; text mode shows it only when present
75
- * and non-null. The dedicated read path for recovering the current
76
- * count after a `test plan put --expected-step-count` 412.
77
- */
78
- planStepCount?: number | null;
79
- /**
80
- * Full FE plan steps when the single-test read endpoint provides them.
81
- * Optional/nullable for older backends and test types without plan steps;
82
- * JSON output preserves the wire objects unchanged.
83
- */
84
- planSteps?: CliPlanStep[] | null;
85
- /**
86
- * M2.1: structured `processingStatus` / `testStatus` pair plus the
87
- * deprecated `rawStatus` mirror. Pre-M2.1 servers may still emit
88
- * `{ rawStatus }` only — keep the structured fields optional on
89
- * the wire even though M2.1 servers always populate them. The CLI
90
- * accepts both shapes.
91
- */
92
- details?: Partial<CliTestStatusDetails>;
93
- /**
94
- * G1a — test priority label as stored ("High" | "Medium" | "Low").
95
- * Optional on the wire: pre-G1a backends omit the field; `null` means
96
- * no priority has been set. Text mode surfaces it only when truthy.
97
- */
40
+ category?: string | null;
98
41
  priority?: string | null;
99
- /**
100
- * Per-test step timeout in milliseconds. The execution engine applies it
101
- * to every step. Optional/nullable for older backends and tests that use
102
- * the engine defaults; text mode surfaces it only when it is a number.
103
- */
42
+ /** The active version: its hash, and the label the UI shows (`v1.0`). */
43
+ version?: {
44
+ hash: string;
45
+ label: string | null;
46
+ };
47
+ /** Frontend cases: how many steps the active version has; `get` lists them in `steps`. */
48
+ stepCount?: number | null;
49
+ steps?: CliPlanStep[] | null;
50
+ /** Frontend-only timeout applied to every step; omitted when unset and on backend tests. */
104
51
  stepTimeoutMs?: number | null;
105
- /**
106
- * Backend-only dependency declarations that drive wave ordering.
107
- * Optional on the wire so older facades that don't ship them still
108
- * type-check; text mode surfaces them only when present/non-empty.
109
- */
52
+ /** Backend-only dependency declarations that drive wave ordering. */
110
53
  produces?: string[] | null;
111
54
  consumes?: string[] | null;
112
- category?: string | null;
113
- }
114
- export type CliPublicStatus = 'draft' | 'ready' | 'queued' | 'running' | 'passed' | 'failed' | 'blocked' | 'cancelled' | 'unknown';
115
- /**
116
- * §6.3 TestCode wire shape. `code` is either the inline source body
117
- * (when < 100 KB) or a presigned `https://` URL (when >= 100 KB). The
118
- * caller distinguishes via {@link isPresignedCodeUrl}.
119
- */
120
- export interface CliTestCode {
121
- testId: string;
122
- language: 'typescript' | 'javascript' | 'python';
123
- framework: 'playwright' | 'pytest';
124
- code: string;
125
- codeVersion: string | null;
126
- etag?: string | null;
127
- }
128
- /** §6.4 TestStep wire shape. `null` is "not known", not "absent". */
129
- export interface CliTestStep {
130
- testId: string;
131
- stepIndex: number;
132
- action: string;
133
- description: string;
134
- status: 'passed' | 'failed' | null;
135
- screenshotUrl: string | null;
136
- htmlSnapshotUrl: string | null;
137
- runIdIfAvailable: string | null;
138
- codeVersion: string | null;
139
- capturedAt: string | null;
55
+ createdAt: string;
140
56
  updatedAt: string;
141
- /**
142
- * §6.4 / M2.1 piece 4 — derived flag the facade owns. `true` only on
143
- * step(s) that actually contributed to the test failure. `null`
144
- * when the underlying backend row hasn't been classified yet (pre-
145
- * M2.1 persistence). Optional on the wire so pre-M2.1 servers
146
- * that don't emit the field still type-check.
147
- */
148
- outcomeContributesToFailure?: boolean | null;
149
- /**
150
- * Per-step failure text, carried from `RunStepDto.error` on the run-scoped
151
- * endpoint (`GET /runs/{id}?includeSteps=true`). Only present on `--run-id`
152
- * responses; the cumulative `/tests/{id}/steps` rows do not carry it, so the
153
- * field stays optional (additive, non-breaking for existing consumers).
154
- */
155
- error?: string | null;
156
- /**
157
- * Wire step kind from `RunStepDto.type` on the run-scoped endpoint. Same
158
- * availability rules as `error`. Named `stepType` to avoid colliding with
159
- * the free-form `action` label above.
160
- */
161
- stepType?: 'action' | 'assertion';
162
- }
163
- /**
164
- * §6.5 failureKind enum (M2.1 piece 4 widened from six to nine values).
165
- * The CLI accepts unrecognized strings from the wire as `unknown` so
166
- * adding a future enum value (e.g. `quota_exceeded`) is non-breaking
167
- * — agents must not switch on raw strings outside the enumerated set.
168
- */
169
- export type CliFailureKind = 'assertion' | 'assertion_blocked' | 'routing_404' | 'network_timeout' | 'network' | 'timeout' | 'browser_crash' | 'infra' | 'unknown' | null;
170
- /** test VERDICT (the outcome of a completed run). */
171
- export type CliVerdict = 'passed' | 'failed' | 'blocked';
172
- /** execution LIFECYCLE (where the test is in its run lifecycle). */
173
- export type CliExecutionStatus = 'draft' | 'ready' | 'queued' | 'running' | 'completed' | 'cancelled' | 'unknown';
174
- /** §6.5 LatestResult wire shape. All correlation fields are required. */
175
- export interface CliLatestResult {
176
- testId: string;
177
- status: CliPublicStatus;
178
- startedAt: string | null;
179
- finishedAt: string | null;
180
- videoUrl: string | null;
181
- failureAnalysisUrl: string | null;
182
- snapshotId: string;
183
- runIdIfAvailable: string | null;
184
- codeVersion: string | null;
185
- /**
186
- * The target URL used for this run. May be `null` when `targetUrlSource`
187
- * is `'unresolved'` (the stored run row had no target URL and the backend
188
- * did not fall back to the project default).
189
- */
190
- targetUrl: string | null;
191
- /**
192
- * D1 — provenance of `targetUrl`. Present on backends that have shipped
193
- * the D1 fix; omitted on older backends (treat as unknown when absent).
194
- *
195
- * - `'run'` — URL was stored explicitly on the TestRun row.
196
- * - `'project-default'` — URL came from the project's configured default.
197
- * - `'unresolved'` — no URL on the run row AND no project default;
198
- * `targetUrl` will be `null`.
199
- * - `null` — backend sent the field explicitly as null
200
- * (semantically equivalent to `'unresolved'`).
201
- */
202
- targetUrlSource?: 'run' | 'project-default' | 'unresolved' | null;
203
- /**
204
- * The environment the latest run resolved to. Absent on an older backend;
205
- * `null` when the row names no environment.
206
- */
207
- environment?: RunEnvironmentRef | null;
208
- failedStepIndex: number | null;
209
- failureKind: CliFailureKind;
210
- /**
211
- * the test VERDICT only (`passed | failed | blocked`), or `null`
212
- * when the latest run produced no verdict yet (never run / queued / running /
213
- * cancelled). Lifecycle lives in `executionStatus`; `status` above is the
214
- * legacy conflated field, retained for back-compat.
215
- */
216
- verdict: CliVerdict | null;
217
- /** the execution LIFECYCLE (terminal runs collapse to `completed`). */
218
- executionStatus: CliExecutionStatus;
219
- /**
220
- * a human/agent-readable description of the latest run (replaces the
221
- * former `{passed,failed,skipped}` count object).
222
- */
223
- summary: string;
224
- /**
225
- * Captured stdout (`api_output`) from a backend-test execution.
226
- * Present (possibly null) only for backend tests; omitted for FE/MCP and on
227
- * older backends that omit them. Capped at 50 KB UTF-8 by the server.
228
- */
229
- apiOutput?: string | null;
230
- /**
231
- * Python traceback from a backend-test execution (ends with the
232
- * `ExceptionType: message` line). Present (possibly null) only for backend
233
- * tests; omitted for FE/MCP and on older backends.
234
- */
235
- trace?: string | null;
236
- /**
237
- * §6.5.1 (M2.1 piece 3) — inline failure analysis. Present when the
238
- * caller passed `--include-analysis` (`?includeAnalysis=true` on
239
- * the wire); absent on the byte-identical-to-pre-M2.1 default.
240
- */
241
- analysis?: CliAnalysisBlock;
242
- }
243
- /**
244
- * §6.5.1 (M2.1 piece 3) — analysis fields surfaced inline on
245
- * `/result?includeAnalysis=true` and as the body of `/failure/summary`.
246
- *
247
- * Stable shape: ships even on passing/in-flight runs with every field
248
- * inside `null`. `recommendedFixTarget` is `null` (not the always-
249
- * `unknown` wrapper) when the analysis pipeline didn't fill it.
250
- * `failureKind` mirrors `LatestResult.failureKind` for caller
251
- * convenience. `snapshotId` mirrors the outer snapshot, so a caller
252
- * comparing the inline analysis with a later `/failure` bundle can
253
- * detect drift without a second round-trip.
254
- */
255
- export interface CliAnalysisBlock {
256
- rootCauseHypothesis: string | null;
257
- recommendedFixTarget: CliFixTarget | null;
258
- failureKind: CliFailureKind;
259
- snapshotId: string;
260
- /**
261
- * L141 — set to `true` (JSON output only) when `rootCauseHypothesis`
262
- * ends with `…` (U+2026), indicating the server truncated the text.
263
- * Omitted when the field is null or untouched. This is a CLI-side
264
- * observation; the server does not send this field. Full untruncated
265
- * text requires backend support (backend follow-up).
266
- */
267
- rootCauseHypothesisTruncated?: true;
268
- /**
269
- * L141 — set to `true` (JSON output only) when
270
- * `recommendedFixTarget.rationale` ends with `…` (U+2026), indicating
271
- * the server truncated the rationale. Omitted when not truncated.
272
- */
273
- recommendedFixRationaleTruncated?: true;
274
- }
275
- /**
276
- * §5.2 (M2.1 piece 3) — body of `GET /tests/{testId}/failure/summary`.
277
- * One-screen agent triage answer: status + failureKind + analysis,
278
- * no bundle. Sibling of `failure get` for cases where the agent's
279
- * first pass doesn't need video / screenshots / DOM snapshots.
280
- */
281
- export interface CliFailureSummary {
282
- testId: string;
283
- status: CliPublicStatus;
284
- failureKind: CliFailureKind;
285
- snapshotId: string;
286
- rootCauseHypothesis: string | null;
287
- recommendedFixTarget: CliFixTarget | null;
288
- }
289
- /** §6.7 narrow fix-target enum. Agents route on this; M2 emits 'unknown'. */
290
- export type CliFixKind = 'code' | 'selector' | 'data' | 'env' | 'unknown';
291
- export type CliEvidenceKind = 'screenshot' | 'snapshot' | 'log' | 'network' | 'console';
292
- export interface CliFixTarget {
293
- kind: CliFixKind;
294
- reference: string | null;
295
- rationale: string | null;
296
- }
297
- export interface CliEvidence {
298
- kind: CliEvidenceKind;
299
- /** 1-based step index — matches portal display. */
300
- stepIndex: number;
301
- /** Presigned S3 URL with shared 15-min TTL. */
302
- url: string;
303
- /**
304
- * LLM-generated transcription per §6.1. The CLI emits whatever the
305
- * facade returned — never edited or generated client-side.
306
- */
307
- summary: string;
308
- }
309
- export interface CliFailureBlock {
310
- rootCauseHypothesis: string | null;
311
- /**
312
- * §6.7 / M2.1 piece 3 visibility policy: `null` when the analysis
313
- * pipeline didn't fill any of `kind` / `reference` / `rationale`.
314
- * Pre-M2.1 the facade always emitted an `unknown` wrapper here;
315
- * M2.1 drops it so agents route on `null` rather than parsing the
316
- * always-unknown shape.
317
- */
318
- recommendedFixTarget: CliFixTarget | null;
319
- evidence: CliEvidence[];
320
- /**
321
- * Backend-test execution artifacts, surfaced on the failure block
322
- * so triage has stdout + traceback next to the hypothesis (mirrors
323
- * `result.apiOutput` / `result.trace`). Present (possibly null) only for
324
- * backend failures; omitted for FE and on older backends.
325
- */
326
- apiOutput?: string | null;
327
- trace?: string | null;
328
- }
329
- /** §6.7 wire shape — one atomic snapshot of the latest failing run. */
330
- export interface CliFailureContext {
331
- snapshotId: string;
332
- testId: string;
333
- projectId: string;
334
- result: CliLatestResult;
335
- steps: CliTestStep[];
336
- code: CliTestCode;
337
- failure: CliFailureBlock;
338
57
  }
58
+ export type CliPublicStatus = 'draft' | 'ready' | 'queued' | 'running' | 'passed' | 'failed' | 'blocked' | 'cancelled' | 'unknown';
339
59
  export interface TestDeps {
340
60
  environmentCache?: Parameters<typeof resolveEnvironmentRunTarget>[0]['cache'];
341
- creationTargets?: ReadonlyMap<string, ResolvedRunTarget>;
342
- createdTests?: ReadonlyMap<string, RunTargetTest>;
343
61
  environmentTunnel?: EnvironmentTunnelContext;
344
62
  /** Report an exhausted poll deadline without changing the public output/error shape. */
345
63
  onWaitTimeout?: (context: WaitTimeoutTelemetry) => void;
@@ -348,12 +66,6 @@ export interface TestDeps {
348
66
  fetchImpl?: FetchImpl;
349
67
  stdout?: (line: string) => void;
350
68
  stderr?: (line: string) => void;
351
- /**
352
- * Raw stdout writer for streaming code bodies in `test code get`. No
353
- * implicit newline; each call writes verbatim. Defaults to
354
- * `process.stdout.write`. See `Output.writeChunk` for rationale.
355
- */
356
- rawStdout?: (text: string) => void;
357
69
  /**
358
70
  * Injectable sleep function for the polling loop. Defaults to the
359
71
  * `defaultSleep` in `poll.ts` (`setTimeout`-based). Inject an instant
@@ -367,1180 +79,149 @@ export interface TestDeps {
367
79
  * pattern as `sleep` / `fetchImpl`).
368
80
  */
369
81
  shutdown?: ShutdownHandle;
370
- /**
371
- * Tunnel-client factory for `test run --local`. Defaults
372
- * to the vendored `TunnelClient`; tests inject a fake so the command's
373
- * contract can be exercised without a real control plane — same pattern as
374
- * `sleep` / `fetchImpl` / `shutdown`.
375
- */
376
- createTunnelClient?: (options: TunnelClientOptions) => TunnelClientHandle;
377
- /**
378
- * Deprecation entries surfaced as a trailing `deprecations` key on JSON
379
- * object payloads. Set only by the deprecated commands' actions; every
380
- * `Output` built from these deps picks it up, so no print site changes.
381
- */
382
- deprecations?: readonly DeprecationEntry[];
383
- }
384
- /**
385
- * How a `--local` run's wait ended while the run was still non-terminal.
386
- * `tunnel-lost` is the one that is not a detach at all — it is the tunnel
387
- * dying under a run that is otherwise fine.
388
- */
389
- export type TunnelDetachReason = 'interrupt' | 'timeout' | 'request-timeout' | 'rate-limited' | 'tunnel-lost' | 'poll-error';
390
- /** What happened when we tried to stop a doomed tunnel run. */
391
- export type TunnelCancelOutcome = 'cancelled' | 'already-terminal' | 'failed' | 'skipped';
392
- export interface TunnelDetach {
393
- runId: string;
394
- testId: string;
395
- localPort: number;
396
- localHost: LoopbackHost;
397
- automatic?: boolean;
398
- environment?: string;
399
- reason: TunnelDetachReason;
400
- /** The borrowed tunnel owner disappeared while this run was non-terminal. */
401
- ownerGone?: boolean;
402
- cancel: TunnelCancelOutcome;
403
- terminalStatus?: RunStatus;
404
- }
405
- /** Tunnel-specific interrupt outcome consumed by the top-level JSON renderer. */
406
- export interface TunnelInterruptDetach {
407
- runId: string;
408
- cancel: TunnelCancelOutcome;
409
- nextAction: string;
410
- }
411
- /**
412
- * The stderr line for a tunnel run whose wait is ending.
413
- *
414
- * Deliberately NOT built from `stillRunningAndBillingSubject`: that sentence
415
- * is true for an ordinary run and false here, and the whole point of D1 (a)
416
- * is that the four detach paths stop telling a tunnel user something untrue.
417
- */
418
- export declare function tunnelDetachMessage(detach: TunnelDetach, interrupt?: InterruptError): string;
419
- export declare function tunnelInterruptNextAction(detach: TunnelDetach, err: InterruptError): string;
420
- type CommonOptions = FactoryCommonOptions;
421
- interface ListOptions extends CommonOptions {
422
- projectId?: string;
423
- environment?: string;
424
- type?: 'frontend' | 'backend';
425
- createdFrom?: 'portal' | 'mcp' | 'cli';
426
- /**
427
- * §6.6 / M2.1 piece 2 — comma-separated list of public status
428
- * values (e.g. `failed,blocked`). The CLI passes the raw string to
429
- * the facade which validates token-by-token. Pre-validating client-
430
- * side gives a friendlier error for typos like `--status fail`.
431
- */
432
- status?: string;
433
- pageSize?: number;
434
- startingToken?: string;
435
- maxItems?: number;
436
- columns?: string;
437
- noHeader?: boolean;
438
- }
439
- export declare function runList(opts: ListOptions, deps?: TestDeps): Promise<Page<CliTest>>;
440
- /**
441
- * §6.X / M3.2 piece-2 `CreateTestResponse` shape. `codeVersion` is the
442
- * monotonic stamp piece-1 added to FE/BE Portal rows; the CLI re-uses
443
- * it as the `If-Match` etag on `test code put` (piece-4).
444
- */
445
- export interface CliCreateTestResponse {
446
- testId: string;
447
- type: 'frontend' | 'backend';
448
- codeVersion: string;
449
- createdAt: string;
450
- /**
451
- * Non-fatal advisories from the backend (e.g. the BE auth guardrail
452
- * flagging a hardcoded credential). Rendered on stderr; the create
453
- * still succeeded.
454
- */
455
- warnings?: string[];
456
- /**
457
- * Server-built Portal deep link for the created test. Same
458
- * presence/absence contract as `RunResponse.dashboardUrl`
459
- * (`withRunDashboardUrl` below): PRESENT (string or falsy) on a backend
460
- * that resolved the question at all — a falsy value means "there is no
461
- * correct link for this test" (e.g. a V3-native create with no DynamoDB
462
- * mirror row for the client's V2-shaped guess to land on) and must never
463
- * be replaced by the client fallback; ABSENT on an older backend that
464
- * predates this field, which safely reopens the client fallback via
465
- * `resolveDashboardUrl` below. See that function's doc for the reasoning.
466
- */
467
- dashboardUrl?: string | null;
468
- }
469
- export declare const CLI_CREATE_PRIORITIES: readonly ["p0", "p1", "p2", "p3"];
470
- export type CliCreatePriority = (typeof CLI_CREATE_PRIORITIES)[number];
471
- /** Priority spellings accepted as input; reads return High/Medium/Low. */
472
- export declare const CLI_PRIORITY_INPUTS: readonly ["p0", "p1", "p2", "p3", "high", "medium", "low"];
473
- /**
474
- * Normalise a priority input (p0-p3 or high/medium/low, any case) to the
475
- * p0/p1/p2 wire value every backend accepts; p3 folds into p2 (Low).
476
- * Returns undefined for anything else.
477
- */
478
- export declare function normalizePriority(raw: unknown): 'p0' | 'p1' | 'p2' | undefined;
479
- interface CreateOptions extends CommonOptions {
480
- noWait?: boolean;
481
- environment?: string;
482
- projectId?: string;
483
- type: 'frontend' | 'backend';
484
- name: string;
485
- description?: string;
486
- priority?: string;
487
- /** Per-test timeout applied by the execution engine to every step. */
488
- stepTimeoutMs?: number;
489
- /** Source path to the test code. Read into memory; capped at 350 KB. */
490
- codeFile: string;
491
- /** Caller-supplied idempotency token; UUIDv4 minted client-side if absent. */
492
- idempotencyKey?: string;
493
- /** M3.3 chain: trigger a run after create. */
494
- run?: boolean;
495
- /** M3.3 chain: poll until terminal when `run` is true. */
496
- wait?: boolean;
497
- /** M3.3 chain: per-run timeout in seconds. */
498
- timeout?: number;
499
- /**
500
- * M4 piece-2 — BE dependency authoring flags.
501
- * `--produces <var>` (repeatable): variable names this test captures.
502
- * Maps to wire field `produces` → backend serialises as `captures` JSON.
503
- * Backend-only; supplying with --type frontend → exit 5 (FE has no wave model).
504
- */
505
- produces?: string[];
506
- /**
507
- * `--needs <var>` (repeatable): variable names this test consumes.
508
- * Maps to wire field `consumes`. Backend-only.
509
- */
510
- needs?: string[];
511
- /**
512
- * `--category <str>`: free-text category. Use `teardown`/`cleanup` to mark
513
- * a last-wave cleanup test in the wave planner. Backend-only.
514
- */
515
- category?: string;
516
- /**
517
- * B2(c): true when --timeout was NOT explicitly set (the default is in
518
- * effect). Threaded into RunTestRunOptions so the first-run hint fires.
519
- */
520
- timeoutIsDefault?: boolean;
521
- /** M3.3 chain: per-run target URL override. */
522
- targetUrl?: string;
523
- /** Skip the pre-charge --target-url reachability preflight (zero network calls). */
524
- skipPreflight?: boolean;
525
- }
526
- /**
527
- * `test create --code-file <path>` — M3.2 piece-2 first mutation.
528
- *
529
- * Reads the file (with the same 350 KB pre-flight the server enforces)
530
- * and POSTs to `/api/cli/v1/tests` with an `Idempotency-Key` header.
531
- * Default key is `cli-create-<uuidv4>`; a caller-supplied
532
- * `--idempotency-key` lets retry tooling pin the same key across
533
- * attempts so a network blip doesn't double-create. The exact key sent
534
- * is echoed to stderr at `--debug` so an operator can reuse it.
535
- *
536
- * Dry-run: the request still goes through `HttpClient.post`, but the
537
- * `client-factory` swaps in `createDryRunFetch` so no network call
538
- * happens — the caller sees the canned response shape from
539
- * `src/lib/dry-run/samples.ts`. The `--debug` events emit the canonical
540
- * request envelope (URL, method, headers including Idempotency-Key)
541
- * so the user can verify what would be sent. Matches the M2 P6
542
- * convention; no separate "envelope-only" output mode.
543
- */
544
- export declare function runCreate(opts: CreateOptions, deps?: TestDeps): Promise<CliCreateTestResponse>;
545
- /**
546
- * §6.X / M3.2 piece-6 — response from `PUT /tests/{id}/plan-steps`.
547
- * `planStepsHash` is a sha256 over the canonicalized new array so
548
- * agents can detect their own no-op replays without an extra read.
549
- * `stepCount` is the post-update array length.
550
- */
551
- export interface CliPutPlanStepsResponse {
552
- testId: string;
553
- planStepsHash: string;
554
- stepCount: number;
555
- updatedAt: string;
556
- }
557
- interface PlanPutOptions extends CommonOptions {
558
- testId: string;
559
- /** Source path to the new plan-step JSON file (`{ planSteps: [...] }`). */
560
- stepsFile: string;
561
- /**
562
- * Optional defensive concurrency check. Server rejects with 412
563
- * when the current entity's `planSteps.length !== N`. FE has no
564
- * `codeVersion`, so this is the only consistency knob.
565
- */
566
- expectedStepCount?: number;
567
- /**
568
- * Replace even when the server would drop structured fields
569
- * (action / selector / inputValue) from steps whose text changed. Also
570
- * skips the default step-count fence.
571
- */
572
- force?: boolean;
573
- /** Caller-supplied idempotency token; UUIDv4 minted client-side if absent. */
574
- idempotencyKey?: string;
575
- /**
576
- * When set alongside `--dry-run`, synthesises a 412 error envelope
577
- * so the user can preview the retry-hint output and exit code without
578
- * a real API key. Only `PRECONDITION_FAILED` is supported today.
579
- */
580
- dryRunSimulateError?: 'PRECONDITION_FAILED';
581
- }
582
- /**
583
- * `test plan put <test-id> --steps <plan.json>` — M3.2 piece-6.
584
- *
585
- * Replace an FE test's `planSteps[]` with the array in `--steps`. The
586
- * file is a single JSON object `{ planSteps: [...] }`; we don't echo
587
- * the full `CliPlanInput` shape here because `projectId` / `name` etc.
588
- * are not mutable from this endpoint.
589
- *
590
- * FE-only. BE tests get a 400 `VALIDATION_ERROR` from the server with
591
- * a `nextAction` pointing at `test code put`. The CLI does **not**
592
- * pre-fetch the test type — letting the server route saves a round
593
- * trip and matches the piece-6 spec's "server-side routing" decision.
594
- *
595
- * Concurrency: FE has no `codeVersion`, so updates are last-writer-
596
- * wins unless `--expected-step-count <N>` is passed, which sets
597
- * `If-Match-Step-Count`; the server rejects with 412 if the array length
598
- * differs.
599
- *
600
- * Idempotency: `cli-plan-put-<uuid>` is the default key, surfaced to
601
- * stderr so a transport retry can pin it.
602
- */
603
- export declare function runPlanPut(opts: PlanPutOptions, deps?: TestDeps): Promise<CliPutPlanStepsResponse>;
604
- /**
605
- * §6.X / M3.2 piece-3 `UpdateTestResponse` shape. `updatedFields` is
606
- * the array of top-level fields that changed in this call so JSON
607
- * consumers know what landed — useful when the agent passed all three
608
- * flags but the server normalized one to a no-op.
609
- */
610
- export interface CliUpdateTestResponse {
611
- testId: string;
612
- updatedFields: string[];
613
- updatedAt: string;
614
- }
615
- interface UpdateOptions extends CommonOptions {
616
- testId: string;
617
- /** Optional new name; at least one of `name`/`description`/`priority` must be set. */
618
- name?: string;
619
- /** Optional new description (`null` is reserved for "clear"; CLI surfaces both). */
620
- description?: string;
621
- /** Optional new priority. Enum-validated CLI-side. */
622
- priority?: string;
623
- /** Set the per-test timeout applied by the execution engine to every step. */
624
- stepTimeoutMs?: number;
625
- /** Clear the per-test step timeout and restore execution engine defaults. */
626
- clearStepTimeout?: boolean;
627
- /** Backend-only: variable names this test produces (repeatable --produces). */
628
- produces?: string[];
629
- /** Backend-only: variable names this test consumes (repeatable --needs); wire field `consumes`. */
630
- needs?: string[];
631
- /** Backend-only: free-text wave category (--category). */
632
- category?: string;
633
- /** Caller-supplied idempotency token; UUIDv4 minted client-side if absent. */
634
- idempotencyKey?: string;
635
- }
636
- /**
637
- * `test update <test-id>` — M3.2 piece-3.
638
- *
639
- * Metadata-only update: `name?`, `description?`, `priority?`. Code and
640
- * plan-steps are not part of this surface (`test code put` and
641
- * `test plan put` are the dedicated paths). The CLI does not even
642
- * expose `--code` / `--plan-steps` flags here so a caller cannot
643
- * accidentally try; the server would also reject those keys, but
644
- * keeping the surface narrow is the cheaper guard.
645
- *
646
- * Refuses no-op invocations (none of the three set) with a typed
647
- * `VALIDATION_ERROR` so a careless `test update <id>` doesn't burn a
648
- * request. The error includes the accepted field set so an agent
649
- * can self-correct without reading the help text.
650
- *
651
- * Idempotency-Key default is `cli-update-<uuid>`; a caller-supplied
652
- * `--idempotency-key` lets retry tooling pin the key. The generated
653
- * value is echoed to stderr so an operator who hits a transport
654
- * retry-budget exhaustion can re-run with the same key. Surfacing
655
- * matches piece-2's pattern.
656
- */
657
- export declare function runUpdate(opts: UpdateOptions, deps?: TestDeps): Promise<CliUpdateTestResponse>;
658
- /**
659
- * §6.X / M3.2 piece-3 `DeleteTestResponse` shape. `deletedAt` is the
660
- * delete timestamp (an ack) — hard-delete is immediate, so there is no
661
- * restore window.
662
- */
663
- export interface CliDeleteTestResponse {
664
- testId: string;
665
- deletedAt: string;
666
- }
667
- interface DeleteOptions extends CommonOptions {
668
- testId: string;
669
- /** Hard gate — required (unless `--dry-run` is set). No interactive prompts. */
670
- confirm: boolean;
671
- /** Caller-supplied idempotency token; UUIDv4 minted client-side if absent. */
672
- idempotencyKey?: string;
673
- }
674
- /**
675
- * `test delete <test-id> --confirm` — M3.2 piece-3.
676
- *
677
- * Permanent hard-delete via DELETE /tests/{id}. The server removes the
678
- * test row plus its steps and code object immediately — matching the
679
- * Portal's own delete behavior — so the test disappears everywhere at
680
- * once. There is no restore window.
681
- *
682
- * **`--confirm` is required** (unless `--dry-run`). Without either,
683
- * the CLI exits 5 `VALIDATION_ERROR` with a typed envelope explaining
684
- * the convention. The CLI never prompts interactively — matches the
685
- * CI-friendly contract from the CLI error spec §2.
686
- *
687
- * Re-delete on an already-deleted (or missing) row returns 404 from the
688
- * server. The CLI surfaces the envelope as-is; no client-side branching.
689
- */
690
- export declare function runDelete(opts: DeleteOptions, deps?: TestDeps): Promise<CliDeleteTestResponse>;
691
- /**
692
- * Per-test outcome record for `test delete-batch` and `test delete --all`.
693
- */
694
- export interface CliBulkDeleteResult {
695
- testId: string;
696
- status: 'deleted' | 'skipped' | 'error';
697
- /**
698
- * Present when `status === 'deleted'`. ISO 8601 timestamp from the server.
699
- */
700
- deletedAt?: string;
701
- /** Present when `status === 'error'`. Short error description. */
702
- error?: string;
703
- }
704
- export interface CliBulkDeleteSummary {
705
- results: CliBulkDeleteResult[];
706
- summary: {
707
- total: number;
708
- deleted: number;
709
- skipped: number;
710
- failed: number;
711
- };
712
- }
713
- interface DeleteBatchOptions extends CommonOptions {
714
- /** Explicit list of testIds to delete. */
715
- testIds: string[];
716
- /** --all: resolve all tests in the project and delete them. */
717
- all: boolean;
718
- /** --project <id>: required with --all. */
719
- projectId?: string;
720
- /**
721
- * --status <list>: with --all, only delete tests whose status matches.
722
- * Uses the same validated set as `test list --status`.
723
- */
724
- statusFilter?: string;
725
- /** Hard gate — required (unless --dry-run). */
726
- confirm: boolean;
727
- }
728
- /**
729
- * `test delete-batch <test-ids...>` and `test delete --all --project <id>` — dogfood L1800.
730
- *
731
- * Deletes tests sequentially (to avoid hammering the server) and aggregates
732
- * results into a single summary. Gated on `--confirm` (same convention as
733
- * `test delete`). Prints a summary line to stderr and the per-test results
734
- * object to stdout.
735
- *
736
- * Exit code: 0 if all targets were deleted (or `--dry-run`); 1 if any
737
- * deletion failed (server error); 5 if `--confirm` is missing.
738
- */
739
- export declare function runDeleteBatch(opts: DeleteBatchOptions, deps?: TestDeps): Promise<CliBulkDeleteSummary>;
740
- /**
741
- * §6.X / M3.2 piece-5 — plan-step structure. `description` is the
742
- * natural-language instruction the browser-use Lambda interprets at
743
- * run time. `type` is the action/assertion binary the FE pipeline
744
- * uses to decide whether a step is mutating UI or verifying state.
745
- */
746
- export interface CliPlanStep {
747
- type: 'action' | 'assertion';
748
- description: string;
749
- /**
750
- * Read-only view fields: structured steps carry the engine-level action
751
- * the Portal recorded. Optional because older backends omit them; they are
752
- * never part of a create / `plan put` request body.
753
- */
754
- action?: string;
755
- selector?: string;
756
- inputValue?: string;
757
- structured?: boolean;
758
- }
759
- /**
760
- * Plan-from input file shape. Mirrors the body the controller accepts
761
- * at `POST /api/cli/v1/tests` with `planSteps[]` (use-cases.md UC1).
762
- * `priority` and `description` are optional metadata; everything else
763
- * is required.
764
- *
765
- * FE-only after the 2026-05-13 scope cut. `type: "backend"` plans are
766
- * rejected pre-flight by the CLI with a `nextAction` pointing at
767
- * `test create --type backend --code-file <path>`.
768
- */
769
- export interface CliPlanInput {
770
- projectId: string;
771
- type: 'frontend' | 'backend';
772
- name: string;
773
- description?: string;
774
- priority?: string;
775
- planSteps: CliPlanStep[];
776
- }
777
- /**
778
- * §6.X / M3.2 piece-5 — response from POST /tests with planSteps[].
779
- * Same wire shape as the code-based create (piece-2) plus an optional
780
- * `planSteps` echo so the agent doesn't have to keep its own copy
781
- * between create and run. `planSteps` is absent in dry-run mode
782
- * because the sampler doesn't inspect the request body.
783
- */
784
- export interface CliCreateFromPlanResponse extends CliCreateTestResponse {
785
- planSteps?: CliPlanStep[];
786
- }
787
- /**
788
- * Public raw-content URL for
789
- * `schemas/plan.schema.json`, shipped in both the npm package (see
790
- * `package.json` `files`) and the repo. Points at the PUBLIC mirror
791
- * (`TestSprite/testsprite-cli`) since that's what ships to npm consumers;
792
- * the private atlas repo syncs to it via `scripts/make-public-snapshot.sh`.
793
- *
794
- * Pinned to the running CLI's own `v<VERSION>` git tag (the same `VERSION`
795
- * constant `--version` / `doctor` / the update-check registry probe already
796
- * read from `src/version.ts`) rather than the mutable `main` branch — a plan
797
- * file authored against one CLI version should resolve the SAME schema
798
- * forever, not whatever `main` happens to contain when the file is opened
799
- * months later (`main` can gain new required fields between versions).
800
- *
801
- * This is deliberately DIFFERENT from `schemas/plan.schema.json`'s own
802
- * internal `$id`, which stays the canonical `main` URL — `$id` is a schema
803
- * IDENTITY (what this document calls itself, used for cross-referencing),
804
- * not a fetch instruction, so it is intentionally version-independent.
805
- * `PLAN_SCHEMA_URL` is the fetch instruction embedded in generated plan
806
- * files and is intentionally version-PINNED. See DOCUMENTATION.md's "Plan
807
- * file format" section for the same distinction spelled out for humans.
808
- *
809
- * Caveat: the pinned tag only resolves once that version is actually
810
- * released — a locally-built/pre-release checkout may see a 404 until then.
811
- */
812
- export declare const PLAN_SCHEMA_URL = "https://raw.githubusercontent.com/TestSprite/testsprite-cli/v0.16.0/schemas/plan.schema.json";
813
- /**
814
- * The SINGLE canonical example plan. This
815
- * exact value (via `PLAN_TEMPLATE_TEXT` below) is:
816
- * - printed to stdout by `test create --plan-template`
817
- * - embedded verbatim in `test create --help` (`PLAN_TEMPLATE_HELP_TEXT`)
818
- * - asserted in tests against `schemas/plan.schema.json` and against
819
- * `assertPlanShape` so the three surfaces can't drift
820
- *
821
- * Deliberately minimal (no optional `description`/`priority`) — this is
822
- * the smallest shape `assertPlanShape` accepts, not a fully-annotated
823
- * showcase (that lives in `skills/testsprite-verify.skill.md`).
824
- */
825
- export declare const PLAN_TEMPLATE: CliPlanInput;
826
- /** `CliPlanInput` plus the optional editor-discoverability hint. */
827
- export interface PlanFileTemplate extends CliPlanInput {
828
- $schema: string;
829
- }
830
- /**
831
- * `$schema` is an ordinary extra property from `assertPlanShape`'s point of
832
- * view (no `additionalProperties` check exists on the plan-from path) — it
833
- * validates exactly like a bare `CliPlanInput` while giving editors (VS
834
- * Code's JSON language service, and by extension Copilot inline
835
- * completions) something to resolve for live validation as the file is
836
- * edited.
837
- */
838
- export declare const PLAN_TEMPLATE_WITH_SCHEMA: PlanFileTemplate;
839
- /**
840
- * Rendered once from the object above (never hand-formatted separately) so
841
- * `test create --plan-template`'s stdout and `test create --help`'s example
842
- * are generated from — not merely modeled on — the same source.
843
- */
844
- export declare const PLAN_TEMPLATE_TEXT: string;
845
- /** Per-spec result from `POST /tests/batch`. */
846
- export interface CliBatchSpecResult {
847
- /** Position of the spec in the input JSONL, preserved across the response. */
848
- specIndex: number;
849
- /** Spec outcome. Mirrors the server's per-spec status enum. */
850
- status: 'created' | 'validation_error' | 'not_found';
851
- /** Set on success. */
852
- testId?: string;
853
- /** Set on non-success. Carries the same envelope an `ApiError` would. */
854
- error?: {
855
- code: string;
856
- message: string;
857
- field?: string;
858
- };
859
- /**
860
- * Server-built Portal deep link for this created item. Same
861
- * presence/absence contract as `CliCreateTestResponse.dashboardUrl` —
862
- * see that field's doc.
863
- */
864
- dashboardUrl?: string | null;
865
- }
866
- export interface CliCreateBatchResponse {
867
- results: CliBatchSpecResult[];
868
- summary: {
869
- total: number;
870
- created: number;
871
- failed: number;
872
- };
873
- }
874
- /**
875
- * Per-run result from the `--run` fan-out on `test create-batch`.
876
- * Each entry mirrors the shape of a single `test run --wait` JSON output
877
- * so automation can process the array the same way it processes a single run.
878
- */
879
- export interface CliBatchRunResult {
880
- /** Test that was triggered. */
881
- testId: string;
882
- /** Run ID minted by the trigger call (or the in-flight runId on CONFLICT resume). */
883
- runId: string;
884
- /** Terminal status if `--wait`; `queued` if no `--wait`. */
885
- status: string;
886
- /** Code version resolved at trigger time. */
887
- codeVersion: string;
888
- /** Resolved target URL. */
889
- videoUrl?: string | null;
890
- /** Failure kind if status is `failed` or `blocked`. */
891
- failureKind?: string | null;
892
- /** Error envelope when the trigger itself failed (network/auth/validation). */
893
- error?: {
894
- code: string;
895
- message: string;
896
- exitCode: number;
897
- details?: Record<string, unknown>;
898
- };
899
- /**
900
- * Portal deep link (R3b), threaded through from the SAME per-item
901
- * create-time decision `test create-batch`'s own output carries — never
902
- * recomputed at run time. Absent when unresolvable OR explicitly
903
- * suppressed by the server (see `resolveDashboardUrl`'s doc).
904
- */
905
- dashboardUrl?: string;
906
- }
907
- /** Envelope emitted by `test create-batch --run` in JSON mode. */
908
- export interface CliCreateBatchRunResponse {
909
- results: CliBatchRunResult[];
910
- }
911
- /**
912
- * Default max in-flight run-triggers for `create-batch --run`.
913
- *
914
- * Rationale: the server caps run-triggers at 60/min/key
915
- * (`CLI_RUN_RATE_LIMIT_PER_MIN`, default 60 → `RATE_LIMITED` / exit 11).
916
- * A `create-batch` holds at most MAX_BATCH_SPECS (50) specs, so a default
917
- * of 50 lets a full batch dispatch all of its runs at once and finish
918
- * launching within a single window. With async Lambda invoke each trigger
919
- * returns in ~1s, so this bound mainly smooths the dispatch burst.
920
- *
921
- * NOTE: because 50 == MAX_BATCH_SPECS, a single `create-batch --run` can
922
- * never trip the client-side `BATCH_RUN_RATE_LIMIT` token bucket (also
923
- * 50/min) — the server's 60/min/key is the real backstop. The client
924
- * throttle still guards repeated runs within a window from one process.
925
- *
926
- * Callers can override this default via `--max-concurrency` (raising it
927
- * cannot lift the effective rate above the server cap).
928
- */
929
- export declare const DEFAULT_BATCH_RUN_CONCURRENCY = 50;
930
- /** Hard upper bound for --max-concurrency. Values above this are rejected with exit 5 (VALIDATION_ERROR). */
931
- export declare const MAX_BATCH_CONCURRENCY = 100;
932
- /** Client-side run-trigger throttle: 50 triggers per 60-second rolling window per key (sits just under the server's 60/min/key cap). */
933
- export declare const BATCH_RUN_RATE_LIMIT = 50;
934
- /** Rolling window duration (ms) for the client-side trigger rate throttle. */
935
- export declare const BATCH_RUN_RATE_WINDOW_MS = 60000;
936
- /** Maximum number of outer RATE_LIMITED retries inside the batch fan-out (beyond HTTP-layer retries). */
937
- export declare const BATCH_RUN_RATE_MAX_OUTER_RETRIES = 5;
938
- /**
939
- * Maximum number of outer RATE_LIMITED retries per member inside the multi-id
940
- * `test wait` fan-out (beyond HTTP-layer retries). Lower than the trigger
941
- * fan-out's budget on purpose: a throttled *poll* costs nothing but latency and
942
- * the run is already executing, so a couple of Retry-After-length backoffs is
943
- * enough to ride out one limiter window — burning the whole `--timeout` on
944
- * backoff instead of reporting the throttle would be worse than reporting it.
945
- */
946
- export declare const WAIT_POLL_RATE_MAX_OUTER_RETRIES = 3;
947
- /**
948
- * Backoff to honour before retrying a `RATE_LIMITED` response, in ms.
949
- *
950
- * Precedence: `ApiError.retryAfterMs` (set by `HttpClient` from the HTTP
951
- * `Retry-After` header, already clamped to [1s, 300s]) → `details.retryAfterSeconds`
952
- * from the envelope body, capped at 120s → 60s. Callers clamp the result to their
953
- * own remaining deadline; this function only decides "how long does the server
954
- * want us to wait."
955
- *
956
- * Shared by the `test run --all` trigger fan-out and the multi-id `test wait`
957
- * poll fan-out so the two can't drift — they were hand-copies of the same
958
- * precedence rule.
959
- */
960
- /**
961
- * Sleep that a termination signal cuts short by rejecting with the signal's
962
- * `InterruptError`, so the caller's existing catch owns the detach UX.
963
- *
964
- * Mirrors `HttpClient.sleepBeforeRetry` — an in-flight backoff must not be a
965
- * window where a first Ctrl-C waits for a timer before the command exits.
966
- */
967
- export declare function sleepUntilOrInterrupt(ms: number, signal: AbortSignal | undefined, sleep: (ms: number, signal?: AbortSignal) => Promise<void>): Promise<void>;
968
- export declare function resolveRateLimitRetryMs(err: ApiError): number;
969
- /**
970
- * Returns `true` when a `RATE_LIMITED` error is the **transient per-minute**
971
- * rate limit from `RunRateLimiterGuard` — the one worth retrying.
972
- *
973
- * The backend surfaces two distinct situations as `RATE_LIMITED` (429):
974
- *
975
- * 1. **Per-minute trigger cap** (RunRateLimiterGuard):
976
- * message = `"Run trigger rate limit exceeded: N triggers per minute per key."`
977
- * Has `Retry-After` header + `details.retryAfterSeconds`.
978
- * → TRANSIENT — safe to retry once the window expires.
979
- *
980
- * 2. **Insufficient credits** (InsufficientCreditsException):
981
- * message starts with `"Insufficient credits: N credit(s) required."`
982
- * No `Retry-After` header, no `details.retryAfterSeconds`.
983
- * → PERMANENT — retrying cannot succeed; only a top-up will fix it.
984
- *
985
- * We prefer a structural match (presence of `retryAfterMs` on the thrown
986
- * `ApiError`, which is set only when the HTTP response carried a `Retry-After`
987
- * header) as the primary discriminator, with the per-minute message wording as
988
- * a secondary guard. If both fields are absent we treat the error as permanent
989
- * to avoid silently burning the entire retry budget on a non-recoverable state.
990
- *
991
- * A 429 whose `details.reason` names a standing condition (see
992
- * `STANDING_RATE_LIMIT_REASONS` in `lib/http.ts` — e.g. the live
993
- * tunnel-binding cap) is also permanent, even though it now carries a real
994
- * `Retry-After`: that header says when a retry COULD first succeed if the
995
- * caller frees the resource, not that the condition clears on its own.
996
- *
997
- * Limitation: a hypothetical future backend that emits `RATE_LIMITED` for a
998
- * new reason without a `Retry-After` header AND without the per-minute
999
- * wording would be classified as permanent here. Document this if it occurs.
1000
- */
1001
- export declare function isTransientRateLimit(err: ApiError): boolean;
1002
- interface CreateFromPlanOptions extends CommonOptions {
1003
- noWait?: boolean;
1004
- environment?: string;
1005
- /** Path to the JSON file containing one `CliPlanInput`. */
1006
- planFrom: string;
1007
- /** Caller-supplied idempotency token; UUIDv4 minted client-side if absent. */
1008
- idempotencyKey?: string;
1009
- /**
1010
- * Reserved for the M3.3 chain. When `true`, the CLI will (once M3.3
1011
- * lands) call `POST /tests/{id}/runs` after the create returns. For
1012
- * v0.1.0 piece-5 this is wired but emits exit 7 `UNSUPPORTED`
1013
- * pointing at the Portal trigger.
1014
- */
1015
- run?: boolean;
1016
- /** Reserved for the M3.3 chain. Honored when `--run` is set. */
1017
- wait?: boolean;
1018
- /** Reserved for the M3.3 chain. Per-run timeout in seconds. */
1019
- timeout?: number;
1020
- /**
1021
- * B2(c): true when --timeout was NOT explicitly set (the default is in
1022
- * effect). Threaded into RunTestRunOptions so the first-run hint fires.
1023
- */
1024
- timeoutIsDefault?: boolean;
1025
- /** Reserved for the M3.3 chain. Per-run target URL override. */
1026
- targetUrl?: string;
1027
- /** Skip the pre-charge --target-url reachability preflight (zero network calls). */
1028
- skipPreflight?: boolean;
1029
- /**
1030
- * Names of `test create` flags the caller supplied that `--plan-from`
1031
- * ignores (identity lives in the JSON). Surfaced as a stderr advisory
1032
- * AFTER the plan validates, so a malformed plan (e.g. missing
1033
- * `projectId`) fails fast with a clear field error instead of the
1034
- * misleading "ignoring --project" line landing first (dogfood L1778).
1035
- */
1036
- ignoredFlags?: string[];
1037
- }
1038
- /**
1039
- * `test create --plan-from <plan.json>` — M3.2 piece-5.
1040
- *
1041
- * FE-only path: agent writes a `planSteps[]` JSON file describing the
1042
- * test in natural language; CLI ships it to the backend; backend
1043
- * stores it on `FrontendTestEntity` for the browser-use Lambda to
1044
- * interpret at run time. The plan is the test definition — no
1045
- * server-side LLM compile happens at create time (that was the
1046
- * 2026-05-13 BE codegen scope cut; FE was never on that path).
1047
- *
1048
- * BE plans rejected pre-flight: if `plan.json` has `type: "backend"`,
1049
- * exit 5 `VALIDATION_ERROR` with a `nextAction` pointing at
1050
- * `test create --type backend --code-file <path>`. Same envelope the
1051
- * server would return, just emitted without burning a round trip.
1052
- *
1053
- * `--run` is reserved for the M3.3 chain — currently exits 7
1054
- * `UNSUPPORTED` per piece-5 spec; rewires to a real `POST /runs` call
1055
- * when M3.3 lands.
1056
- */
1057
- export declare function runCreateFromPlan(opts: CreateFromPlanOptions, deps?: TestDeps): Promise<CliCreateFromPlanResponse>;
1058
- interface CreateBatchOptions extends CommonOptions {
1059
- noWait?: boolean;
1060
- environment?: string;
1061
- /** Path to the JSONL file containing one `CliPlanInput` per line. */
1062
- plans: string;
1063
- /**
1064
- * Path to a directory containing `*.json` plan files. Globs all `*.json`
1065
- * files (sorted by name for determinism), assembles them in-process into the
1066
- * same spec array as `--plans`, then runs the existing create-batch path.
1067
- * Mutually exclusive with `--plans`.
1068
- */
1069
- planFromDir?: string;
1070
- /** Caller-supplied idempotency token; UUIDv4 minted client-side if absent. */
1071
- idempotencyKey?: string;
1072
- /** When true, trigger a run for each created test after the batch create. */
1073
- run?: boolean;
1074
- /** With `--run`, max number of in-flight triggers at once (default: `DEFAULT_BATCH_RUN_CONCURRENCY` = 50). */
1075
- maxConcurrency?: number;
1076
- /** With `--run`, poll each run until terminal status before returning. */
1077
- wait?: boolean;
1078
- /** With `--run --wait`, per-run max seconds to wait (1..3600, default 600). */
1079
- timeoutSeconds?: number;
1080
- /** With `--run`, override the project default env URL for each triggered run. */
1081
- targetUrl?: string;
1082
- /** Skip the pre-charge --target-url reachability preflight (zero network calls). */
1083
- skipPreflight?: boolean;
1084
- }
1085
- /**
1086
- * `test create-batch --plans <plans.jsonl>` — M3.2 piece-5.
1087
- *
1088
- * Reads one `CliPlanInput` per line of the JSONL file, ships them as
1089
- * a single `POST /tests/batch` request, returns per-spec results.
1090
- * The endpoint is FE-only; any spec with `type: "backend"` returns
1091
- * `validation_error` per-spec without aborting siblings.
1092
- *
1093
- * Caps:
1094
- * - 50 specs per batch (CLI rejects locally before sending)
1095
- * - 5 MB total body (CLI checks after stringify)
1096
- * - 200 steps + 256 KB per individual plan (per-line validation)
1097
- *
1098
- * BE specs in the batch are flagged on stderr with their `specIndex`
1099
- * so the operator can see what will fail server-side, but the batch
1100
- * still proceeds — the FE specs are perfectly valid. No interactive
1101
- * prompt (the CLI is CI-friendly per piece-3's convention).
1102
- *
1103
- * Exit code: `0` if **any** spec succeeded (POSIX partial-success
1104
- * convention per use-cases.md UC2 item 6). Non-zero only when zero
1105
- * specs succeeded — in which case the underlying API failure is
1106
- * surfaced via the normal exit-code mapper.
1107
- *
1108
- * `--run` triggers each successfully-created test after the batch
1109
- * create completes. `--max-concurrency` bounds the in-flight trigger
1110
- * count. `--wait` polls each run until terminal. `--timeout` is
1111
- * per-run (not aggregate). Output in JSON mode is
1112
- * `{ results: CliBatchRunResult[] }`. Exit code: 0 if every run
1113
- * passed; 1 if any failed/blocked/cancelled; 7 if ALL runs timed out;
1114
- * falls back to 1 for mixed outcomes.
1115
- */
1116
- export declare function runCreateBatch(opts: CreateBatchOptions, deps?: TestDeps): Promise<CliCreateBatchResponse>;
1117
- interface GetOptions extends CommonOptions {
1118
- testId: string;
1119
- }
1120
- export declare function runGet(opts: GetOptions, deps?: TestDeps): Promise<CliTest>;
1121
- interface CodeGetOptions extends CommonOptions {
1122
- testId: string;
1123
- /**
1124
- * Optional output file path. When set, the source body (text mode) or
1125
- * the JSON envelope (json mode) is written to this file instead of
1126
- * stdout. Streaming + backpressure are preserved: presigned downloads
1127
- * pipe straight into the file's write stream so a multi-MB body never
1128
- * sits in memory waiting for the full download. Per
1129
- * the CLI validation spec §4 P4: "the CLI streams the body to stdout
1130
- * (or `--out`) without buffering the whole thing in memory."
1131
- */
1132
- out?: string;
1133
- }
1134
- /**
1135
- * `test code get` — fetches §6.3 `TestCode`. JSON mode prints the wire
1136
- * shape verbatim (the caller decides whether to follow `code` as a URL).
1137
- * Text mode prints the source body itself: inline bodies pass through
1138
- * directly; presigned URLs are dereferenced via the same fetch impl
1139
- * (without API-key headers — the URL is the bearer of authority).
1140
- *
1141
- * `--out <path>` redirects the same bytes into a file. We validate the
1142
- * path and open a sibling temp file before issuing the network request
1143
- * so a permission/dir error fails fast (exit 5 / VALIDATION_ERROR)
1144
- * without spending an API call. The temp file is renamed onto the real
1145
- * `--out` path only after a successful, complete write; on any error
1146
- * (or the "no code generated yet" branch, which writes nothing) the
1147
- * temp file is discarded and the user's pre-existing `--out` file, if
1148
- * any, is left untouched.
1149
- */
1150
- export declare function runCodeGet(opts: CodeGetOptions, deps?: TestDeps): Promise<CliTestCode>;
1151
- /**
1152
- * §6.X / M3.2 piece-4 `PutTestCodeResponse` shape. `codeVersion` is
1153
- * the freshly bumped value the server stamped on the entity. Used as
1154
- * the next call's `If-Match` so an agent can chain put → put without
1155
- * round-tripping through `test get` between writes.
1156
- */
1157
- export interface CliPutTestCodeResponse {
1158
- testId: string;
1159
- codeVersion: string;
1160
- updatedAt: string;
1161
- /**
1162
- * Non-fatal advisories (e.g. the BE auth guardrail flagging a hardcoded
1163
- * credential in the replaced code). Rendered on stderr; the update still
1164
- * succeeded.
1165
- */
1166
- warnings?: string[];
1167
- }
1168
- type CodePutLanguage = CliTestCode['language'];
1169
- interface CodePutOptions extends CommonOptions {
1170
- testId: string;
1171
- /** Source path to the new code body. Read into memory; capped at 350 KB. */
1172
- codeFile: string;
1173
- /**
1174
- * `If-Match: <codeVersion>` value. Mutually exclusive with `force`.
1175
- * When neither is set, the CLI auto-fetches the current
1176
- * `codeVersion` via `GET /tests/{id}/code` and uses that — a
1177
- * convenience for human callers; agents should set this explicitly.
1178
- */
1179
- expectedVersion?: string;
1180
- /** `--force` → sends `If-Match: *`. Audit-logged with `force: true`. */
1181
- force?: boolean;
1182
- /** Optional language override; server defaults from the test's existing language otherwise. */
1183
- language?: CodePutLanguage;
1184
- /** Caller-supplied idempotency token; UUIDv4 minted client-side if absent. */
1185
- idempotencyKey?: string;
1186
- /**
1187
- * When set alongside `--dry-run`, synthesises an error envelope and
1188
- * runs through the error-handler path so the user can preview the
1189
- * retry-hint output and exit code without a real API key.
1190
- * Only `PRECONDITION_FAILED` is supported today.
1191
- */
1192
- dryRunSimulateError?: 'PRECONDITION_FAILED';
1193
- }
1194
- /**
1195
- * `test code put <test-id> --code-file <path>` — M3.2 piece-4.
1196
- *
1197
- * Replace the test's code body with optimistic concurrency. Backend
1198
- * checks `If-Match: <codeVersion>` against the current entity row; on
1199
- * match, bumps to `v(N+1)` and writes the new body via
1200
- * `StorageService.saveCodeContent`. On mismatch, returns 412
1201
- * `PRECONDITION_FAILED` with `currentCodeVersion` in the error body so
1202
- * the caller can retry without an extra `GET`.
1203
- *
1204
- * Concurrency flag negotiation (CLI side):
1205
- *
1206
- * --expected-version <v> → If-Match: <v> (preferred for agents)
1207
- * --force → If-Match: * (audit-logged with force)
1208
- * (neither) → auto-fetch via GET, then If-Match: <fetched>
1209
- *
1210
- * The auto-fetch path is **a convenience for human callers**. Agents
1211
- * should always pass `--expected-version` explicitly because the
1212
- * auto-fetch introduces a TOCTOU window: a concurrent writer can bump
1213
- * the version between our GET and our PUT. The CLI emits a stderr
1214
- * advisory whenever it takes the auto-fetch path so an operator
1215
- * watching the run can see what `If-Match` value was used.
1216
- *
1217
- * `--force` and `--expected-version` are mutually exclusive — passing
1218
- * both is a caller bug and we reject locally (exit 5) rather than
1219
- * silently picking one. Same is true for missing `--code-file`.
1220
- *
1221
- * 412 handling: the CLI extracts `currentCodeVersion` from the error
1222
- * envelope's `details` block (server populates it per piece-1's
1223
- * `CliPreconditionFailedError`) and prints a typed retry hint. The
1224
- * underlying `ApiError` is re-thrown so the exit-code mapper in
1225
- * `index.ts` lands on exit 6 — the CLI does not auto-retry.
1226
- *
1227
- * Dry-run skips all I/O including the auto-fetch — we substitute the
1228
- * dry-run sample's `codeVersion` (`v3`) so the canned response makes
1229
- * sense (v3 → v4 bump). Matches piece-2's pattern.
1230
- */
1231
- export declare function runCodePut(opts: CodePutOptions, deps?: TestDeps): Promise<CliPutTestCodeResponse>;
1232
- interface StepsOptions extends CommonOptions {
1233
- testId: string;
1234
- pageSize?: number;
1235
- startingToken?: string;
1236
- maxItems?: number;
1237
- /**
1238
- * When set, fetch per-run steps from the authoritative run-scoped endpoint
1239
- * `GET /runs/{runId}?includeSteps=true` instead of client-filtering the
1240
- * cumulative `/tests/{id}/steps` response.
1241
- *
1242
- * Background: FE Portal step rows in `FrontendTestStepEntity` don't reliably
1243
- * carry per-run `runIdIfAvailable`, so client-side filtering of the cumulative
1244
- * list returns an empty result for every runId (even completed runs). The
1245
- * run-scoped endpoint reads from `TestRunStepEntity` directly and returns
1246
- * only the steps for that specific run.
1247
- *
1248
- * Pagination flags (`--page-size`, `--starting-token`, `--max-items`) are
1249
- * ignored when `--run-id` is supplied — the run-scoped endpoint returns all
1250
- * steps in a single response.
1251
- */
1252
- runId?: string;
1253
- }
1254
- export interface DiffOptions extends CommonOptions {
1255
- runA: string;
1256
- runB: string;
1257
- }
1258
- /** One step whose status flipped between the two compared runs. */
1259
- export interface CliDiffStep {
1260
- stepIndex: number;
1261
- statusA: string;
1262
- statusB: string;
1263
- /** First divergent failing side's error text, when the wire carried one. */
1264
- errorA?: string | null;
1265
- errorB?: string | null;
1266
- }
1267
- export interface CliRunDiff {
1268
- runA: {
1269
- runId: string;
1270
- testId: string;
1271
- status: string;
1272
- failureKind: string | null;
1273
- failedStepIndex: number | null;
1274
- codeVersion: string | null;
1275
- };
1276
- runB: {
1277
- runId: string;
1278
- testId: string;
1279
- status: string;
1280
- failureKind: string | null;
1281
- failedStepIndex: number | null;
1282
- codeVersion: string | null;
1283
- };
1284
- verdictChanged: boolean;
1285
- failedStepIndexChanged: boolean;
1286
- failureKindChanged: boolean;
1287
- codeVersionChanged: boolean;
1288
- /** True when the two runs belong to DIFFERENT tests (deltas may be meaningless). */
1289
- crossTest: boolean;
1290
- changedSteps: CliDiffStep[];
1291
- }
1292
- /**
1293
- * `test diff <runA> <runB>` (issue #124): isolate what regressed between two
1294
- * runs, the first question when CI goes red ("what changed since the last
1295
- * green run?"). Pure client-side composition of the existing per-run read
1296
- * (`GET /runs/{id}?includeSteps=true`); the endpoint accepts any two run-ids,
1297
- * so a cross-test pair is a WARNING, not an error. Exit 0 when the verdicts
1298
- * match, exit 1 when they differ, so the command is CI-scriptable —
1299
- * `--dry-run` honors the same contract: the canned sample has a
1300
- * changed verdict, so `test diff --dry-run` (with no overrides) exits 1,
1301
- * same as a real regressed pair would.
1302
- */
1303
- export declare function runDiff(opts: DiffOptions, deps?: TestDeps): Promise<CliRunDiff>;
1304
- export interface LintOptions extends CommonOptions {
1305
- planFrom?: string;
1306
- planFromDir?: string;
1307
- plans?: string;
1308
- steps?: string;
1309
- }
1310
- export interface CliLintIssue {
1311
- file: string;
1312
- field: string;
1313
- reason: string;
1314
- }
1315
- export interface CliLintReport {
1316
- checked: number;
1317
- valid: number;
1318
- issues: CliLintIssue[];
82
+ /**
83
+ * Tunnel-client factory for a run on a local environment. Defaults
84
+ * to the vendored `TunnelClient`; tests inject a fake so the command's
85
+ * contract can be exercised without a real control plane — same pattern as
86
+ * `sleep` / `fetchImpl` / `shutdown`.
87
+ */
88
+ createTunnelClient?: (options: TunnelClientOptions) => TunnelClientHandle;
1319
89
  }
1320
90
  /**
1321
- * `test lint` (issue #98): validate plan/steps files fully OFFLINE with the
1322
- * SAME validators the create paths run, but collecting EVERY problem instead
1323
- * of dying on the first one, and without any network write. The create-batch
1324
- * reader is first-error-fatal and only reachable through a command that POSTs,
1325
- * so authoring a 12-plan directory meant one error per paid round-trip. Zero
1326
- * network, zero credentials: exit 0 when everything is valid, 5 otherwise, so
1327
- * it drops into a pre-commit hook or CI step before `create-batch`.
1328
- *
1329
- * The collection granularity used to be per-FILE, not per-PROBLEM — a single
1330
- * plan with 6 independent field errors reported one at a time across 6
1331
- * fix-and-rerun cycles, because each file was validated through the
1332
- * throw-on-first `assertPlanShape`/`assertPlanStepsShape`. Every branch below
1333
- * now separates "parse the file" (still a single fatal issue on I/O/JSON
1334
- * failure — there's nothing left to validate) from "check the parsed shape"
1335
- * (routed through `collectPlanIssues` / `collectPlanStepsIssues`, which
1336
- * report every failing field in one pass).
91
+ * How a tunnel run's wait ended while the run was still non-terminal.
92
+ * `tunnel-lost` is the one that is not a detach at all — it is the tunnel
93
+ * dying under a run that is otherwise fine.
1337
94
  */
1338
- export declare function runLint(opts: LintOptions, deps?: TestDeps): Promise<CliLintReport>;
1339
- export interface ScaffoldOptions extends CommonOptions {
1340
- scaffoldType: 'frontend' | 'backend';
1341
- out?: string;
1342
- force: boolean;
95
+ export type TunnelDetachReason = 'interrupt' | 'timeout' | 'request-timeout' | 'rate-limited' | 'tunnel-lost' | 'poll-error';
96
+ /** What happened when we tried to stop a doomed tunnel run. */
97
+ export type TunnelCancelOutcome = 'cancelled' | 'already-terminal' | 'failed' | 'skipped';
98
+ export interface TunnelDetach {
99
+ /** The result id (wire name). */
100
+ resultId?: string;
101
+ /** The launch the result belongs to (wire name); absent on an older backend. */
102
+ runId?: string;
103
+ testId: string;
104
+ automatic?: boolean;
105
+ environment?: string;
106
+ reason: TunnelDetachReason;
107
+ /** The borrowed tunnel owner disappeared while this run was non-terminal. */
108
+ ownerGone?: boolean;
109
+ cancel: TunnelCancelOutcome;
110
+ terminalStatus?: RunStatus;
1343
111
  }
1344
- /** JSON payload `test scaffold --type backend` prints under --output json. */
1345
- export interface CliBackendScaffold {
1346
- type: 'backend';
1347
- language: 'python';
1348
- code: string;
112
+ /** Tunnel-specific interrupt outcome consumed by the top-level JSON renderer. */
113
+ export interface TunnelInterruptDetach {
114
+ /** The result id (wire name); the envelope prints it as `resultId`. */
115
+ resultId: string;
116
+ /** The launch (wire name); the envelope prints it as `runId` when known. */
117
+ runId?: string;
118
+ cancel: TunnelCancelOutcome;
119
+ nextAction: string;
1349
120
  }
1350
121
  /**
1351
- * `test scaffold` — emit a schema-correct starter test definition so a first
1352
- * test never starts from hand-copied JSON. Pure-local: no network, no
1353
- * credentials, no filesystem reads. The frontend template is a `CliPlanInput`
1354
- * (the exact shape `--plan-from` ingests; sourceRef: CliPlanInput /
1355
- * PLAN_STEP_TYPES above), so `scaffold | create --plan-from -`-style flows
1356
- * validate out of the box. The backend template is the minimal `requests`
1357
- * script the onboarding skill mandates: define a test function with a
1358
- * concrete status assertion, then CALL it (a defined-but-never-called test
1359
- * would pass without asserting anything).
1360
- */
1361
- export declare function runScaffold(opts: ScaffoldOptions, deps?: TestDeps): Promise<CliPlanInput | CliBackendScaffold>;
1362
- /**
1363
- * `test create --plan-template` — prints the canonical minimal
1364
- * valid plan file (`PLAN_TEMPLATE_WITH_SCHEMA` / `PLAN_TEMPLATE_TEXT`,
1365
- * defined above near `CliPlanInput`) to stdout and exits — before any of
1366
- * `test create`'s other flag handling runs. Pure-local: no network, no
1367
- * credentials, no filesystem I/O.
122
+ * The stderr line for a tunnel run whose wait is ending.
1368
123
  *
1369
- * Deliberately simpler than `test scaffold --type frontend` (which
1370
- * substitutes a live `TESTSPRITE_PROJECT_ID` when set, and supports
1371
- * `--out`): `--plan-template`'s job is a single deterministic ground-truth
1372
- * document that is BYTE-IDENTICAL every invocation, because it doubles as
1373
- * the literal example embedded in `test create --help` and the
1374
- * fixture asserted against `schemas/plan.schema.json` in tests.
124
+ * Deliberately NOT built from `stillRunningAndBillingSubject`: that sentence
125
+ * is true for an ordinary run and false here, and the whole point of D1 (a)
126
+ * is that the four detach paths stop telling a tunnel user something untrue.
1375
127
  */
1376
- export declare function runPlanTemplate(opts: CommonOptions, deps?: TestDeps): PlanFileTemplate;
1377
- export interface OpenOptions extends CommonOptions {
1378
- testId: string;
1379
- /** Print the URL only; never spawn a browser (SSH/headless/CI/agents). */
1380
- noBrowser: boolean;
128
+ export declare function tunnelDetachMessage(detach: TunnelDetach, interrupt?: InterruptError): string;
129
+ export declare function tunnelInterruptNextAction(detach: TunnelDetach, err: InterruptError): string;
130
+ type CommonOptions = FactoryCommonOptions;
131
+ interface ListOptions extends CommonOptions {
132
+ projectId?: string;
133
+ type?: 'frontend' | 'backend';
134
+ pageSize?: number;
135
+ startingToken?: string;
136
+ maxItems?: number;
137
+ columns?: string;
138
+ noHeader?: boolean;
1381
139
  }
140
+ export declare function runList(opts: ListOptions, deps?: TestDeps): Promise<Page<CliTest>>;
1382
141
  /**
1383
- * `test open <test-id>` (issue #121): jump from the terminal to the test's
1384
- * dashboard page. The CLI already computes this deep-link and prints it as
1385
- * text on other commands; this closes the last inch (the `gh browse` /
1386
- * `cypress open` hop). The URL is ALWAYS printed to stdout (so `--no-browser`
1387
- * and headless use still compose), then the OS browser is spawned unless
1388
- * --no-browser. An endpoint with no known portal mapping is a hard error
1389
- * rather than a silent no-op.
142
+ * §6.X / M3.2 piece-5 — plan-step structure. `description` is the
143
+ * natural-language instruction the browser-use Lambda interprets at
144
+ * run time. `type` is the action/assertion binary the FE pipeline
145
+ * uses to decide whether a step is mutating UI or verifying state.
1390
146
  */
1391
- export declare function runOpen(opts: OpenOptions, deps?: TestDeps, opener?: (url: string) => void): Promise<{
1392
- dashboardUrl: string;
1393
- }>;
1394
- export declare function runSteps(opts: StepsOptions, deps?: TestDeps): Promise<Page<CliTestStep>>;
1395
- interface ResultOptions extends CommonOptions {
1396
- testId: string;
147
+ export interface CliPlanStep {
148
+ type: 'action' | 'assertion';
149
+ description: string;
1397
150
  /**
1398
- * §6.5.1 (M2.1 piece 3) — when set, the CLI requests the inline
1399
- * `analysis` block from the facade and renders it under the result
1400
- * summary in text mode. JSON mode prints the wire envelope as
1401
- * received (the `analysis` block lives under the `analysis` key).
1402
- * Optional with default `false` so pre-M2.1 callers don't have to
1403
- * thread the flag through every call site.
151
+ * Read-only view fields: structured steps carry the engine-level action
152
+ * the Portal recorded. Optional because older backends omit them; they are
153
+ * never part of a request body.
1404
154
  */
1405
- includeAnalysis?: boolean;
155
+ action?: string;
156
+ selector?: string;
157
+ inputValue?: string;
158
+ structured?: boolean;
1406
159
  }
1407
- export declare function runResult(opts: ResultOptions, deps?: TestDeps): Promise<CliLatestResult>;
160
+ /** Default server dispatch limit per project execution without a tunnel. */
161
+ export declare const DEFAULT_BATCH_RUN_CONCURRENCY = 50;
162
+ /** Hard upper bound for the server execution cap. */
163
+ export declare const MAX_BATCH_CONCURRENCY = 100;
1408
164
  /**
1409
- * Parse a duration string (`24h`, `7d`) or ISO timestamp to an absolute
1410
- * ISO string for use as the `?since=` query parameter.
1411
- *
1412
- * - `24h` → `now - 24 hours`
1413
- * - `7d` → `now - 7 days`
1414
- * - Any other value is returned verbatim (assumed to be an ISO timestamp
1415
- * or epoch ms string that the server will validate).
165
+ * Sleep that a termination signal cuts short by rejecting with the signal's
166
+ * `InterruptError`, so the caller's existing catch owns the detach UX.
1416
167
  *
1417
- * Translation is done client-side per piece-5 design decision #3.
168
+ * Mirrors `HttpClient.sleepBeforeRetry` — an in-flight backoff must not be a
169
+ * window where a first Ctrl-C waits for a timer before the command exits.
1418
170
  */
1419
- export declare function parseDuration(raw: string, now?: Date): string;
1420
- interface ResultHistoryOptions extends CommonOptions {
1421
- testId: string;
1422
- /** Filter by trigger source. */
1423
- source?: RunSource;
1424
- /**
1425
- * Lower bound for `createdAt`. Accepts `24h`, `7d`, or an ISO timestamp.
1426
- * Translated client-side to an absolute ISO string before the request.
1427
- */
1428
- since?: string;
1429
- /** Page size 1–100 (default 20). */
1430
- pageSize?: number;
1431
- /** Opaque cursor from a prior page's `nextCursor`. */
1432
- cursor?: string;
1433
- /**
1434
- * Client-side rerun filter. `true` → only reruns (isRerun), `false` → only
1435
- * fresh runs, `undefined` → no filter. Applied to each page after the fetch.
1436
- */
1437
- rerun?: boolean;
1438
- /** `--env <name>`: only runs whose credentials came from this environment (server-side filter). */
1439
- environment?: string;
1440
- columns?: string;
1441
- noHeader?: boolean;
1442
- }
171
+ export declare function sleepUntilOrInterrupt(ms: number, signal: AbortSignal | undefined, sleep: (ms: number, signal?: AbortSignal) => Promise<void>): Promise<void>;
172
+ export declare function resolveRateLimitRetryMs(err: ApiError): number;
1443
173
  /**
1444
- * `test result <test-id> --history [options]`
174
+ * Returns `true` when a `RATE_LIMITED` error is the **transient per-minute**
175
+ * rate limit from `RunRateLimiterGuard` — the one worth retrying.
1445
176
  *
1446
- * List a test's prior runs (M3.4 piece-5). Complements the M2 `test result`
1447
- * "latest result" mode (unchanged). Branches on `--history` inside the shared
1448
- * action handler — the function exposed here is the `--history` branch only;
1449
- * bare `test result <id>` continues to call `runResult`.
1450
- */
1451
- export declare function runResultHistory(opts: ResultHistoryOptions, deps?: TestDeps): Promise<ListRunsResponse>;
1452
- interface FailureSummaryOptions extends CommonOptions {
1453
- testId: string;
1454
- }
1455
- /**
1456
- * `test failure summary <test-id>` — M2.1 piece 3.
177
+ * The backend surfaces two distinct situations as `RATE_LIMITED` (429):
1457
178
  *
1458
- * Sibling of `test failure get`. Returns one-screen failure triage
1459
- * info (status, failureKind, root-cause hypothesis, suggested fix
1460
- * target if the analysis pipeline produced one) without downloading
1461
- * video, screenshots, or DOM snapshots. The command an agent should
1462
- * reach for first when investigating a reported failure.
179
+ * 1. **Per-minute trigger cap** (RunRateLimiterGuard):
180
+ * message = `"Run trigger rate limit exceeded: N triggers per minute per key."`
181
+ * Has `Retry-After` header + `details.retryAfterSeconds`.
182
+ * → TRANSIENT — safe to retry once the window expires.
1463
183
  *
1464
- * 404 NOT_FOUND propagates as exit 4. The facade's `details.reason`
1465
- * (`not_found` / `no_failing_run`) reaches the user via the
1466
- * `nextAction` template.
1467
- */
1468
- export declare function runFailureSummary(opts: FailureSummaryOptions, deps?: TestDeps): Promise<CliFailureSummary>;
1469
- interface FailureGetOptions extends CommonOptions {
1470
- testId: string;
1471
- /**
1472
- * Directory to write the §7 disk layout into. When unset, the CLI
1473
- * prints the wire envelope (`--output json`) or a human summary
1474
- * (`--output text`) to stdout — useful for an agent piping straight
1475
- * to a vision-aware LLM. When set, stdout is silent on success
1476
- * (the on-disk artifact is the contract).
1477
- */
1478
- out?: string;
1479
- /** §7.4 — keep only the failed step ± 1 in `steps[]` and `evidence[]`. */
1480
- failedOnly: boolean;
1481
- }
1482
- export interface FailureGetResult {
1483
- /** The wire envelope as returned by the facade. */
1484
- context: CliFailureContext;
1485
- /** Set when `--out` was used; otherwise undefined. */
1486
- bundle?: WriteBundleResult;
1487
- }
1488
- /**
1489
- * `test failure get` — the agent-facing entry point. Fetches the §6.7
1490
- * `FailureContext` for `<test-id>` and either writes the §7 disk
1491
- * layout (when `--out` is set) or prints the wire envelope to stdout
1492
- * (default).
184
+ * 2. **Insufficient credits** (InsufficientCreditsException):
185
+ * message starts with `"Insufficient credits: N credit(s) required."`
186
+ * No `Retry-After` header, no `details.retryAfterSeconds`.
187
+ * → PERMANENT — retrying cannot succeed; only a top-up will fix it.
1493
188
  *
1494
- * Without `--out`:
1495
- * - `--output json` (the agent default) — full wire envelope on
1496
- * stdout. Presigned URLs left intact for the agent to fetch on
1497
- * its own.
1498
- * - `--output text` — human summary block (status, failureKind,
1499
- * failedStepIndex, hypothesis, fix target, evidence count).
189
+ * We prefer a structural match (presence of `retryAfterMs` on the thrown
190
+ * `ApiError`, which is set only when the HTTP response carried a `Retry-After`
191
+ * header) as the primary discriminator, with the per-minute message wording as
192
+ * a secondary guard. If both fields are absent we treat the error as permanent
193
+ * to avoid silently burning the entire retry budget on a non-recoverable state.
1500
194
  *
1501
- * With `--out <dir>`:
1502
- * - Atomic write under `<dir>/.tmp/...` → `rename()`. `meta.json`
1503
- * renames last; its presence implies "bundle complete and
1504
- * self-consistent." On any failure, `<dir>/.partial` is written
1505
- * and the CLI exits non-zero with the underlying error code.
1506
- * - stdout prints one line per output mode after the bundle is
1507
- * written, matching the rest of M2's `--out` ergonomics.
195
+ * A 429 whose `details.reason` names a standing condition (see
196
+ * `STANDING_RATE_LIMIT_REASONS` in `lib/http.ts` — e.g. the live
197
+ * tunnel-binding cap) is also permanent, even though it now carries a real
198
+ * `Retry-After`: that header says when a retry COULD first succeed if the
199
+ * caller frees the resource, not that the condition clears on its own.
1508
200
  *
1509
- * 404 NOT_FOUND propagates as exit 4. The facade's `details.reason`
1510
- * (`not_found` / `no_failing_run` / `no_code`) reaches the user via
1511
- * the `nextAction` template — the CLI doesn't re-derive its own
1512
- * remediation text per §5.4.
201
+ * Limitation: a hypothetical future backend that emits `RATE_LIMITED` for a
202
+ * new reason without a `Retry-After` header AND without the per-minute
203
+ * wording would be classified as permanent here. Document this if it occurs.
1513
204
  */
1514
- export declare function runFailureGet(opts: FailureGetOptions, deps?: TestDeps): Promise<FailureGetResult>;
205
+ export declare function isTransientRateLimit(err: ApiError): boolean;
206
+ interface GetOptions extends CommonOptions {
207
+ testId: string;
208
+ }
209
+ export declare function runGet(opts: GetOptions, deps?: TestDeps): Promise<CliTest>;
1515
210
  interface RunTestRunOptions extends CommonOptions {
1516
211
  knownTest?: RunTargetTest;
1517
212
  noWait?: boolean;
1518
213
  testId: string;
1519
- targetUrl?: string;
1520
- /**
1521
- * `false` only when the caller passed `--no-auto-heal`. Anything
1522
- * else leaves the field off the wire, which is how the server's protected
1523
- * default ("heal, but replay a user-authored body") is requested; see
1524
- * `TriggerRunBody.autoHeal` for why an explicit `true` is never sent.
1525
- */
1526
- autoHeal?: false;
1527
214
  /** BE only: run just the named test without expanding the producer/teardown closure. */
1528
215
  skipDependencies?: boolean;
1529
- /**
1530
- * Skip the pre-charge --target-url reachability preflight (zero
1531
- * network calls). Also set by a delegating caller (`runCreate`/
1532
- * `runCreateFromPlan` chaining `--run`) that already ran the same probe
1533
- * against the same URL before its own create POST, so this run doesn't
1534
- * probe twice.
1535
- */
216
+ /** Skip a local environment's port check before its tunnel opens (zero network calls). */
1536
217
  skipPreflight?: boolean;
1537
218
  wait: boolean;
1538
219
  timeoutSeconds: number;
1539
220
  /**
1540
221
  * B2(c): true when --timeout was not explicitly set by the user (the default
1541
222
  * is in effect). Used to decide whether to emit the first-run hint.
1542
- * Defaults to false (no hint) when not set; only the `test run` / `test
1543
- * create --run` command wiring sets this to `cmdOpts.timeout === undefined`.
223
+ * Defaults to false (no hint) when not set; only the `run` command
224
+ * wiring sets this to `cmdOpts.timeout === undefined`.
1544
225
  */
1545
226
  timeoutIsDefault?: boolean;
1546
227
  idempotencyKey?: string;
@@ -1552,36 +233,6 @@ interface RunTestRunOptions extends CommonOptions {
1552
233
  ghOutput?: boolean;
1553
234
  /** --summary-file: also write the reduced machine summary JSON to this path. */
1554
235
  summaryFile?: string;
1555
- /**
1556
- * Per codex round-1 P1: when chained from `test create --run`, the caller
1557
- * passes the create response here so `runTestRun` can emit a single merged
1558
- * envelope `{ ...createContext, run: <trigger|final> }` on stdout. Without
1559
- * this, `test create --run --output json` produces two JSON objects back-to-
1560
- * back and agents cannot `JSON.parse` the result.
1561
- */
1562
- createContext?: CliCreateTestResponse | CliCreateFromPlanResponse;
1563
- /**
1564
- * Optional type hint supplied by the caller when the type is already known
1565
- * client-side (e.g. the `test create --run` chain knows `opts.type`).
1566
- * Used to derive `isBackend` for the step-summary renderer BEFORE the
1567
- * `beFallbackUsed` fallback fires, so fast backend runs that are terminal
1568
- * on the first poll still render `steps: n/a (backend)` correctly.
1569
- * Leave unset for `test run <id>` where the type is only discoverable via
1570
- * the `resolveAlternate` probe (an extra round-trip we deliberately avoid).
1571
- */
1572
- type?: 'frontend' | 'backend';
1573
- /**
1574
- * `--local <port>` — run against an app on THIS machine, reached through a
1575
- * TestSprite tunnel. Implies `--wait` (the tunnel's lifetime is this
1576
- * process's lifetime) and is mutually exclusive with `--target-url`.
1577
- */
1578
- localPort?: number;
1579
- /**
1580
- * `--local-host` — which loopback spelling to name in the run's target URL.
1581
- * Already normalised and validated by the command wiring; the accepted set
1582
- * is `lib/local-target.ts::LOOPBACK_HOSTS`, which mirrors the server's.
1583
- */
1584
- localHost?: LoopbackHost;
1585
236
  /**
1586
237
  * `--tunnel-client <id>` — attach to a tunnel someone else already started
1587
238
  * (`testsprite tunnel start`) instead of minting one. The client id is a
@@ -1598,242 +249,161 @@ interface RunTestRunOptions extends CommonOptions {
1598
249
  */
1599
250
  cancelOnInterrupt?: boolean;
1600
251
  /**
1601
- * `--env <name>` — the project environment whose credentials, auto-auth and
1602
- * OTP settings this run uses. Composes with `--local` / `--target-url` (those
1603
- * choose WHERE the browser goes; this chooses WHOSE login it uses). Absent →
1604
- * the project's default environment, byte-identical to today. Feature-gated
1605
- * per workspace: checked client-side before anything is minted or billed.
1606
- */
1607
- environment?: string;
1608
- }
1609
- interface RunTestWaitOptions extends CommonOptions {
1610
- runId: string;
1611
- timeoutSeconds: number;
1612
- }
1613
- interface RunTestRerunOptions extends CommonOptions {
1614
- knownTests?: ReadonlyMap<string, Pick<CliTest, 'type' | 'projectId'>>;
1615
- noWait?: boolean;
1616
- skipPreflight?: boolean;
1617
- concurrencyIsDefault?: boolean;
1618
- batchResolved?: boolean;
1619
- /** One or more testIds to rerun. Empty + all=false → validation error (exit 5). */
1620
- testIds: string[];
1621
- /** --all: resolve all tests in the project and batch-rerun them. */
1622
- all: boolean;
1623
- /** --project: used with --all to resolve the project's tests. */
1624
- projectId?: string;
1625
- /** --wait: block until terminal (or --timeout). */
1626
- wait: boolean;
1627
- /** Polling / overall deadline. Default 600, max 3600. */
1628
- timeoutSeconds: number;
1629
- /**
1630
- * Auto-heal: defaults true for FE reruns (use --no-auto-heal to opt out).
1631
- * Backend ignores the server-side tier gate for CLI callers — Free + paid
1632
- * both get auto-heal; charged 0.2 credits per engage when Phase-2 runs.
1633
- */
1634
- autoHeal: boolean;
1635
- /**
1636
- * Whether the user explicitly requested a specific auto-heal state via a
1637
- * flag (as opposed to the default-on value). Used to suppress the BE-test
1638
- * "ignoring auto-heal" warning when the value was never explicitly set.
1639
- *
1640
- * With `--no-auto-heal` as the only flag (no `--auto-heal`), this is always
1641
- * false — the default-on value is never an explicit user request, so the BE
1642
- * warning is suppressed on every default-on rerun. Only future addition of
1643
- * an explicit `--auto-heal` flag would set this to true.
252
+ * `--env <name>` — the project environment this run uses: its address,
253
+ * credentials, auto-auth and OTP settings. Absent → the project's default
254
+ * environment. Feature-gated per workspace: checked client-side before
255
+ * anything is minted or billed.
1644
256
  */
1645
- autoHealExplicit: boolean;
1646
- /** --skip-dependencies: BE only. Don't expand the producer/teardown closure. */
1647
- skipDependencies: boolean;
1648
- /** `--env <name>`: see `RunTestRunOptions.environment` — the environment to replay against. */
1649
257
  environment?: string;
1650
- /** --max-concurrency: bounds the --wait poll fan-out (batch / BE closure). */
1651
- maxConcurrency: number;
1652
- /** --idempotency-key: caller-supplied; auto-minted UUID when absent. */
1653
- idempotencyKey?: string;
1654
- /**
1655
- * --skip-terminal: with --all, exclude tests already in a terminal status
1656
- * (passed|failed|blocked|cancelled) before dispatch so an interrupted sweep
1657
- * doesn't re-replay finished tests.
1658
- */
1659
- skipTerminal?: boolean;
1660
- /**
1661
- * --status <list>: comma-separated list of public status values. With --all,
1662
- * only tests whose status matches one of the listed values are dispatched.
1663
- * Reuses the same validated set as `test list --status`.
1664
- */
1665
- statusFilter?: string;
1666
- /**
1667
- * --filter <substr>: with --all, only rerun tests whose name contains this
1668
- * substring (case-insensitive). Applied after --skip-terminal and --status
1669
- * filters. Client-side only.
1670
- */
1671
- nameFilter?: string;
1672
- /** --report junit: write a JUnit XML sidecar after batch --wait completes. */
1673
- report?: JUnitReportFormat;
1674
- /** --report-file: destination path for the JUnit XML artifact. */
1675
- reportFile?: string;
1676
- /** --report-suite-name: optional override for the JUnit <testsuite name=...>. */
1677
- reportSuiteName?: string;
1678
- /**
1679
- * --gh-output: force the GitHub-native output layer (::error:: annotations +
1680
- * job-summary table) on the batch-rerun `--wait` result, even off-Actions.
1681
- */
1682
- ghOutput?: boolean;
1683
- /** --summary-file: also write the reduced machine summary JSON to this path. */
1684
- summaryFile?: string;
1685
- /**
1686
- * --allow-empty: with --all, exit 0 (instead of failing with exit 5) when the
1687
- * resolved test set is EMPTY — no tests match --filter/--status/--skip-terminal,
1688
- * or the project has none. Mirrors `test run --all --allow-empty`;
1689
- * it does NOT cover ids the server rejected (notFound still gates, exit 4).
1690
- */
1691
- allowEmpty?: boolean;
1692
- }
1693
- /** Minimal client surface the backend-test wait fallback needs. */
1694
- interface ResultReadClient {
1695
- get<T>(path: string, options?: {
1696
- signal?: AbortSignal;
1697
- }): Promise<T>;
1698
258
  }
1699
- /**
1700
- * Overlay a terminal testId-scoped {@link CliLatestResult} onto the polled
1701
- * (non-terminal) {@link RunResponse} so a backend test whose run-surface row
1702
- * never finalizes still renders a complete, correctly-correlated run envelope.
1703
- * The real correlation metadata (`runId`, `testId`, `projectId`, `userId`,
1704
- * `source`, `createdAt`, `createdFrom`) is preserved from the polled run row;
1705
- * only the verdict/result fields are taken from the test record (codex
1706
- * round-2: don't fabricate blank correlation fields).
1707
- */
1708
- export declare function backendResultToRunResponse(result: CliLatestResult, run: RunResponse, testTitle?: string | null): RunResponse;
1709
- /**
1710
- * Decide whether a testId-scoped result belongs to THIS run (vs a stale
1711
- * verdict from a prior run of the same test). Backend serializes runs per
1712
- * testId, so the next terminal verdict after our trigger is ours — but a
1713
- * just-finished prior run could still be showing. Gate:
1714
- * - result names our runId → accept (strongest signal);
1715
- * - result names a different runId → reject (a different run);
1716
- * - result has no runId (legacy) → accept iff finishedAt >= notBefore.
1717
- */
1718
- export declare function backendResultIsForThisRun(result: CliLatestResult, runId: string, notBefore: string | undefined): boolean;
1719
- /**
1720
- * Build a `resolveAlternate` callback for `pollRunUntilTerminal` that falls
1721
- * back to the testId-scoped verdict for **backend** tests (dogfood L1888).
1722
- *
1723
- * - The first non-terminal run tick does a one-time `GET /tests/{id}` to learn
1724
- * the test type (cached). Frontend tests → no-op forever, so the FE path is
1725
- * byte-identical to before.
1726
- * - For backend tests, each later non-terminal tick reads
1727
- * `GET /tests/{id}/result`; once that record is terminal AND belongs to this
1728
- * run, a synthesized terminal `RunResponse` resolves the wait (exit 0/1)
1729
- * instead of timing out (exit 7).
1730
- * - Every lookup is best-effort: any error → "keep polling the run row", so
1731
- * the fallback can never make either path worse than the prior timeout.
1732
- */
1733
- export declare function makeBackendWaitFallback(args: {
1734
- client: ResultReadClient;
1735
- resolveTestId: (run: RunResponse) => string;
1736
- resolveNotBefore: (run: RunResponse) => string | undefined;
1737
- onResolved?: (testId: string, status: CliPublicStatus) => void;
1738
- }): (run: RunResponse, elapsedMs: number, signal: AbortSignal) => Promise<RunResponse | null>;
1739
- /**
1740
- * Render a `RunResponse` to human-readable text. JSON mode callers get
1741
- * the wire envelope via `out.print`.
1742
- *
1743
- * Pass `isBackend: true` to suppress the per-step breakdown (BE tests are
1744
- * atomic — no per-step breakdown exists; showing `0/0 (passed=0, failed=0)`
1745
- * reads like a no-op rather than a passing/failing atomic result).
1746
- */
1747
- export declare function renderRunResponseText(run: RunResponse, { isBackend }?: {
1748
- isBackend?: boolean;
1749
- }): string;
1750
- export declare function runTestRun(opts: RunTestRunOptions, deps?: TestDeps): Promise<TriggerRunResponse | RunResponse>;
1751
- /** One row of the `test wait <run-id...>` multi-run payload. */
1752
- export interface CliMultiWaitResult {
1753
- runId: string;
1754
- /** Terminal run status, or 'timeout', or 'error:<CODE>' when the poll failed. */
1755
- status: string;
1756
- /** Test the run belongs to, when the poll observed it. */
1757
- testId?: string;
1758
- }
1759
- export interface RunTestWaitManyOptions extends CommonOptions {
259
+ /** Reject an explicitly empty name filter; omission alone selects every test. */
260
+ export declare function parseNameFilter(raw: string | undefined): string | undefined;
261
+ export declare function runTestRun(opts: RunTestRunOptions, deps?: TestDeps): Promise<ProjectLaunchOutput>;
262
+ export interface RunTestWaitOptions extends CommonOptions {
263
+ /** The runs to wait for, as `run` prints them. */
1760
264
  runIds: string[];
1761
265
  timeoutSeconds: number;
1762
- maxConcurrency: number;
1763
266
  }
1764
- /**
1765
- * `test wait <run-id...>` with two or more ids: attach to N already-dispatched
1766
- * runs in ONE invocation. This closes the loop the CLI itself opens: every
1767
- * batch/closure timeout prints one `testsprite test wait <runId>` hint PER
1768
- * member, which previously meant N sequential blocking invocations. The runs
1769
- * are polled concurrently under a bounded pool with ONE shared deadline
1770
- * (`--timeout` bounds the whole invocation, not each member), each member's
1771
- * poll is total (a transient error on one run never discards the others), and
1772
- * the exit code is the worst status across members: auth errors escalate to
1773
- * exit 3, any timeout or poll error exits 7, any non-passed terminal exits 1.
1774
- * Distinct from a run journal (issue #80): no persistence, just N known ids.
1775
- */
1776
- export declare function runTestWaitMany(opts: RunTestWaitManyOptions, deps?: TestDeps): Promise<{
1777
- results: CliMultiWaitResult[];
1778
- summary: Record<string, number>;
267
+ /** Wait for each execution to finish, including results created after its unit phase. */
268
+ export declare function runTestWait(opts: RunTestWaitOptions, deps?: TestDeps): Promise<{
269
+ summary: RunCounts;
270
+ thenPoll?: string | undefined;
271
+ dryRun: boolean;
272
+ requests: {
273
+ method: "GET" | "POST";
274
+ path: string;
275
+ body?: unknown;
276
+ idempotencyKey?: string;
277
+ }[];
278
+ partial?: true | undefined;
279
+ runFailures?: {
280
+ runId: string;
281
+ status: "cancelled" | "error" | "timeout";
282
+ message: string;
283
+ }[] | undefined;
284
+ runs: {
285
+ cancel?: string;
286
+ error?: ({
287
+ code: string;
288
+ message: string;
289
+ exitCode?: number;
290
+ nextAction?: string;
291
+ serverNextAction?: string;
292
+ requestId?: string;
293
+ details?: Record<string, unknown>;
294
+ apiUrl?: string;
295
+ } & {
296
+ exitCode: number;
297
+ }) | undefined;
298
+ timedOut?: boolean | undefined;
299
+ listed?: boolean | undefined;
300
+ status?: "running" | (string & {}) | "finished" | undefined;
301
+ cancelled?: boolean | null | undefined;
302
+ runId: string;
303
+ projectId?: string | null | undefined;
304
+ created?: string | null | undefined;
305
+ modified?: string | null | undefined;
306
+ targetUrl?: string | null | undefined;
307
+ dashboardUrl?: string | null | undefined;
308
+ blocked?: {
309
+ testId: string;
310
+ resultId: string;
311
+ reason: string;
312
+ message?: string;
313
+ }[] | undefined;
314
+ environment?: import("../lib/runs.types.js").RunEnvironmentRef | null | undefined;
315
+ total?: number | undefined;
316
+ autoHeal?: boolean | undefined;
317
+ enqueuedAt?: string | undefined;
318
+ maxConcurrency?: number | undefined;
319
+ tunnelClientId?: string | undefined;
320
+ held?: {
321
+ testId: string;
322
+ runId: string;
323
+ resultId: string;
324
+ }[] | undefined;
325
+ joined?: boolean;
326
+ }[];
327
+ results: RunResult[];
328
+ } | {
329
+ summary: RunCounts;
330
+ partial?: true | undefined;
331
+ runFailures?: {
332
+ runId: string;
333
+ status: "cancelled" | "error" | "timeout";
334
+ message: string;
335
+ }[] | undefined;
336
+ runs: {
337
+ cancel?: string;
338
+ error?: ({
339
+ code: string;
340
+ message: string;
341
+ exitCode?: number;
342
+ nextAction?: string;
343
+ serverNextAction?: string;
344
+ requestId?: string;
345
+ details?: Record<string, unknown>;
346
+ apiUrl?: string;
347
+ } & {
348
+ exitCode: number;
349
+ }) | undefined;
350
+ timedOut?: boolean | undefined;
351
+ listed?: boolean | undefined;
352
+ status?: "running" | (string & {}) | "finished" | undefined;
353
+ cancelled?: boolean | null | undefined;
354
+ runId: string;
355
+ projectId?: string | null | undefined;
356
+ created?: string | null | undefined;
357
+ modified?: string | null | undefined;
358
+ targetUrl?: string | null | undefined;
359
+ dashboardUrl?: string | null | undefined;
360
+ blocked?: {
361
+ testId: string;
362
+ resultId: string;
363
+ reason: string;
364
+ message?: string;
365
+ }[] | undefined;
366
+ environment?: import("../lib/runs.types.js").RunEnvironmentRef | null | undefined;
367
+ total?: number | undefined;
368
+ autoHeal?: boolean | undefined;
369
+ enqueuedAt?: string | undefined;
370
+ maxConcurrency?: number | undefined;
371
+ tunnelClientId?: string | undefined;
372
+ held?: {
373
+ testId: string;
374
+ runId: string;
375
+ resultId: string;
376
+ }[] | undefined;
377
+ joined?: boolean;
378
+ }[];
379
+ results: RunResult[];
1779
380
  }>;
1780
381
  export interface RunTestCancelOptions extends CommonOptions {
382
+ /** The runs to cancel, as `run` prints them. */
1781
383
  runIds: string[];
1782
384
  }
1783
- /** One run's outcome in a multi-id `test cancel` summary. */
1784
- export interface CliCancelResultRow {
1785
- runId: string;
1786
- status: 'cancelled' | 'alreadyCancelled' | 'conflict' | 'notFound' | 'error';
1787
- /** Terminal status the run was already in, for a `conflict` row. */
1788
- conflictStatus?: string;
1789
- error?: string;
1790
- }
1791
- /** JSON payload for a multi-id `test cancel`. */
385
+ /** Execution ID lists and errors; each run response carries its result outcomes. */
1792
386
  export interface CliCancelSummary {
1793
387
  cancelled: string[];
1794
388
  alreadyCancelled: string[];
1795
- conflicts: Array<{
1796
- runId: string;
1797
- status: string;
1798
- }>;
389
+ /** Executions that had finished before cancellation. */
390
+ alreadyFinished: string[];
1799
391
  notFound: string[];
1800
392
  /**
1801
- * Runs that errored for a reason other than 404/409 (e.g. auth, transport).
1802
- * Always present — an empty array on full success — so machine consumers
1803
- * can rely on a stable shape.
393
+ * Results whose cancel failed for a reason other than 404/409 (e.g. auth,
394
+ * transport). Always present — an empty array on full success — so machine
395
+ * consumers can rely on a stable shape.
1804
396
  */
1805
397
  errors: Array<{
1806
398
  runId: string;
1807
399
  message: string;
1808
400
  }>;
1809
401
  }
1810
- /**
1811
- * `test cancel <run-id...>`.
1812
- *
1813
- * User-initiated cancel of one or more queued/running runs via
1814
- * `POST /api/cli/v1/runs/{runId}/cancel`. Naturally idempotent: a
1815
- * repeat cancel of the same run is a 200 `alreadyCancelled` success, not an
1816
- * error. Dispatches serially (per-id volume is tiny — no batch endpoint;
1817
- * a batch-level cancel endpoint would be YAGNI).
1818
- *
1819
- * Single id: renders the returned run card (`status cancelled`); an
1820
- * `alreadyCancelled` response adds an `[advisory]` line. Exit code mirrors
1821
- * the server response directly — 0 on success (fresh or already-cancelled),
1822
- * 4 on 404 (unknown/cross-tenant), 6 on 409 (already terminal).
1823
- *
1824
- * Multi-id: prints a `{cancelled, alreadyCancelled, conflicts, notFound}`
1825
- * summary. Exit precedence (CXL-11): any `notFound` → 4 (outranks conflict —
1826
- * it signals a caller bug, wrong id/tenant); else any `conflicts` → 6; else 0.
1827
- */
1828
- export declare function runTestCancel(opts: RunTestCancelOptions, deps?: TestDeps): Promise<CancelRunResponse | CliCancelSummary>;
402
+ /** Cancel each execution once; the server owns membership, refunds and terminal races. */
403
+ export declare function runTestCancel(opts: RunTestCancelOptions, deps?: TestDeps): Promise<CliCancelSummary & {
404
+ runs: CancelRunResponse[];
405
+ }>;
1829
406
  export declare function createTestCancelCommand(deps: TestDeps): Command;
1830
- /**
1831
- * `test wait <run-id>` — M3.3 piece-3.
1832
- *
1833
- * Polls `GET /api/cli/v1/runs/{runId}` until terminal status. Exit
1834
- * codes match the `--wait` behavior matrix in the spec.
1835
- */
1836
- export declare function runTestWait(opts: RunTestWaitOptions, deps?: TestDeps): Promise<RunResponse>;
1837
407
  export interface RunTestRunAllOptions extends CommonOptions {
1838
408
  environmentResolutionComplete?: boolean;
1839
409
  cancelOnInterrupt?: boolean;
@@ -1844,13 +414,11 @@ export interface RunTestRunAllOptions extends CommonOptions {
1844
414
  projectId?: string;
1845
415
  /** --filter <substr>: only run tests whose name contains this substring (case-insensitive). */
1846
416
  nameFilter?: string;
1847
- /** --status <list>: only run tests whose status (in `environment`, when set) is one of these. */
1848
- statusFilter?: string;
1849
417
  /** --wait: block until terminal or --timeout. */
1850
418
  wait: boolean;
1851
419
  /** Polling / overall deadline in seconds. Default 600, max 3600. */
1852
420
  timeoutSeconds: number;
1853
- /** --max-concurrency: bounds the --wait poll fan-out. */
421
+ /** --max-concurrency: server dispatch limit per project execution. */
1854
422
  maxConcurrency: number;
1855
423
  /** Internal CI policy. The public `ci run` entry point always enables wait. */
1856
424
  ci?: {
@@ -1875,12 +443,10 @@ export interface RunTestRunAllOptions extends CommonOptions {
1875
443
  /**
1876
444
  * --allow-empty: exit 0 (instead of failing) when the batch dispatches ZERO
1877
445
  * tests (all skipped / empty project / --filter matched nothing). Default off:
1878
- * a zero-dispatch `--all` is a CI false-green, so it fails with exit 5 by
446
+ * a zero-dispatch project run is a CI false-green, so it fails with exit 5 by
1879
447
  * default and still emits the summary / annotation / JUnit report.
1880
448
  */
1881
449
  allowEmpty?: boolean;
1882
- /** See `RunTestRunOptions.autoHeal`. */
1883
- autoHeal?: false;
1884
450
  /** `--env <name>`: see `RunTestRunOptions.environment` — applied to every test in the batch. */
1885
451
  environment?: string;
1886
452
  /** Per-run URL override for every frontend test in the batch. */
@@ -1892,7 +458,7 @@ export interface RunTestRunAllOptions extends CommonOptions {
1892
458
  * client-side retry. A backend that read the field echoes it; a missing
1893
459
  * echo is refused the way an unconfirmed `targetUrl` is.
1894
460
  */
1895
- admission?: 'budget' | 'all';
461
+ admission?: 'all';
1896
462
  /** `ci run` in a pull request: run in a temporary clone of `environment` at `targetUrl`. */
1897
463
  previewName?: string;
1898
464
  /** `ci run` in GitHub Actions: where the run came from, for the Portal's PR link. */
@@ -1902,7 +468,7 @@ export interface RunTestRunAllOptions extends CommonOptions {
1902
468
  /** See `RunTestRunOptions.skipDependencies`; sent on every dispatch leg. */
1903
469
  skipDependencies?: boolean;
1904
470
  /**
1905
- * Run exactly these tests (`test run <id> <id> ...`) instead of a whole project.
471
+ * Run exactly these tests (`run <id> <id> ...`) instead of a whole project.
1906
472
  * Each id's project is read first and the ids are dispatched per project.
1907
473
  */
1908
474
  testIds?: string[];
@@ -1927,16 +493,36 @@ export declare function writeBatchJUnitReportIfRequested(opts: {
1927
493
  testTitle?: string | null;
1928
494
  })[], nameByTestId?: ReadonlyMap<string, string>): Promise<void>;
1929
495
  /**
1930
- * `test run --all --project <id>` — M4 piece-2.
496
+ * `run --project <id>` — M4 piece-2.
1931
497
  *
1932
498
  * Triggers a fresh wave-ordered batch run via `POST /tests/batch/run`.
1933
499
  * FE tests in the project are skipped by the BE-only engine (advisory).
1934
- * With `--wait`, polls each accepted runId.
500
+ * With `--wait`, polls each accepted resultId.
1935
501
  */
1936
- export declare function runTestRunAll(opts: RunTestRunAllOptions, deps?: TestDeps): Promise<BatchRunFreshResponse | undefined>;
502
+ export interface ProjectLaunchOutput {
503
+ runs: RunReceipt[];
504
+ joinedRuns?: Array<{
505
+ runId: string;
506
+ resultIds: string[];
507
+ }>;
508
+ held?: ProjectRunResponse['held'];
509
+ skipped?: Array<{
510
+ testId: string;
511
+ runId?: string;
512
+ resultId?: string;
513
+ reason: string;
514
+ }>;
515
+ results?: RunResult[];
516
+ summary?: RunCounts;
517
+ }
518
+ /** Launch once per project; the server owns membership expansion and pacing. */
519
+ export declare function runTestRunAll(opts: RunTestRunAllOptions & {
520
+ tunnelClientId?: string;
521
+ resolvedTarget?: ResolvedRunTarget;
522
+ single?: boolean;
523
+ }, deps?: TestDeps): Promise<ProjectLaunchOutput>;
1937
524
  interface RunTestRunLocalBatchOptions extends CommonOptions {
1938
525
  wait?: boolean;
1939
- targetUrl?: string;
1940
526
  noWait?: boolean;
1941
527
  concurrencyIsDefault?: boolean;
1942
528
  resolvedTarget?: ResolvedRunTarget;
@@ -1944,13 +530,14 @@ interface RunTestRunLocalBatchOptions extends CommonOptions {
1944
530
  all: boolean;
1945
531
  projectId?: string;
1946
532
  nameFilter?: string;
1947
- statusFilter?: string;
1948
- localPort?: number;
1949
- localHost?: LoopbackHost;
1950
533
  skipPreflight: boolean;
1951
534
  tunnelClientId?: string;
1952
535
  cancelOnInterrupt: boolean;
1953
536
  timeoutSeconds: number;
537
+ /**
538
+ * Per-execution server dispatch cap, including executions using a tunnel.
539
+ * The client groups by project and never divides this into pacing shares.
540
+ */
1954
541
  maxConcurrency: number;
1955
542
  idempotencyKey?: string;
1956
543
  report?: JUnitReportFormat;
@@ -1959,81 +546,18 @@ interface RunTestRunLocalBatchOptions extends CommonOptions {
1959
546
  ghOutput?: boolean;
1960
547
  summaryFile?: string;
1961
548
  allowEmpty: boolean;
1962
- autoHeal?: false;
1963
549
  environment?: string;
1964
550
  /** See `RunTestRunOptions.skipDependencies`; forwarded to every dispatch. */
1965
551
  skipDependencies?: boolean;
1966
552
  /** `--timeout` was not given: a batch run that needs no tunnel uses the ordinary default. */
1967
553
  timeoutIsDefault?: boolean;
1968
554
  }
1969
- /** One bounded trigger-and-wait pool shares one local tunnel for its full lifetime. */
1970
- export declare function runTestRunLocalBatch(opts: RunTestRunLocalBatchOptions, deps?: TestDeps): Promise<void>;
1971
- export declare function runTestRerun(opts: RunTestRerunOptions, deps?: TestDeps): Promise<RerunResponse | BatchRerunResponse | undefined>;
1972
- export interface ArtifactGetOptions extends CommonOptions {
1973
- runId: string;
1974
- /**
1975
- * Directory to write the §7 disk layout into. When absent, defaults to
1976
- * `./.testsprite/runs/<run-id>/` (computed at action time from `process.cwd()`).
1977
- * The default is intentionally not stored here to ensure it is computed freshly
1978
- * at action time; pass the resolved path when you want an explicit directory.
1979
- */
1980
- out?: string;
1981
- /** §7.4 — keep only the failed step ± 1 in `steps[]` and `evidence[]`. */
1982
- failedOnly: boolean;
1983
- }
1984
- export interface ArtifactGetResult {
1985
- /** The wire envelope as returned by the facade. */
1986
- context: CliFailureContext;
1987
- /** Set when bundle was written to disk. */
1988
- bundle?: WriteBundleResult;
1989
- }
1990
- export declare function resolveDefaultArtifactDir(runId: string, cwd?: string): string;
1991
- /**
1992
- * Validate that the parent directory of `resolvedDir` exists and is a
1993
- * directory. Surfaces `VALIDATION_ERROR` (exit 5) — matches the convention
1994
- * from `closeOutputFile` for single-file `--out` flags (P4 D4 convention).
1995
- *
1996
- * The bundle directory itself (`resolvedDir`) may or may not exist;
1997
- * `writeBundle` creates it if absent.
1998
- */
1999
- export declare function assertOutDirParentExists(resolvedDir: string): Promise<void>;
2000
- /**
2001
- * `test artifact get <run-id>` — run-scoped failure-bundle download.
2002
- *
2003
- * Downloads `GET /api/cli/v1/runs/{runId}/failure` and either:
2004
- * - Writes the §7 disk layout under `<dir>` (default `./.testsprite/runs/<run-id>/`)
2005
- * - Or prints the wire envelope / human summary to stdout when `--out` is absent.
2006
- *
2007
- * Differences from M2 `test failure get`:
2008
- * - Addresses the bundle by `runId` (exact run) not `testId` (latest).
2009
- * - Enforces `meta.runId === <run-id>` as a cross-check against backend bugs.
2010
- * - Passes `{ requireRunId: true }` to `assertContextIntegrity`.
2011
- */
2012
- export declare function runArtifactGet(opts: ArtifactGetOptions, deps?: TestDeps): Promise<ArtifactGetResult>;
555
+ /** Several selected projects share one tunnel; each execution is paced by the server. */
556
+ export declare function runTestRunLocalBatch(opts: RunTestRunLocalBatchOptions, deps?: TestDeps): Promise<ProjectLaunchOutput>;
2013
557
  export declare function createTestCommand(deps?: TestDeps): Command;
2014
- interface RunTestFlakyOptions extends CommonOptions {
2015
- testId: string;
2016
- /** Number of replays to run (1..MAX_FLAKY_RUNS). */
2017
- runs: number;
2018
- /** Stop at the first non-passing attempt. */
2019
- untilFail: boolean;
2020
- /** Per-attempt polling deadline in seconds. */
2021
- timeoutSeconds: number;
2022
- }
2023
- /**
2024
- * `test flaky <test-id>` — replay a test N times and report a stability score.
2025
- *
2026
- * Each attempt is a `POST /tests/{id}/runs/rerun` with auto-heal OFF (a strict
2027
- * verbatim replay) followed by `pollRunUntilTerminal`. Each replay is billed
2028
- * as a rerun (0.5 credits FE / 0.2 credits BE, same as a fresh run; legacy V2
2029
- * accounts: FE rerun remains free) — a one-line credit advisory is printed
2030
- * for backend tests. The pure scoring lives in
2031
- * `lib/flaky.ts`; this function is the I/O orchestrator.
2032
- *
2033
- * Exit code: 0 when every observed attempt passed (stable), else 1 — so CI can
2034
- * gate a merge on flakiness.
2035
- */
2036
- export declare function runFlaky(opts: RunTestFlakyOptions, deps?: TestDeps): Promise<FlakyReport | undefined>;
558
+ /** Public launch adapter; execution engines remain shared in this module. */
559
+ export declare function createRunCommand(deps?: TestDeps): Command;
560
+ export declare function createRunWaitCommand(deps?: TestDeps): Command;
2037
561
  /**
2038
562
  * D4 (dogfood CoderCup 2026-06-05): under `--wait` the user opts into a
2039
563
  * long-running operation bounded by `--timeout`. The default 120s per-request
@@ -2042,7 +566,7 @@ export declare function runFlaky(opts: RunTestFlakyOptions, deps?: TestDeps): Pr
2042
566
  * command even though `--timeout` is large and the run finishes fine
2043
567
  * server-side. Raise the per-request window to cover `--timeout` (capped at
2044
568
  * {@link REQUEST_TIMEOUT_MAX_MS}, floored at the resolved default so we never
2045
- * lower it). The poll loop's own deadline-aware `AbortSignal` (poll.ts) still
569
+ * lower it). The whole-run waiter's deadline-aware `AbortSignal` (run-wait.ts) still
2046
570
  * bounds the TOTAL wait to `--timeout`; non-wait callers are unchanged.
2047
571
  */
2048
572
  export declare function resolveWaitRequestTimeoutMs(opts: {
@@ -2050,69 +574,8 @@ export declare function resolveWaitRequestTimeoutMs(opts: {
2050
574
  timeoutSeconds?: number;
2051
575
  requestTimeoutMs?: number;
2052
576
  }): number | undefined;
2053
- /** A presigned `code` body is any `https://` URL — never anything else. */
2054
- export declare function isPresignedCodeUrl(code: string): boolean;
2055
577
  export declare function renderTestListText(page: Page<CliTest>, options?: {
2056
578
  columns?: string;
2057
579
  noHeader?: boolean;
2058
- environment?: string;
2059
580
  }): string;
2060
- interface PlanGenerateOptions extends CommonOptions {
2061
- projectId?: string;
2062
- timeoutSeconds: number;
2063
- idempotencyKey?: string;
2064
- }
2065
- interface PlanAcceptOptions extends CommonOptions {
2066
- projectId?: string;
2067
- /** Raw `--only` tokens from Commander (variadic); undefined = flag absent. */
2068
- only?: string[];
2069
- idempotencyKey?: string;
2070
- }
2071
- /** Text card for a settled successful generate (or `--dry-run`). */
2072
- /** Exported for the renderer-level spec: the zero-proposals branch is not
2073
- * reachable through `runGenerationLadder` today (after the proposals rung it
2074
- * polls until staged/failed/timeout), so it is pinned directly. */
2075
- export declare function renderPlanGenerateResultText(plans: CliGetPlansResponse, projectId: string, creditsUsed: number | null, skippedCategories?: number | null): string;
2076
- /** Plan-generate interrupt outcome consumed by the top-level JSON renderer
2077
- * (`buildInterruptEnvelope`), the way `TunnelInterruptDetach` is for tunnels. */
2078
- export interface PlanInterruptDetach {
2079
- projectId: string;
2080
- stagesRemaining: CliGenerationStage[] | null;
2081
- nextAction: string;
2082
- }
2083
- /**
2084
- * `test plan generate --project <id>`.
2085
- *
2086
- * Drives the server's generation ladder (exploration → strategy →
2087
- * proposals) through `runGenerationLadder` and renders the staged
2088
- * proposals. Exit 0 on staged proposals, 1 on a server-side stage failure,
2089
- * 7 on timeout (typed `UNSUPPORTED` envelope — the raw ladder timeout is
2090
- * not a CLI error), 130/143 on Ctrl-C (the running stage finishes server-side;
2091
- * nothing after it starts until a re-run, see PlanStageTracker), plus the
2092
- * usual catalog exits for trigger errors
2093
- * (412 → 6 with the exact fix command, 402 → 12, 404 → 4, 429 → 11).
2094
- */
2095
- export declare function runPlanGenerate(opts: PlanGenerateOptions, deps?: TestDeps): Promise<unknown>;
2096
- /** Derived, additive result the CLI prints for `accept` — the server truth
2097
- * (`acceptedCount`, `caseKeys`) plus the client-side discard count. A
2098
- * frontend/API split used to be derived from the selected proposals' `type`
2099
- * fields; it was dropped — the backend fills every
2100
- * proposal's `type` from the PROJECT, so the split was always (all, 0) or
2101
- * (0, all) and would be actively wrong for mixed projects. */
2102
- interface PlanAcceptResult {
2103
- projectId: string;
2104
- acceptedCount: number;
2105
- caseKeys: string[];
2106
- discardedCount: number;
2107
- }
2108
- /**
2109
- * `test plan accept --project <id> [--only <ids...>]`.
2110
- *
2111
- * Reads the staged batch, selects all of it (or the `--only` subset),
2112
- * and POSTs an EXPLICIT id list. Free — the generation charge already
2113
- * covered it. Exit 0 on success, 5 on a bad `--only` selection (request
2114
- * never sent), 6 when nothing is staged (pointer at `test plan generate`).
2115
- */
2116
- export declare function runPlanAccept(opts: PlanAcceptOptions, deps?: TestDeps): Promise<PlanAcceptResult | undefined>;
2117
- export declare function createTestArtifactCommand(deps: TestDeps): Command;
2118
581
  export {};