@testsprite/testsprite-cli 0.16.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) hide show
  1. package/README.md +52 -147
  2. package/dist/commands/agent.d.ts +12 -4
  3. package/dist/commands/agent.js +48 -63
  4. package/dist/commands/auth.d.ts +6 -10
  5. package/dist/commands/auth.js +40 -56
  6. package/dist/commands/ci.d.ts +23 -100
  7. package/dist/commands/ci.js +293 -487
  8. package/dist/commands/conversation.d.ts +27 -0
  9. package/dist/commands/conversation.js +741 -0
  10. package/dist/commands/doctor.d.ts +5 -1
  11. package/dist/commands/doctor.js +129 -34
  12. package/dist/commands/init.d.ts +4 -45
  13. package/dist/commands/init.js +108 -66
  14. package/dist/commands/project-env.d.ts +62 -2
  15. package/dist/commands/project-env.js +434 -43
  16. package/dist/commands/project-sign-in.d.ts +0 -48
  17. package/dist/commands/project-sign-in.js +1 -229
  18. package/dist/commands/project.d.ts +19 -186
  19. package/dist/commands/project.js +108 -926
  20. package/dist/commands/result.d.ts +10 -0
  21. package/dist/commands/result.js +216 -0
  22. package/dist/commands/schedule.d.ts +0 -29
  23. package/dist/commands/schedule.js +28 -87
  24. package/dist/commands/test.d.ts +301 -1838
  25. package/dist/commands/test.js +1880 -13917
  26. package/dist/commands/testlist.d.ts +130 -5
  27. package/dist/commands/testlist.js +300 -342
  28. package/dist/commands/tunnel.d.ts +3 -3
  29. package/dist/commands/tunnel.js +23 -20
  30. package/dist/commands/usage.d.ts +12 -45
  31. package/dist/commands/usage.js +50 -131
  32. package/dist/index.js +191 -110
  33. package/dist/lib/agent-detect.js +9 -5
  34. package/dist/lib/agent-targets.d.ts +21 -2
  35. package/dist/lib/agent-targets.js +88 -11
  36. package/dist/lib/args.d.ts +13 -0
  37. package/dist/lib/args.js +49 -0
  38. package/dist/lib/basic-auth.d.ts +3 -0
  39. package/dist/lib/basic-auth.js +15 -0
  40. package/dist/lib/billing-refusal.js +4 -3
  41. package/dist/lib/ci-linkage.d.ts +4 -82
  42. package/dist/lib/ci-linkage.js +4 -157
  43. package/dist/lib/ci-run.js +1 -1
  44. package/dist/lib/client-factory.d.ts +12 -4
  45. package/dist/lib/client-factory.js +41 -30
  46. package/dist/lib/commit-signal.d.ts +65 -0
  47. package/dist/lib/commit-signal.js +305 -0
  48. package/dist/lib/concurrency-limiter.d.ts +6 -0
  49. package/dist/lib/concurrency-limiter.js +29 -0
  50. package/dist/lib/config.js +10 -5
  51. package/dist/lib/conflict-reason.d.ts +9 -3
  52. package/dist/lib/conflict-reason.js +6 -3
  53. package/dist/lib/conversation/answers.d.ts +9 -0
  54. package/dist/lib/conversation/answers.js +49 -0
  55. package/dist/lib/conversation/api.d.ts +75 -0
  56. package/dist/lib/conversation/api.js +151 -0
  57. package/dist/lib/conversation/change.d.ts +31 -0
  58. package/dist/lib/conversation/change.js +124 -0
  59. package/dist/lib/conversation/context.d.ts +29 -0
  60. package/dist/lib/conversation/context.js +82 -0
  61. package/dist/lib/conversation/environment.d.ts +16 -0
  62. package/dist/lib/conversation/environment.js +21 -0
  63. package/dist/lib/conversation/follow.d.ts +24 -0
  64. package/dist/lib/conversation/follow.js +42 -0
  65. package/dist/lib/conversation/render.d.ts +33 -0
  66. package/dist/lib/conversation/render.js +318 -0
  67. package/dist/lib/conversation/title.d.ts +2 -0
  68. package/dist/lib/conversation/title.js +18 -0
  69. package/dist/lib/conversation/types.d.ts +158 -0
  70. package/dist/lib/conversation/types.js +6 -0
  71. package/dist/lib/credentials.js +67 -11
  72. package/dist/lib/cron.d.ts +1 -1
  73. package/dist/lib/cron.js +2 -2
  74. package/dist/lib/dispatch-stop.d.ts +20 -0
  75. package/dist/lib/dispatch-stop.js +30 -0
  76. package/dist/lib/download.d.ts +100 -0
  77. package/dist/lib/download.js +408 -0
  78. package/dist/lib/dry-run/fetch.d.ts +10 -0
  79. package/dist/lib/dry-run/fetch.js +20 -0
  80. package/dist/lib/dry-run/samples.d.ts +6 -34
  81. package/dist/lib/dry-run/samples.js +375 -747
  82. package/dist/lib/environment-tunnel.d.ts +19 -30
  83. package/dist/lib/environment-tunnel.js +168 -202
  84. package/dist/lib/errors.d.ts +20 -4
  85. package/dist/lib/errors.js +36 -16
  86. package/dist/lib/facade.d.ts +7 -29
  87. package/dist/lib/facade.js +7 -36
  88. package/dist/lib/failing-fe-resolver.d.ts +13 -58
  89. package/dist/lib/failing-fe-resolver.js +47 -132
  90. package/dist/lib/first-suite-hint.d.ts +20 -30
  91. package/dist/lib/first-suite-hint.js +57 -72
  92. package/dist/lib/gh-output.d.ts +76 -21
  93. package/dist/lib/gh-output.js +171 -90
  94. package/dist/lib/git-utils.d.ts +56 -0
  95. package/dist/lib/git-utils.js +212 -0
  96. package/dist/lib/github-context.d.ts +2 -0
  97. package/dist/lib/github-context.js +40 -8
  98. package/dist/lib/history-retention.d.ts +6 -2
  99. package/dist/lib/history-retention.js +10 -7
  100. package/dist/lib/http.d.ts +58 -134
  101. package/dist/lib/http.js +354 -291
  102. package/dist/lib/interrupt.d.ts +14 -8
  103. package/dist/lib/interrupt.js +28 -10
  104. package/dist/lib/junit-report.d.ts +57 -4
  105. package/dist/lib/junit-report.js +202 -32
  106. package/dist/lib/local-target.d.ts +8 -7
  107. package/dist/lib/local-target.js +14 -13
  108. package/dist/lib/output.d.ts +2 -41
  109. package/dist/lib/output.js +13 -51
  110. package/dist/lib/pagination.d.ts +2 -5
  111. package/dist/lib/pagination.js +2 -5
  112. package/dist/lib/presigned-url.d.ts +22 -0
  113. package/dist/lib/presigned-url.js +90 -0
  114. package/dist/lib/prompt.js +36 -2
  115. package/dist/lib/proxy.js +2 -1
  116. package/dist/lib/redact.d.ts +2 -2
  117. package/dist/lib/redact.js +3 -4
  118. package/dist/lib/removed-commands.d.ts +18 -0
  119. package/dist/lib/removed-commands.js +170 -0
  120. package/dist/lib/render-error.d.ts +31 -6
  121. package/dist/lib/render-error.js +88 -25
  122. package/dist/lib/response-schemas.d.ts +38 -30
  123. package/dist/lib/response-schemas.js +207 -207
  124. package/dist/lib/result/api.d.ts +24 -0
  125. package/dist/lib/result/api.js +28 -0
  126. package/dist/lib/result/evidence.d.ts +73 -0
  127. package/dist/lib/result/evidence.js +422 -0
  128. package/dist/lib/result/render.d.ts +20 -0
  129. package/dist/lib/result/render.js +194 -0
  130. package/dist/lib/result/types.d.ts +122 -0
  131. package/dist/lib/result/types.js +19 -0
  132. package/dist/lib/run-output.d.ts +275 -0
  133. package/dist/lib/run-output.js +227 -0
  134. package/dist/lib/run-render.d.ts +101 -0
  135. package/dist/lib/run-render.js +183 -0
  136. package/dist/lib/run-wait.d.ts +192 -0
  137. package/dist/lib/run-wait.js +452 -0
  138. package/dist/lib/runs.types.d.ts +118 -367
  139. package/dist/lib/runs.types.js +0 -14
  140. package/dist/lib/secret-file.d.ts +1 -1
  141. package/dist/lib/secret-file.js +11 -2
  142. package/dist/lib/skill-nudge.d.ts +7 -27
  143. package/dist/lib/skill-nudge.js +9 -37
  144. package/dist/lib/target-path.d.ts +15 -0
  145. package/dist/lib/target-path.js +35 -0
  146. package/dist/lib/target-url-advisory.d.ts +19 -0
  147. package/dist/lib/target-url-advisory.js +31 -0
  148. package/dist/lib/target-url-preflight.d.ts +9 -0
  149. package/dist/lib/target-url-preflight.js +214 -106
  150. package/dist/lib/target-url.d.ts +8 -8
  151. package/dist/lib/target-url.js +14 -24
  152. package/dist/lib/telemetry.d.ts +35 -15
  153. package/dist/lib/telemetry.js +38 -9
  154. package/dist/lib/terminal-text.d.ts +41 -0
  155. package/dist/lib/terminal-text.js +127 -0
  156. package/dist/lib/testlist.types.d.ts +16 -8
  157. package/dist/lib/testlist.types.js +1 -1
  158. package/dist/lib/text-equality.d.ts +2 -0
  159. package/dist/lib/text-equality.js +5 -0
  160. package/dist/lib/text-file.d.ts +16 -0
  161. package/dist/lib/text-file.js +41 -0
  162. package/dist/lib/text-table.d.ts +46 -0
  163. package/dist/lib/text-table.js +72 -4
  164. package/dist/lib/ticker.d.ts +9 -2
  165. package/dist/lib/ticker.js +16 -3
  166. package/dist/lib/transport-failure.d.ts +22 -0
  167. package/dist/lib/transport-failure.js +126 -0
  168. package/dist/lib/tunnel-session.d.ts +8 -2
  169. package/dist/lib/tunnel-session.js +24 -11
  170. package/dist/lib/update-check.js +3 -2
  171. package/dist/lib/url-template.d.ts +43 -0
  172. package/dist/lib/url-template.js +151 -0
  173. package/dist/lib/validate.d.ts +0 -64
  174. package/dist/lib/validate.js +2 -131
  175. package/dist/lib/version-notice.js +4 -3
  176. package/dist/lib/wait-exit.d.ts +37 -2
  177. package/dist/lib/wait-exit.js +88 -30
  178. package/dist/lib/workspace-status.js +10 -2
  179. package/dist/version.d.ts +1 -1
  180. package/dist/version.js +1 -1
  181. package/package.json +2 -3
  182. package/skills/testsprite-ci.skill.md +52 -23
  183. package/skills/testsprite-onboard.skill.md +70 -153
  184. package/skills/testsprite-verify.codex.md +54 -58
  185. package/skills/testsprite-verify.skill.md +189 -358
  186. package/dist/lib/browser.d.ts +0 -6
  187. package/dist/lib/browser.js +0 -54
  188. package/dist/lib/bundle.d.ts +0 -234
  189. package/dist/lib/bundle.js +0 -781
  190. package/dist/lib/deprecate.d.ts +0 -32
  191. package/dist/lib/deprecate.js +0 -39
  192. package/dist/lib/flaky.d.ts +0 -91
  193. package/dist/lib/flaky.js +0 -71
  194. package/dist/lib/plan-poll.d.ts +0 -171
  195. package/dist/lib/plan-poll.js +0 -441
  196. package/dist/lib/plans.types.d.ts +0 -130
  197. package/dist/lib/plans.types.js +0 -31
  198. package/dist/lib/poll.d.ts +0 -100
  199. package/dist/lib/poll.js +0 -290
  200. package/dist/lib/rate-throttle.d.ts +0 -49
  201. package/dist/lib/rate-throttle.js +0 -75
  202. package/dist/lib/run-progress.d.ts +0 -41
  203. package/dist/lib/run-progress.js +0 -56
  204. package/dist/lib/v3-advisory.d.ts +0 -55
  205. package/dist/lib/v3-advisory.js +0 -74
  206. package/schemas/plan.schema.json +0 -61
