@testsprite/testsprite-cli 0.1.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 (63) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +190 -0
  3. package/dist/assets/agent-skill/testsprite-verify.codex.md +119 -0
  4. package/dist/assets/agent-skill/testsprite-verify.skill.md +423 -0
  5. package/dist/commands/agent.d.ts +51 -0
  6. package/dist/commands/agent.js +552 -0
  7. package/dist/commands/auth.d.ts +38 -0
  8. package/dist/commands/auth.js +247 -0
  9. package/dist/commands/init.d.ts +63 -0
  10. package/dist/commands/init.js +350 -0
  11. package/dist/commands/project.d.ts +72 -0
  12. package/dist/commands/project.js +400 -0
  13. package/dist/commands/test.d.ts +1245 -0
  14. package/dist/commands/test.js +6214 -0
  15. package/dist/commands/usage.d.ts +63 -0
  16. package/dist/commands/usage.js +156 -0
  17. package/dist/index.d.ts +2 -0
  18. package/dist/index.js +146 -0
  19. package/dist/lib/agent-targets.d.ts +50 -0
  20. package/dist/lib/agent-targets.js +99 -0
  21. package/dist/lib/bundle.d.ts +178 -0
  22. package/dist/lib/bundle.js +600 -0
  23. package/dist/lib/client-factory.d.ts +72 -0
  24. package/dist/lib/client-factory.js +120 -0
  25. package/dist/lib/config.d.ts +24 -0
  26. package/dist/lib/config.js +30 -0
  27. package/dist/lib/credentials.d.ts +17 -0
  28. package/dist/lib/credentials.js +122 -0
  29. package/dist/lib/dry-run/fetch.d.ts +18 -0
  30. package/dist/lib/dry-run/fetch.js +52 -0
  31. package/dist/lib/dry-run/samples.d.ts +50 -0
  32. package/dist/lib/dry-run/samples.js +676 -0
  33. package/dist/lib/errors.d.ts +118 -0
  34. package/dist/lib/errors.js +388 -0
  35. package/dist/lib/facade.d.ts +48 -0
  36. package/dist/lib/facade.js +104 -0
  37. package/dist/lib/failing-fe-resolver.d.ts +60 -0
  38. package/dist/lib/failing-fe-resolver.js +103 -0
  39. package/dist/lib/http.d.ts +255 -0
  40. package/dist/lib/http.js +608 -0
  41. package/dist/lib/output.d.ts +55 -0
  42. package/dist/lib/output.js +70 -0
  43. package/dist/lib/pagination.d.ts +56 -0
  44. package/dist/lib/pagination.js +81 -0
  45. package/dist/lib/poll.d.ts +88 -0
  46. package/dist/lib/poll.js +221 -0
  47. package/dist/lib/prompt.d.ts +8 -0
  48. package/dist/lib/prompt.js +97 -0
  49. package/dist/lib/rate-throttle.d.ts +49 -0
  50. package/dist/lib/rate-throttle.js +75 -0
  51. package/dist/lib/render-error.d.ts +15 -0
  52. package/dist/lib/render-error.js +44 -0
  53. package/dist/lib/runs.types.d.ts +344 -0
  54. package/dist/lib/runs.types.js +25 -0
  55. package/dist/lib/target-url.d.ts +25 -0
  56. package/dist/lib/target-url.js +127 -0
  57. package/dist/lib/ticker.d.ts +37 -0
  58. package/dist/lib/ticker.js +63 -0
  59. package/dist/lib/validate.d.ts +82 -0
  60. package/dist/lib/validate.js +165 -0
  61. package/dist/version.d.ts +1 -0
  62. package/dist/version.js +2 -0
  63. package/package.json +65 -0
