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