Files
rea/scripts/verify-evm-interface.mjs
morluto 123b693f08 feat(delivery)!: bound default results by an agent result budget (#14252)
* feat(delivery)!: bound default results by an agent result budget

Omitted detail now returns complete Evidence only when it fits the new
delivery.agent_result_budget_bytes runtime setting (default 49152 compact
JSON bytes, about 12k tokens at an estimated 4 bytes per token). Larger
results are retained and delivered as the producer's summary with a
limitation naming the budget and the recovery call; nothing is refused or
truncated. inspect_analysis_view gains an evidence-json view that pages the
exact JSON text of retained Evidence. The CLI applies the same budget and
publishes the complete bundle with --evidence_output.

inspect_managed_members type_names now also narrows member_refs and
exported_types, and inspect-byte-entropy gains CLI evidence delivery.

BREAKING CHANGE: An omitted detail no longer always returns complete
Evidence inline on MCP or the CLI for tools with a detail selector
(including inspect_managed_members, inspect_managed_artifact,
inspect_byte_entropy, inspect_artifact, analyze_javascript_application,
list_procedures, list_strings and the other operations listed in
src/domain/agentBudgetOperations.ts). Over the budget they return the
retained summary; pass detail complete (--detail complete) for complete
inline delivery. inspect_managed_members type_names narrows member_refs
and exported_types.

Fixes #14172
Fixes #14180
Part of #14187
Part of #14156

* test(schemas): record advertised summaries for budgeted detail

* fix(delivery): keep budgeted summaries canonical and carry delivery facts beside them

Review fixes for the agent result budget:

- Deliver the producer's own summary record, identical to detail summary,
  so its identity holds in summary consumers such as compare_artifacts.
  The budget, sizes, retention and the exact paging call travel as
  delivery facts: a second MCP text block and _meta, or a delivery field
  in CLI output.
- Capture the caller's detail for application-validated tools too, so
  inspect_binary_layout and similar tools are budgeted.
- Keep recovery facts when a budgeted summary itself exceeds the frame.
- Size an omitted evidence-json limit by escaped UTF-8 bytes and never
  split a surrogate pair, even in a one-unit page.
- Add the REA_AGENT_RESULT_BUDGET_BYTES launch seed; the shared test
  environment raises it for semantic tests, and budget tests clear it.
- Align tool descriptions and verifiers that read complete Evidence.

* fix(delivery): retain the budgeted summary like an explicit summary

* fix(delivery): read the budget seed from the captured environment and count delivery facts in the frame

- The agent result budget seed is read from the environment the server or
  CLI invocation captured: ToolResultDelivery takes it at construction,
  and a CLI invocation binds it in its publication context. The ambient
  process environment is no longer read.
- The frame check reserves the bytes of the delivery block and _meta that
  are added after encoding, so a budgeted response cannot exceed the frame.
- Conformance workflows that resend complete Evidence raise the budget
  through the shared inline-Evidence environment, as do the artifact and
  binary layout verifiers.

* fix(delivery)!: request complete Evidence explicitly and never spill CLI overflow

- Shared test and verifier environments no longer raise the agent result
  budget. Every test and verifier workflow that reads complete Evidence
  from a budgeted tool now requests it with detail complete or --detail
  complete, including the real-provider verifiers outside PR CI (Ghidra,
  Hopper, IDA, Kuna and client verifiers). Default delivery is exercised
  as shipped.
- Budgeting applies only to tools with a detail selector, so every
  budgeted call has a complete opt-out.
- CLI overflow without --evidence_output writes nothing; its delivery
  facts carry exact rerun argv for --detail complete and
  --evidence_output, omitted when the command declares sensitive values.

* test(delivery): prove captured budget seeds with valid in-range values

* test: state complete-detail requests once and fix codemod regressions

- Add tests/support/completeDetail.ts with COMPLETE_DETAIL and
  completeArguments so tests that read complete Evidence request it in one
  place, keeping functions within max-lines-per-function without raising
  the limit.
- Restore provider-client tests (GhidraClient, Hopper health): their
  callTool("name", ...) calls are bridge requests, not MCP tools, and take
  no detail.
- Update the game-scale type inventory test for member_refs narrowing.

* test: request complete Evidence in shared JavaScript analysis helpers and remaining CLI workflows

* test: request complete Evidence by default in the shared test transports

The shared MCP client helpers (createTestMcp, connectLocalToolsMcp and
the CLI fixture's shared MCP session) and the CLI runners (the cli
fixture and the shared CLI session) now apply one named default,
completeEvidenceByDefault. A budgeted tool called with neither detail nor
view gets detail complete; the CLI does the same with --detail complete,
chosen by the command's tool contract. A budgeted operation that resolves
to no contract fails loudly at load. Tests whose subject is delivery opt
out with delivery "budgeted". This is a test-harness choice; production
delivery is unchanged and the budget tests prove the default path.

Per-call complete-detail edits are reverted in the 204 test files whose
transports all apply the default. Explicit requests remain where a test
drives its own SDK client, server, CLI instance or process, and where
the detail choice is the test's subject.

* test: resolve CLI complete-detail defaults from the CLI registry

The Real Apple and browser verifiers read complete Evidence through
artifactCliEvidence, which ran the compiled CLI without a detail choice
and got the budgeted {summary, delivery} output. The helper now requests
complete Evidence for commands that take --detail, read from the compiled
CLI's own registry (scripts/lib/complete-evidence-cli.mjs).

The test harness default had a sibling bug: it treated every cli-flagged
budgeted contract as taking --detail, but only Evidence-delivery commands
do (inspect-binary-layout does not). It now reads the source CLI registry
too, and covers every command the CLI budgets.

* test(verifiers): request complete Evidence at each verifier's SDK client and CLI argv

The real-browser failure was the same missing normalized_result as the
Apple one: browser-capture-metadata-budget-e2e reads analyze-web-bundle
through artifactCliEvidence, fixed in the previous commit.

The shared verifier module, scripts/lib/complete-evidence.mjs, now owns
both transports:
- completeEvidenceClient wraps each verifier's SDK Client once, so every
  callTool to a budgeted tool with neither detail nor view requests
  complete Evidence, whatever local call helper a verifier uses (86
  clients, including the Ghidra, Hopper, IDA and Kuna verifiers'
  argument-less list_procedures and inspect_native_load_image calls).
- completeEvidenceCliArguments covers the remaining verifier CLI argv
  that chose no detail, such as function, decompile, analyze and the
  Android and Apple commands.
Commands and tools that are not budgeted are sent as written.

* test(delivery): await async completeEvidenceCliArguments helper in boundary test

* test(delivery): request complete detail in Electron CLI artifact format test

* docs(delivery): document delivery.rerun as add-only argument arrays

* test(schemas): record advertised summaries for the unified delivery budget

Tool descriptions now name the agent result budget, and the evidence-json default page is derived from the 32 KiB default, which changes the advertised input digests of the 28 affected tools. Recorded from the Build package job's output.

* test(delivery): pin the budget boundary and keep failures unbudgeted

Main's retainedSummaryDelivery tests pinned the size decision at exactly
32,768 and 32,769 UTF-8 JSON bytes. Unifying that decision into
budgetedSummaryBytes deleted them, and their port never landed, so the
byte measurement went unchecked.

Restore them against budgetedSummaryBytes at the configured budget and
one byte over, for the default and a runtime budget, with ASCII, escaped
and multibyte text, plus each condition of the decision. Off-by-one
mutants (< for <=, a cap one byte short) fail six cases; measuring UTF-16
code units instead of UTF-8 bytes fails the multibyte cases.

An MCP case pins that a target failure from a budgeted tool under the
minimum budget is identical with detail omitted and complete, with no
delivery facts.

* test(verifiers): route literal CLI argv for budgeted commands through complete Evidence

real-browser failed with "Scenario CLI did not report external disconnect
ownership": runScenarioCli ran capture-browser-scenario without --detail,
so an over-budget capture came back as its summary, which has no
browser.cleanup. The earlier sweep counted these files as covered
because their MCP clients were wrapped, but their CLI argv was not.

Route the shared runScenarioCli helper (five callers), the local cli
helpers in the module, source-map and script-export verifiers, and
every other literal argv for a budgeted CLI command without --detail or
--view (EVM interface, binary layout, packet capture, devicetree, DOM
destinations, Ghidra relocation symbols, WABT cleanup, Termux browser)
through completeEvidenceCliArguments. A sweep of scripts/ for budgeted
command literals with --json and no detail selection now finds none.

* fix(verifiers): leave clients without callTool unwrapped

The native verifier cleanup test drives native-value-e2e with a connection double whose Client has only connect and close. completeEvidenceClient bound client.callTool unconditionally, so wrapping threw a TypeError before connect ran. That TypeError replaced the primary connection failure the test asserts is preserved, and all four fault cases failed in Test shard 5 and Portable tests. A client without callTool has no tool call to complete, so the helper now returns it unchanged. Locally all five fault modes of the fixture now exit 0.

* fix(delivery): keep the catalog recorder on shipped helpers and expect view-implied summary

The verifier sweep wrapped record-mcp-catalog.mjs in completeEvidenceClient,
which lives in an unshipped helper. deferredRuntime copies only the
package's shipped files plus the recorder, so the recorder failed to load
(ERR_MODULE_NOT_FOUND) and its cleanup recorder never wrote. The recorder
only lists tools and prompts, so the wrapper had no effect; it is removed.

This branch makes a view with no --detail select summary delivery, as MCP
does for a view. Three CLI cases still expected the old view refusal; with
a view alone the missing input is now the summary bundle, so they expect
evidence_output, and a view with --detail complete still refuses the view.

* fix(delivery): request complete Evidence where callers need the whole result

Budgeted delivery made four callers receive a summary they cannot use:

- The GitHub Actions example uploads the analysis as a CI artifact, so it
  now asks for --detail complete; over budget it had saved a summary.
- javascriptIntegrityPolicyCli spawns the CLI itself, outside the test
  harness default, and reads normalized_result; it now applies the same
  completeEvidenceCliArguments default.
- nativeObservationViewsMcp builds its own client to prove complete
  observations overflow into a paging continuation; it now applies the
  harness default so each call asks for complete Evidence.
- The CLI parity goldens are re-recorded for the --detail and
  --evidence_output options the budgeted commands now advertise.

* fix(tests): give processes tests spawn the largest agent result budget

About 90 tests spawn scripts/rea.mjs or a server directly, outside the
harness default that asks for complete Evidence, and read analysis facts
from the result. Over the default budget they received a summary instead;
javascriptChildHandleOwnership failed this way.

The Vitest environment now seeds REA_AGENT_RESULT_BUDGET_BYTES with the
largest accepted value, so a spawned CLI or server delivers complete
Evidence, as the in-process default does. Delivery tests keep their own
budget: agentResultBudgetMcp builds its server without the seed, so its
default-budget cases still exercise the shipped default.

* fix(tests): give budgeted harness tests the shipped agent result budget

The test environment seeds the largest agent result budget so spawned
processes deliver complete Evidence. In-memory servers built by
createApplicationMcpHarness (and connectGhidraMcp, which uses it) inherit
process.env too, so a test that chose testDelivery "budgeted" kept the
seed: the 600-row list_procedures case and the omitted-detail web page
views returned complete Evidence instead of a summary.

testDeliveryEnvironment now owns that choice: a budgeted test's server
environment drops the seed and uses the shipped default. The application
harness applies it to every server it builds.

* fix(tests): expect view-implied summary delivery in the Playwright trace refusal

A view with no --detail now selects summary delivery, so its refusal
names the missing evidence_output bundle; --detail complete still refuses
the view. The trace test still expected a view refusal in both cases.
2026-11-25 11:25:18 -05:00

631 lines
21 KiB
JavaScript

#!/usr/bin/env node
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { access, readFile, readdir, writeFile } from "node:fs/promises";
import { constants } from "node:fs";
import { isAbsolute, join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { parseEvidence } from "../dist/domain/evidence.js";
import { isOwnershipPsExecution } from "./lib/ownership-ps-trace.mjs";
import {
requireMcpOutput,
requireMcpToolError,
} from "./lib/mcp-verifier-results.mjs";
import { createVerifierCommands } from "./lib/verify-commands.mjs";
import {
assertVerifierCleanupComplete,
createVerifierRun,
completeVerifierRun,
} from "./lib/verifier-run.mjs";
import { VerifierFixture } from "./lib/verifier-fixture.mjs";
import {
completeEvidenceCliArguments,
completeEvidenceClient,
} from "./lib/complete-evidence.mjs";
const manifest = JSON.parse(
await readFile(new URL("../package.json", import.meta.url), "utf8"),
);
const expectedEngine = `evmole@${manifest.dependencies.evmole}`;
const solcModule = process.env.REA_VERIFY_SOLC_MODULE;
const strace = process.env.REA_VERIFY_STRACE_COMMAND;
if (
process.platform !== "linux" ||
process.arch !== "x64" ||
!isAbsolute(solcModule ?? "") ||
!isAbsolute(strace ?? "")
)
throw new Error(
"verify:evm:interface requires Linux x64, caller-supplied util-linux prlimit and absolute REA_VERIFY_SOLC_MODULE pointing to unchanged solc 0.8.30 and absolute REA_VERIFY_STRACE_COMMAND. No target or chain is executed.",
);
try {
await access(
process.env.REA_EVM_PRLIMIT_COMMAND ?? "/usr/bin/prlimit",
constants.X_OK,
);
await access(solcModule, constants.R_OK);
await access(strace, constants.X_OK);
} catch (cause) {
throw new Error(
"verify:evm:interface prerequisite unavailable: selected solc module, strace or util-linux prlimit",
{ cause },
);
}
const solc = (await import(pathToFileURL(solcModule).href)).default;
assert.equal(solc.version(), "0.8.30+commit.73712a01.Emscripten.clang");
const source = await readFile(
new URL("./fixtures/evm-interface.sol", import.meta.url),
"utf8",
);
const entrypoint =
process.argv[2] ?? fileURLToPath(new URL("./rea.mjs", import.meta.url));
const run = createVerifierRun();
const commands = await createVerifierCommands();
const environment = Object.fromEntries(
Object.entries(process.env).filter(([, value]) => typeof value === "string"),
);
const root = await VerifierFixture.open({ prefix: "rea-evm-verifier-" });
const client = completeEvidenceClient(
new Client({ name: "evm-interface-verifier", version: "1" }),
);
const transport = new StdioClientTransport({
command: process.execPath,
args: [entrypoint, "mcp"],
env: environment,
stderr: "pipe",
});
const failures = [];
/** @type {Awaited<ReturnType<typeof completeVerifierRun>> | undefined} */
let verifier;
let cases = 0;
try {
await client.connect(transport);
const tools = await client.listTools();
assert.ok(tools.tools.some(({ name }) => name === "inspect_evm_interface"));
const inspect = async (
mode,
path,
encoding,
expectedCategory,
scope = { command: process.execPath, prefix: [], client },
) => {
let value;
if (mode === "cli") {
let stdout;
try {
({ stdout } = await commands.exec(
scope.command,
[
...scope.prefix,
entrypoint,
...(await completeEvidenceCliArguments([
"inspect-evm-interface",
path,
encoding,
"--json",
])),
],
{
env: scope.environment ?? environment,
timeout: 45_000,
maxBuffer: 32 * 1024 * 1024,
},
));
} catch (cause) {
if (cause?.name !== "VerifierCommandExitError") throw cause;
stdout = cause.snapshot.stdout.text;
}
value = JSON.parse(stdout);
} else {
const reply = await scope.client.callTool({
name: "inspect_evm_interface",
arguments: { detail: "complete", path, encoding },
});
value =
expectedCategory !== undefined
? requireMcpToolError(reply)
: requireMcpOutput(reply, "inspect_evm_interface");
}
if (expectedCategory !== undefined) {
assert.equal(value.category, expectedCategory, JSON.stringify(value));
return value;
}
assert.equal(
value.category,
undefined,
`Unexpected public failure: ${JSON.stringify(value)}`,
);
const evidence = parseEvidence(value);
const report = evidence.normalized_result;
assert.equal(report.diagnostics.truncated, false);
assert.equal(evidence.provider.version, expectedEngine);
assert.equal(evidence.confidence, "inferred");
assert.equal(report.artifact.path, path);
assert.equal(report.artifact.encoding, encoding);
const carrier = await readFile(path);
assert.equal(
report.artifact.sha256,
createHash("sha256").update(carrier).digest("hex"),
);
assert.equal(evidence.subject.identity.sha256, report.artifact.sha256);
assert.equal(report.artifact.bytes, carrier.length);
assert.equal(
report.bytecode.sha256,
createHash("sha256")
.update(Buffer.from(report.bytecode.hex, "hex"))
.digest("hex"),
);
assert.equal(report.bytecode.bytes, report.bytecode.hex.length / 2);
for (const key of ["kind", "hardfork", "deployment_authenticity"])
assert.equal(report.bytecode[key], "unknown");
assert.equal(report.discovery_completeness, "unknown");
assert.equal(report.runtime_execution, "not-performed");
assert.deepEqual(
report.functions.map((fn) => ({
selector: fn.selector.slice(2),
bytecodeOffset: fn.bytecode_offset,
dispatch: fn.dispatch,
...(fn.inferred_arguments === null
? {}
: { arguments: fn.inferred_arguments }),
...(fn.inferred_state_mutability === null
? {}
: { stateMutability: fn.inferred_state_mutability }),
})),
evidence.raw_result.functions ?? [],
);
if (mode === "mcp") assert.deepEqual(value.normalized_result, report);
return report;
};
// Ownership inventory runs ps from fixed system locations, so a caller PATH
// without ps neither hides nor replaces it and inspection still completes.
const ownershipProbe = join(root.path, "ownership-prerequisite.hex");
await writeFile(ownershipProbe, "0x00");
const pathWithoutPs = await inspect("cli", ownershipProbe, "hex", undefined, {
command: process.execPath,
prefix: [],
client,
environment: { ...environment, PATH: root.path },
});
assert.equal(pathWithoutPs.bytecode.hex, "00");
cases++;
for (const [name, optimizer, viaIR] of [
["plain", false, false],
["optimized", true, false],
["via-ir", true, true],
]) {
const output = JSON.parse(
solc.compile(
JSON.stringify({
language: "Solidity",
sources: { "Interface.sol": { content: source } },
settings: {
optimizer: { enabled: optimizer, runs: 200 },
viaIR,
evmVersion: "cancun",
outputSelection: {
"*": {
"*": [
"evm.deployedBytecode.object",
"evm.methodIdentifiers",
"abi",
],
},
},
},
}),
),
);
assert.ok(
!output.errors?.some(({ severity }) => severity === "error"),
JSON.stringify(output.errors),
);
const artifact = output.contracts["Interface.sol"].InterfaceFixture;
const hex = artifact.evm.deployedBytecode.object;
const expected = Object.values(artifact.evm.methodIdentifiers)
.map((selector) => "0x" + selector)
.sort();
const forms = [
["hex", ` \t0x${hex.toUpperCase()}\r\n`],
["raw", Buffer.from(hex, "hex")],
];
for (const [encoding, data] of forms) {
const path = join(root.path, `${name}.${encoding}`);
await writeFile(path, data);
const original = await readFile(path);
for (const mode of ["cli", "mcp"]) {
const report = await inspect(mode, path, encoding);
assert.equal(report.bytecode.hex, hex);
assert.equal(report.bytecode.metadata.status, "decoded");
assert.deepEqual(report.bytecode.metadata.compiler_version, {
representation: "release-bytes",
value: "0.8.30",
});
assert.equal(
report.bytecode.metadata.bytecode_offset +
report.bytecode.metadata.cbor_bytes +
2,
Buffer.from(hex, "hex").length,
);
assert.ok(
report.bytecode.metadata.entries.some(
({ key, value }) =>
key.kind === "text" &&
key.value === "solc" &&
value.kind === "bytes" &&
value.value === "00081e",
),
);
assert.deepEqual(
report.functions
.filter(({ dispatch }) => dispatch === "abi")
.map(({ selector }) => selector)
.sort(),
expected,
);
assert.ok(
report.functions.every(
({ bytecode_offset }) => bytecode_offset < report.bytecode.bytes,
),
);
const set = report.functions.find(
({ selector }) =>
selector === "0x" + artifact.evm.methodIdentifiers["set(uint256)"],
);
assert.equal(set.inferred_arguments, "uint256");
assert.equal(set.inferred_state_mutability, "nonpayable");
cases++;
}
assert.deepEqual(await readFile(path), original);
}
}
for (const [name, data, encoding] of [
["empty", "0x", "hex"],
["empty-raw", Buffer.alloc(0), "raw"],
["incomplete-push", Buffer.from([0x7f]), "raw"],
["no-dispatch", "60006000f3", "hex"],
]) {
const path = join(root.path, name);
await writeFile(path, data);
for (const mode of ["cli", "mcp"]) {
const report = await inspect(mode, path, encoding);
assert.equal(report.functions.length, 0);
cases++;
}
}
for (const [name, hex, expected] of [
["zero-selector", "60003560e01c630000000014601057005b00", ["0x00000000"]],
["push-immediate", "63123456785060006000f3", []],
]) {
const path = join(root.path, name);
await writeFile(path, hex);
for (const mode of ["cli", "mcp"]) {
const report = await inspect(mode, path, "hex");
assert.deepEqual(
report.functions.map(({ selector }) => selector),
expected,
);
cases++;
}
}
for (const [encoding, data] of [
["raw", Buffer.from("ef0001", "hex")],
["hex", "0xef0001"],
]) {
const path = join(root.path, "eof." + encoding);
await writeFile(path, data);
for (const mode of ["cli", "mcp"]) {
const failure = await inspect(mode, path, encoding, "unsupported_target");
assert.equal(failure.code, "unsupported_target");
assert.equal(failure.details.path, path);
assert.match(failure.details.reason, /EF00/);
assert.equal(failure.details.failure_kind, "unsupported");
assert.equal(failure.details.format, "evm-bytecode");
cases++;
}
}
for (const [name, data] of [
["odd", "0x1"],
["invalid-hex", "xyz"],
["interior-space", "60 00"],
["bom", "\uFEFF6000"],
["utf8", Buffer.from([0xff])],
]) {
const path = join(root.path, name);
await writeFile(path, data);
for (const mode of ["cli", "mcp"]) {
// An undecodable hex carrier is the target's bytes, not the request.
const failure = await inspect(mode, path, "hex", "unsupported_target");
assert.equal(failure.details.failure_kind, "malformed");
assert.equal(failure.details.format, "evm-bytecode");
cases++;
}
}
for (const mode of ["cli", "mcp"]) {
await inspect(mode, join(root.path, "absent"), "raw", "invalid_input");
cases++;
}
for (const [option, expected] of [
["--as=2147483648", "address_space_bytes=2147483648"],
["--cpu=20", "cpu_seconds=20"],
["--fsize=8388608", "file_size_bytes=8388608"],
]) {
const limiter = environment.REA_EVM_PRLIMIT_COMMAND ?? "/usr/bin/prlimit";
const prefix = [
option,
"--",
process.execPath,
"--disable-wasm-trap-handler",
];
const limitedClient = completeEvidenceClient(
new Client({
name: "limited-evm-verifier",
version: "1",
}),
);
const limitedTransport = new StdioClientTransport({
command: limiter,
args: [...prefix, entrypoint, "mcp"],
env: environment,
stderr: "pipe",
});
try {
await limitedClient.connect(limitedTransport);
const scope = { command: limiter, prefix, client: limitedClient };
for (const mode of ["cli", "mcp"]) {
const report = await inspect(
mode,
join(root.path, "zero-selector"),
"hex",
undefined,
scope,
);
assert.ok(report.limitations.some((item) => item.includes(expected)));
cases++;
}
} finally {
// A close that fails keeps the root until release confirms it.
await root.closeEarly([
() => limitedClient.close(),
() => limitedTransport.close(),
]);
}
}
const brokenLimiter = join(root.path, "broken-limiter");
await writeFile(brokenLimiter, "#!/rea-verifier-missing-interpreter\n", {
mode: 0o700,
});
const signalLimiter = join(root.path, "signal-limiter");
await writeFile(signalLimiter, '#!/bin/sh\nulimit -c 0\nkill -XCPU "$$"\n', {
mode: 0o700,
});
const fileLimiter = join(root.path, "file-size-limiter");
const unmarkedLimiter = join(root.path, "unmarked-file-size-limiter");
await writeFile(
unmarkedLimiter,
'#!/bin/sh\nprintf "launcher exit 76\\n" >&2\nexit 76\n',
{ mode: 0o700 },
);
// Fixture-only launcher: run the actual Node/WASM worker with a one-byte
// file allowance, keeping the usual address-space, CPU and core budgets.
await writeFile(
fileLimiter,
'#!/bin/sh\nwhile [ "$#" -gt 0 ] && [ "$1" != "--" ]; do shift; done\n[ "$#" -gt 0 ] || exit 64\nshift\nexec /usr/bin/prlimit --as=3221225472: --cpu=30: --fsize=1: --core=0: -- "$@"\n',
{ mode: 0o700 },
);
for (const [limiter, category, resource] of [
[root.path, "unsupported_provider"],
[brokenLimiter, "unsupported_provider"],
[signalLimiter, "resource_constraint", "cpu"],
[fileLimiter, "resource_constraint", "file-size"],
[unmarkedLimiter, "execution_failure"],
]) {
const selectedEnvironment = {
...environment,
REA_EVM_PRLIMIT_COMMAND: limiter,
};
const selectedClient = completeEvidenceClient(
new Client({
name: "unavailable-evm-limiter-verifier",
version: "1",
}),
);
const selectedTransport = new StdioClientTransport({
command: process.execPath,
args: [entrypoint, "mcp"],
env: selectedEnvironment,
stderr: "pipe",
});
try {
await selectedClient.connect(selectedTransport);
const scope = {
command: process.execPath,
prefix: [],
client: selectedClient,
environment: selectedEnvironment,
};
for (const mode of ["cli", "mcp"]) {
const error = await inspect(
mode,
join(root.path, "zero-selector"),
"hex",
category,
scope,
);
if (category === "resource_constraint") {
assert.equal(error.code, "resource_constraint");
assert.equal(error.details.resource, resource);
assert.equal(
error.details.reported_limits.effective_soft_limits,
null,
);
assert.equal(
typeof error.details.reported_limits.configured_soft_limits
.cpu_seconds,
"number",
);
assert.ok(
JSON.stringify(error).includes(
resource === "cpu" ? "SIGXCPU" : "EFBIG",
),
);
} else if (category === "execution_failure") {
assert.equal(error.code, "execution_failure");
assert.ok(JSON.stringify(error).includes("launcher exit 76"));
assert.ok(JSON.stringify(error).includes("file_size_failure_marker"));
} else {
assert.equal(error.code, "capability_unavailable");
assert.ok(JSON.stringify(error).includes(limiter));
}
cases++;
}
} finally {
// A close that fails keeps the root until release confirms it.
await root.closeEarly([
() => selectedClient.close(),
() => selectedTransport.close(),
]);
}
}
for (const [name, encoding] of [
["plain.hex", "hex"],
["via-ir.raw", "raw"],
]) {
await commands.exec(
strace,
[
"-ff",
"-e",
"trace=network,execve,execveat",
"-s",
"4096",
"-o",
join(root.path, `offline.trace.${name}`),
process.execPath,
entrypoint,
...(await completeEvidenceCliArguments([
"inspect-evm-interface",
join(root.path, name),
encoding,
"--json",
])),
],
{
env: { ...environment, PATH: "/usr/bin:/bin" },
timeout: 45_000,
maxBuffer: 32 * 1024 * 1024,
},
);
}
const observedExecutables = new Set();
for (const file of await readdir(root.path)) {
if (!file.startsWith("offline.trace.")) continue;
const localSocketDescriptors = new Set();
for (const line of (await readFile(join(root.path, file), "utf8")).split(
"\n",
)) {
if (/execve(?:at)?\(/.test(line)) {
const match = /^execve\("([^"]+)"/.exec(line);
assert.notEqual(match, null, `Unresolved executable identity: ${line}`);
assert.ok(
line.endsWith(" = 0") || / = -1 [A-Z]+/.test(line),
`Incomplete exec observation: ${line}`,
);
const ownershipInspection = isOwnershipPsExecution(line);
assert.ok(
[
process.execPath,
environment.REA_EVM_PRLIMIT_COMMAND ?? "/usr/bin/prlimit",
].includes(match[1]) || ownershipInspection,
`Unexpected host execution: ${line}`,
);
observedExecutables.add(match[1]);
} else if (/^[a-z]+\(/.test(line)) {
assert.ok(
permitsStdioSocketObservation(line, localSocketDescriptors),
`Unexpected attempted network operation: ${line}`,
);
}
}
}
assert.ok(observedExecutables.has(process.execPath));
assert.ok(
observedExecutables.has(
environment.REA_EVM_PRLIMIT_COMMAND ?? "/usr/bin/prlimit",
),
);
cases += 2;
} catch (cause) {
failures.push(cause);
} finally {
root.releaseAfter(() => commands.close());
root.releaseAfter(() => client.close());
root.releaseAfter(() => transport.close());
root.releaseAfter(async () => {
verifier = await completeVerifierRun(run);
assertVerifierCleanupComplete(verifier.process_lineage);
});
try {
await root.release();
} catch (cause) {
failures.push(cause);
}
}
console.log(
JSON.stringify(
{
status: failures.length === 0 ? "passed" : "failed",
public_cases: cases,
compiler: solc.version(),
engine: expectedEngine,
...(failures.length === 0
? {
target_execution: "exec-syscalls-verified-absent",
network_requests: "socket-syscalls-verified-absent",
}
: {}),
verifier,
},
null,
2,
),
);
if (failures.length !== 0)
throw Object.assign(
new AggregateError(
failures,
"Offline EVM interface verification failed; cleanup failures retained.",
),
// The caller can retry the retained root from the final failure.
root.released ? {} : { cleanupLeases: [root] },
);
function permitsStdioSocketObservation(line, localDescriptors) {
if (line.startsWith("socketpair(AF_UNIX,")) {
const pair = /\[(\d+), (\d+)\]\)\s+= 0$/.exec(line);
if (pair !== null) {
localDescriptors.add(pair[1]);
localDescriptors.add(pair[2]);
}
return true;
}
const name = /^getsockname\((\d+), \{sa_family=AF_UNIX\}/.exec(line);
if (name !== null) {
localDescriptors.add(name[1]);
return true;
}
// A failed descriptor query performs no request and identifies no socket.
if (line.startsWith("getsockname(") && / = -1 ENOTSOCK/.test(line))
return true;
const metadata =
/^(?:getsockopt\((\d+), SOL_SOCKET, SO_TYPE,|setsockopt\((\d+), SOL_SOCKET, SO_(?:RCVBUF|SNDBUF),|shutdown\((\d+), SHUT_WR\))/.exec(
line,
);
const descriptor = metadata?.[1] ?? metadata?.[2] ?? metadata?.[3];
// Allow descriptor queries/buffer configuration only after observing a local
// stdio socket. Other socket creation, connection and data operations fail.
return descriptor !== undefined && localDescriptors.has(descriptor);
}