@@ -0,0 +1,212 @@
1
+ import { existsSync, lstatSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import fs from 'node:fs/promises';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ /** Give a CLI-owned .testsprite directory its default rules without replacing user rules. */
5
+ export function ensureStateGitignore(dir) {
6
+ try {
7
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- fixed filename inside the CLI state directory.
8
+ writeFileSync(join(dir, '.gitignore'), "# This machine's TestSprite CLI state; not for git.\n*\n", { flag: 'wx' });
9
+ }
10
+ catch (err) {
11
+ if (err.code !== 'EEXIST')
12
+ throw err;
13
+ }
14
+ }
15
+ /**
16
+ * Returns the nearest directory at or above `dir` that contains `.git` (a directory,
17
+ * or a file as in worktrees and submodules), or null. `dir` is resolved to an absolute
18
+ * path first so relative inputs walk the real tree.
19
+ */
20
+ export function findGitRoot(dir, deps = {}) {
21
+ const exists = deps.existsSync ?? existsSync;
22
+ let current = resolve(dir);
23
+ while (true) {
24
+ if (exists(join(current, '.git')))
25
+ return current;
26
+ const parent = dirname(current);
27
+ if (parent === current)
28
+ return null;
29
+ current = parent;
30
+ }
31
+ }
32
+ /** Async variant of {@link findGitRoot}. Errors from the existence check propagate. */
33
+ export async function findGitRootAsync(dir, deps = {}) {
34
+ const exists = deps.exists ?? (async (p) => (deps.existsSync ?? existsSync)(p));
35
+ let current = resolve(dir);
36
+ while (true) {
37
+ if (await exists(join(current, '.git')))
38
+ return current;
39
+ const parent = dirname(current);
40
+ if (parent === current)
41
+ return null;
42
+ current = parent;
43
+ }
44
+ }
45
+ /** True when `dir` is inside a Git repository (`.git` directory or file found at or above it). */
46
+ export function isInsideGitRepo(dir, deps = {}) {
47
+ return findGitRoot(dir, deps) !== null;
48
+ }
49
+ /** Async variant of {@link isInsideGitRepo}. */
50
+ export async function isInsideGitRepoAsync(dir, deps = {}) {
51
+ return (await findGitRootAsync(dir, deps)) !== null;
52
+ }
53
+ /**
54
+ * Checks if `.testsprite` is ignored given the raw content of a `.gitignore` file.
55
+ */
56
+ export function isTestspriteIgnored(content) {
57
+ const lines = content.split(/\r?\n/);
58
+ let ignored = false;
59
+ let contentPatternActive = false;
60
+ for (const line of lines) {
61
+ const cleaned = line.trim();
62
+ if (!cleaned || cleaned.startsWith('#'))
63
+ continue;
64
+ // A negation pattern like `!.testsprite/` un-ignores the directory.
65
+ const isNegation = cleaned.startsWith('!');
66
+ const pattern = isNegation ? cleaned.slice(1) : cleaned;
67
+ if (pattern === '.testsprite' ||
68
+ pattern === '.testsprite/' ||
69
+ pattern === '**/.testsprite' ||
70
+ pattern === '**/.testsprite/' ||
71
+ pattern === '.testsprite/*' ||
72
+ pattern === '.testsprite/**' ||
73
+ pattern === '**/.testsprite/*' ||
74
+ pattern === '**/.testsprite/**' ||
75
+ pattern === '/.testsprite' ||
76
+ pattern === '/.testsprite/' ||
77
+ pattern === '/.testsprite/*' ||
78
+ pattern === '/.testsprite/**') {
79
+ ignored = !isNegation;
80
+ contentPatternActive =
81
+ !isNegation &&
82
+ (pattern === '.testsprite/*' ||
83
+ pattern === '.testsprite/**' ||
84
+ pattern === '**/.testsprite/*' ||
85
+ pattern === '**/.testsprite/**' ||
86
+ pattern === '/.testsprite/*' ||
87
+ pattern === '/.testsprite/**');
88
+ }
89
+ if (contentPatternActive &&
90
+ isNegation &&
91
+ (pattern.startsWith('.testsprite/') ||
92
+ pattern.startsWith('**/.testsprite/') ||
93
+ pattern.startsWith('/.testsprite/'))) {
94
+ ignored = false;
95
+ }
96
+ }
97
+ return ignored;
98
+ }
99
+ /**
100
+ * Returns true if a `.gitignore` exists in the target directory and ignores `.testsprite/`.
101
+ */
102
+ export async function checkTestspriteIgnored(dir, deps = {}) {
103
+ const exists = deps.exists ?? (async (p) => (deps.existsSync ?? existsSync)(p));
104
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- reads the target repository's .gitignore file
105
+ const read = deps.readFile ?? (p => fs.readFile(p, 'utf8'));
106
+ const gitignorePath = join(dir, '.gitignore');
107
+ if (!(await exists(gitignorePath))) {
108
+ return false;
109
+ }
110
+ try {
111
+ const content = await read(gitignorePath);
112
+ return isTestspriteIgnored(content);
113
+ }
114
+ catch {
115
+ return false;
116
+ }
117
+ }
118
+ /**
119
+ * Synchronous check for diagnostics: is `dir` inside a Git repository, and is
120
+ * `.testsprite/` ignored by a `.gitignore` between `dir` and the repository root
121
+ * (inclusive)? Reads files only; never shells out to git and never throws.
122
+ */
123
+ export function inspectTestspriteIgnore(dir, deps = {}) {
124
+ const exists = deps.existsSync ?? existsSync;
125
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- reads the target repository's .gitignore file
126
+ const read = deps.readFileSync ?? ((p) => readFileSync(p, 'utf8'));
127
+ const lstatOf = deps.lstatSync ?? defaultLstatSync;
128
+ const root = findGitRoot(dir, deps);
129
+ if (root === null)
130
+ return { inRepo: false, ignored: false };
131
+ let current = resolve(dir);
132
+ while (true) {
133
+ const candidate = join(current, '.gitignore');
134
+ try {
135
+ // Git ignores a .gitignore that is a symlink, so its contents prove nothing.
136
+ if (exists(candidate) &&
137
+ !lstatOf(candidate)?.isSymbolicLink &&
138
+ isTestspriteIgnored(read(candidate))) {
139
+ return { inRepo: true, ignored: true };
140
+ }
141
+ }
142
+ catch {
143
+ // Unreadable .gitignore: treat as not ignoring and keep walking.
144
+ }
145
+ if (current === root)
146
+ break;
147
+ const parent = dirname(current);
148
+ if (parent === current)
149
+ break;
150
+ current = parent;
151
+ }
152
+ return { inRepo: true, ignored: false };
153
+ }
154
+ /**
155
+ * Ensures that `.testsprite/` is ignored in the target directory's `.gitignore`.
156
+ * Does nothing outside a Git repository. If `.gitignore` is missing it is created;
157
+ * otherwise the entry is appended (never rewritten), so a concurrent edit is not lost.
158
+ * Refuses to write through a symlinked `.gitignore` (throws).
159
+ *
160
+ * Returns true if the file was modified or created, false if nothing was changed.
161
+ */
162
+ export async function ensureTestspriteIgnored(dir, deps = {}) {
163
+ const projectDir = resolve(dir);
164
+ if (!(await isInsideGitRepoAsync(projectDir, deps))) {
165
+ return false;
166
+ }
167
+ const exists = deps.exists ?? (async (p) => (deps.existsSync ?? existsSync)(p));
168
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- reads the target repository's .gitignore file
169
+ const read = deps.readFile ?? (p => fs.readFile(p, 'utf8'));
170
+ const lstat = deps.lstat ?? defaultLstat;
171
+ const append = deps.appendFile ??
172
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- appends to the target repository's .gitignore file
173
+ ((p, text) => fs.appendFile(p, text, 'utf8'));
174
+ const gitignorePath = join(projectDir, '.gitignore');
175
+ const stat = await lstat(gitignorePath);
176
+ if (stat?.isSymbolicLink) {
177
+ throw new Error(`refusing to modify ${gitignorePath}: it is a symlink`);
178
+ }
179
+ let content = '';
180
+ if (stat !== null || (await exists(gitignorePath))) {
181
+ content = await read(gitignorePath);
182
+ }
183
+ if (isTestspriteIgnored(content)) {
184
+ return false; // already ignored, no changes made
185
+ }
186
+ // Keep a leading newline when the file does not end with one so the entry starts on its own line.
187
+ const separator = content.length === 0 || content.endsWith('\n') ? '' : '\n';
188
+ await append(gitignorePath, `${separator}\n# TestSprite failure artifacts\n.testsprite/\n`);
189
+ return true;
190
+ }
191
+ function defaultLstatSync(p) {
192
+ try {
193
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- inspects the target repository's .gitignore without following symlinks
194
+ return { isSymbolicLink: lstatSync(p).isSymbolicLink() };
195
+ }
196
+ catch {
197
+ return null;
198
+ }
199
+ }
200
+ async function defaultLstat(p) {
201
+ try {
202
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- inspects the target repository's .gitignore without following symlinks
203
+ const s = await fs.lstat(p);
204
+ return { isSymbolicLink: s.isSymbolicLink() };
205
+ }
206
+ catch (err) {
207
+ if (err.code === 'ENOENT')
208
+ return null;
209
+ throw err;
210
+ }
211
+ }
212
+ //# sourceMappingURL=git-utils.js.map
@@ -15,6 +15,8 @@ export interface GithubContextDeps {
15
15
  /** Reads `$GITHUB_EVENT_PATH`; injectable so tests never touch the runner. */
16
16
  readFile?: (path: string) => string;
17
17
  fetchImpl?: FetchImpl;
18
+ /** Budget for the GitHub pull-request lookup, as `--request-timeout` gives every other call. */
19
+ requestTimeoutMs?: number;
18
20
  }
19
21
  /** The temporary environment a pull request's runs live in — shared with the GitHub App. */
20
22
  export declare function previewEnvironmentName(prNumber: number): string;
@@ -11,6 +11,8 @@
11
11
  */
12
12
  import { readFileSync } from 'node:fs';
13
13
  import { CLIError, localValidationError } from './errors.js';
14
+ /** Same default as the HttpClient's per-request budget when no flag or env var sets one. */
15
+ const DEFAULT_LOOKUP_TIMEOUT_MS = 30_000;
14
16
  /** The temporary environment a pull request's runs live in — shared with the GitHub App. */
15
17
  export function previewEnvironmentName(prNumber) {
16
18
  return `github-pr-${prNumber}`;
@@ -55,12 +57,18 @@ export async function readGithubRunContext(env, deps = {}) {
55
57
  if (!token) {
56
58
  throw localValidationError('GITHUB_TOKEN', 'a deployment_status event names only a commit; ci run looks up its pull request with the job token — add `GITHUB_TOKEN: ${{ github.token }}` to the step env', undefined, 'field');
57
59
  }
58
- const pulls = await listPullsForCommit({ env, repoOwner, repoName, sha, token }, deps.fetchImpl ?? globalThis.fetch);
59
- // The PR whose head IS this commit is the one this deployment belongs to.
60
- // Anything looser (several open PRs, a merged one) is not a gate target.
61
- const exact = pulls.filter(p => p.headSha === sha);
62
- const open = pulls.filter(p => p.state === 'open');
63
- const chosen = exact[0] ?? (open.length === 1 ? open[0] : undefined);
60
+ const pulls = await listPullsForCommit({
61
+ env,
62
+ repoOwner,
63
+ repoName,
64
+ sha,
65
+ token,
66
+ timeoutMs: deps.requestTimeoutMs ?? DEFAULT_LOOKUP_TIMEOUT_MS,
67
+ }, deps.fetchImpl ?? globalThis.fetch);
68
+ // Only an OPEN PR whose head IS this commit is the one this deployment belongs to.
69
+ // Anything looser (an open PR that merely contains the commit, a merged or closed one) is
70
+ // not a gate target: a redeploy of a merged PR's head commit must not clone an environment.
71
+ const chosen = pulls.find(p => p.headSha === sha && p.state === 'open');
64
72
  if (!chosen) {
65
73
  return {
66
74
  kind: 'no_pull_request',
@@ -115,10 +123,17 @@ async function listPullsForCommit(args, fetchImpl) {
115
123
  authorization: `Bearer ${args.token}`,
116
124
  'x-github-api-version': '2022-11-28',
117
125
  },
126
+ // Without a budget a GitHub API that never answers hangs the job until the runner kills it.
127
+ signal: AbortSignal.timeout(args.timeoutMs),
118
128
  });
119
129
  }
120
130
  catch (err) {
121
- throw new CLIError(`Could not look up the pull request for commit ${args.sha.slice(0, 7)}: ${err instanceof Error ? err.message : String(err)}`, 10);
131
+ throw new CLIError(`Could not look up the pull request for commit ${args.sha.slice(0, 7)}: ` +
132
+ (isTimeout(err)
133
+ ? `GitHub did not answer within ${Math.round(args.timeoutMs / 1000)}s`
134
+ : err instanceof Error
135
+ ? err.message
136
+ : String(err)), 10);
122
137
  }
123
138
  if (!response.ok) {
124
139
  throw new CLIError(`Could not look up the pull request for commit ${args.sha.slice(0, 7)}: GitHub answered ${response.status}` +
@@ -126,7 +141,21 @@ async function listPullsForCommit(args, fetchImpl) {
126
141
  ? ' — the job token needs `pull-requests: read`'
127
142
  : ''), response.status === 401 || response.status === 403 ? 5 : 10);
128
143
  }
129
- const body = await response.json();
144
+ let body;
145
+ try {
146
+ body = await response.json();
147
+ }
148
+ catch (err) {
149
+ // A proxy or captive portal answering 200 with HTML must be a transient failure, not an uncaught crash; so is
150
+ // a body that stalls until the timeout aborts it, which is reported as the timeout it is, and a connection that
151
+ // drops mid-body, which is reported with its own cause rather than as "not JSON".
152
+ throw new CLIError(`Could not look up the pull request for commit ${args.sha.slice(0, 7)}: ` +
153
+ (isTimeout(err)
154
+ ? `GitHub did not finish answering within ${Math.round(args.timeoutMs / 1000)}s`
155
+ : err instanceof SyntaxError
156
+ ? `GitHub answered ${response.status} with a body that is not JSON`
157
+ : `GitHub's ${response.status} response body could not be read: ${err instanceof Error ? err.message : String(err)}`), 10);
158
+ }
130
159
  if (!Array.isArray(body))
131
160
  return [];
132
161
  return body.flatMap((item) => {
@@ -150,4 +179,7 @@ function asRecord(value) {
150
179
  ? value
151
180
  : undefined;
152
181
  }
182
+ function isTimeout(err) {
183
+ return err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError');
184
+ }
153
185
  //# sourceMappingURL=github-context.js.map
@@ -4,5 +4,9 @@ export interface HistoryRetentionMeta {
4
4
  hiddenCount?: number;
5
5
  billingUrl?: string;
6
6
  }
7
- /** Returns no text for older backends, unlimited history, or an unhidden page. */
8
- export declare function historyRetentionNote(meta: HistoryRetentionMeta | undefined, apiUrl: string, derived?: boolean): string | undefined;
7
+ /**
8
+ * Returns no text for older backends, unlimited history, or an unhidden page.
9
+ * `noun` names what was hidden, in the unit of the rows the note sits under:
10
+ * runs by default, results for one test's history.
11
+ */
12
+ export declare function historyRetentionNote(meta: HistoryRetentionMeta | undefined, apiUrl: string, noun?: 'run' | 'result'): string | undefined;
@@ -1,6 +1,10 @@
1
1
  import { resolveBillingLinks } from './billing-refusal.js';
2
- /** Returns no text for older backends, unlimited history, or an unhidden page. */
3
- export function historyRetentionNote(meta, apiUrl, derived = false) {
2
+ /**
3
+ * Returns no text for older backends, unlimited history, or an unhidden page.
4
+ * `noun` names what was hidden, in the unit of the rows the note sits under:
5
+ * runs by default, results for one test's history.
6
+ */
7
+ export function historyRetentionNote(meta, apiUrl, noun = 'run') {
4
8
  if (!meta || !Number.isFinite(meta.hiddenCount) || !meta.hiddenCount || meta.hiddenCount <= 0) {
5
9
  return undefined;
6
10
  }
@@ -11,14 +15,13 @@ export function historyRetentionNote(meta, apiUrl, derived = false) {
11
15
  billingUrl: meta.billingUrl,
12
16
  });
13
17
  const count = meta.hiddenCount;
14
- const runs = `${count} run${count === 1 ? '' : 's'}`;
18
+ const nouns = `${noun}${count === 1 ? '' : 's'}`;
15
19
  const plan = meta.tier ? `the ${meta.tier} plan` : 'your plan';
16
- const prefix = derived ? "This suggestion only covers the plan's visible history. " : '';
17
20
  // Paused is a plan tier whose window is zero days: every run is hidden, not
18
21
  // just older ones, and "keeps 0 days" would read oddly.
19
22
  const reason = meta.tier === 'Paused' || meta.retentionDays === 0
20
- ? `${runs} hidden — this workspace is on the Paused plan, which keeps no run history.`
21
- : `${count} older run${count === 1 ? '' : 's'} hidden — ${plan} keeps ${meta.retentionDays} day${meta.retentionDays === 1 ? '' : 's'} of run history.`;
22
- return `${prefix}${reason}\n` + ` upgrade: ${pricing}\n` + ` billing: ${billing}`;
23
+ ? `${count} ${nouns} hidden — this workspace is on the Paused plan, which keeps no run history.`
24
+ : `${count} older ${nouns} hidden — ${plan} keeps ${meta.retentionDays} day${meta.retentionDays === 1 ? '' : 's'} of run history.`;
25
+ return `${reason}\n` + ` upgrade: ${pricing}\n` + ` billing: ${billing}`;
23
26
  }
24
27
  //# sourceMappingURL=history-retention.js.map
@@ -2,8 +2,7 @@ import * as v from 'valibot';
2
2
  import type { ErrorCode } from './errors.js';
3
3
  import { ApiError } from './errors.js';
4
4
  import type { CliTestListRunResponse } from './testlist.types.js';
5
- import type { TriggerRunBody, TriggerRunResponse, RunResponse, RerunRequest, RerunResponse, BatchRerunRequest, BatchRerunResponse, BatchRunFreshRequest, BatchRunFreshResponse, ListRunsQuery, ListRunsResponse, CancelRunResponse, ExecutionReportResponse } from './runs.types.js';
6
- import type { CliAcceptPlansResponse, CliGeneratePlansResponse, CliGetPlansResponse } from './plans.types.js';
5
+ import type { ProjectRunRequest, ProjectRunResponse, TriggerRunBody, TriggerRunResponse, RunResponse, BatchRunFreshRequest, BatchRunFreshResponse, CancelRunResponse, ExecutionReportResponse } from './runs.types.js';
7
6
  import type { MintTunnelBody, TunnelListResponse, TunnelMintResponse, TunnelStatusResponse } from './tunnel.types.js';
8
7
  import type { ShutdownHandle } from './interrupt.js';
9
8
  export type FetchImpl = typeof globalThis.fetch;
@@ -25,7 +24,7 @@ export interface DebugEvent {
25
24
  * by the polling layer), while still failing fast on a dead backend.
26
25
  *
27
26
  * The 15-minute test-execution ceiling is enforced separately by the `--timeout`
28
- * / polling path (`poll.ts`) which supplies its own `AbortSignal` per iteration.
27
+ * / whole-run waiting path (`run-wait.ts`) which supplies its own `AbortSignal` per iteration.
29
28
  * That path is unaffected — each 25s long-poll request still falls well within
30
29
  * this 120s per-request guard.
31
30
  *
@@ -136,9 +135,8 @@ export interface RequestOptions<T = unknown> {
136
135
  * field paths (never the body itself). When absent, behavior is unchanged:
137
136
  * the body is returned via the historical blind `as T` cast.
138
137
  *
139
- * Wired by the typed run helpers only (`triggerRun`, `triggerRunWithMeta`,
140
- * `triggerRerun`, `triggerBatchRerun`, `triggerBatchRunFresh`, `getRun`,
141
- * `listTestRuns`, `cancelRun`); generic `get`/`post`/... callers stay opt-in.
138
+ * Wired by the typed HttpClient helpers (the run, test-list, tunnel and
139
+ * execution-report calls); generic `get`/`post`/... callers stay opt-in.
142
140
  * sourceRef: response-schemas.ts.
143
141
  */
144
142
  schema?: v.GenericSchema<unknown, T>;
@@ -157,28 +155,35 @@ export interface RequestOptions<T = unknown> {
157
155
  /**
158
156
  * Whether to retry on 409 CONFLICT.
159
157
  *
160
- * The shared retry policy retries CONFLICT once by default (read paths
161
- * where 409 = mid-mutation snapshot). Set to `false` for write paths
162
- * where 409 is a persistent condition (e.g. POST /tests/{testId}/runs
163
- * when another run is already in flight) — retrying there would enqueue
164
- * a second run once the first finishes.
158
+ * The shared retry policy retries CONFLICT once by default, for a
159
+ * transient server-side conflict. Set to `false` where a 409 is persistent
160
+ * (a run trigger, when another run is already in flight): retrying there
161
+ * would enqueue a second run once the first finishes.
165
162
  *
166
- * Defaults to `true` to preserve the original M2 read-path behavior.
163
+ * Defaults to `true`.
167
164
  */
168
165
  retryOnConflict?: boolean;
169
166
  /**
170
167
  * Whether the HTTP layer should retry internally on 429 RATE_LIMITED.
171
168
  *
172
- * Set to `false` for the batch-run trigger path where the outer
173
- * `runBatchRun` loop is the single owner of rate-limit handling —
174
- * keeping the HTTP layer from adding up to 3 extra retries per outer
175
- * attempt, which would multiply trigger POSTs per spec (e.g. 50×3 = 150/min)
176
- * instead of staying within the client throttle's 50/min.
169
+ * Set to `false` where the caller owns rate-limit handling itself (or a
170
+ * best-effort lookup should give up on the first 429), keeping the HTTP
171
+ * layer from adding up to 3 extra retries per call.
177
172
  *
178
173
  * Defaults to `true` to preserve backward-compatible behavior for all
179
174
  * other callers.
180
175
  */
181
176
  retryOnRateLimit?: boolean;
177
+ /**
178
+ * The endpoint absorbs a replay with no side effect even without an
179
+ * `Idempotency-Key` (a re-cancel is a 200 no-op, a binding is gone after
180
+ * any DELETE), so a keyless write may still retry a 5xx envelope and a
181
+ * transport failure (a fetch rejection, a connection dropped mid-response,
182
+ * a bare 408/502/504). Without it, keyless POST/PUT/PATCH/DELETE are sent
183
+ * once on either: the server may have committed before failing. Never set
184
+ * it on an arbitrary keyless mutation.
185
+ */
186
+ replaySafe?: boolean;
182
187
  /**
183
188
  * Disable every automatic retry for a read whose caller owns its cadence.
184
189
  *
@@ -242,15 +247,17 @@ export declare class HttpClient {
242
247
  patch<T>(path: string, options?: RequestOptions<T>): Promise<T>;
243
248
  delete<T>(path: string, options?: RequestOptions<T>): Promise<T>;
244
249
  /**
245
- * Like `get` / `post` / etc. but returns the full `RequestResult` including
250
+ * Like `post` / `delete` but returns the full `RequestResult` including
246
251
  * `requestId` and `status`, so callers can surface the requestId in
247
- * happy-path output.
252
+ * happy-path output. The run triggers and the tunnel mint and delete use them.
248
253
  */
249
- getWithMeta<T>(path: string, options?: RequestOptions<T>): Promise<RequestResult<T>>;
250
254
  postWithMeta<T>(path: string, options?: RequestOptions<T>): Promise<RequestResult<T>>;
251
- putWithMeta<T>(path: string, options?: RequestOptions<T>): Promise<RequestResult<T>>;
252
- patchWithMeta<T>(path: string, options?: RequestOptions<T>): Promise<RequestResult<T>>;
253
255
  deleteWithMeta<T>(path: string, options?: RequestOptions<T>): Promise<RequestResult<T>>;
256
+ /** Launch exactly one execution for this project, with server-owned pacing. */
257
+ triggerProjectRun(projectId: string, body: ProjectRunRequest, options: {
258
+ idempotencyKey: string;
259
+ signal?: AbortSignal;
260
+ }): Promise<RequestResult<ProjectRunResponse>>;
254
261
  /**
255
262
  * POST /api/cli/v1/tests/{testId}/runs
256
263
  * Trigger a run and return the queued-run envelope.
@@ -264,44 +271,11 @@ export declare class HttpClient {
264
271
  /**
265
272
  * Like `triggerRun` but returns the full `RequestResult` so the caller
266
273
  * can surface the `requestId` in happy-path CLI output.
267
- *
268
- * `retryOnRateLimit` defaults to `true` so single `test run` and
269
- * `test create --run` retain the standard HTTP-layer 429 retry budget.
270
- *
271
- * Pass `retryOnRateLimit: false` ONLY at the batch fan-out call site
272
- * (`runBatchRun` / `triggerOne`) where the outer loop is the single owner
273
- * of rate-limit handling — preventing the HTTP layer from adding up to 3
274
- * extra retries per outer attempt, which would multiply POSTs per spec (e.g. 50×3 = 150/min).
275
274
  */
276
275
  triggerRunWithMeta(testId: string, body: TriggerRunBody, options: {
277
276
  idempotencyKey: string;
278
277
  signal?: AbortSignal;
279
- retryOnRateLimit?: boolean;
280
278
  }): Promise<RequestResult<TriggerRunResponse>>;
281
- /**
282
- * POST /api/cli/v1/tests/{testId}/runs/rerun
283
- * Trigger a rerun (replay) for a single test. FE: verbatim script replay, billed at
284
- * 0.5 credits (same as a fresh run; legacy V2 accounts: free). BE: dependency-closure
285
- * re-run, billed at 0.2 credits. Returns `runId` + optional `closure` (BE).
286
- *
287
- * `retryOnConflict: false` — 409 on rerun means the test is already in-flight,
288
- * a persistent condition. Retrying would race against the running test.
289
- */
290
- triggerRerun(testId: string, body: RerunRequest, options: {
291
- idempotencyKey: string;
292
- signal?: AbortSignal;
293
- }): Promise<RerunResponse>;
294
- /**
295
- * POST /api/cli/v1/tests/batch/rerun
296
- * Trigger a batch rerun across multiple tests (mixed FE/BE allowed).
297
- * BE closure is deduped server-side per project.
298
- *
299
- * `retryOnConflict: false` — 409 on batch rerun is persistent ("in flight").
300
- */
301
- triggerBatchRerun(body: BatchRerunRequest, options: {
302
- idempotencyKey: string;
303
- signal?: AbortSignal;
304
- }): Promise<BatchRerunResponse>;
305
279
  /**
306
280
  * POST /api/cli/v1/tests/batch/run
307
281
  * Trigger a fresh wave-ordered batch run across all (or a subset of) BE tests
@@ -327,42 +301,23 @@ export declare class HttpClient {
327
301
  testIds?: string[];
328
302
  tunnelClientId?: string;
329
303
  targetUrl?: string;
304
+ maxConcurrency?: number;
330
305
  }, options: {
331
306
  idempotencyKey: string;
332
307
  signal?: AbortSignal;
333
308
  }): Promise<CliTestListRunResponse>;
334
309
  /**
335
- * GET /api/cli/v1/tests/{testId}/runs
336
- * List a test's prior run history, newest-first.
337
- *
338
- * Limit-before-filter caveat: a `source`-filtered page may return fewer
339
- * than `pageSize` rows while still yielding a non-null `nextCursor`.
340
- * That means "none in THIS window", not end-of-history.
310
+ * GET /api/cli/v1/runs/{resultId}
311
+ * Fetch an individual result card, including steps and artifacts. Optional
312
+ * waitSeconds is retained for callers of this existing result endpoint.
313
+ * Whole-execution waiting uses GET /results?run= through run-wait.ts.
341
314
  */
342
- listTestRuns(testId: string, query: ListRunsQuery, options?: {
343
- signal?: AbortSignal;
344
- retry?: boolean;
345
- }): Promise<ListRunsResponse>;
346
- /**
347
- * GET /api/cli/v1/runs/{runId}
348
- * Fetch the current state of a run. When `waitSeconds` is provided
349
- * (1–25) the server performs a bounded long-poll and returns when the
350
- * run is terminal or when `waitSeconds` elapses, whichever comes
351
- * first. On `400 VALIDATION_ERROR` (server doesn't support
352
- * `waitSeconds`) the caller should retry without the param and switch
353
- * to client-side backoff — see `src/lib/poll.ts`.
354
- *
355
- * When `includeSteps` is `true`, the server appends the full ordered
356
- * `steps[]` array (M3.4 piece-4). Default (absent/false) is byte-
357
- * identical to the M3.3 summary shape — the polling path is unaffected.
358
- */
359
- getRun(runId: string, options?: {
315
+ getRun(resultId: string, options?: {
360
316
  waitSeconds?: number;
361
- includeSteps?: boolean;
362
317
  signal?: AbortSignal;
363
318
  }): Promise<RunResponse>;
364
319
  /**
365
- * POST /api/cli/v1/tunnel — mint a tunnel client for `test run --local`.
320
+ * POST /api/cli/v1/tunnel — mint a tunnel client for a run on a local environment.
366
321
  *
367
322
  * The ONLY response on this surface that carries a secret. Deliberately NOT
368
323
  * sent with an `Idempotency-Key`: the interceptor persists the response body
@@ -403,7 +358,7 @@ export declare class HttpClient {
403
358
  * execution. `ready: false` asks the caller to poll again; the server keeps
404
359
  * building the report meanwhile.
405
360
  */
406
- getExecutionReport(executionId: string, options?: {
361
+ getExecutionReport(runId: string, options?: {
407
362
  signal?: AbortSignal;
408
363
  retry?: boolean;
409
364
  }): Promise<ExecutionReportResponse>;
@@ -419,58 +374,14 @@ export declare class HttpClient {
419
374
  }): Promise<void>;
420
375
  /**
421
376
  * POST /api/cli/v1/runs/{runId}/cancel
422
- * User-initiated cancel of a queued/running run. No
423
- * body, no `Idempotency-Key` — the endpoint is naturally idempotent:
424
- * re-cancel → 200 `alreadyCancelled: true`; already-terminal (passed/
425
- * failed/blocked) → 409 CONFLICT; unknown/cross-tenant runId → 404.
426
- *
427
- * `retryOnConflict: false` — same rationale as `triggerRun`: a 409 here is
428
- * a truthful terminal answer ("already finished"), not a transient
429
- * snapshot conflict to paper over with a retry.
377
+ * Cancel the entire execution without enumerating its results. Repeated and
378
+ * terminal cancellation returns HTTP 200 with alreadyCancelled/alreadyFinished;
379
+ * unknown and cross-tenant execution IDs return 404. Per-result refund outcomes
380
+ * are returned by the server. No request body or idempotency key is required.
430
381
  */
431
382
  cancelRun(runId: string, options?: {
432
383
  signal?: AbortSignal;
433
384
  }): Promise<CancelRunResponse>;
434
- /**
435
- * POST /api/cli/v1/projects/{projectId}/plans/generate
436
- * Start whichever generation stage the project is missing next. The body
437
- * is empty by contract — the server decides which rung fires. 202 both
438
- * for `accepted` (a stage started) and `nothing_to_start` (proposals are
439
- * already staged; the facade's no-restart guard refuses a duplicate
440
- * append because it would wipe the batch and re-bill 2 credits).
441
- *
442
- * `retryOnConflict: false` — a 409 here is `stage_in_flight`, a flow
443
- * signal the ladder answers by attaching and polling, never a transient
444
- * snapshot conflict to paper over with a retry.
445
- */
446
- generatePlans(projectId: string, options: {
447
- idempotencyKey: string;
448
- signal?: AbortSignal;
449
- }): Promise<CliGeneratePlansResponse>;
450
- /**
451
- * GET /api/cli/v1/projects/{projectId}/plans
452
- * Pure read: the facade-synthesized generation status, the staged
453
- * proposal list (stable proposalIds — what `accept --only` consumes),
454
- * and a best-effort credits block. When `waitSeconds` (1–25) is
455
- * provided the server long-polls: one request per window, answered
456
- * early on any change.
457
- */
458
- getPlans(projectId: string, options?: {
459
- waitSeconds?: number;
460
- signal?: AbortSignal;
461
- }): Promise<CliGetPlansResponse>;
462
- /**
463
- * POST /api/cli/v1/projects/{projectId}/plans/accept
464
- * Convert staged proposals into real test cases. `only` is ALWAYS an
465
- * explicit, non-empty id list — the caller enforces the two §3.3 safety
466
- * rules (full list when the user didn't subset; an empty selection is a
467
- * client-side validation error because `[]` is server-destructive:
468
- * it means "reject everything" and clears the staged batch).
469
- */
470
- acceptPlans(projectId: string, only: string[], options: {
471
- idempotencyKey: string;
472
- signal?: AbortSignal;
473
- }): Promise<CliAcceptPlansResponse>;
474
385
  /**
475
386
  * Classify an error thrown while issuing OR reading a request. When it is an
476
387
  * abort/timeout and our per-request timeout signal fired (and the caller had
@@ -482,15 +393,28 @@ export declare class HttpClient {
482
393
  private rethrowIfAbort;
483
394
  requestWithMeta<T>(method: string, path: string, options?: RequestOptions<T>): Promise<RequestResult<T>>;
484
395
  private requestWithMetaUntracked;
396
+ /** Follow redirects explicitly so credentials never leave the original origin. */
397
+ private fetchSameOrigin;
485
398
  private buildHeaders;
486
399
  /**
487
- * Retry-delay sleep that bails the moment the shutdown signal fires: a
488
- * RATE_LIMITED `Retry-After: 60` or a transport backoff must not delay the
489
- * honest-detach exit by up to a minute — reject with the InterruptError
490
- * reason immediately. Mirrors poll.ts::sleepUnlessInterrupted.
400
+ * Retry-delay sleep that ends the moment the shutdown signal or the caller's
401
+ * own signal for this request fires, rejecting with that signal's reason: a
402
+ * RATE_LIMITED `Retry-After: 60` or a transport backoff must neither delay
403
+ * the honest-detach exit by up to a minute nor outlast a deadline the caller
404
+ * set (`run wait --timeout`). An interrupt outranks the caller's signal when
405
+ * both have fired. The race itself is poll-support.ts::sleepUnlessInterrupted,
406
+ * over the two signals composed into one.
491
407
  */
492
408
  private sleepBeforeRetry;
493
409
  private debug;
410
+ /**
411
+ * Shared handling for a transport failure — the fetch itself rejected, or
412
+ * the connection dropped while the body was being read. Records the failure,
413
+ * then either throws {@link TransportError} (retries not allowed for this
414
+ * request, or the transport budget is spent) or announces the retry and
415
+ * returns the backoff delay for the caller to sleep before `continue`.
416
+ */
417
+ private transportRetryDelayOrThrow;
494
418
  private transition;
495
419
  /**
496
420
  * Legacy alias kept for backward-compat with test files that call