@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.
- package/README.md +52 -147
- package/dist/commands/agent.d.ts +12 -4
- package/dist/commands/agent.js +48 -63
- package/dist/commands/auth.d.ts +6 -10
- package/dist/commands/auth.js +40 -56
- package/dist/commands/ci.d.ts +23 -100
- package/dist/commands/ci.js +293 -487
- package/dist/commands/conversation.d.ts +27 -0
- package/dist/commands/conversation.js +741 -0
- package/dist/commands/doctor.d.ts +5 -1
- package/dist/commands/doctor.js +129 -34
- package/dist/commands/init.d.ts +4 -45
- package/dist/commands/init.js +108 -66
- package/dist/commands/project-env.d.ts +62 -2
- package/dist/commands/project-env.js +434 -43
- package/dist/commands/project-sign-in.d.ts +0 -48
- package/dist/commands/project-sign-in.js +1 -229
- package/dist/commands/project.d.ts +19 -186
- package/dist/commands/project.js +108 -926
- package/dist/commands/result.d.ts +10 -0
- package/dist/commands/result.js +216 -0
- package/dist/commands/schedule.d.ts +0 -29
- package/dist/commands/schedule.js +28 -87
- package/dist/commands/test.d.ts +301 -1838
- package/dist/commands/test.js +1880 -13917
- package/dist/commands/testlist.d.ts +130 -5
- package/dist/commands/testlist.js +300 -342
- package/dist/commands/tunnel.d.ts +3 -3
- package/dist/commands/tunnel.js +23 -20
- package/dist/commands/usage.d.ts +12 -45
- package/dist/commands/usage.js +50 -131
- package/dist/index.js +191 -110
- package/dist/lib/agent-detect.js +9 -5
- package/dist/lib/agent-targets.d.ts +21 -2
- package/dist/lib/agent-targets.js +88 -11
- package/dist/lib/args.d.ts +13 -0
- package/dist/lib/args.js +49 -0
- package/dist/lib/basic-auth.d.ts +3 -0
- package/dist/lib/basic-auth.js +15 -0
- package/dist/lib/billing-refusal.js +4 -3
- package/dist/lib/ci-linkage.d.ts +4 -82
- package/dist/lib/ci-linkage.js +4 -157
- package/dist/lib/ci-run.js +1 -1
- package/dist/lib/client-factory.d.ts +12 -4
- package/dist/lib/client-factory.js +41 -30
- package/dist/lib/commit-signal.d.ts +65 -0
- package/dist/lib/commit-signal.js +305 -0
- package/dist/lib/concurrency-limiter.d.ts +6 -0
- package/dist/lib/concurrency-limiter.js +29 -0
- package/dist/lib/config.js +10 -5
- package/dist/lib/conflict-reason.d.ts +9 -3
- package/dist/lib/conflict-reason.js +6 -3
- package/dist/lib/conversation/answers.d.ts +9 -0
- package/dist/lib/conversation/answers.js +49 -0
- package/dist/lib/conversation/api.d.ts +75 -0
- package/dist/lib/conversation/api.js +151 -0
- package/dist/lib/conversation/change.d.ts +31 -0
- package/dist/lib/conversation/change.js +124 -0
- package/dist/lib/conversation/context.d.ts +29 -0
- package/dist/lib/conversation/context.js +82 -0
- package/dist/lib/conversation/environment.d.ts +16 -0
- package/dist/lib/conversation/environment.js +21 -0
- package/dist/lib/conversation/follow.d.ts +24 -0
- package/dist/lib/conversation/follow.js +42 -0
- package/dist/lib/conversation/render.d.ts +33 -0
- package/dist/lib/conversation/render.js +318 -0
- package/dist/lib/conversation/title.d.ts +2 -0
- package/dist/lib/conversation/title.js +18 -0
- package/dist/lib/conversation/types.d.ts +158 -0
- package/dist/lib/conversation/types.js +6 -0
- package/dist/lib/credentials.js +67 -11
- package/dist/lib/cron.d.ts +1 -1
- package/dist/lib/cron.js +2 -2
- package/dist/lib/dispatch-stop.d.ts +20 -0
- package/dist/lib/dispatch-stop.js +30 -0
- package/dist/lib/download.d.ts +100 -0
- package/dist/lib/download.js +408 -0
- package/dist/lib/dry-run/fetch.d.ts +10 -0
- package/dist/lib/dry-run/fetch.js +20 -0
- package/dist/lib/dry-run/samples.d.ts +6 -34
- package/dist/lib/dry-run/samples.js +375 -747
- package/dist/lib/environment-tunnel.d.ts +19 -30
- package/dist/lib/environment-tunnel.js +168 -202
- package/dist/lib/errors.d.ts +20 -4
- package/dist/lib/errors.js +36 -16
- package/dist/lib/facade.d.ts +7 -29
- package/dist/lib/facade.js +7 -36
- package/dist/lib/failing-fe-resolver.d.ts +13 -58
- package/dist/lib/failing-fe-resolver.js +47 -132
- package/dist/lib/first-suite-hint.d.ts +20 -30
- package/dist/lib/first-suite-hint.js +57 -72
- package/dist/lib/gh-output.d.ts +76 -21
- package/dist/lib/gh-output.js +171 -90
- package/dist/lib/git-utils.d.ts +56 -0
- package/dist/lib/git-utils.js +212 -0
- package/dist/lib/github-context.d.ts +2 -0
- package/dist/lib/github-context.js +40 -8
- package/dist/lib/history-retention.d.ts +6 -2
- package/dist/lib/history-retention.js +10 -7
- package/dist/lib/http.d.ts +58 -134
- package/dist/lib/http.js +354 -291
- package/dist/lib/interrupt.d.ts +14 -8
- package/dist/lib/interrupt.js +28 -10
- package/dist/lib/junit-report.d.ts +57 -4
- package/dist/lib/junit-report.js +202 -32
- package/dist/lib/local-target.d.ts +8 -7
- package/dist/lib/local-target.js +14 -13
- package/dist/lib/output.d.ts +2 -41
- package/dist/lib/output.js +13 -51
- package/dist/lib/pagination.d.ts +2 -5
- package/dist/lib/pagination.js +2 -5
- package/dist/lib/presigned-url.d.ts +22 -0
- package/dist/lib/presigned-url.js +90 -0
- package/dist/lib/prompt.js +36 -2
- package/dist/lib/proxy.js +2 -1
- package/dist/lib/redact.d.ts +2 -2
- package/dist/lib/redact.js +3 -4
- package/dist/lib/removed-commands.d.ts +18 -0
- package/dist/lib/removed-commands.js +170 -0
- package/dist/lib/render-error.d.ts +31 -6
- package/dist/lib/render-error.js +88 -25
- package/dist/lib/response-schemas.d.ts +38 -30
- package/dist/lib/response-schemas.js +207 -207
- package/dist/lib/result/api.d.ts +24 -0
- package/dist/lib/result/api.js +28 -0
- package/dist/lib/result/evidence.d.ts +73 -0
- package/dist/lib/result/evidence.js +422 -0
- package/dist/lib/result/render.d.ts +20 -0
- package/dist/lib/result/render.js +194 -0
- package/dist/lib/result/types.d.ts +122 -0
- package/dist/lib/result/types.js +19 -0
- package/dist/lib/run-output.d.ts +275 -0
- package/dist/lib/run-output.js +227 -0
- package/dist/lib/run-render.d.ts +101 -0
- package/dist/lib/run-render.js +183 -0
- package/dist/lib/run-wait.d.ts +192 -0
- package/dist/lib/run-wait.js +452 -0
- package/dist/lib/runs.types.d.ts +118 -367
- package/dist/lib/runs.types.js +0 -14
- package/dist/lib/secret-file.d.ts +1 -1
- package/dist/lib/secret-file.js +11 -2
- package/dist/lib/skill-nudge.d.ts +7 -27
- package/dist/lib/skill-nudge.js +9 -37
- package/dist/lib/target-path.d.ts +15 -0
- package/dist/lib/target-path.js +35 -0
- package/dist/lib/target-url-advisory.d.ts +19 -0
- package/dist/lib/target-url-advisory.js +31 -0
- package/dist/lib/target-url-preflight.d.ts +9 -0
- package/dist/lib/target-url-preflight.js +214 -106
- package/dist/lib/target-url.d.ts +8 -8
- package/dist/lib/target-url.js +14 -24
- package/dist/lib/telemetry.d.ts +35 -15
- package/dist/lib/telemetry.js +38 -9
- package/dist/lib/terminal-text.d.ts +41 -0
- package/dist/lib/terminal-text.js +127 -0
- package/dist/lib/testlist.types.d.ts +16 -8
- package/dist/lib/testlist.types.js +1 -1
- package/dist/lib/text-equality.d.ts +2 -0
- package/dist/lib/text-equality.js +5 -0
- package/dist/lib/text-file.d.ts +16 -0
- package/dist/lib/text-file.js +41 -0
- package/dist/lib/text-table.d.ts +46 -0
- package/dist/lib/text-table.js +72 -4
- package/dist/lib/ticker.d.ts +9 -2
- package/dist/lib/ticker.js +16 -3
- package/dist/lib/transport-failure.d.ts +22 -0
- package/dist/lib/transport-failure.js +126 -0
- package/dist/lib/tunnel-session.d.ts +8 -2
- package/dist/lib/tunnel-session.js +24 -11
- package/dist/lib/update-check.js +3 -2
- package/dist/lib/url-template.d.ts +43 -0
- package/dist/lib/url-template.js +151 -0
- package/dist/lib/validate.d.ts +0 -64
- package/dist/lib/validate.js +2 -131
- package/dist/lib/version-notice.js +4 -3
- package/dist/lib/wait-exit.d.ts +37 -2
- package/dist/lib/wait-exit.js +88 -30
- package/dist/lib/workspace-status.js +10 -2
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +2 -3
- package/skills/testsprite-ci.skill.md +52 -23
- package/skills/testsprite-onboard.skill.md +70 -153
- package/skills/testsprite-verify.codex.md +54 -58
- package/skills/testsprite-verify.skill.md +189 -358
- package/dist/lib/browser.d.ts +0 -6
- package/dist/lib/browser.js +0 -54
- package/dist/lib/bundle.d.ts +0 -234
- package/dist/lib/bundle.js +0 -781
- package/dist/lib/deprecate.d.ts +0 -32
- package/dist/lib/deprecate.js +0 -39
- package/dist/lib/flaky.d.ts +0 -91
- package/dist/lib/flaky.js +0 -71
- package/dist/lib/plan-poll.d.ts +0 -171
- package/dist/lib/plan-poll.js +0 -441
- package/dist/lib/plans.types.d.ts +0 -130
- package/dist/lib/plans.types.js +0 -31
- package/dist/lib/poll.d.ts +0 -100
- package/dist/lib/poll.js +0 -290
- package/dist/lib/rate-throttle.d.ts +0 -49
- package/dist/lib/rate-throttle.js +0 -75
- package/dist/lib/run-progress.d.ts +0 -41
- package/dist/lib/run-progress.js +0 -56
- package/dist/lib/v3-advisory.d.ts +0 -55
- package/dist/lib/v3-advisory.js +0 -74
- package/schemas/plan.schema.json +0 -61
package/dist/lib/bundle.js
DELETED
|
@@ -1,781 +0,0 @@
|
|
|
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 { randomUUID } from 'node:crypto';
|
|
36
|
-
import { mkdir, mkdtemp, readdir, rename, rm, stat, unlink, writeFile } from 'node:fs/promises';
|
|
37
|
-
import { pipeline } from 'node:stream/promises';
|
|
38
|
-
import { createWriteStream } from 'node:fs';
|
|
39
|
-
import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
|
40
|
-
import { ApiError, InterruptError, TransportError, localValidationError } from './errors.js';
|
|
41
|
-
import { globalShutdown } from './interrupt.js';
|
|
42
|
-
import { defaultSleep, sleepUnlessInterrupted } from './poll-support.js';
|
|
43
|
-
import { requireEnum } from './validate.js';
|
|
44
|
-
/** Schema version stamped into `meta.json`. Bumps with the contract. */
|
|
45
|
-
export const BUNDLE_SCHEMA_VERSION = 'cli-v1';
|
|
46
|
-
/** Max fetch attempts for each presigned URL (initial + retries). */
|
|
47
|
-
export const STREAM_URL_MAX_RETRIES = 3;
|
|
48
|
-
/** Delay between retries for transient transport failures (ms). */
|
|
49
|
-
export const STREAM_URL_RETRY_DELAY_MS = 1000;
|
|
50
|
-
/** Default radius around the failed step when `--failed-only` is set. */
|
|
51
|
-
export const FAILED_ONLY_RADIUS = 1;
|
|
52
|
-
/**
|
|
53
|
-
* Compose the FailureContext spec §3 invariants into a single
|
|
54
|
-
* trip wire. Throwing here is the agent-safety gate — we trust the
|
|
55
|
-
* facade for the data, not for self-consistency.
|
|
56
|
-
*
|
|
57
|
-
* - Bundle-level `snapshotId` MUST equal `result.snapshotId`.
|
|
58
|
-
* - All steps in the bundle MUST share `runIdIfAvailable` (or all
|
|
59
|
-
* be `null`). Mixed values means a stitched read leaked through.
|
|
60
|
-
*
|
|
61
|
-
* The error envelope is `VALIDATION_ERROR` rather than `INTERNAL`
|
|
62
|
-
* because the operator-facing remediation is "retry once" (the
|
|
63
|
-
* snapshot may genuinely have been mid-mutation; a fresh fetch will
|
|
64
|
-
* succeed). `requestId` is the original request id so support can
|
|
65
|
-
* trace the bad envelope back.
|
|
66
|
-
*/
|
|
67
|
-
export function assertContextIntegrity(ctx, requestId, opts) {
|
|
68
|
-
if (opts?.requireRunId && !ctx.result.runIdIfAvailable) {
|
|
69
|
-
throw bundleIntegrityError('run_id_missing', 'meta.runId (result.runIdIfAvailable) is required for run-scoped bundles but is null or missing', requestId);
|
|
70
|
-
}
|
|
71
|
-
if (ctx.snapshotId !== ctx.result.snapshotId) {
|
|
72
|
-
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 });
|
|
73
|
-
}
|
|
74
|
-
// Per codex round-1 P2: every embedded testId must equal ctx.testId.
|
|
75
|
-
// §6.X duplicates `testId` in `result`, `code`, and each step so a
|
|
76
|
-
// bundle stitched together from rows of two different tests is
|
|
77
|
-
// detectable without external state. Without this gate, an agent
|
|
78
|
-
// could open `meta.json` for `test_A`, edit the file the bundle
|
|
79
|
-
// claims is its code, and have the edit actually target `test_B`'s
|
|
80
|
-
// source — exactly the cross-test contamination the failure bundle
|
|
81
|
-
// exists to prevent.
|
|
82
|
-
if (ctx.result.testId !== ctx.testId) {
|
|
83
|
-
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 });
|
|
84
|
-
}
|
|
85
|
-
if (ctx.code.testId !== ctx.testId) {
|
|
86
|
-
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 });
|
|
87
|
-
}
|
|
88
|
-
for (const step of ctx.steps) {
|
|
89
|
-
if (step.testId !== ctx.testId) {
|
|
90
|
-
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 });
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
// §6.7: code is "version pinned to result.codeVersion." If both
|
|
94
|
-
// sides are non-null and disagree, the bundle stitched code from
|
|
95
|
-
// one version with a result from another — exactly the drift case
|
|
96
|
-
// the failure bundle exists to prevent. Both-null is fine (the M2
|
|
97
|
-
// backend hasn't shipped versioning yet); only mismatched pairs
|
|
98
|
-
// are corrupt.
|
|
99
|
-
if (ctx.result.codeVersion !== null &&
|
|
100
|
-
ctx.code.codeVersion !== null &&
|
|
101
|
-
ctx.result.codeVersion !== ctx.code.codeVersion) {
|
|
102
|
-
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 });
|
|
103
|
-
}
|
|
104
|
-
// Only DISTINCT NON-NULL runIds indicate cross-run stitching. A `null`
|
|
105
|
-
// `runIdIfAvailable` just means that step row predates runId stamping —
|
|
106
|
-
// FE Portal step rows accumulate across runs and older rows were never
|
|
107
|
-
// stamped, so a multi-run test legitimately carries a mix of one real
|
|
108
|
-
// runId and several nulls. Counting null as a distinct value made
|
|
109
|
-
// `test failure get <test-id>` permanently fail on any test that ran
|
|
110
|
-
// more than once across the M3.1 cutover, and the "re-fetch usually
|
|
111
|
-
// succeeds" hint was wrong because the null is durable, not transient
|
|
112
|
-
// (dogfood 2026-06-04). Tolerate null; flag only when ≥2 *real* runIds
|
|
113
|
-
// are present (genuine cross-run stitching). The run-scoped path below
|
|
114
|
-
// (`requireRunId`) keeps the stricter per-step equality check.
|
|
115
|
-
const nonNullRunIds = new Set();
|
|
116
|
-
for (const step of ctx.steps) {
|
|
117
|
-
if (step.runIdIfAvailable != null)
|
|
118
|
-
nonNullRunIds.add(step.runIdIfAvailable);
|
|
119
|
-
}
|
|
120
|
-
if (nonNullRunIds.size > 1) {
|
|
121
|
-
const runIdList = [...nonNullRunIds];
|
|
122
|
-
throw bundleIntegrityError('run_id_mismatch', `Bundle integrity check failed: steps carry mixed runIds [${runIdList.join(', ')}]`, requestId, { observedRunIds: runIdList });
|
|
123
|
-
}
|
|
124
|
-
// Run-scoped path: additionally assert that every step's runIdIfAvailable
|
|
125
|
-
// matches result.runIdIfAvailable. The check above only catches steps
|
|
126
|
-
// that disagree with *each other*; a backend stitching all steps from
|
|
127
|
-
// "run_other" into a result for "run_abc" would pass the set-size check
|
|
128
|
-
// (all steps agree) but fail here.
|
|
129
|
-
//
|
|
130
|
-
// Also assert per-step codeVersion matches result.codeVersion when both
|
|
131
|
-
// are present — a mixed version bundle could point an agent at the wrong
|
|
132
|
-
// fix target.
|
|
133
|
-
if (opts?.requireRunId) {
|
|
134
|
-
const expectedRunId = ctx.result.runIdIfAvailable; // guarded by run_id_missing check above
|
|
135
|
-
const resultCodeVersion = ctx.result.codeVersion;
|
|
136
|
-
for (const step of ctx.steps) {
|
|
137
|
-
if (step.runIdIfAvailable !== expectedRunId) {
|
|
138
|
-
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 });
|
|
139
|
-
}
|
|
140
|
-
if (resultCodeVersion !== null &&
|
|
141
|
-
step.codeVersion !== null &&
|
|
142
|
-
step.codeVersion !== resultCodeVersion) {
|
|
143
|
-
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 });
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
if (ctx.failure.evidence.length > 0 && ctx.result.failedStepIndex !== null) {
|
|
148
|
-
const hasFailedStep = ctx.failure.evidence.some(e => e.stepIndex === ctx.result.failedStepIndex);
|
|
149
|
-
if (!hasFailedStep) {
|
|
150
|
-
// §6.2: when evidence[] is non-empty, at least one entry must
|
|
151
|
-
// attach to the failed step so an agent can route on it.
|
|
152
|
-
throw bundleIntegrityError('evidence_missing_failed_step', `bundle evidence does not include failedStepIndex=${ctx.result.failedStepIndex}`, requestId);
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
/**
|
|
157
|
-
* Apply the `--failed-only` filter — drop neighbor steps and their
|
|
158
|
-
* evidence, keep the failed step. Idempotent: returns `ctx` unchanged
|
|
159
|
-
* when `failedStepIndex` is null (no step-level diagnosis to filter)
|
|
160
|
-
* or when the existing window already matches.
|
|
161
|
-
*/
|
|
162
|
-
export function applyFailedOnly(ctx) {
|
|
163
|
-
const failedIdx = ctx.result.failedStepIndex;
|
|
164
|
-
if (failedIdx === null)
|
|
165
|
-
return ctx;
|
|
166
|
-
const inWindow = (idx) => Math.abs(idx - failedIdx) <= FAILED_ONLY_RADIUS;
|
|
167
|
-
const filteredSteps = ctx.steps.filter(s => inWindow(s.stepIndex));
|
|
168
|
-
const filteredEvidence = ctx.failure.evidence.filter(e => inWindow(e.stepIndex));
|
|
169
|
-
return {
|
|
170
|
-
...ctx,
|
|
171
|
-
steps: filteredSteps,
|
|
172
|
-
failure: { ...ctx.failure, evidence: filteredEvidence },
|
|
173
|
-
};
|
|
174
|
-
}
|
|
175
|
-
/**
|
|
176
|
-
* Strip trailing path separators, tolerating both `/` and `\` since a
|
|
177
|
-
* native Windows `--out` value (typed or pasted from Explorer) commonly
|
|
178
|
-
* ends in a backslash. Preserves a bare drive root (`C:\`) — stripping
|
|
179
|
-
* its separator would turn it into `C:`, which Windows resolves as
|
|
180
|
-
* "current directory on drive C", not the drive root.
|
|
181
|
-
*/
|
|
182
|
-
function stripTrailingSeparators(rawPath) {
|
|
183
|
-
if (rawPath.length <= 1)
|
|
184
|
-
return rawPath;
|
|
185
|
-
let end = rawPath.length;
|
|
186
|
-
while (end > 1 && (rawPath[end - 1] === '/' || rawPath[end - 1] === '\\')) {
|
|
187
|
-
if (end === 3 && rawPath[1] === ':' && /[A-Za-z]/.test(rawPath[0]))
|
|
188
|
-
break;
|
|
189
|
-
end--;
|
|
190
|
-
}
|
|
191
|
-
return rawPath.slice(0, end);
|
|
192
|
-
}
|
|
193
|
-
/**
|
|
194
|
-
* Resolve the user-supplied `--out` path into an absolute directory.
|
|
195
|
-
* Empty strings are rejected with `VALIDATION_ERROR` for consistency
|
|
196
|
-
* with `test code get --out`. We do NOT pre-create the directory or
|
|
197
|
-
* its `.tmp` child — `writeBundle` mkdir's after the integrity check
|
|
198
|
-
* passes so a forged response never modifies the operator's filesystem.
|
|
199
|
-
*/
|
|
200
|
-
export function resolveBundleDir(rawPath) {
|
|
201
|
-
if (typeof rawPath !== 'string' || rawPath.length === 0) {
|
|
202
|
-
throw ApiError.fromEnvelope({
|
|
203
|
-
error: {
|
|
204
|
-
code: 'VALIDATION_ERROR',
|
|
205
|
-
message: 'Invalid request.',
|
|
206
|
-
nextAction: 'Flag `--out` is invalid: must be a non-empty directory path.',
|
|
207
|
-
requestId: 'local',
|
|
208
|
-
details: { field: 'out', reason: 'must be a non-empty directory path' },
|
|
209
|
-
},
|
|
210
|
-
});
|
|
211
|
-
}
|
|
212
|
-
const trimmed = stripTrailingSeparators(rawPath);
|
|
213
|
-
return isAbsolute(trimmed) ? trimmed : resolve(process.cwd(), trimmed);
|
|
214
|
-
}
|
|
215
|
-
/**
|
|
216
|
-
* Pick a code-file extension for `<dir>/code.<ext>` based on the §6.3
|
|
217
|
-
* `language` + `framework`. The extension matches the test code's
|
|
218
|
-
* language, not the user-app code under test.
|
|
219
|
-
*/
|
|
220
|
-
export function pickCodeExtension(language, framework) {
|
|
221
|
-
if (language === 'python')
|
|
222
|
-
return 'py';
|
|
223
|
-
if (language === 'javascript')
|
|
224
|
-
return 'js';
|
|
225
|
-
if (language === 'typescript')
|
|
226
|
-
return 'ts';
|
|
227
|
-
// Fallback when the server didn't stamp a language: both TestSprite
|
|
228
|
-
// frameworks are Python — backend `pytest` and frontend Playwright
|
|
229
|
-
// (`playwright.async_api`) — so default to `.py`. (Legacy TS/JS rows
|
|
230
|
-
// carry an explicit `language` above and are honored as `.ts`/`.js`.)
|
|
231
|
-
if (framework === 'pytest')
|
|
232
|
-
return 'py';
|
|
233
|
-
return 'py';
|
|
234
|
-
}
|
|
235
|
-
/** Recording container extensions the bundle writer will trust from `videoUrl`. */
|
|
236
|
-
const KNOWN_VIDEO_EXTENSIONS = new Set(['mp4', 'webm', 'mov', 'mkv', 'avi']);
|
|
237
|
-
/**
|
|
238
|
-
* Pick the on-disk extension for `<dir>/video.<ext>` from the actual
|
|
239
|
-
* `result.videoUrl`, instead of hardcoding `mp4` (the
|
|
240
|
-
* recording is sometimes a `.webm` container; saving it under a `video.mp4`
|
|
241
|
-
* name misleads strict-extension consumers). Falls back to `mp4` when the
|
|
242
|
-
* URL is malformed or its extension isn't a recognized container, so a
|
|
243
|
-
* response-controlled field can never smuggle an arbitrary suffix onto disk.
|
|
244
|
-
*/
|
|
245
|
-
export function pickVideoExtension(url) {
|
|
246
|
-
try {
|
|
247
|
-
const match = /\.([A-Za-z0-9]+)$/.exec(new URL(url).pathname);
|
|
248
|
-
const ext = match?.[1]?.toLowerCase();
|
|
249
|
-
if (ext !== undefined && KNOWN_VIDEO_EXTENSIONS.has(ext))
|
|
250
|
-
return ext;
|
|
251
|
-
}
|
|
252
|
-
catch {
|
|
253
|
-
// Malformed URL — fall through to the default below.
|
|
254
|
-
}
|
|
255
|
-
return 'mp4';
|
|
256
|
-
}
|
|
257
|
-
/**
|
|
258
|
-
* Step filename per §7.2 — 1-based index, zero-padded to two digits
|
|
259
|
-
* for indices ≤ 99, three digits for ≥ 100. `${stepIndex}-snapshot.html`
|
|
260
|
-
* etc. Never truncates: an agent constructing the path with
|
|
261
|
-
* `padStart(2, '0')` works for the common case, and step ≥ 100 widens
|
|
262
|
-
* naturally without breaking existing fixtures.
|
|
263
|
-
*/
|
|
264
|
-
export function stepFilenamePrefix(stepIndex) {
|
|
265
|
-
return stepIndex >= 100 ? String(stepIndex).padStart(3, '0') : String(stepIndex).padStart(2, '0');
|
|
266
|
-
}
|
|
267
|
-
/**
|
|
268
|
-
* Refuse a composed artifact path that escapes `baseDir`. Step filenames are
|
|
269
|
-
* built from response-controlled fields, so this is the final containment
|
|
270
|
-
* check before any write. Returns the validated absolute path.
|
|
271
|
-
*/
|
|
272
|
-
export function assertNoEscape(baseDir, segment) {
|
|
273
|
-
const composed = resolve(baseDir, segment);
|
|
274
|
-
const rel = relative(baseDir, composed);
|
|
275
|
-
if (rel.startsWith('..') || isAbsolute(rel)) {
|
|
276
|
-
throw localValidationError('out', 'resolved artifact path escapes the bundle directory', undefined, 'field');
|
|
277
|
-
}
|
|
278
|
-
return composed;
|
|
279
|
-
}
|
|
280
|
-
/**
|
|
281
|
-
* Build the §7.1 meta.json given a context. Pure function, no I/O —
|
|
282
|
-
* lets specs assert the meta shape without touching disk.
|
|
283
|
-
*/
|
|
284
|
-
export function buildMeta(ctx, fetchedAt = new Date()) {
|
|
285
|
-
return {
|
|
286
|
-
schemaVersion: BUNDLE_SCHEMA_VERSION,
|
|
287
|
-
snapshotId: ctx.snapshotId,
|
|
288
|
-
testId: ctx.testId,
|
|
289
|
-
projectId: ctx.projectId,
|
|
290
|
-
codeVersion: ctx.code.codeVersion ?? ctx.result.codeVersion ?? null,
|
|
291
|
-
runIdIfAvailable: ctx.result.runIdIfAvailable,
|
|
292
|
-
targetUrl: ctx.result.targetUrl,
|
|
293
|
-
failedStepIndex: ctx.result.failedStepIndex,
|
|
294
|
-
failureKind: ctx.result.failureKind,
|
|
295
|
-
capturedAt: ctx.result.finishedAt,
|
|
296
|
-
fetchedAt: fetchedAt.toISOString(),
|
|
297
|
-
};
|
|
298
|
-
}
|
|
299
|
-
/**
|
|
300
|
-
* Top-level bundle writer. The order matters:
|
|
301
|
-
*
|
|
302
|
-
* 1. `assertContextIntegrity` — fail closed on a forged envelope.
|
|
303
|
-
* 2. `applyFailedOnly` — narrow before download (saves bytes).
|
|
304
|
-
* 3. `mkdir <dir>/.tmp/` — fresh; clean any stale temp.
|
|
305
|
-
* 4. `writeFile result.json / failure.json / code.<ext>` — local data.
|
|
306
|
-
* 5. `fetch + stream` for `video.<ext>` (when set; extension matches the
|
|
307
|
-
* actual recording container) and per-step snapshot/screenshot/
|
|
308
|
-
* evidence-json files.
|
|
309
|
-
* 6. `writeFile meta.json` LAST — its presence means "bundle complete".
|
|
310
|
-
* 7. `rename .tmp/<file> -> <file>` for every file. Last rename
|
|
311
|
-
* makes meta.json visible.
|
|
312
|
-
*
|
|
313
|
-
* On any failure between (3) and (6), write a `<dir>/.partial` marker
|
|
314
|
-
* and re-throw so `index.ts` produces a typed exit code (UNAVAILABLE
|
|
315
|
-
* → 10 by default; the original ApiError is preserved when applicable).
|
|
316
|
-
*/
|
|
317
|
-
export async function writeBundle(ctx, options) {
|
|
318
|
-
const requestId = options.requestId ?? 'local';
|
|
319
|
-
assertContextIntegrity(ctx, requestId);
|
|
320
|
-
const filtered = options.failedOnly ? applyFailedOnly(ctx) : ctx;
|
|
321
|
-
// Re-check after filtering — in theory a buggy filter could leave a
|
|
322
|
-
// mismatched evidence list. Cheap defense-in-depth.
|
|
323
|
-
assertContextIntegrity(filtered, requestId);
|
|
324
|
-
const dir = resolveBundleDir(options.dir);
|
|
325
|
-
const fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);
|
|
326
|
-
const downloadDeps = {
|
|
327
|
-
shutdownSignal: options.shutdownSignal,
|
|
328
|
-
shutdown: options.shutdown,
|
|
329
|
-
};
|
|
330
|
-
const meta = buildMeta(filtered);
|
|
331
|
-
const codeExt = pickCodeExtension(filtered.code.language, filtered.code.framework);
|
|
332
|
-
await mkdir(dir, { recursive: true });
|
|
333
|
-
// Fresh `.tmp/` each run. A previous SIGKILL'd run can leave bytes
|
|
334
|
-
// behind; we don't want to mix them with the new fetch.
|
|
335
|
-
const tmpDir = await freshTmpDir(dir);
|
|
336
|
-
const stepsTmpDir = join(tmpDir, 'steps');
|
|
337
|
-
await mkdir(stepsTmpDir, { recursive: true });
|
|
338
|
-
const filesWritten = [];
|
|
339
|
-
try {
|
|
340
|
-
// result.json + failure.json + code.<ext> are local writes; no
|
|
341
|
-
// network, no streaming.
|
|
342
|
-
await writeFile(join(tmpDir, 'result.json'), JSON.stringify(filtered.result, null, 2) + '\n', 'utf8');
|
|
343
|
-
filesWritten.push('result.json');
|
|
344
|
-
await writeFile(join(tmpDir, 'failure.json'), JSON.stringify(filtered.failure, null, 2) + '\n', 'utf8');
|
|
345
|
-
filesWritten.push('failure.json');
|
|
346
|
-
const codeFile = `code.${codeExt}`;
|
|
347
|
-
if (isPresignedUrl(filtered.code.code)) {
|
|
348
|
-
// §6.3 alt: when the `code` field is a presigned URL (>= 100 KB
|
|
349
|
-
// bodies), stream the URL into the file rather than embedding
|
|
350
|
-
// the URL in code.<ext>. M2's backend hasn't shipped the
|
|
351
|
-
// >=100KB branch yet, but the contract supports it.
|
|
352
|
-
await streamUrlToFile(filtered.code.code, join(tmpDir, codeFile), fetchImpl, downloadDeps);
|
|
353
|
-
}
|
|
354
|
-
else {
|
|
355
|
-
await writeFile(join(tmpDir, codeFile), filtered.code.code, 'utf8');
|
|
356
|
-
}
|
|
357
|
-
filesWritten.push(codeFile);
|
|
358
|
-
// Optional video. Wire field is `result.videoUrl` (not in `failure`),
|
|
359
|
-
// and the CLI surfaces it as a top-level on-disk artifact for agent
|
|
360
|
-
// ergonomics — the agent doesn't have to know which sub-object held
|
|
361
|
-
// it on the wire. Extension matches the actual recording container
|
|
362
|
-
// (some runs ship `.webm`, not `.mp4`).
|
|
363
|
-
if (filtered.result.videoUrl) {
|
|
364
|
-
const videoFile = `video.${pickVideoExtension(filtered.result.videoUrl)}`;
|
|
365
|
-
await streamUrlToFile(filtered.result.videoUrl, join(tmpDir, videoFile), fetchImpl, downloadDeps);
|
|
366
|
-
filesWritten.push(videoFile);
|
|
367
|
-
}
|
|
368
|
-
for (const step of filtered.steps) {
|
|
369
|
-
await writeStepArtifacts(step, filtered.failure.evidence, stepsTmpDir, fetchImpl, filesWritten, downloadDeps);
|
|
370
|
-
}
|
|
371
|
-
// meta.json LAST. Its presence is the sentinel that the bundle
|
|
372
|
-
// is complete. An agent that opens <dir> and finds meta.json can
|
|
373
|
-
// safely consume.
|
|
374
|
-
await writeFile(join(tmpDir, 'meta.json'), JSON.stringify(meta, null, 2) + '\n', 'utf8');
|
|
375
|
-
filesWritten.push('meta.json');
|
|
376
|
-
// Atomic rename: move every file from <dir>/.tmp/* into <dir>/*.
|
|
377
|
-
// Steps subdir gets renamed wholesale; meta.json renames last so
|
|
378
|
-
// its visibility implies "bundle is complete and atomic on disk."
|
|
379
|
-
await commitBundle(tmpDir, dir, filesWritten);
|
|
380
|
-
return { meta, dir, files: filesWritten };
|
|
381
|
-
}
|
|
382
|
-
catch (err) {
|
|
383
|
-
await writePartialMarker(dir, err, requestId, ctx.snapshotId).catch(() => undefined);
|
|
384
|
-
throw err;
|
|
385
|
-
}
|
|
386
|
-
}
|
|
387
|
-
/**
|
|
388
|
-
* Make a fresh `<dir>/.tmp/` directory, removing any pre-existing
|
|
389
|
-
* orphaned tmp from a prior aborted run. Using `mkdtemp` would dodge
|
|
390
|
-
* the rm step but would make the rename target unpredictable; this
|
|
391
|
-
* way the temp path is stable (`<dir>/.tmp`) so a SIGKILL between two
|
|
392
|
-
* runs doesn't leave a tree of `.tmp.<rand>` directories.
|
|
393
|
-
*/
|
|
394
|
-
async function freshTmpDir(dir) {
|
|
395
|
-
const tmpDir = join(dir, '.tmp');
|
|
396
|
-
await rm(tmpDir, { recursive: true, force: true });
|
|
397
|
-
await mkdir(tmpDir, { recursive: true });
|
|
398
|
-
return tmpDir;
|
|
399
|
-
}
|
|
400
|
-
/**
|
|
401
|
-
* Whether a top-level directory entry belongs to the bundle format —
|
|
402
|
-
* i.e. something a prior `writeBundle` could have produced and this
|
|
403
|
-
* commit is therefore allowed to clean up. `code.<ext>` and `video.<ext>`
|
|
404
|
-
* are matched by pattern (not the current run's extension) so a stale
|
|
405
|
-
* `code.py` or `video.webm` is still swept when the new bundle writes
|
|
406
|
-
* `code.ts` / `video.mp4` (or no video at all). Everything else in the
|
|
407
|
-
* directory is the user's and must never be deleted (`--out` can point at
|
|
408
|
-
* a pre-existing, populated directory).
|
|
409
|
-
*/
|
|
410
|
-
export function isBundleOwnedEntry(entry) {
|
|
411
|
-
if (entry === 'result.json' ||
|
|
412
|
-
entry === 'failure.json' ||
|
|
413
|
-
entry === 'meta.json' ||
|
|
414
|
-
entry === 'steps' ||
|
|
415
|
-
entry === '.tmp' ||
|
|
416
|
-
entry === '.partial') {
|
|
417
|
-
return true;
|
|
418
|
-
}
|
|
419
|
-
// Videos: only the extensions the bundle itself can write (see
|
|
420
|
-
// KNOWN_VIDEO_EXTENSIONS / pickVideoExtension). A broader `video.*`
|
|
421
|
-
// pattern would claim user files like `video.txt` sitting in a
|
|
422
|
-
// pre-existing `--out` directory and delete them in the sweep.
|
|
423
|
-
return (/^code\.[A-Za-z0-9]+$/.test(entry) ||
|
|
424
|
-
(entry.startsWith('video.') && KNOWN_VIDEO_EXTENSIONS.has(entry.slice('video.'.length))));
|
|
425
|
-
}
|
|
426
|
-
/**
|
|
427
|
-
* Atomically install the complete bundle staged in `tmpDir` into `dir`.
|
|
428
|
-
*
|
|
429
|
-
* Compatible with the #162 data-loss guard: only `isBundleOwnedEntry`
|
|
430
|
-
* names are moved aside or replaced — foreign files in `--out` survive.
|
|
431
|
-
*
|
|
432
|
-
* Re-commit safety: bundle-owned entries are renamed to a sibling
|
|
433
|
-
* aside directory before the new artifacts land. The prior `meta.json`
|
|
434
|
-
* is moved aside first (§3/§7.3 — no meta ⇒ refuse to consume) so a
|
|
435
|
-
* concurrent reader never sees meta pointing at steps already gone.
|
|
436
|
-
* The new `meta.json` is installed last. On failure, aside entries are
|
|
437
|
-
* restored so a failed re-commit never leaves the directory unusable.
|
|
438
|
-
*/
|
|
439
|
-
export async function commitBundle(tmpDir, dir, files) {
|
|
440
|
-
const parent = dirname(dir);
|
|
441
|
-
const base = basename(dir);
|
|
442
|
-
const asideDir = join(parent, `.${base}.aside.${randomUUID()}`);
|
|
443
|
-
const asideLog = [];
|
|
444
|
-
const asideIfPresent = async (entry) => {
|
|
445
|
-
const restorePath = join(dir, entry);
|
|
446
|
-
if (!(await pathExists(restorePath)))
|
|
447
|
-
return;
|
|
448
|
-
const asidePath = join(asideDir, entry);
|
|
449
|
-
await mkdir(dirname(asidePath), { recursive: true });
|
|
450
|
-
await rename(restorePath, asidePath);
|
|
451
|
-
asideLog.push({ asidePath, restorePath });
|
|
452
|
-
};
|
|
453
|
-
const rollback = async () => {
|
|
454
|
-
for (const { asidePath, restorePath } of [...asideLog].reverse()) {
|
|
455
|
-
await rm(restorePath, { recursive: true, force: true }).catch(() => undefined);
|
|
456
|
-
await rename(asidePath, restorePath).catch(() => undefined);
|
|
457
|
-
}
|
|
458
|
-
await rm(asideDir, { recursive: true, force: true }).catch(() => undefined);
|
|
459
|
-
};
|
|
460
|
-
try {
|
|
461
|
-
const topLevel = files.filter(f => !f.startsWith('steps/'));
|
|
462
|
-
const newTopLevelSet = new Set(topLevel);
|
|
463
|
-
newTopLevelSet.add('meta.json');
|
|
464
|
-
// meta.json first — its presence is the completion signal; do not
|
|
465
|
-
// move steps (or anything else) aside while a stale meta is still visible.
|
|
466
|
-
await asideIfPresent('meta.json');
|
|
467
|
-
const existing = await readdir(dir).catch(() => []);
|
|
468
|
-
for (const entry of existing) {
|
|
469
|
-
if (entry === '.tmp' || entry === 'meta.json')
|
|
470
|
-
continue;
|
|
471
|
-
if (!isBundleOwnedEntry(entry))
|
|
472
|
-
continue;
|
|
473
|
-
const isStale = entry !== 'steps' && entry !== '.partial' && !newTopLevelSet.has(entry);
|
|
474
|
-
const willReplace = entry === 'steps' || newTopLevelSet.has(entry);
|
|
475
|
-
if (isStale || willReplace) {
|
|
476
|
-
await asideIfPresent(entry);
|
|
477
|
-
}
|
|
478
|
-
}
|
|
479
|
-
const stepsTmp = join(tmpDir, 'steps');
|
|
480
|
-
const stepsDir = join(dir, 'steps');
|
|
481
|
-
if (await dirExists(stepsTmp)) {
|
|
482
|
-
await rename(stepsTmp, stepsDir);
|
|
483
|
-
}
|
|
484
|
-
const metaIdx = topLevel.indexOf('meta.json');
|
|
485
|
-
const beforeMeta = metaIdx >= 0 ? topLevel.filter((_, i) => i !== metaIdx) : topLevel;
|
|
486
|
-
for (const file of beforeMeta) {
|
|
487
|
-
await rename(join(tmpDir, file), join(dir, file));
|
|
488
|
-
}
|
|
489
|
-
if (metaIdx >= 0) {
|
|
490
|
-
await rename(join(tmpDir, 'meta.json'), join(dir, 'meta.json'));
|
|
491
|
-
}
|
|
492
|
-
await unlink(join(dir, '.partial')).catch(() => undefined);
|
|
493
|
-
await rm(tmpDir, { recursive: true, force: true });
|
|
494
|
-
// Best-effort aside cleanup — failures must not roll back a committed bundle.
|
|
495
|
-
await rm(asideDir, { recursive: true, force: true }).catch(() => undefined);
|
|
496
|
-
}
|
|
497
|
-
catch (err) {
|
|
498
|
-
await rollback();
|
|
499
|
-
await rm(tmpDir, { recursive: true, force: true }).catch(() => undefined);
|
|
500
|
-
throw err;
|
|
501
|
-
}
|
|
502
|
-
}
|
|
503
|
-
async function pathExists(path) {
|
|
504
|
-
try {
|
|
505
|
-
await stat(path);
|
|
506
|
-
return true;
|
|
507
|
-
}
|
|
508
|
-
catch {
|
|
509
|
-
return false;
|
|
510
|
-
}
|
|
511
|
-
}
|
|
512
|
-
async function dirExists(path) {
|
|
513
|
-
try {
|
|
514
|
-
const s = await stat(path);
|
|
515
|
-
return s.isDirectory();
|
|
516
|
-
}
|
|
517
|
-
catch {
|
|
518
|
-
return false;
|
|
519
|
-
}
|
|
520
|
-
}
|
|
521
|
-
/**
|
|
522
|
-
* Write per-step artifacts under `<tmp>/steps/`. Each step gets up to
|
|
523
|
-
* three files: `<NN>-screenshot.png` (when a screenshot URL exists —
|
|
524
|
-
* M2 backend never sets one yet), `<NN>-snapshot.html` (when
|
|
525
|
-
* `htmlSnapshotUrl` exists), and `<NN>-evidence.json` (a small JSON
|
|
526
|
-
* file containing the non-snapshot evidence summaries — log/network/
|
|
527
|
-
* console — for that step). The evidence-json file is omitted when
|
|
528
|
-
* there's nothing to put in it; it's NOT a placeholder.
|
|
529
|
-
*/
|
|
530
|
-
async function writeStepArtifacts(step, allEvidence, stepsTmpDir, fetchImpl, filesWritten, downloadDeps) {
|
|
531
|
-
// stepIndex comes straight from the response and is used to build the
|
|
532
|
-
// filename — reject anything that isn't a real index before composing a path.
|
|
533
|
-
if (!Number.isInteger(step.stepIndex) || step.stepIndex < 0) {
|
|
534
|
-
throw localValidationError('stepIndex', 'must be a non-negative integer', undefined, 'field');
|
|
535
|
-
}
|
|
536
|
-
const prefix = stepFilenamePrefix(step.stepIndex);
|
|
537
|
-
if (step.screenshotUrl) {
|
|
538
|
-
const file = `${prefix}-screenshot.png`;
|
|
539
|
-
await streamUrlToFile(step.screenshotUrl, assertNoEscape(stepsTmpDir, file), fetchImpl, downloadDeps);
|
|
540
|
-
filesWritten.push(`steps/${file}`);
|
|
541
|
-
}
|
|
542
|
-
if (step.htmlSnapshotUrl) {
|
|
543
|
-
const file = `${prefix}-snapshot.html`;
|
|
544
|
-
await streamUrlToFile(step.htmlSnapshotUrl, assertNoEscape(stepsTmpDir, file), fetchImpl, downloadDeps);
|
|
545
|
-
filesWritten.push(`steps/${file}`);
|
|
546
|
-
}
|
|
547
|
-
// Evidence sidecar artifacts. Per codex round-1 P2: the bundle must
|
|
548
|
-
// be self-contained — every `evidence[].url` in the failure response
|
|
549
|
-
// resolves to a local file by the time `meta.json` is written. The
|
|
550
|
-
// earlier filter dropped screenshot/snapshot kinds on the assumption
|
|
551
|
-
// they were always duplicates of `step.screenshotUrl` /
|
|
552
|
-
// `step.htmlSnapshotUrl`, but if the evidence carries a different URL
|
|
553
|
-
// (different snapshot variant, a per-evidence sidecar shot, etc.) the
|
|
554
|
-
// bundle silently lost it and `failure.json` still referenced an
|
|
555
|
-
// expiring presigned link. Rule now: include every evidence entry;
|
|
556
|
-
// remap to the existing step file when URLs match, download a fresh
|
|
557
|
-
// sidecar otherwise.
|
|
558
|
-
//
|
|
559
|
-
// Critical: leaving any URL inside `<NN>-evidence.json` means the
|
|
560
|
-
// bundle claims completeness but actually points at presigned URLs
|
|
561
|
-
// that expire after 15 min — an agent opening the bundle one hour
|
|
562
|
-
// later would see metadata referencing dead links. Streaming the
|
|
563
|
-
// bytes here makes the bundle self-contained.
|
|
564
|
-
const sidecar = allEvidence.filter(e => e.stepIndex === step.stepIndex);
|
|
565
|
-
if (sidecar.length > 0) {
|
|
566
|
-
const dereferenced = await Promise.all(sidecar.map(async (entry, i) => {
|
|
567
|
-
// kind comes from the response and is used in the filename — validate it.
|
|
568
|
-
requireEnum('kind', entry.kind, ['screenshot', 'snapshot', 'log', 'network', 'console']);
|
|
569
|
-
// Reuse the already-downloaded step file when the evidence URL
|
|
570
|
-
// matches the step's primary screenshot/snapshot URL. Cheap
|
|
571
|
-
// dedupe — no extra HTTP round-trip, no duplicate bytes on disk.
|
|
572
|
-
if (entry.kind === 'screenshot' && step.screenshotUrl && step.screenshotUrl === entry.url) {
|
|
573
|
-
return {
|
|
574
|
-
kind: entry.kind,
|
|
575
|
-
stepIndex: entry.stepIndex,
|
|
576
|
-
summary: entry.summary,
|
|
577
|
-
path: `steps/${prefix}-screenshot.png`,
|
|
578
|
-
};
|
|
579
|
-
}
|
|
580
|
-
if (entry.kind === 'snapshot' &&
|
|
581
|
-
step.htmlSnapshotUrl &&
|
|
582
|
-
step.htmlSnapshotUrl === entry.url) {
|
|
583
|
-
return {
|
|
584
|
-
kind: entry.kind,
|
|
585
|
-
stepIndex: entry.stepIndex,
|
|
586
|
-
summary: entry.summary,
|
|
587
|
-
path: `steps/${prefix}-snapshot.html`,
|
|
588
|
-
};
|
|
589
|
-
}
|
|
590
|
-
const ext = sidecarExtension(entry.kind);
|
|
591
|
-
const filename = `${prefix}-${entry.kind}-${i}.${ext}`;
|
|
592
|
-
await streamUrlToFile(entry.url, assertNoEscape(stepsTmpDir, filename), fetchImpl, downloadDeps);
|
|
593
|
-
filesWritten.push(`steps/${filename}`);
|
|
594
|
-
return {
|
|
595
|
-
kind: entry.kind,
|
|
596
|
-
stepIndex: entry.stepIndex,
|
|
597
|
-
summary: entry.summary,
|
|
598
|
-
// Replace the (soon-expired) URL with a path relative to the
|
|
599
|
-
// bundle root so an agent can resolve it without ambient
|
|
600
|
-
// knowledge of the bundle's working directory.
|
|
601
|
-
path: `steps/${filename}`,
|
|
602
|
-
};
|
|
603
|
-
}));
|
|
604
|
-
const file = `${prefix}-evidence.json`;
|
|
605
|
-
await writeFile(assertNoEscape(stepsTmpDir, file), JSON.stringify(dereferenced, null, 2) + '\n', 'utf8');
|
|
606
|
-
filesWritten.push(`steps/${file}`);
|
|
607
|
-
}
|
|
608
|
-
}
|
|
609
|
-
function sidecarExtension(kind) {
|
|
610
|
-
if (kind === 'network' || kind === 'console')
|
|
611
|
-
return 'json';
|
|
612
|
-
if (kind === 'screenshot')
|
|
613
|
-
return 'png';
|
|
614
|
-
if (kind === 'snapshot')
|
|
615
|
-
return 'html';
|
|
616
|
-
// log evidence is text-shaped — `.txt` is the safest default. The
|
|
617
|
-
// actual content-type the URL serves may be log-specific (e.g.
|
|
618
|
-
// .ndjson for stream-of-events logs); we don't try to guess.
|
|
619
|
-
return 'txt';
|
|
620
|
-
}
|
|
621
|
-
/**
|
|
622
|
-
* Stream a presigned URL into a file with bounded retry on transport
|
|
623
|
-
* failures. 4xx (presigned URL expired or unauthorized) is NOT
|
|
624
|
-
* retried — the URL won't recover on its own; an upstream re-fetch
|
|
625
|
-
* is the only fix. Maps to `UNAVAILABLE` so `index.ts` exits 10.
|
|
626
|
-
*
|
|
627
|
-
* Streaming uses `pipeline` to honor backpressure: a slow disk pauses
|
|
628
|
-
* the upstream reader rather than buffering chunks in V8 heap. This
|
|
629
|
-
* matters for video files (multi-MB) and for very large HTML
|
|
630
|
-
* snapshots.
|
|
631
|
-
*
|
|
632
|
-
* Transport failures (network reset, DNS blip, mid-stream EOF) are
|
|
633
|
-
* retried up to STREAM_URL_MAX_RETRIES times with a fixed delay.
|
|
634
|
-
* Presigned URLs are valid for 15 minutes, so retries are safe.
|
|
635
|
-
*/
|
|
636
|
-
export async function streamUrlToFile(url, filePath, fetchImpl, deps) {
|
|
637
|
-
const shutdownSignal = deps?.shutdownSignal ?? globalShutdown.signal;
|
|
638
|
-
const shutdown = deps?.shutdown ?? globalShutdown;
|
|
639
|
-
return shutdown.runCriticalOperation(() => streamUrlToFileTracked(url, filePath, fetchImpl, deps?.sleep ?? defaultSleep, shutdownSignal));
|
|
640
|
-
}
|
|
641
|
-
async function streamUrlToFileTracked(url, filePath, fetchImpl, sleepFn, shutdownSignal) {
|
|
642
|
-
const artifactUrl = redactArtifactUrlForDetails(url);
|
|
643
|
-
for (let attempt = 1; attempt <= STREAM_URL_MAX_RETRIES; attempt++) {
|
|
644
|
-
if (shutdownSignal.aborted)
|
|
645
|
-
throw shutdownSignal.reason;
|
|
646
|
-
let response;
|
|
647
|
-
try {
|
|
648
|
-
response = await fetchImpl(url, { redirect: 'error', signal: shutdownSignal });
|
|
649
|
-
}
|
|
650
|
-
catch (err) {
|
|
651
|
-
if (err instanceof InterruptError || shutdownSignal.aborted)
|
|
652
|
-
throw shutdownSignal.reason ?? err;
|
|
653
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
654
|
-
if (attempt < STREAM_URL_MAX_RETRIES) {
|
|
655
|
-
await sleepUnlessInterrupted(sleepFn, STREAM_URL_RETRY_DELAY_MS, shutdownSignal);
|
|
656
|
-
continue;
|
|
657
|
-
}
|
|
658
|
-
throw new TransportError(`Failed to download presigned URL ${artifactUrl}: ${message}`);
|
|
659
|
-
}
|
|
660
|
-
if (shutdownSignal.aborted)
|
|
661
|
-
throw shutdownSignal.reason;
|
|
662
|
-
if (!response.ok) {
|
|
663
|
-
// Non-2xx: the URL itself is bad (expired, unauthorized, not found).
|
|
664
|
-
// Retrying the same URL won't help — surface immediately.
|
|
665
|
-
throw ApiError.fromEnvelope({
|
|
666
|
-
error: {
|
|
667
|
-
code: 'UNAVAILABLE',
|
|
668
|
-
message: `Failed to download presigned URL (HTTP ${response.status}).`,
|
|
669
|
-
nextAction: 'Re-run `testsprite test failure get`. Presigned URLs in the bundle expire after 15 minutes.',
|
|
670
|
-
requestId: 'local',
|
|
671
|
-
details: { status: response.status, artifactUrl },
|
|
672
|
-
},
|
|
673
|
-
});
|
|
674
|
-
}
|
|
675
|
-
if (!response.body) {
|
|
676
|
-
// Some test runtimes / fetch polyfills don't expose `body` as a
|
|
677
|
-
// ReadableStream. Fall back to a buffered write — same correctness,
|
|
678
|
-
// just no streaming benefit. The bundle is bounded by the
|
|
679
|
-
// backend's 15-min TTL, so even a multi-MB video buffers fully in
|
|
680
|
-
// a tolerable amount of memory.
|
|
681
|
-
try {
|
|
682
|
-
const buffer = Buffer.from(await response.arrayBuffer());
|
|
683
|
-
await writeFile(filePath, buffer);
|
|
684
|
-
if (shutdownSignal.aborted) {
|
|
685
|
-
await rm(filePath, { force: true }).catch(() => undefined);
|
|
686
|
-
throw shutdownSignal.reason;
|
|
687
|
-
}
|
|
688
|
-
return;
|
|
689
|
-
}
|
|
690
|
-
catch (err) {
|
|
691
|
-
if (err instanceof InterruptError || shutdownSignal.aborted) {
|
|
692
|
-
await rm(filePath, { force: true }).catch(() => undefined);
|
|
693
|
-
throw shutdownSignal.reason ?? err;
|
|
694
|
-
}
|
|
695
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
696
|
-
if (attempt < STREAM_URL_MAX_RETRIES) {
|
|
697
|
-
await sleepUnlessInterrupted(sleepFn, STREAM_URL_RETRY_DELAY_MS, shutdownSignal);
|
|
698
|
-
continue;
|
|
699
|
-
}
|
|
700
|
-
throw new TransportError(`Failed to download presigned URL ${artifactUrl}: ${message}`);
|
|
701
|
-
}
|
|
702
|
-
}
|
|
703
|
-
await mkdir(dirname(filePath), { recursive: true });
|
|
704
|
-
// `response.body` is a Web ReadableStream. Node's `pipeline` accepts
|
|
705
|
-
// it via `Readable.fromWeb` (Node >= 18). Wrap in a try so any error
|
|
706
|
-
// from the stream propagates as a TransportError, preserving the
|
|
707
|
-
// exit-code contract. `pipeline` destroys both streams on error, so
|
|
708
|
-
// a new WriteStream on retry starts clean.
|
|
709
|
-
const fileSink = createWriteStream(filePath);
|
|
710
|
-
try {
|
|
711
|
-
const webBody = response.body;
|
|
712
|
-
const { Readable } = await import('node:stream');
|
|
713
|
-
const nodeStream = Readable.fromWeb(webBody);
|
|
714
|
-
await pipeline(nodeStream, fileSink);
|
|
715
|
-
if (shutdownSignal.aborted)
|
|
716
|
-
throw shutdownSignal.reason;
|
|
717
|
-
return;
|
|
718
|
-
}
|
|
719
|
-
catch (err) {
|
|
720
|
-
if (err instanceof InterruptError || shutdownSignal.aborted) {
|
|
721
|
-
await rm(filePath, { force: true }).catch(() => undefined);
|
|
722
|
-
throw shutdownSignal.reason ?? err;
|
|
723
|
-
}
|
|
724
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
725
|
-
if (attempt < STREAM_URL_MAX_RETRIES) {
|
|
726
|
-
await sleepUnlessInterrupted(sleepFn, STREAM_URL_RETRY_DELAY_MS, shutdownSignal);
|
|
727
|
-
continue;
|
|
728
|
-
}
|
|
729
|
-
throw new TransportError(`Failed mid-download of ${artifactUrl}: ${message}`);
|
|
730
|
-
}
|
|
731
|
-
}
|
|
732
|
-
}
|
|
733
|
-
function redactArtifactUrlForDetails(url) {
|
|
734
|
-
try {
|
|
735
|
-
const parsed = new URL(url);
|
|
736
|
-
return `${parsed.origin}${parsed.pathname}`;
|
|
737
|
-
}
|
|
738
|
-
catch {
|
|
739
|
-
return '<invalid-url>';
|
|
740
|
-
}
|
|
741
|
-
}
|
|
742
|
-
function isPresignedUrl(value) {
|
|
743
|
-
return value.startsWith('https://');
|
|
744
|
-
}
|
|
745
|
-
/**
|
|
746
|
-
* Write `<dir>/.partial` so an agent inspecting the dir can detect
|
|
747
|
-
* an aborted bundle. The marker is small JSON — the contract is "if
|
|
748
|
-
* `.partial` exists, do not consume `<dir>` until the CLI is re-run
|
|
749
|
-
* and `.partial` disappears."
|
|
750
|
-
*
|
|
751
|
-
* We DO NOT clean the `.tmp/` contents on partial — leaving them on
|
|
752
|
-
* disk is intentional for forensics. The next successful `writeBundle`
|
|
753
|
-
* call clears them.
|
|
754
|
-
*/
|
|
755
|
-
async function writePartialMarker(dir, err, requestId, snapshotId) {
|
|
756
|
-
await mkdir(dir, { recursive: true });
|
|
757
|
-
const body = {
|
|
758
|
-
schemaVersion: BUNDLE_SCHEMA_VERSION,
|
|
759
|
-
snapshotId,
|
|
760
|
-
requestId,
|
|
761
|
-
error: err instanceof Error ? err.message : String(err),
|
|
762
|
-
createdAt: new Date().toISOString(),
|
|
763
|
-
};
|
|
764
|
-
await writeFile(join(dir, '.partial'), JSON.stringify(body, null, 2) + '\n', 'utf8');
|
|
765
|
-
}
|
|
766
|
-
function bundleIntegrityError(reason, message, requestId, ids) {
|
|
767
|
-
return ApiError.fromEnvelope({
|
|
768
|
-
error: {
|
|
769
|
-
code: 'VALIDATION_ERROR',
|
|
770
|
-
message,
|
|
771
|
-
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.',
|
|
772
|
-
requestId,
|
|
773
|
-
details: { reason, ...(ids ?? {}) },
|
|
774
|
-
},
|
|
775
|
-
});
|
|
776
|
-
}
|
|
777
|
-
// Avoid unused-import lint warning for the `mkdtemp` and `readdir`
|
|
778
|
-
// helpers reserved for forensics + future resume work.
|
|
779
|
-
void mkdtemp;
|
|
780
|
-
void readdir;
|
|
781
|
-
//# sourceMappingURL=bundle.js.map
|