mirror of
https://github.com/morluto/rea.git
synced 2026-12-05 06:21:12 +00:00
* 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.
485 lines
18 KiB
JavaScript
485 lines
18 KiB
JavaScript
#!/usr/bin/env node
|
|
import { closeVerifierResources } from "./lib/verifier-cleanup.mjs";
|
|
import assert from "node:assert/strict";
|
|
import {
|
|
requireMcpLifecycleResult,
|
|
requireMcpOutput,
|
|
} from "./lib/mcp-verifier-results.mjs";
|
|
import { createHash } from "node:crypto";
|
|
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
|
import { basename, isAbsolute, join, resolve } from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
import { Client } from "@modelcontextprotocol/client";
|
|
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
|
import { parseEvidence } from "../dist/domain/evidence.js";
|
|
import { nativeDataTypeSchema } from "../dist/domain/native/nativeDataType.js";
|
|
import { nativeLoadImageSchema } from "../dist/domain/native/nativeLoadImage.js";
|
|
|
|
import { createVerifierCommands } from "./lib/verify-commands.mjs";
|
|
import { bindVerifierCommandInterruption } from "./lib/verifier-command-interruption.mjs";
|
|
import {
|
|
assertVerifierCleanupComplete,
|
|
createVerifierRun,
|
|
completeVerifierRun,
|
|
} from "./lib/verifier-run.mjs";
|
|
import {
|
|
VerifierFixture,
|
|
withVerifierFixture,
|
|
} from "./lib/verifier-fixture.mjs";
|
|
import { completeEvidenceClient } from "./lib/complete-evidence.mjs";
|
|
const run = createVerifierRun();
|
|
const mode = process.argv[2] ?? "symbols";
|
|
if (
|
|
![
|
|
"symbols",
|
|
"stripped",
|
|
"ordinary",
|
|
"unsupported",
|
|
"malformed",
|
|
"ambiguous",
|
|
"loader-failure",
|
|
"default-native",
|
|
].includes(mode) ||
|
|
process.argv.length > 3
|
|
)
|
|
throw new Error(
|
|
"Usage: verify-real-ghidra-nativeaot.mjs [symbols|stripped|ordinary|unsupported|malformed|ambiguous|loader-failure|default-native]",
|
|
);
|
|
if (process.platform !== "linux" || process.arch !== "x64")
|
|
throw new Error(
|
|
"verify:ghidra:nativeaot requires a Linux x64 host; Windows host mutation is not supported.",
|
|
);
|
|
for (const key of ["loader-failure", "default-native"].includes(mode)
|
|
? ["GHIDRA_INSTALL_DIR"]
|
|
: ["GHIDRA_INSTALL_DIR", "REA_GHIDRA_NATIVEAOT_JAR"])
|
|
if (!process.env[key] || !isAbsolute(process.env[key]))
|
|
throw new Error(
|
|
`verify:ghidra:nativeaot prerequisite missing: absolute ${key}`,
|
|
);
|
|
const fixtureRoot = resolve(
|
|
process.env.REA_NATIVEAOT_PROOF_FIXTURE_ROOT ??
|
|
"_reference/nativeaot-integration/generated/linux-x64",
|
|
);
|
|
const oracle = JSON.parse(
|
|
await readFile(join(fixtureRoot, "oracle.json"), "utf8"),
|
|
);
|
|
const symbolTarget = join(
|
|
fixtureRoot,
|
|
"symbols",
|
|
oracle.runtime === "win-x64" ? "NativeAotFixture.exe" : "NativeAotFixture",
|
|
);
|
|
const target =
|
|
mode === "stripped"
|
|
? join(fixtureRoot, "stripped", basename(symbolTarget))
|
|
: [
|
|
"ordinary",
|
|
"unsupported",
|
|
"malformed",
|
|
"ambiguous",
|
|
"loader-failure",
|
|
"default-native",
|
|
].includes(mode)
|
|
? join(
|
|
fixtureRoot,
|
|
["loader-failure", "default-native"].includes(mode)
|
|
? "ordinary"
|
|
: mode,
|
|
)
|
|
: symbolTarget;
|
|
const bytes = await readFile(target);
|
|
const sha256 = hash(bytes);
|
|
const workspaceFixture = await VerifierFixture.open({
|
|
prefix: "rea-nativeaot-proof-",
|
|
});
|
|
const workspace = workspaceFixture.path;
|
|
const runtime = join(workspace, "runtime");
|
|
await mkdir(runtime);
|
|
const packageRoot = process.env.REA_NATIVEAOT_PROOF_PACKAGE_ROOT;
|
|
if (packageRoot !== undefined && !isAbsolute(packageRoot))
|
|
throw new Error("REA_NATIVEAOT_PROOF_PACKAGE_ROOT must be absolute");
|
|
const entrypoint =
|
|
packageRoot === undefined
|
|
? fileURLToPath(new URL("./rea.mjs", import.meta.url))
|
|
: join(packageRoot, "scripts/rea.mjs");
|
|
const env = {
|
|
PATH: process.env.PATH ?? "/usr/bin:/bin",
|
|
TMPDIR: runtime,
|
|
REA_LOG_LEVEL: "silent",
|
|
REA_ANALYSIS_PROVIDER: "ghidra",
|
|
GHIDRA_INSTALL_DIR: process.env.GHIDRA_INSTALL_DIR,
|
|
REA_GHIDRA_NATIVEAOT_JAR: process.env.REA_GHIDRA_NATIVEAOT_JAR,
|
|
GHIDRA_HEADLESS_MAXMEM: process.env.GHIDRA_HEADLESS_MAXMEM ?? "768M",
|
|
...(process.env.JAVA_HOME === undefined
|
|
? {}
|
|
: { JAVA_HOME: process.env.JAVA_HOME }),
|
|
};
|
|
if (mode === "default-native") delete env.REA_GHIDRA_NATIVEAOT_JAR;
|
|
// Source-built linkage failure exercises the actual JVM loader boundary, not
|
|
// a simulated producer report. Its class/JAR exist only in the owned workspace.
|
|
if (mode === "loader-failure")
|
|
env.REA_GHIDRA_NATIVEAOT_JAR = join(workspace, "bad-extension.jar");
|
|
// javac, jar, and the optional CLI share one command owner. A timeout stops that process group.
|
|
const commands = await createVerifierCommands();
|
|
const commandInterruption = bindVerifierCommandInterruption(commands);
|
|
const execOwned = commandInterruption.exec;
|
|
const { untilInterrupted, throwIfInterrupted } = commandInterruption;
|
|
const finishCommandInterruption = () => commandInterruption.finish();
|
|
async function prepareLoaderFailure() {
|
|
const source = join(workspace, "NativeAotExtension.java");
|
|
const classes = join(workspace, "classes");
|
|
await mkdir(classes);
|
|
await writeFile(
|
|
source,
|
|
`package rea.extensions.nativeaot;
|
|
public final class NativeAotExtension {
|
|
static { fail(); }
|
|
private static void fail() { throw new IllegalStateException("REA_INITIALIZER_FIXTURE"); }
|
|
public NativeAotExtension() {}
|
|
}
|
|
`,
|
|
);
|
|
const command = (name) =>
|
|
process.env.JAVA_HOME === undefined
|
|
? name
|
|
: join(process.env.JAVA_HOME, "bin", name);
|
|
await execOwned(
|
|
command("javac"),
|
|
["-J-Xmx512m", "-J-XX:ActiveProcessorCount=1", "-d", classes, source],
|
|
{ timeout: 60000 },
|
|
);
|
|
await execOwned(
|
|
command("jar"),
|
|
["--create", "--file", env.REA_GHIDRA_NATIVEAOT_JAR, "-C", classes, "."],
|
|
{ timeout: 60000 },
|
|
);
|
|
}
|
|
const transport = new StdioClientTransport({
|
|
command: process.execPath,
|
|
args: [entrypoint, "mcp"],
|
|
env,
|
|
stderr: "pipe",
|
|
});
|
|
const client = completeEvidenceClient(
|
|
new Client({ name: "rea-nativeaot-proof", version: "1" }),
|
|
);
|
|
let stderr = "";
|
|
transport.stderr?.on("data", (chunk) => {
|
|
stderr = (stderr + chunk.toString()).slice(-65536);
|
|
});
|
|
let opened = false;
|
|
let connected = false;
|
|
let verifierRun;
|
|
let report;
|
|
workspaceFixture.releaseAfter(async () => {
|
|
await closeVerifierResources([
|
|
async () => {
|
|
if (connected) await call("close_binary", {});
|
|
},
|
|
() => client.close(),
|
|
() => transport.close(),
|
|
]);
|
|
assert.deepEqual(
|
|
await readdir(runtime),
|
|
[],
|
|
"Owned runtime/project/extension files leaked after close",
|
|
);
|
|
verifierRun = await completeVerifierRun(run);
|
|
assertVerifierCleanupComplete(verifierRun.process_lineage);
|
|
});
|
|
commandInterruption.retainWorkspaceIfInterrupted(workspaceFixture);
|
|
await withVerifierFixture(workspaceFixture, async () => {
|
|
let primaryFailure;
|
|
try {
|
|
if (mode === "loader-failure") await prepareLoaderFailure();
|
|
await untilInterrupted(
|
|
client.connect(transport, { signal: commandInterruption.signal }),
|
|
);
|
|
connected = true;
|
|
const response = await client.callTool(
|
|
{
|
|
name: "open_binary",
|
|
arguments: { path: target, provider_id: "ghidra" },
|
|
},
|
|
{ timeout: 360000, signal: commandInterruption.signal },
|
|
);
|
|
if (
|
|
["unsupported", "malformed", "ambiguous", "loader-failure"].includes(mode)
|
|
) {
|
|
// MCP open binds a lazy session; the first inspection starts import.
|
|
let failure = response;
|
|
if (failure.isError !== true) {
|
|
opened = true;
|
|
failure = await client.callTool(
|
|
{
|
|
name: "inspect_native_load_image",
|
|
arguments: { detail: "complete" },
|
|
},
|
|
{ timeout: 360000, signal: commandInterruption.signal },
|
|
);
|
|
}
|
|
assert.equal(failure.isError, true, JSON.stringify(failure));
|
|
const diagnostic = JSON.stringify(failure);
|
|
assert.match(
|
|
diagnostic,
|
|
mode === "unsupported"
|
|
? /Unsupported NativeAOT RTR format/
|
|
: mode === "malformed"
|
|
? /Reversed NativeAOT section/
|
|
: mode === "loader-failure"
|
|
? /ExceptionInInitializerError.*REA_INITIALIZER_FIXTURE/
|
|
: /Ambiguous NativeAOT directory candidates/,
|
|
);
|
|
report = { mode, target, sha256, typed_failure: failure };
|
|
} else if (mode === "default-native") {
|
|
assert.notEqual(response.isError, true, JSON.stringify(response));
|
|
opened = true;
|
|
const image = nativeLoadImageSchema.parse(
|
|
await call("inspect_native_load_image"),
|
|
);
|
|
assert.equal(image.observations.metadata_recovery, undefined);
|
|
report = { mode, target, sha256, image };
|
|
} else {
|
|
assert.notEqual(response.isError, true, JSON.stringify(response));
|
|
opened = true;
|
|
const image = nativeLoadImageSchema.parse(
|
|
await call("inspect_native_load_image"),
|
|
);
|
|
const summary = image.observations.metadata_recovery?.[0];
|
|
assert.ok(
|
|
summary,
|
|
"Loaded-image inspection omitted inline runtime-format discovery",
|
|
);
|
|
assert.equal(summary.format, "dotnet-nativeaot");
|
|
assert.equal(
|
|
summary.analysis_artifact_sha256,
|
|
hash(await readFile(env.REA_GHIDRA_NATIVEAOT_JAR)),
|
|
);
|
|
if (mode === "ordinary") {
|
|
assert.equal(summary.status, "not_applicable");
|
|
assert.equal(summary.method_tables, 0);
|
|
assert.deepEqual(summary.types, []);
|
|
report = { mode, target, sha256, summary };
|
|
} else {
|
|
assert.ok(["complete", "partial"].includes(summary.status));
|
|
assert.equal(summary.format_major, 9);
|
|
assert.equal(summary.format_minor, 1);
|
|
assert.equal(summary.types.length, summary.method_tables);
|
|
assert.ok(summary.method_tables > 0);
|
|
assert.equal(
|
|
summary.discovery,
|
|
mode === "stripped" || oracle.runtime === "win-x64"
|
|
? "signature-heuristic"
|
|
: "symbol",
|
|
);
|
|
assert.equal(summary.derived_memory.file_offset, null);
|
|
assert.ok(summary.coverage.frozen_objects_annotated > 0);
|
|
// Independent compiler/linker symbols identify fixture classes. Recovered
|
|
// Class_address names are never treated as the original source identities.
|
|
const symbols = await readFile(
|
|
join(fixtureRoot, "symbols.txt"),
|
|
"utf8",
|
|
);
|
|
const bias =
|
|
oracle.runtime === "linux-x64"
|
|
? BigInt(image.observations.image_base)
|
|
: 0n;
|
|
const addressOf = (name) => {
|
|
const line = symbols
|
|
.split(/\r?\n/u)
|
|
.find((line) => line.split(/\s+/u).includes(name));
|
|
assert.ok(line, `Independent symbol missing: ${name}`);
|
|
const match =
|
|
oracle.runtime === "linux-x64"
|
|
? line.match(/^([a-f0-9]+)\s/iu)
|
|
: line.match(/\s([a-f0-9]{16})\s/iu);
|
|
assert.ok(match, `Unrecognized independent symbol line: ${line}`);
|
|
return `0x${(BigInt(`0x${match[1]}`) + bias).toString(16)}`;
|
|
};
|
|
const fixtureSymbols =
|
|
oracle.symbols ??
|
|
(oracle.runtime === "win-x64"
|
|
? {
|
|
base: "??_7NativeAotFixture_BaseProbe@@6B@",
|
|
derived: "??_7NativeAotFixture_DerivedProbe@@6B@",
|
|
interface: "??_7NativeAotFixture_IProbe@@6B@",
|
|
compute: "NativeAotFixture_DerivedProbe__Compute",
|
|
dispatch: "NativeAotFixture_Program__Dispatch",
|
|
}
|
|
: {
|
|
base: "_ZTV26NativeAotFixture_BaseProbe",
|
|
derived: "_ZTV29NativeAotFixture_DerivedProbe",
|
|
interface: "_ZTV23NativeAotFixture_IProbe",
|
|
compute: "NativeAotFixture_DerivedProbe__Compute",
|
|
dispatch: "NativeAotFixture_Program__Dispatch",
|
|
});
|
|
const lookup = (address) => {
|
|
const identity = summary.types.find(
|
|
(type) => type.address === address,
|
|
);
|
|
assert.ok(identity?.type, `Recovered identity missing at ${address}`);
|
|
return identity.type;
|
|
};
|
|
const derivedAddress = addressOf(fixtureSymbols.derived);
|
|
const baseAddress = addressOf(fixtureSymbols.base);
|
|
const interfaceAddress = addressOf(fixtureSymbols.interface);
|
|
const derived = nativeDataTypeSchema.parse(
|
|
await call("inspect_native_data_type", {
|
|
type: lookup(derivedAddress),
|
|
}),
|
|
);
|
|
const metadata = derived.metadata_recovery;
|
|
assert.ok(metadata);
|
|
assert.equal(metadata.original_name, null);
|
|
assert.equal(metadata.name_origin, "generated");
|
|
assert.equal(metadata.method_table_address, derivedAddress);
|
|
assert.equal(metadata.related_type.address, baseAddress);
|
|
assert.ok(
|
|
metadata.interfaces.some((type) => type.address === interfaceAddress),
|
|
);
|
|
assert.ok(
|
|
metadata.virtual_slots.some(
|
|
(slot) => slot.target_address === addressOf(fixtureSymbols.compute),
|
|
),
|
|
);
|
|
const compute = await call("analyze_function", {
|
|
procedure: addressOf(fixtureSymbols.compute),
|
|
detail: "complete",
|
|
});
|
|
assert.ok(compute.pseudocode.trim());
|
|
assert.doesNotMatch(
|
|
compute.pseudocode,
|
|
/\b__thiscall\b/u,
|
|
"Upstream x64 calling-convention rewrite leaked into recovered pseudocode",
|
|
);
|
|
assert.match(compute.pseudocode, /(?:0xb|\b11\b|<<)/u);
|
|
const dispatch = await call("analyze_function", {
|
|
procedure: addressOf(fixtureSymbols.dispatch),
|
|
detail: "complete",
|
|
});
|
|
assert.ok(dispatch.pseudocode.trim());
|
|
for (const literal of oracle.expected_strings)
|
|
assert.ok(
|
|
(
|
|
await call("search_strings", {
|
|
detail: "complete",
|
|
pattern: literal,
|
|
})
|
|
).length > 0,
|
|
`Frozen string missing: ${literal}`,
|
|
);
|
|
const observed = await call("read_bytes", {
|
|
address: metadata.virtual_slots[0].slot_address,
|
|
length: 8,
|
|
});
|
|
assert.equal(observed.complete, true);
|
|
assert.equal(
|
|
`0x${Buffer.from(observed.bytes_hex, "hex").readBigUInt64LE().toString(16)}`,
|
|
metadata.virtual_slots[0].target_address,
|
|
);
|
|
report = { mode, target, sha256, summary, derived, compute, dispatch };
|
|
await call("close_binary");
|
|
opened = false;
|
|
// One representative CLI boundary, selected explicitly to avoid repeated
|
|
// full NativeAOT auto-analysis during each focused iteration.
|
|
if (process.env.REA_NATIVEAOT_PROOF_CLI === "1") {
|
|
const { stdout } = await execOwned(
|
|
process.execPath,
|
|
[
|
|
entrypoint,
|
|
"inspect-native-data-type",
|
|
target,
|
|
"--type",
|
|
lookup(derivedAddress),
|
|
"--provider",
|
|
"ghidra",
|
|
"--json",
|
|
],
|
|
{ env, timeout: 360000, maxBuffer: 16 * 1024 * 1024 },
|
|
);
|
|
const evidence = parseEvidence(JSON.parse(stdout));
|
|
assert.equal(evidence.subject.identity.sha256, sha256);
|
|
assert.deepEqual(
|
|
evidence.normalized_result.metadata_recovery,
|
|
metadata,
|
|
);
|
|
report.cli_metadata = evidence.normalized_result.metadata_recovery;
|
|
}
|
|
}
|
|
}
|
|
assert.equal(
|
|
hash(await readFile(target)),
|
|
sha256,
|
|
"Input executable changed",
|
|
);
|
|
if (opened) {
|
|
await call("close_binary");
|
|
opened = false;
|
|
}
|
|
} catch (error) {
|
|
console.error(stderr);
|
|
primaryFailure = error;
|
|
}
|
|
// Close the command owner before release observes the parent tree.
|
|
let cleanupFailure;
|
|
try {
|
|
await workspaceFixture.closeEarly([() => commands.close()]);
|
|
} catch (cause) {
|
|
cleanupFailure = cause;
|
|
}
|
|
if (cleanupFailure !== undefined || primaryFailure !== undefined)
|
|
throw workspaceFixture.retainedError(
|
|
`NativeAOT verification failed; retained diagnostic workspace: ${workspace}`,
|
|
{
|
|
cause:
|
|
cleanupFailure === undefined
|
|
? primaryFailure
|
|
: primaryFailure === undefined
|
|
? cleanupFailure
|
|
: new AggregateError(
|
|
[primaryFailure, cleanupFailure],
|
|
"NativeAOT verification and command cleanup both failed",
|
|
),
|
|
},
|
|
);
|
|
const interrupted = commandInterruption.reason();
|
|
if (interrupted !== undefined)
|
|
throw workspaceFixture.retainedError(
|
|
`NativeAOT verification interrupted; retained diagnostic workspace: ${workspace}`,
|
|
{ cause: interrupted },
|
|
);
|
|
});
|
|
const releaseInterrupted = finishCommandInterruption();
|
|
if (releaseInterrupted !== undefined) throw releaseInterrupted;
|
|
const capture = process.env.REA_NATIVEAOT_PROOF_CAPTURE_DIR;
|
|
if (capture !== undefined) {
|
|
assert.ok(isAbsolute(capture));
|
|
await mkdir(capture, { recursive: true });
|
|
await writeFile(
|
|
join(capture, `${oracle.runtime}-${mode}.json`),
|
|
JSON.stringify(report, null, 2) + "\n",
|
|
);
|
|
}
|
|
const outcome = report.typed_failure
|
|
? "MCP refusal"
|
|
: mode === "default-native"
|
|
? "native load image without metadata recovery"
|
|
: "MCP metadata";
|
|
console.log(
|
|
`PASS real Ghidra NativeAOT ${oracle.runtime}/${mode}: ${outcome}, source unchanged and runtime directory empty${report?.compute ? ", independent type/slot oracle and pseudocode" : ""}${report?.cli_metadata ? ", equivalent CLI" : ""}`,
|
|
);
|
|
|
|
function hash(bytes) {
|
|
return createHash("sha256").update(bytes).digest("hex");
|
|
}
|
|
async function call(name, args = {}) {
|
|
throwIfInterrupted();
|
|
const response = await client.callTool(
|
|
{ name, arguments: args },
|
|
{ timeout: 360000, signal: commandInterruption.signal },
|
|
);
|
|
if (name === "close_binary") return requireMcpLifecycleResult(response, name);
|
|
const evidence = parseEvidence(requireMcpOutput(response, name));
|
|
assert.equal(evidence.subject.identity.sha256, sha256);
|
|
return evidence.normalized_result;
|
|
}
|