@@ -0,0 +1,600 @@
1
+ /**
2
+ * §6.7 FailureContext bundle writer.
3
+ *
4
+ * Given a `FailureContext` JSON envelope (returned by
5
+ * `GET /api/cli/v1/tests/{id}/failure`), `writeBundle` dereferences
6
+ * every presigned URL into local bytes and writes the §7 disk layout
7
+ * under `<dir>`. The contract is "agent-safe" — every guarantee in
8
+ * the FailureContext spec §3 + §7 is enforced here:
9
+ *
10
+ * 1. **Atomic** — every artifact in the bundle came from one
11
+ * `snapshotId`. We refuse a forged response where
12
+ * `bundle.snapshotId !== result.snapshotId` or steps disagree on
13
+ * `runIdIfAvailable` (`assertContextIntegrity`).
14
+ * 2. **Atomic on disk** — we write to `<dir>/.tmp/...` first and
15
+ * `rename()` each file into place. `meta.json` is renamed last so
16
+ * the presence of `<dir>/meta.json` ⇔ "bundle is complete and
17
+ * self-consistent".
18
+ * 3. **`.partial` on failure** — any download or fs failure leaves
19
+ * a `<dir>/.partial` marker (with `requestId`, error summary,
20
+ * snapshotId) and exits non-zero. Agents check `.partial` before
21
+ * consuming.
22
+ * 4. **Bounded budget** — the writer streams URL → file (no full-
23
+ * buffer), so a 200MB video doesn't sit in V8's heap.
24
+ *
25
+ * What this module deliberately does NOT do:
26
+ *
27
+ * - Re-derive `snapshotId`. The CLI trusts whatever the facade
28
+ * returned. A snapshotId mismatch is a backend bug and we surface
29
+ * it as a typed validation error rather than try to "heal" it.
30
+ * - Generate `summary` strings. Those are server-side per §6.1 of
31
+ * the spec; the CLI emits whatever the facade produced.
32
+ * - Resume after a partial bundle. M2 always re-fetches from scratch
33
+ * when the agent re-runs. M3 may add resume.
34
+ */
35
+ import { mkdir, mkdtemp, readdir, rename, rm, stat, unlink, writeFile } from 'node:fs/promises';
36
+ import { pipeline } from 'node:stream/promises';
37
+ import { createWriteStream } from 'node:fs';
38
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
39
+ import { ApiError, TransportError } from './errors.js';
40
+ /** Schema version stamped into `meta.json`. Bumps with the contract. */
41
+ export const BUNDLE_SCHEMA_VERSION = 'cli-v1';
42
+ /** Default radius around the failed step when `--failed-only` is set. */
43
+ export const FAILED_ONLY_RADIUS = 1;
44
+ /**
45
+ * Compose the FailureContext spec §3 invariants into a single
46
+ * trip wire. Throwing here is the agent-safety gate — we trust the
47
+ * facade for the data, not for self-consistency.
48
+ *
49
+ * - Bundle-level `snapshotId` MUST equal `result.snapshotId`.
50
+ * - All steps in the bundle MUST share `runIdIfAvailable` (or all
51
+ * be `null`). Mixed values means a stitched read leaked through.
52
+ *
53
+ * The error envelope is `VALIDATION_ERROR` rather than `INTERNAL`
54
+ * because the operator-facing remediation is "retry once" (the
55
+ * snapshot may genuinely have been mid-mutation; a fresh fetch will
56
+ * succeed). `requestId` is the original request id so support can
57
+ * trace the bad envelope back.
58
+ */
59
+ export function assertContextIntegrity(ctx, requestId, opts) {
60
+ if (opts?.requireRunId && !ctx.result.runIdIfAvailable) {
61
+ throw bundleIntegrityError('run_id_missing', 'meta.runId (result.runIdIfAvailable) is required for run-scoped bundles but is null or missing', requestId);
62
+ }
63
+ if (ctx.snapshotId !== ctx.result.snapshotId) {
64
+ throw bundleIntegrityError('snapshot_id_mismatch', `Bundle integrity check failed: expected snapshotId=${ctx.snapshotId} got snapshotId=${ctx.result.snapshotId}`, requestId, { expectedSnapshotId: ctx.snapshotId, actualSnapshotId: ctx.result.snapshotId });
65
+ }
66
+ // Per codex round-1 P2: every embedded testId must equal ctx.testId.
67
+ // §6.X duplicates `testId` in `result`, `code`, and each step so a
68
+ // bundle stitched together from rows of two different tests is
69
+ // detectable without external state. Without this gate, an agent
70
+ // could open `meta.json` for `test_A`, edit the file the bundle
71
+ // claims is its code, and have the edit actually target `test_B`'s
72
+ // source — exactly the cross-test contamination the failure bundle
73
+ // exists to prevent.
74
+ if (ctx.result.testId !== ctx.testId) {
75
+ throw bundleIntegrityError('test_id_mismatch', `Bundle integrity check failed: expected testId=${ctx.testId} got testId=${ctx.result.testId} (in result)`, requestId, { expectedTestId: ctx.testId, actualTestId: ctx.result.testId });
76
+ }
77
+ if (ctx.code.testId !== ctx.testId) {
78
+ throw bundleIntegrityError('test_id_mismatch', `Bundle integrity check failed: expected testId=${ctx.testId} got testId=${ctx.code.testId} (in code)`, requestId, { expectedTestId: ctx.testId, actualTestId: ctx.code.testId });
79
+ }
80
+ for (const step of ctx.steps) {
81
+ if (step.testId !== ctx.testId) {
82
+ throw bundleIntegrityError('test_id_mismatch', `Bundle integrity check failed: expected testId=${ctx.testId} got testId=${step.testId} (in step[${step.stepIndex}])`, requestId, { expectedTestId: ctx.testId, actualTestId: step.testId });
83
+ }
84
+ }
85
+ // §6.7: code is "version pinned to result.codeVersion." If both
86
+ // sides are non-null and disagree, the bundle stitched code from
87
+ // one version with a result from another — exactly the drift case
88
+ // the failure bundle exists to prevent. Both-null is fine (the M2
89
+ // backend hasn't shipped versioning yet); only mismatched pairs
90
+ // are corrupt.
91
+ if (ctx.result.codeVersion !== null &&
92
+ ctx.code.codeVersion !== null &&
93
+ ctx.result.codeVersion !== ctx.code.codeVersion) {
94
+ throw bundleIntegrityError('code_version_mismatch', `Bundle integrity check failed: expected codeVersion=${ctx.result.codeVersion} got codeVersion=${ctx.code.codeVersion}`, requestId, { expectedCodeVersion: ctx.result.codeVersion, actualCodeVersion: ctx.code.codeVersion });
95
+ }
96
+ // Only DISTINCT NON-NULL runIds indicate cross-run stitching. A `null`
97
+ // `runIdIfAvailable` just means that step row predates runId stamping —
98
+ // FE Portal step rows accumulate across runs and older rows were never
99
+ // stamped, so a multi-run test legitimately carries a mix of one real
100
+ // runId and several nulls. Counting null as a distinct value made
101
+ // `test failure get <test-id>` permanently fail on any test that ran
102
+ // more than once across the M3.1 cutover, and the "re-fetch usually
103
+ // succeeds" hint was wrong because the null is durable, not transient
104
+ // (dogfood 2026-06-04). Tolerate null; flag only when ≥2 *real* runIds
105
+ // are present (genuine cross-run stitching). The run-scoped path below
106
+ // (`requireRunId`) keeps the stricter per-step equality check.
107
+ const nonNullRunIds = new Set();
108
+ for (const step of ctx.steps) {
109
+ if (step.runIdIfAvailable != null)
110
+ nonNullRunIds.add(step.runIdIfAvailable);
111
+ }
112
+ if (nonNullRunIds.size > 1) {
113
+ const runIdList = [...nonNullRunIds];
114
+ throw bundleIntegrityError('run_id_mismatch', `Bundle integrity check failed: steps carry mixed runIds [${runIdList.join(', ')}]`, requestId, { observedRunIds: runIdList });
115
+ }
116
+ // Run-scoped path: additionally assert that every step's runIdIfAvailable
117
+ // matches result.runIdIfAvailable. The check above only catches steps
118
+ // that disagree with *each other*; a backend stitching all steps from
119
+ // "run_other" into a result for "run_abc" would pass the set-size check
120
+ // (all steps agree) but fail here.
121
+ //
122
+ // Also assert per-step codeVersion matches result.codeVersion when both
123
+ // are present — a mixed version bundle could point an agent at the wrong
124
+ // fix target.
125
+ if (opts?.requireRunId) {
126
+ const expectedRunId = ctx.result.runIdIfAvailable; // guarded by run_id_missing check above
127
+ const resultCodeVersion = ctx.result.codeVersion;
128
+ for (const step of ctx.steps) {
129
+ if (step.runIdIfAvailable !== expectedRunId) {
130
+ throw bundleIntegrityError('run_id_mismatch', `Bundle integrity check failed: expected runId=${expectedRunId} got runId=${String(step.runIdIfAvailable)} (in step[${step.stepIndex}])`, requestId, { expectedRunId, actualRunId: step.runIdIfAvailable });
131
+ }
132
+ if (resultCodeVersion !== null &&
133
+ step.codeVersion !== null &&
134
+ step.codeVersion !== resultCodeVersion) {
135
+ throw bundleIntegrityError('code_version_mismatch', `Bundle integrity check failed: expected codeVersion=${resultCodeVersion} got codeVersion=${step.codeVersion} (in step[${step.stepIndex}])`, requestId, { expectedCodeVersion: resultCodeVersion, actualCodeVersion: step.codeVersion });
136
+ }
137
+ }
138
+ }
139
+ if (ctx.failure.evidence.length > 0 && ctx.result.failedStepIndex !== null) {
140
+ const hasFailedStep = ctx.failure.evidence.some(e => e.stepIndex === ctx.result.failedStepIndex);
141
+ if (!hasFailedStep) {
142
+ // §6.2: when evidence[] is non-empty, at least one entry must
143
+ // attach to the failed step so an agent can route on it.
144
+ throw bundleIntegrityError('evidence_missing_failed_step', `bundle evidence does not include failedStepIndex=${ctx.result.failedStepIndex}`, requestId);
145
+ }
146
+ }
147
+ }
148
+ /**
149
+ * Apply the `--failed-only` filter — drop neighbor steps and their
150
+ * evidence, keep the failed step. Idempotent: returns `ctx` unchanged
151
+ * when `failedStepIndex` is null (no step-level diagnosis to filter)
152
+ * or when the existing window already matches.
153
+ */
154
+ export function applyFailedOnly(ctx) {
155
+ const failedIdx = ctx.result.failedStepIndex;
156
+ if (failedIdx === null)
157
+ return ctx;
158
+ const inWindow = (idx) => Math.abs(idx - failedIdx) <= FAILED_ONLY_RADIUS;
159
+ const filteredSteps = ctx.steps.filter(s => inWindow(s.stepIndex));
160
+ const filteredEvidence = ctx.failure.evidence.filter(e => inWindow(e.stepIndex));
161
+ return {
162
+ ...ctx,
163
+ steps: filteredSteps,
164
+ failure: { ...ctx.failure, evidence: filteredEvidence },
165
+ };
166
+ }
167
+ /**
168
+ * Resolve the user-supplied `--out` path into an absolute directory.
169
+ * Empty strings are rejected with `VALIDATION_ERROR` for consistency
170
+ * with `test code get --out`. We do NOT pre-create the directory or
171
+ * its `.tmp` child — `writeBundle` mkdir's after the integrity check
172
+ * passes so a forged response never modifies the operator's filesystem.
173
+ */
174
+ export function resolveBundleDir(rawPath) {
175
+ if (typeof rawPath !== 'string' || rawPath.length === 0) {
176
+ throw ApiError.fromEnvelope({
177
+ error: {
178
+ code: 'VALIDATION_ERROR',
179
+ message: 'Invalid request.',
180
+ nextAction: 'Flag `--out` is invalid: must be a non-empty directory path.',
181
+ requestId: 'local',
182
+ details: { field: 'out', reason: 'must be a non-empty directory path' },
183
+ },
184
+ });
185
+ }
186
+ const trimmed = rawPath.endsWith('/') ? rawPath.slice(0, -1) : rawPath;
187
+ return isAbsolute(trimmed) ? trimmed : resolve(process.cwd(), trimmed);
188
+ }
189
+ /**
190
+ * Pick a code-file extension for `<dir>/code.<ext>` based on the §6.3
191
+ * `language` + `framework`. The extension matches the test code's
192
+ * language, not the user-app code under test.
193
+ */
194
+ export function pickCodeExtension(language, framework) {
195
+ if (language === 'python')
196
+ return 'py';
197
+ if (language === 'javascript')
198
+ return 'js';
199
+ if (language === 'typescript')
200
+ return 'ts';
201
+ // Fallback: framework-keyed default. pytest is python, playwright TS.
202
+ if (framework === 'pytest')
203
+ return 'py';
204
+ return 'ts';
205
+ }
206
+ /**
207
+ * Step filename per §7.2 — 1-based index, zero-padded to two digits
208
+ * for indices ≤ 99, three digits for ≥ 100. `${stepIndex}-snapshot.html`
209
+ * etc. Never truncates: an agent constructing the path with
210
+ * `padStart(2, '0')` works for the common case, and step ≥ 100 widens
211
+ * naturally without breaking existing fixtures.
212
+ */
213
+ export function stepFilenamePrefix(stepIndex) {
214
+ return stepIndex >= 100 ? String(stepIndex).padStart(3, '0') : String(stepIndex).padStart(2, '0');
215
+ }
216
+ /**
217
+ * Build the §7.1 meta.json given a context. Pure function, no I/O —
218
+ * lets specs assert the meta shape without touching disk.
219
+ */
220
+ export function buildMeta(ctx, fetchedAt = new Date()) {
221
+ return {
222
+ schemaVersion: BUNDLE_SCHEMA_VERSION,
223
+ snapshotId: ctx.snapshotId,
224
+ testId: ctx.testId,
225
+ projectId: ctx.projectId,
226
+ codeVersion: ctx.code.codeVersion ?? ctx.result.codeVersion ?? null,
227
+ runIdIfAvailable: ctx.result.runIdIfAvailable,
228
+ targetUrl: ctx.result.targetUrl,
229
+ failedStepIndex: ctx.result.failedStepIndex,
230
+ failureKind: ctx.result.failureKind,
231
+ capturedAt: ctx.result.finishedAt,
232
+ fetchedAt: fetchedAt.toISOString(),
233
+ };
234
+ }
235
+ /**
236
+ * Top-level bundle writer. The order matters:
237
+ *
238
+ * 1. `assertContextIntegrity` — fail closed on a forged envelope.
239
+ * 2. `applyFailedOnly` — narrow before download (saves bytes).
240
+ * 3. `mkdir <dir>/.tmp/` — fresh; clean any stale temp.
241
+ * 4. `writeFile result.json / failure.json / code.<ext>` — local data.
242
+ * 5. `fetch + stream` for `video.mp4` (when set) and per-step
243
+ * snapshot/screenshot/evidence-json files.
244
+ * 6. `writeFile meta.json` LAST — its presence means "bundle complete".
245
+ * 7. `rename .tmp/<file> -> <file>` for every file. Last rename
246
+ * makes meta.json visible.
247
+ *
248
+ * On any failure between (3) and (6), write a `<dir>/.partial` marker
249
+ * and re-throw so `index.ts` produces a typed exit code (UNAVAILABLE
250
+ * → 10 by default; the original ApiError is preserved when applicable).
251
+ */
252
+ export async function writeBundle(ctx, options) {
253
+ const requestId = options.requestId ?? 'local';
254
+ assertContextIntegrity(ctx, requestId);
255
+ const filtered = options.failedOnly ? applyFailedOnly(ctx) : ctx;
256
+ // Re-check after filtering — in theory a buggy filter could leave a
257
+ // mismatched evidence list. Cheap defense-in-depth.
258
+ assertContextIntegrity(filtered, requestId);
259
+ const dir = resolveBundleDir(options.dir);
260
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);
261
+ const meta = buildMeta(filtered);
262
+ const codeExt = pickCodeExtension(filtered.code.language, filtered.code.framework);
263
+ await mkdir(dir, { recursive: true });
264
+ // Fresh `.tmp/` each run. A previous SIGKILL'd run can leave bytes
265
+ // behind; we don't want to mix them with the new fetch.
266
+ const tmpDir = await freshTmpDir(dir);
267
+ const stepsTmpDir = join(tmpDir, 'steps');
268
+ await mkdir(stepsTmpDir, { recursive: true });
269
+ const filesWritten = [];
270
+ try {
271
+ // result.json + failure.json + code.<ext> are local writes; no
272
+ // network, no streaming.
273
+ await writeFile(join(tmpDir, 'result.json'), JSON.stringify(filtered.result, null, 2) + '\n', 'utf8');
274
+ filesWritten.push('result.json');
275
+ await writeFile(join(tmpDir, 'failure.json'), JSON.stringify(filtered.failure, null, 2) + '\n', 'utf8');
276
+ filesWritten.push('failure.json');
277
+ const codeFile = `code.${codeExt}`;
278
+ if (isPresignedUrl(filtered.code.code)) {
279
+ // §6.3 alt: when the `code` field is a presigned URL (>= 100 KB
280
+ // bodies), stream the URL into the file rather than embedding
281
+ // the URL in code.<ext>. M2's backend hasn't shipped the
282
+ // >=100KB branch yet, but the contract supports it.
283
+ await streamUrlToFile(filtered.code.code, join(tmpDir, codeFile), fetchImpl);
284
+ }
285
+ else {
286
+ await writeFile(join(tmpDir, codeFile), filtered.code.code, 'utf8');
287
+ }
288
+ filesWritten.push(codeFile);
289
+ // Optional video. Wire field is `result.videoUrl` (not in `failure`),
290
+ // and the CLI surfaces it as a top-level on-disk artifact for agent
291
+ // ergonomics — the agent doesn't have to know which sub-object held
292
+ // it on the wire.
293
+ if (filtered.result.videoUrl) {
294
+ await streamUrlToFile(filtered.result.videoUrl, join(tmpDir, 'video.mp4'), fetchImpl);
295
+ filesWritten.push('video.mp4');
296
+ }
297
+ for (const step of filtered.steps) {
298
+ await writeStepArtifacts(step, filtered.failure.evidence, stepsTmpDir, fetchImpl, filesWritten);
299
+ }
300
+ // meta.json LAST. Its presence is the sentinel that the bundle
301
+ // is complete. An agent that opens <dir> and finds meta.json can
302
+ // safely consume.
303
+ await writeFile(join(tmpDir, 'meta.json'), JSON.stringify(meta, null, 2) + '\n', 'utf8');
304
+ filesWritten.push('meta.json');
305
+ // Atomic rename: move every file from <dir>/.tmp/* into <dir>/*.
306
+ // Steps subdir gets renamed wholesale; meta.json renames last so
307
+ // its visibility implies "bundle is complete and atomic on disk."
308
+ await commitBundle(tmpDir, dir, filesWritten);
309
+ return { meta, dir, files: filesWritten };
310
+ }
311
+ catch (err) {
312
+ await writePartialMarker(dir, err, requestId, ctx.snapshotId).catch(() => undefined);
313
+ throw err;
314
+ }
315
+ }
316
+ /**
317
+ * Make a fresh `<dir>/.tmp/` directory, removing any pre-existing
318
+ * orphaned tmp from a prior aborted run. Using `mkdtemp` would dodge
319
+ * the rm step but would make the rename target unpredictable; this
320
+ * way the temp path is stable (`<dir>/.tmp`) so a SIGKILL between two
321
+ * runs doesn't leave a tree of `.tmp.<rand>` directories.
322
+ */
323
+ async function freshTmpDir(dir) {
324
+ const tmpDir = join(dir, '.tmp');
325
+ await rm(tmpDir, { recursive: true, force: true });
326
+ await mkdir(tmpDir, { recursive: true });
327
+ return tmpDir;
328
+ }
329
+ /**
330
+ * Rename `<tmp>/<file>` → `<dir>/<file>` for every file in `files`.
331
+ *
332
+ * Critical ordering for atomicity (the §3 "agent-safe" contract):
333
+ *
334
+ * 1. **Remove the OLD `meta.json` first.** The bundle's completion
335
+ * signal is `meta.json`'s presence; an agent reading `<dir>` while
336
+ * we're mutating it must see "no meta → bundle absent or
337
+ * mid-write" rather than "meta points at a snapshot that's already
338
+ * been partially overwritten." Removing the old meta is what
339
+ * makes the rest of the swap safe to do in place.
340
+ * 2. Wipe stale top-level files (e.g. an old `video.mp4` when the new
341
+ * bundle has no video). Without this, a fresh bundle could ship
342
+ * with a stale video lingering at the top level.
343
+ * 3. Replace `<dir>/steps/` wholesale.
344
+ * 4. Rename top-level files into place.
345
+ * 5. **Rename `meta.json` LAST.** Its visible presence is the atomic
346
+ * completion signal; until step 5 lands, agents see "incomplete."
347
+ *
348
+ * The window between (1) and (5) is bounded by a handful of `rename`
349
+ * syscalls — small enough that a SIGKILL there is rare, and any agent
350
+ * caught reading the dir during it sees no meta and refuses to consume
351
+ * (per §7.3). That's what we want.
352
+ */
353
+ async function commitBundle(tmpDir, dir, files) {
354
+ // (1) Remove the prior bundle's completion signal FIRST.
355
+ await unlink(join(dir, 'meta.json')).catch(() => undefined);
356
+ // (2) Sweep stale top-level files that the new bundle won't write.
357
+ // If the prior run wrote `video.mp4` and the new run has no video,
358
+ // an in-place rename leaves the old video lingering. Enumerate
359
+ // current top-level entries and remove anything that isn't being
360
+ // freshly renamed in.
361
+ const topLevel = files.filter(f => !f.startsWith('steps/'));
362
+ const newTopLevelSet = new Set(topLevel);
363
+ newTopLevelSet.add('meta.json'); // about to land last, do not delete
364
+ const existing = await readdir(dir).catch(() => []);
365
+ for (const entry of existing) {
366
+ // Preserve the writer's own scratch dir + the .partial marker
367
+ // (we'll re-evaluate .partial at the end of commit). Anything else
368
+ // not-listed in the new bundle is stale.
369
+ if (entry === '.tmp' || entry === '.partial')
370
+ continue;
371
+ if (newTopLevelSet.has(entry))
372
+ continue;
373
+ if (entry === 'steps')
374
+ continue; // handled below
375
+ await rm(join(dir, entry), { recursive: true, force: true });
376
+ }
377
+ // (3) Replace `<dir>/steps/` with `<tmp>/steps/`.
378
+ const stepsTmp = join(tmpDir, 'steps');
379
+ const stepsDir = join(dir, 'steps');
380
+ await rm(stepsDir, { recursive: true, force: true });
381
+ if (await dirExists(stepsTmp)) {
382
+ await rename(stepsTmp, stepsDir);
383
+ }
384
+ // (4) Top-level files (result/failure/code/video). meta.json renames
385
+ // LAST; track it separately.
386
+ const metaIdx = topLevel.indexOf('meta.json');
387
+ const beforeMeta = metaIdx >= 0 ? topLevel.filter((_, i) => i !== metaIdx) : topLevel;
388
+ for (const file of beforeMeta) {
389
+ await rename(join(tmpDir, file), join(dir, file));
390
+ }
391
+ // (5) meta.json LAST → atomic completion signal.
392
+ if (metaIdx >= 0) {
393
+ await rename(join(tmpDir, 'meta.json'), join(dir, 'meta.json'));
394
+ }
395
+ // .partial from a prior aborted run is now stale. Remove it so an
396
+ // agent inspecting the dir sees only the fresh bundle.
397
+ await unlink(join(dir, '.partial')).catch(() => undefined);
398
+ // Clean up the now-empty tmp dir.
399
+ await rm(tmpDir, { recursive: true, force: true });
400
+ }
401
+ async function dirExists(path) {
402
+ try {
403
+ const s = await stat(path);
404
+ return s.isDirectory();
405
+ }
406
+ catch {
407
+ return false;
408
+ }
409
+ }
410
+ /**
411
+ * Write per-step artifacts under `<tmp>/steps/`. Each step gets up to
412
+ * three files: `<NN>-screenshot.png` (when a screenshot URL exists —
413
+ * M2 backend never sets one yet), `<NN>-snapshot.html` (when
414
+ * `htmlSnapshotUrl` exists), and `<NN>-evidence.json` (a small JSON
415
+ * file containing the non-snapshot evidence summaries — log/network/
416
+ * console — for that step). The evidence-json file is omitted when
417
+ * there's nothing to put in it; it's NOT a placeholder.
418
+ */
419
+ async function writeStepArtifacts(step, allEvidence, stepsTmpDir, fetchImpl, filesWritten) {
420
+ const prefix = stepFilenamePrefix(step.stepIndex);
421
+ if (step.screenshotUrl) {
422
+ const file = `${prefix}-screenshot.png`;
423
+ await streamUrlToFile(step.screenshotUrl, join(stepsTmpDir, file), fetchImpl);
424
+ filesWritten.push(`steps/${file}`);
425
+ }
426
+ if (step.htmlSnapshotUrl) {
427
+ const file = `${prefix}-snapshot.html`;
428
+ await streamUrlToFile(step.htmlSnapshotUrl, join(stepsTmpDir, file), fetchImpl);
429
+ filesWritten.push(`steps/${file}`);
430
+ }
431
+ // Evidence sidecar artifacts. Per codex round-1 P2: the bundle must
432
+ // be self-contained — every `evidence[].url` in the failure response
433
+ // resolves to a local file by the time `meta.json` is written. The
434
+ // earlier filter dropped screenshot/snapshot kinds on the assumption
435
+ // they were always duplicates of `step.screenshotUrl` /
436
+ // `step.htmlSnapshotUrl`, but if the evidence carries a different URL
437
+ // (different snapshot variant, a per-evidence sidecar shot, etc.) the
438
+ // bundle silently lost it and `failure.json` still referenced an
439
+ // expiring presigned link. Rule now: include every evidence entry;
440
+ // remap to the existing step file when URLs match, download a fresh
441
+ // sidecar otherwise.
442
+ //
443
+ // Critical: leaving any URL inside `<NN>-evidence.json` means the
444
+ // bundle claims completeness but actually points at presigned URLs
445
+ // that expire after 15 min — an agent opening the bundle one hour
446
+ // later would see metadata referencing dead links. Streaming the
447
+ // bytes here makes the bundle self-contained.
448
+ const sidecar = allEvidence.filter(e => e.stepIndex === step.stepIndex);
449
+ if (sidecar.length > 0) {
450
+ const dereferenced = await Promise.all(sidecar.map(async (entry, i) => {
451
+ // Reuse the already-downloaded step file when the evidence URL
452
+ // matches the step's primary screenshot/snapshot URL. Cheap
453
+ // dedupe — no extra HTTP round-trip, no duplicate bytes on disk.
454
+ if (entry.kind === 'screenshot' && step.screenshotUrl && step.screenshotUrl === entry.url) {
455
+ return {
456
+ kind: entry.kind,
457
+ stepIndex: entry.stepIndex,
458
+ summary: entry.summary,
459
+ path: `steps/${prefix}-screenshot.png`,
460
+ };
461
+ }
462
+ if (entry.kind === 'snapshot' &&
463
+ step.htmlSnapshotUrl &&
464
+ step.htmlSnapshotUrl === entry.url) {
465
+ return {
466
+ kind: entry.kind,
467
+ stepIndex: entry.stepIndex,
468
+ summary: entry.summary,
469
+ path: `steps/${prefix}-snapshot.html`,
470
+ };
471
+ }
472
+ const ext = sidecarExtension(entry.kind);
473
+ const filename = `${prefix}-${entry.kind}-${i}.${ext}`;
474
+ await streamUrlToFile(entry.url, join(stepsTmpDir, filename), fetchImpl);
475
+ filesWritten.push(`steps/${filename}`);
476
+ return {
477
+ kind: entry.kind,
478
+ stepIndex: entry.stepIndex,
479
+ summary: entry.summary,
480
+ // Replace the (soon-expired) URL with a path relative to the
481
+ // bundle root so an agent can resolve it without ambient
482
+ // knowledge of the bundle's working directory.
483
+ path: `steps/${filename}`,
484
+ };
485
+ }));
486
+ const file = `${prefix}-evidence.json`;
487
+ await writeFile(join(stepsTmpDir, file), JSON.stringify(dereferenced, null, 2) + '\n', 'utf8');
488
+ filesWritten.push(`steps/${file}`);
489
+ }
490
+ }
491
+ function sidecarExtension(kind) {
492
+ if (kind === 'network' || kind === 'console')
493
+ return 'json';
494
+ if (kind === 'screenshot')
495
+ return 'png';
496
+ if (kind === 'snapshot')
497
+ return 'html';
498
+ // log evidence is text-shaped — `.txt` is the safest default. The
499
+ // actual content-type the URL serves may be log-specific (e.g.
500
+ // .ndjson for stream-of-events logs); we don't try to guess.
501
+ return 'txt';
502
+ }
503
+ /**
504
+ * Stream a presigned URL into a file with bounded retry on transport
505
+ * failures. 4xx (presigned URL expired or unauthorized) is NOT
506
+ * retried — the URL won't recover on its own; an upstream re-fetch
507
+ * is the only fix. Maps to `UNAVAILABLE` so `index.ts` exits 10.
508
+ *
509
+ * Streaming uses `pipeline` to honor backpressure: a slow disk pauses
510
+ * the upstream reader rather than buffering chunks in V8 heap. This
511
+ * matters for video files (multi-MB) and for very large HTML
512
+ * snapshots.
513
+ */
514
+ export async function streamUrlToFile(url, filePath, fetchImpl) {
515
+ let response;
516
+ try {
517
+ response = await fetchImpl(url);
518
+ }
519
+ catch (err) {
520
+ const message = err instanceof Error ? err.message : String(err);
521
+ throw new TransportError(`Failed to download presigned URL ${url}: ${message}`);
522
+ }
523
+ if (!response.ok) {
524
+ throw ApiError.fromEnvelope({
525
+ error: {
526
+ code: 'UNAVAILABLE',
527
+ message: `Failed to download presigned URL (HTTP ${response.status}).`,
528
+ nextAction: 'Re-run `testsprite test failure get`. Presigned URLs in the bundle expire after 15 minutes.',
529
+ requestId: 'local',
530
+ details: { status: response.status, url },
531
+ },
532
+ });
533
+ }
534
+ if (!response.body) {
535
+ // Some test runtimes / fetch polyfills don't expose `body` as a
536
+ // ReadableStream. Fall back to a buffered write — same correctness,
537
+ // just no streaming benefit. The bundle is bounded by the
538
+ // backend's 15-min TTL, so even a multi-MB video buffers fully in
539
+ // a tolerable amount of memory.
540
+ const buffer = Buffer.from(await response.arrayBuffer());
541
+ await writeFile(filePath, buffer);
542
+ return;
543
+ }
544
+ await mkdir(dirname(filePath), { recursive: true });
545
+ // `response.body` is a Web ReadableStream. Node's `pipeline` accepts
546
+ // it via `Readable.fromWeb` (Node ≥ 18). Wrap in a try so any error
547
+ // from the stream propagates as a TransportError, preserving the
548
+ // exit-code contract.
549
+ const fileSink = createWriteStream(filePath);
550
+ try {
551
+ const webBody = response.body;
552
+ const { Readable } = await import('node:stream');
553
+ const nodeStream = Readable.fromWeb(webBody);
554
+ await pipeline(nodeStream, fileSink);
555
+ }
556
+ catch (err) {
557
+ const message = err instanceof Error ? err.message : String(err);
558
+ throw new TransportError(`Failed mid-download of ${url}: ${message}`);
559
+ }
560
+ }
561
+ function isPresignedUrl(value) {
562
+ return value.startsWith('https://');
563
+ }
564
+ /**
565
+ * Write `<dir>/.partial` so an agent inspecting the dir can detect
566
+ * an aborted bundle. The marker is small JSON — the contract is "if
567
+ * `.partial` exists, do not consume `<dir>` until the CLI is re-run
568
+ * and `.partial` disappears."
569
+ *
570
+ * We DO NOT clean the `.tmp/` contents on partial — leaving them on
571
+ * disk is intentional for forensics. The next successful `writeBundle`
572
+ * call clears them.
573
+ */
574
+ async function writePartialMarker(dir, err, requestId, snapshotId) {
575
+ await mkdir(dir, { recursive: true });
576
+ const body = {
577
+ schemaVersion: BUNDLE_SCHEMA_VERSION,
578
+ snapshotId,
579
+ requestId,
580
+ error: err instanceof Error ? err.message : String(err),
581
+ createdAt: new Date().toISOString(),
582
+ };
583
+ await writeFile(join(dir, '.partial'), JSON.stringify(body, null, 2) + '\n', 'utf8');
584
+ }
585
+ function bundleIntegrityError(reason, message, requestId, ids) {
586
+ return ApiError.fromEnvelope({
587
+ error: {
588
+ code: 'VALIDATION_ERROR',
589
+ message,
590
+ nextAction: 'Re-run `testsprite test failure get`. The backend may have been mid-snapshot — a fresh fetch usually succeeds. Report the requestId to support if it persists.',
591
+ requestId,
592
+ details: { reason, ...(ids ?? {}) },
593
+ },
594
+ });
595
+ }
596
+ // Avoid unused-import lint warning for the `mkdtemp` and `readdir`
597
+ // helpers reserved for forensics + future resume work.
598
+ void mkdtemp;
599
+ void readdir;
600
+ //# sourceMappingURL=bundle.js.map
@@ -0,0 +1,72 @@
1
+ import type { FetchImpl } from './http.js';
2
+ import { HttpClient } from './http.js';
3
+ import type { OutputMode } from './output.js';
4
+ export interface CommonOptions {
5
+ profile: string;
6
+ output: OutputMode;
7
+ endpointUrl?: string;
8
+ debug: boolean;
9
+ /**
10
+ * When true: emit human-readable transition messages (HTTP retry, rate-limit,
11
+ * polling-mode switch) to stderr without the full debug JSON firehose.
12
+ * Sits between the default (silent retries) and `--debug` (full trace).
13
+ */
14
+ verbose?: boolean;
15
+ /**
16
+ * When true: skip credential read, skip the network, return canned
17
+ * samples per `src/lib/dry-run/samples.ts`. The CLI binary still
18
+ * runs all argument validation, output formatting, and exit-code
19
+ * mapping, so dry-run output is byte-identical to a real success
20
+ * response (modulo the data values being canned).
21
+ *
22
+ * Optional so legacy call sites (P1–P5 tests) don't need to pass
23
+ * `false` everywhere — undefined is treated as `false`.
24
+ */
25
+ dryRun?: boolean;
26
+ /**
27
+ * Per-request wall-clock timeout in milliseconds. Applied to every
28
+ * outgoing fetch call. Defaults to {@link REQUEST_TIMEOUT_DEFAULT_MS}
29
+ * (120 000 ms). Set via `--request-timeout <s>` flag (seconds) or
30
+ * `TESTSPRITE_REQUEST_TIMEOUT_MS` env var (milliseconds).
31
+ *
32
+ * Precedence: `--request-timeout` flag > `TESTSPRITE_REQUEST_TIMEOUT_MS`
33
+ * env var > default (120s).
34
+ *
35
+ * Clamped to [{@link REQUEST_TIMEOUT_MIN_MS}, {@link REQUEST_TIMEOUT_MAX_MS}].
36
+ */
37
+ requestTimeoutMs?: number;
38
+ }
39
+ export interface ClientFactoryDeps {
40
+ env?: NodeJS.ProcessEnv;
41
+ credentialsPath?: string;
42
+ fetchImpl?: FetchImpl;
43
+ stderr?: (line: string) => void;
44
+ }
45
+ /**
46
+ * The fake API key used in dry-run. Never sent — the dry-run fetch
47
+ * impl ignores headers and returns a canned sample. Documented in the
48
+ * runbook so secret-scanners don't flag it as a leak.
49
+ */
50
+ export declare const DRY_RUN_API_KEY = "sk-user-DRY-RUN";
51
+ /** Stable banner text. Snapshot tests assert on this string. */
52
+ export declare const DRY_RUN_BANNER = "[dry-run] sample response \u2014 not from the server";
53
+ export declare function emitDryRunBanner(stderr: (line: string) => void): void;
54
+ export declare function resetDryRunBannerForTesting(): void;
55
+ /**
56
+ * Resolve per-request timeout in milliseconds.
57
+ *
58
+ * Precedence: `--request-timeout` flag (already converted to ms by the caller)
59
+ * > `TESTSPRITE_REQUEST_TIMEOUT_MS` env var > default (120s).
60
+ *
61
+ * The flag is supplied in seconds (consistent with `--timeout`); the caller
62
+ * multiplies by 1000 before storing in `opts.requestTimeoutMs`. The env var
63
+ * is in milliseconds to give scripts sub-second granularity and match the
64
+ * typical convention for `*_MS` env vars.
65
+ *
66
+ * Values are clamped to [REQUEST_TIMEOUT_MIN_MS, REQUEST_TIMEOUT_MAX_MS];
67
+ * values below the minimum are raised to 1s, values above the maximum are
68
+ * lowered to 10m — both silently (no exit 5), since this is a tuning knob,
69
+ * not a safety-critical gate.
70
+ */
71
+ export declare function resolveRequestTimeoutMs(opts: Pick<CommonOptions, 'requestTimeoutMs'>, env: NodeJS.ProcessEnv): number;
72
+ export declare function makeHttpClient(opts: CommonOptions, deps?: ClientFactoryDeps): HttpClient;