Files
reverse-engineering-anything/scripts/verify-agentenv-environment.mjs
T
02e049744f feat(environment): build agent environments from a prompt (#6946)
* feat(environment): report what an environment serves with an environment-coverage view

A new inspect_analysis_view kind over capture Evidence. It projects the
state an environment derives with the given template rules and reports
each tool as answered from state, replayed with its view reason, a served
write, or a withheld write with its reason, the records behind it and a
hint about what to record next. The hints cover every write reason, so a
new reason without one fails to compile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(environment): build an environment bundle in one command

rea environment-build <capture> [directory] inspects a HAR (or reads
capture Evidence), projects the environment manifest from the in-memory
Evidence, authenticates the pair, prepares the state and writes the bundle
environment-export writes. Every bundle file is byte-identical to the
three-step path for the same capture and options.

The report adds the capture and manifest identities, the coverage summary,
warnings (a loopback capture named after its file, credential-named body
members by pointer) and the next command. --dry-run writes nothing. The
default template rules are the four the published environments use.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(environment): cover environment-build and the coverage view

Domain tests check the hint table against the state view's reasons, the
summary, and the view against the environment-state view it summarizes.
Service tests build the fixture capture and compare every file with the
three-step path, a dry run, loopback naming and the refusals. A CLI test
compares a HAR built in one step with the three CLI steps byte for byte,
and an MCP test projects the view from every source kind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(environment): build the real-agentenv lane's bundle with environment-build

The lane now runs the command users run: it builds the Grafana-shaped HAR
with environment-build and the packed checkout, checks the report, then
runs the bundle with agent-env as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(environment): document environment-build and the coverage view

The agent environments guide opens with the one-step build: the report,
the hint for each withheld write reason, and what a bundle ships. The CLI
guide, the capture guide and the skill reference name the command and the
environment-coverage view.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(environment): harden environment-build after review

- The credential scan walks with its own stack, so a deeply nested body
  cannot crash the build, and it also reports credential-named header
  names, query names, form body members and string arrays.
- The build checks SIGINT between stages: cancelled before the bundle
  stage it writes nothing, during the write it names the written bundle.
- A dry run opens the package tarball, so it refuses what a build refuses.
- Repeated template rules are refused, a HAR saved as .json gets a hint,
  file-derived names follow the bundle name rules, `localhost.` counts as
  a loopback origin, and the next command is shell-quoted.
- --capture-timeout-ms passes through to the HAR inspection, and a
  missing directory is refused before inspection.
- The no-observation hint covers updates and deletes of entities the state
  never held; the coverage view states that it does not apply the
  serve-time admission checks; the inspect_analysis_view description
  names the view.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(environment): state the build's conditions and record its verification

The guides now state when the one-step bundle equals the three-step one,
which headers inspection excludes, what the credential warning scans, how
cancellation behaves, and that the coverage view does not apply the
serve-time admission checks. The spec folder records the census, the end
to end runs, the gates and the review.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(environment): dispatch a pending interrupt before each build stage check

The manifest, state and coverage stages run synchronously, so a SIGINT
that arrived during them was only dispatched once the bundle write had
begun. Each check now yields first, so an interrupt before the bundle
stage cancels the build with nothing written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(browser): send declared requests from a scenario page with a request step

A capture_browser_scenario step `request` sends one declared HTTP request
through the page's own fetch, with its cookies and session, the way the
application's frontend would, and reads the whole response so the capture
records the transaction like any other. The path must resolve to the start
URL's origin, and the page must be on that origin when the step runs.
Query values and header values may be literals or declared secrets, and a
header may read its value from a cookie or a local storage entry, which is
then redacted from later records like a declared secret. `expected_status`
fails the step on any other status. Scenarios without a request step are
unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(browser): verify request steps in a real browser through to a built environment

verify:browser:request records a write session against a fixture item API
that refuses writes without its CSRF cookie header and stored bearer
token. It checks that every request lands in its own step, that the page
values authenticated each write and appear in no record, header or body,
that an unexpected status fails the step and cancels the rest, and that
environment-build serves the recorded create, update and delete.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(environment): export environment bundles over MCP

export_environment_bundle writes the bundle environment-build writes, from
capture Evidence retained in the session or one capture Evidence file,
into an absolute output directory that must not exist and whose parent
must exist, as extract_firmware and export_web_scripts require; it never
creates the parent or reuses a directory. It returns the same report,
whose schema now lives in the domain so the CLI and the tool share it, and
dry_run reports without writing. A loopback capture without a file needs a
name. The build's refusal messages no longer name CLI flags.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(environment): scan scenario credentials, own the dry-run tarball and serialize Evidence once

A browser scenario's retained header values and the query parameters of its recorded URLs are scanned for credential
names as a HAR's are, through a review projection of its records. A dry run admits and releases the package tarball
through the export's regular-file scope, so a close it cannot confirm keeps its owner, and checks for cancellation
after that last await. Evidence is written into one exactly sized buffer instead of chunks joined by a copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(environment): record the review round's checks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(skill): build agent environments from a prompt with request steps and the bundle tool

Add the environments reference to the skill and install it with setup: record
against a disposable instance, sign in through the UI, write with request
steps and read each write back, check coverage, re-record by withheld reason
and export the bundle. Route it from SKILL.md, name agent environments in the
skill description, and document the request step, the export tool and
recording writes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(browser): split the request lane and header resolution into smaller functions

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* style(environment): format the build spec

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(environment): say when an untimed capture learns no write clock

Coverage of a capture whose records are not all timed, which includes every
browser scenario capture, now states that the state learns no clock, so an
update stamped with a server-set modification time stays unexplained-change
however often it is recorded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(skill): give agents a whole scenario shape with step timeouts

Agents guessed the scenario schema field by field and two hung on steps
without timeout_ms. The reference now starts from a complete scenario with a
timeout on every step, and says a scenario capture cannot serve updates the
application stamps with a modification time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(browser): keep request steps on their origin and their page values redacted

- Follow no redirects: a redirect fails the step and nothing reaches the
  location it names (checked in real Chrome), and check the page's origin
  again in the page as the request is sent.
- Send nothing once the step's time has run out or it was cancelled while
  header values were read; the in-page deadline is what remains of the step's.
- Keep every page value redacted under a repeated or colliding label, keep a
  value's first marker when it is read again, and leave values shorter than
  8 characters unredacted rather than rewriting ids, ports and hosts.
- Refuse a header name given twice, User-Agent (Chrome drops it) and line
  breaks in literal values and prefixes; fail before sending when a secret or
  page value holds them.
- Append query entries after the path's literal query without re-encoding it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(environment): document request step limits and word bundle refusals for both surfaces

Document redirects, timeouts, page value redaction, HttpOnly cookie sources
and header refusals for request steps. Refusals shared by environment-build
and export_environment_bundle no longer name CLI flags, and the retained
loopback refusal no longer prints an empty file name. The skill reference
asks for read-backs after each write, shows the coverage view's source, names
package_tarball for unreleased builds and the browser path a scenario ships.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(environment): scan every form occurrence and MIME-less scenario bodies

The build's credential scan collapsed form bodies with Object.fromEntries, so a
repeated field kept only its last occurrence: `api_key=secret&api_key=` warned
about nothing although the Evidence ships the value, and repeated values were
undercounted. Form fields are now scanned as ordered name/value pairs, as
headers and query strings already are.

The review projection of a capture_browser_scenario dropped a request body
recorded without a media type, so the scan never saw it. Review keeps such a
body's text with an empty media type; the manifest projection still reads only
bodies it can classify.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(browser): close request step edge cases from the second review

- Append query entries correctly after a path ending in "?", "&" or "#".
- Refuse 3xx expected statuses, which an unfollowed redirect can never
  report, and say a redirected write may already have been applied.
- Redact a page value also as fetch sends it, without surrounding spaces
  and tabs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(environment): document page value body costs, redirects and MCP dry runs

Document that reading a page value shrinks the bodies a capture keeps under
the default allocation limit, that redirected writes may have landed, that
the MCP dry_run still checks its output directory and which refusals name
the tool, and keep the .har hint in the HAR-as-JSON refusal for both
surfaces.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(environment): record the prompt-to-environment verification

Gates, the real-browser lanes, five environments built from prompts by an
agent on disposable VMs and evaluated with two models, and the two reviews.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(skill): count rollback failures from the managed skill files

The environments reference made the skill eight files, so the recovery tests now derive the counts they expect from
MANAGED_SKILL_FILES instead of fixing them at six and seven.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(adb): restore the portable Java float pattern a merge rewrote

A lint autofix during a merge unescaped the hyphens in javaFloatValuePattern, which is invalid in a v-mode character
class, so the advertised start_adb_activity schema failed to compile in every JS regex mode. The file now matches main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(browser): show the request step inside a whole scenario

Every JSON example in the browser scenario guide is a capture_browser_scenario input the catalog test parses, so the
request step example now sits in a launch scenario instead of standing alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(environment): scan structured HAR form params and the request side of unattributed scenario transactions

A HAR request recorded with postData.params and no text is scanned by those parameters, each occurrence counting, and
the review projection keeps the request side of a scenario transaction whose response cannot be attributed, so the
credential warning covers what evidence.json ships in both cases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(environment): validate build paths and read dry-run tarballs

* fix(environment): report bodies too large for the credential scan

Text bodies over the scan's 4 MiB limit, including a response decoded only as a prefix, are reported as a
credential-scan-incomplete warning by record and side, never by content, so an absent credential-named-members
warning no longer reads as a complete check. The spec and agent-environments guide also state the path validation and
dry-run tarball read that e52ae1cd added.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(verification): release cold source transform services

* fix(javascript): retain capture context along covered mutation paths

* fix(environment): guard request dispatch and report export limits

* fix(environment): admit serialized exports and scan HAR form fallbacks

* fix(environment): admit in-memory build inputs against heap headroom and scan SaveHar null-text forms

The inspected HAR's Evidence and the projected manifest are checked against live heap headroom before they are
serialized, with the same check the file route uses, so a capture too large to parse and seal is refused as
resource_constraint before anything is written. A request whose postData text is SaveHar's null is scanned by its
structured params.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(environment): measure the credential scan limit in UTF-8 bytes

A body counts against the 4 MiB limit by its UTF-8 length, not its UTF-16 code units, so multibyte text over the
limit is reported as unscanned instead of parsed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(browser): send request steps only before their deadline and keep page reads on the start origin

The page receives the step's absolute deadline and a one-second start window, so a busy page that runs the request
late, or after the step is cancelled, sends nothing; local storage is read only on the start origin; the response is
drained without keeping its body; an unparseable path is a field issue; retained Evidence is refused for heap headroom
before it is serialized; and the skill says how to reach server-assigned ids.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* style: format integrated export admission

* fix(javascript): erase inline type imports before binding values

* fix(browser): run the request lane under the shared verifier command owner

The browser request lane runs each CLI call through createPackageVerifierCommands on a private runtime root, so a
timeout, output overflow or failure stops the CLI and the browser it launched before the root is removed, and a failed
stop is reported with the root retained. The verification record states the lane's current counts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(environment): scan scenario content by event and read bodies by their media type

A browser scenario's credential scan reads every retained network-content event, including a response attached
mid-flight and a transaction no record represents, with event pointers, and each transaction URL's query once; the
review record projection it replaces is removed. A body is parsed as a form or as JSON by its recorded media type,
falling back to its shape, so valid forms such as `password=x&` are scanned and sentences are not read as forms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-10-24 21:51:41 +08:00

343 lines
12 KiB
JavaScript

#!/usr/bin/env node
import assert from "node:assert/strict";
import { access, readFile, writeFile } from "node:fs/promises";
import { dirname, isAbsolute, join, resolve } from "node:path";
import { setTimeout as pause } from "node:timers/promises";
import { fileURLToPath } from "node:url";
import { PrivateRuntimeRoot } from "../dist/process/PrivateRuntimeRoot.js";
import { createVerifierRun, completeVerifierRun } from "./lib/verifier-run.mjs";
import { createPackageVerifierCommands } from "./lib/verify-package-commands.mjs";
const AGENTENV_VERSION = "0.9.1334";
const AGENTENV_PIN = `agentenv-framework ${AGENTENV_VERSION}`;
// The framework builds its infra images from public ECR, whose anonymous pull quota hosted
// runners share; a rate refusal earns one retry, anything else fails at once.
const PUBLIC_ECR_QUOTA =
/public\.ecr\.aws[\s\S]{0,400}?(?:429 Too Many Requests|toomanyrequests)/u;
// The anonymous data-transfer cap is counted per source IP, so a pause on the same runner
// cannot lift it; the receipt names it instead of retrying.
const PUBLIC_ECR_DATA_LIMIT = /toomanyrequests: Data limit exceeded/u;
const QUOTA_RETRY_PAUSE_MS = 90_000;
// Both bundle attempts share this budget inside the 30-minute job; a retry needs real time left.
const RUN_BUDGET_MS = 22 * 60_000;
const FIRST_ATTEMPT_MS = 15 * 60_000;
const MIN_RETRY_MS = 5 * 60_000;
// Both tools are caller-supplied absolute paths, as every real-* lane names its upstream.
for (const key of ["REA_AGENT_ENV_COMMAND", "REA_DOCKER_COMMAND"])
if (!isAbsolute(process.env[key] ?? ""))
throw new Error(
`verify:agentenv:environment requires absolute ${key}; see docs/testing.md. No dependencies are installed by this verifier.`,
);
const agentEnv = process.env.REA_AGENT_ENV_COMMAND;
const docker = process.env.REA_DOCKER_COMMAND;
// The framework's local image store keeps its registry:2 helper running across runs; a first
// run on a fresh host creates it, so it is reported separately rather than counted as a leak.
const IMAGE_STORE_HELPER = /^agentenv-registry(?:-\d+)?$/u;
await Promise.all([access(agentEnv), access(docker)]);
const entrypoint =
process.argv[2] ?? fileURLToPath(new URL("./rea.mjs", import.meta.url));
const checkout = resolve(dirname(entrypoint), "..");
const run = createVerifierRun();
const runtime = await PrivateRuntimeRoot.create({
prefix: "rea-agentenv-verifier-",
});
const environment = Object.fromEntries(
Object.entries(process.env).filter(([, value]) => typeof value === "string"),
);
const failures = [];
let cases = 0;
const receipt = {};
let knownContainers;
let commands;
try {
commands = await createPackageVerifierCommands({ workspace: runtime });
const version = await commands.exec(agentEnv, ["--version"], {
env: environment,
timeout: 10_000,
maxBuffer: 64 * 1024,
});
receipt.agent_env_version = version.stdout.trim();
assert.equal(
receipt.agent_env_version,
`agent-env ${AGENTENV_VERSION}`,
"The verifier requires the pinned framework executable; its observed version is retained in the receipt.",
);
const containersBefore = await containers();
knownContainers = new Set(containersBefore.map((entry) => entry.id));
receipt.docker_before = {
containers: containersBefore.length,
images: (await imageIds()).length,
};
// Source-owned capture: the Grafana-shaped HAR builder the view tests use.
const { environmentManifestHar } = await import(
new URL("../tests/fixtures/historicalHar.ts", import.meta.url).href
);
const harPath = join(runtime.path, "capture.har");
await writeFile(harPath, JSON.stringify(environmentManifestHar()));
// The lane proves this checkout, not the registry package: pack it and install the tarball in the image.
const { stdout: packed } = await commands.execNpm(
["pack", "--ignore-scripts", "--json", "--pack-destination", runtime.path],
{ cwd: checkout, env: environment, maxBuffer: 16 * 1024 * 1024 },
);
const tarball = join(runtime.path, packedFilename(JSON.parse(packed)));
await access(tarball);
// The one-step build users run: it inspects the HAR, projects the manifest and writes the bundle.
const bundle = join(runtime.path, "grafana-example");
const built = await cli(
"environment-build",
harPath,
bundle,
"--package-tarball",
tarball,
);
assert.equal(built.status, "built");
assert.equal(built.capture.operation, "inspect_web_network_capture");
assert.equal(built.capture.records, 28);
cases++;
assert.equal(built.name, "grafana-example");
const toolCount = built.manifest.tools;
assert.ok(toolCount > 0);
assert.deepEqual(built.manifest.template_rules, [
"after-uid-literal",
"opaque-token",
"sibling-variance",
"prefix-variance",
]);
cases++;
// The bundle serves the state its server derives from the capture, which leaves the
// manifest's write tools unserved; the build reports the count the bundle serves.
assert.equal(built.state.served, true);
const servedCount = built.tool_count;
assert.ok(servedCount > 0 && servedCount < toolCount);
// Every read tool and every served write tool is in the served catalog.
assert.equal(
built.coverage.reads.state +
built.coverage.reads.recorded +
built.coverage.writes.served.length,
servedCount,
);
assert.equal(built.package_source.kind, "tarball");
assert.deepEqual(built.files.map((file) => file.path).sort(), [
"README.md",
"artifacts/check_grafana-example/verify.py",
"envs/grafana-example/Dockerfile",
"envs/grafana-example/env.toml",
"envs/grafana-example/evidence.json",
"envs/grafana-example/manifest.json",
"envs/grafana-example/rea-agents.tgz",
"tasks/smoke.json",
]);
const shipped = JSON.parse(
await readFile(join(bundle, "envs/grafana-example/manifest.json"), "utf8"),
);
assert.equal(shipped.evidence_id, built.manifest.evidence_id);
assert.equal(
shipped.normalized_result.parent_evidence_id,
built.capture.evidence_id,
);
const dockerfile = await readFile(
join(bundle, "envs/grafana-example/Dockerfile"),
"utf8",
);
assert.ok(dockerfile.includes("COPY rea-agents.tgz /tmp/"));
assert.ok(dockerfile.includes("/tmp/rea-agents.tgz"));
cases++;
// The agentenv runner builds the image, deploys it on the local sandbox and runs the verifier.
// One deadline for both attempts, well under the 30-minute job, so a hung or retried run ends
// with this receipt rather than the runner's kill.
const started = Date.now();
const deadline = started + RUN_BUDGET_MS;
let attempts = 0;
const runBundle = async (timeoutMs) => {
attempts += 1;
let outcome;
try {
const output = await commands.exec(
agentEnv,
["run", bundle, "--sandbox", "local"],
{
cwd: runtime.path,
env: environment,
timeout: timeoutMs,
diagnosticBytes: 4 * 1024 * 1024,
},
);
outcome = {
exitCode: 0,
signal: null,
stdout: { text: output.stdout },
stderr: { text: output.stderr },
};
return outcome;
} catch (cause) {
outcome = cause?.snapshot;
throw cause;
} finally {
// Recorded before the outcome is judged, so a failed receipt still says how the last
// run ended, how many runs there were and whether the registry quota refused it.
receipt.agent_env_run = runRecord(
outcome,
Date.now() - started,
attempts,
);
}
};
let snapshot;
try {
snapshot = await runBundle(
Math.min(FIRST_ATTEMPT_MS, deadline - Date.now()),
);
} catch (cause) {
if (
receipt.agent_env_run?.public_ecr_quota !== "rate" ||
deadline - Date.now() - QUOTA_RETRY_PAUSE_MS < MIN_RETRY_MS
)
throw cause;
await pause(QUOTA_RETRY_PAUSE_MS);
snapshot = await runBundle(deadline - Date.now());
}
assert.equal(snapshot.exitCode, 0);
assert.match(snapshot.stdout.text, /tasks\/smoke\.json v\d+: passed/u);
assert.match(
snapshot.stdout.text,
new RegExp(
`serve: listed ${String(servedCount)} tools, expected ${String(servedCount)};`,
"u",
),
);
cases++;
} catch (cause) {
failures.push(cause);
} finally {
// The container inventory runs whether the bundle passed, failed or timed out, so a failed
// receipt still says what the run left behind.
if (knownContainers !== undefined)
try {
const containersAfter = await containers();
const added = containersAfter.filter(
(entry) => !knownContainers.has(entry.id),
);
const helpers = added.filter((entry) =>
IMAGE_STORE_HELPER.test(entry.name),
);
const leaked = added.filter(
(entry) => !IMAGE_STORE_HELPER.test(entry.name),
);
receipt.docker_after = {
containers: containersAfter.length,
images: (await imageIds()).length,
image_store_helpers: helpers.map((entry) => entry.name),
new_containers: leaked.map((entry) => `${entry.id} ${entry.name}`),
};
assert.deepEqual(leaked, []);
if (failures.length === 0) cases++;
} catch (cause) {
failures.push(cause);
}
try {
if (commands === undefined) await runtime.close();
else await commands.close();
} catch (cause) {
failures.push(cause);
}
}
const verifier = await completeVerifierRun(run);
try {
assert.equal(verifier.process_lineage.status, "verified");
assert.deepEqual(verifier.process_lineage.descendants, []);
} catch (cause) {
failures.push(cause);
}
if (failures.length > 0) {
console.error(
JSON.stringify(
{ status: "failed", public_cases: cases, ...receipt, verifier },
null,
2,
),
);
throw new AggregateError(
failures,
"Environment bundle verification failed; export, run and cleanup failures are retained.",
);
}
console.log(
JSON.stringify(
{
status: "passed",
public_cases: cases,
upstream: AGENTENV_PIN,
runner: `${process.platform} ${process.arch}; host Docker`,
offline: false,
...receipt,
verifier,
},
null,
2,
),
);
async function cli(...args) {
const { stdout } = await commands.exec(
process.execPath,
[entrypoint, ...args, "--json"],
{ env: environment, cwd: runtime.path, maxBuffer: 64 * 1024 * 1024 },
);
return JSON.parse(stdout);
}
// The receipt's view of one `agent-env run`, passed or failed; `outcome` is absent when the
// command failed before producing a snapshot.
function runRecord(outcome, elapsedMs, attempts) {
const quota = publicEcrQuota(outcome?.stderr.text ?? "");
return {
exit_code: outcome?.exitCode ?? null,
...(outcome?.signal ? { signal: outcome.signal } : {}),
seconds: Math.round(elapsedMs / 1000),
attempts,
...(attempts > 1
? { retried_for: "public ECR anonymous pull rate limit (429)" }
: {}),
...(quota === undefined ? {} : { public_ecr_quota: quota }),
stdout_tail: (outcome?.stdout.text ?? "").trim().split("\n").slice(-6),
};
}
// Which public ECR refusal ended a run: the per-IP data cap or a request-rate refusal.
function publicEcrQuota(stderr) {
if (!PUBLIC_ECR_QUOTA.test(stderr)) return undefined;
return PUBLIC_ECR_DATA_LIMIT.test(stderr) ? "data_limit" : "rate";
}
// npm 11 prints `npm pack --json` as a one-element array; npm 12 keys the same record by package name.
function packedFilename(report) {
const record = Array.isArray(report) ? report[0] : Object.values(report)[0];
assert.equal(typeof record?.filename, "string");
return record.filename;
}
// Containers are not verifier descendants, so leaks are checked by id against the pre-run set.
async function containers() {
const { stdout } = await commands.exec(
docker,
["ps", "-a", "--format", "{{.ID}}\t{{.Names}}"],
{ env: environment },
);
return stdout
.split("\n")
.filter((line) => line.length > 0)
.map((line) => {
const [id, name = ""] = line.split("\t");
return { id, name };
})
.sort((left, right) => left.id.localeCompare(right.id));
}
async function imageIds() {
const { stdout } = await commands.exec(docker, ["images", "-q"], {
env: environment,
});
return [...new Set(stdout.split("\n").filter((line) => line.length > 0))];
}