refactor(evm): bind offline analysis through a static descriptor
Share the exact existing operation, CLI name and legacy factory. Pass the selected complete service to registration and cleanup without rebuilding it or wrapping injection identity. Verify SDK schemas, duplicate registration, malformed/optional failures, healthy peers, cancellation recovery and failed-cleanup retry. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
parent
2b61852fe2
commit
152984da77
@@ -6,7 +6,7 @@ graph TD
|
||||
end
|
||||
|
||||
subgraph "Production Composition"
|
||||
COMPOSITION["src/composition/<br/>fresh typed provider and session factories<br/>one-shot binding and independent optional loading<br/>static WASM descriptor: named contract, factory, retryable lifetime"]
|
||||
COMPOSITION["src/composition/<br/>fresh typed provider and session factories<br/>one-shot binding and independent optional loading<br/>static WASM/EVM descriptors: named contracts, factories, retryable lifetimes"]
|
||||
end
|
||||
|
||||
subgraph "Adapters"
|
||||
|
||||
@@ -1,11 +1,28 @@
|
||||
# EVM descriptor and real-template checkpoint
|
||||
|
||||
Continues [#2016](https://github.com/morluto/rea/issues/2016) after the native
|
||||
checkpoint merged. The next internal descriptor will bind the existing exact EVM
|
||||
checkpoint merged. The internal descriptor binds the existing exact EVM
|
||||
contract, CLI name and typed service lifetime. Existing complete inputs, output,
|
||||
provider selection and cleanup remain the baseline. Wiring alone does not establish
|
||||
token or latency savings.
|
||||
|
||||
The descriptor contains only the named contract, existing CLI name and existing
|
||||
factory. The legacy `createEvmInterfaceService` export remains usable. The MCP
|
||||
host selects one complete service instance, preserves injection identity, passes
|
||||
that same instance to registration and retains it for cleanup/retry. No bound
|
||||
service wrapper, generic registry, automatic dependency acquisition or new pack
|
||||
selection is introduced.
|
||||
|
||||
Five actual in-memory SDK boundary scenarios verify converted schemas, duplicate
|
||||
registration rejection before use, malformed inputs, explicit unavailable or
|
||||
incompatible-output failures with a healthy WASM peer, cleanup retry, and request
|
||||
cancellation followed by recovery. Their injected ports are recording seams, not
|
||||
real EVMole/WABT claims. Nine service and 26 provider-boundary cases also pass;
|
||||
two unsupported-host scenarios are skipped on this Linux host. The existing seven
|
||||
WASM MCP scenarios pass. Full `npm run check` passes; its approximately 3 GiB
|
||||
sampled peak and `memory.high` events are excluded from performance claims.
|
||||
Fresh candidate real-artifact/catalog and model comparisons are still pending.
|
||||
|
||||
## Public inputs and independent checks
|
||||
|
||||
[corpus.json](corpus.json) retains the original WETH historical example and adds
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { z } from "incur";
|
||||
import { resolve } from "node:path";
|
||||
import { createEvmInterfaceService } from "../composition/evm.js";
|
||||
import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
import { evmInterfaceModule } from "../composition/evm.js";
|
||||
import { logCliCommand } from "../cliLogging.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import type { Logger } from "pino";
|
||||
@@ -14,8 +13,8 @@ export const registerEvmCommands = (
|
||||
logger: Logger,
|
||||
environment: Readonly<NodeJS.ProcessEnv>,
|
||||
): void => {
|
||||
const service = createEvmInterfaceService(environment);
|
||||
cli.command(CLI_COMMANDS.inspectEvmInterface, {
|
||||
const service = evmInterfaceModule.create(environment);
|
||||
cli.command(evmInterfaceModule.cliCommand, {
|
||||
description: "Infer interface candidates from explicit local EVM bytecode",
|
||||
args: z.object({
|
||||
path: z.string().describe("Local bytecode carrier"),
|
||||
@@ -28,7 +27,7 @@ export const registerEvmCommands = (
|
||||
try {
|
||||
return await logCliCommand(
|
||||
logger,
|
||||
CLI_COMMANDS.inspectEvmInterface,
|
||||
evmInterfaceModule.cliCommand,
|
||||
async () => {
|
||||
const result = await service.inspect(
|
||||
{ path: resolve(args.path), encoding: args.encoding },
|
||||
|
||||
@@ -1,8 +1,21 @@
|
||||
import { EvmInterfaceService } from "../application/evm/EvmInterfaceService.js";
|
||||
import { EvmoleInterfaceProvider } from "../evm/EvmoleInterfaceProvider.js";
|
||||
import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
import { INSPECT_EVM_INTERFACE_CONTRACT } from "../contracts/evm/evmToolContracts.js";
|
||||
|
||||
/** Compose offline interface analysis without import-time I/O or dependency acquisition. */
|
||||
export const createEvmInterfaceService = (
|
||||
environment: Readonly<NodeJS.ProcessEnv> = process.env,
|
||||
): EvmInterfaceService =>
|
||||
new EvmInterfaceService(new EvmoleInterfaceProvider(environment));
|
||||
|
||||
/**
|
||||
* Static binding of the existing operation, command and fresh service factory.
|
||||
* The host owns injected service identity and its retryable cleanup lifetime.
|
||||
* Construction performs no acquisition, target I/O or import-time execution.
|
||||
*/
|
||||
export const evmInterfaceModule = {
|
||||
contract: INSPECT_EVM_INTERFACE_CONTRACT,
|
||||
cliCommand: CLI_COMMANDS.inspectEvmInterface,
|
||||
create: createEvmInterfaceService,
|
||||
} as const;
|
||||
|
||||
@@ -7,20 +7,23 @@ import { toolContractMetadata } from "../toolEffects.js";
|
||||
import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js";
|
||||
|
||||
/** Target-free EVM capabilities are independent of archive/Apple artifact providers. */
|
||||
export const INSPECT_EVM_INTERFACE_CONTRACT = {
|
||||
name: "inspect_evm_interface",
|
||||
...toolContractMetadata("inspect_evm_interface"),
|
||||
kind: "artifact-provider",
|
||||
description:
|
||||
"Inspect an explicit local flat EVM bytecode carrier and infer dispatch selectors, argument strings and mutability without executing the target or accessing a chain/RPC endpoint. Choose raw or hex encoding explicitly. Returns original carrier and decoded-byte SHA-256, full bytecode and interface candidates inline as inferred Evidence; bytecode kind, hardfork, deployed authenticity and discovery completeness remain unknown. Initial real-verified Linux x64 profile uses unchanged bundled EVMole 0.9.3/WASM in a bounded owned worker; EOF-style EF00 containers are unsupported. No signature lookup, wallet action or transaction broadcast.",
|
||||
inputSchema: inspectEvmInterfaceInputSchema,
|
||||
outputSchema: evidenceResultOf(evmInterfaceSchema),
|
||||
examples: [
|
||||
{
|
||||
title: "Inspect a local runtime bytecode hex carrier",
|
||||
input: { path: "/artifacts/runtime.hex", encoding: "hex" },
|
||||
},
|
||||
],
|
||||
} as const satisfies ToolContract;
|
||||
|
||||
/** Preserve the default catalog's exact operation and ordering. */
|
||||
export const EVM_TOOL_CONTRACTS = [
|
||||
{
|
||||
name: "inspect_evm_interface",
|
||||
...toolContractMetadata("inspect_evm_interface"),
|
||||
kind: "artifact-provider",
|
||||
description:
|
||||
"Inspect an explicit local flat EVM bytecode carrier and infer dispatch selectors, argument strings and mutability without executing the target or accessing a chain/RPC endpoint. Choose raw or hex encoding explicitly. Returns original carrier and decoded-byte SHA-256, full bytecode and interface candidates inline as inferred Evidence; bytecode kind, hardfork, deployed authenticity and discovery completeness remain unknown. Initial real-verified Linux x64 profile uses unchanged bundled EVMole 0.9.3/WASM in a bounded owned worker; EOF-style EF00 containers are unsupported. No signature lookup, wallet action or transaction broadcast.",
|
||||
inputSchema: inspectEvmInterfaceInputSchema,
|
||||
outputSchema: evidenceResultOf(evmInterfaceSchema),
|
||||
examples: [
|
||||
{
|
||||
title: "Inspect a local runtime bytecode hex carrier",
|
||||
input: { path: "/artifacts/runtime.hex", encoding: "hex" },
|
||||
},
|
||||
],
|
||||
},
|
||||
INSPECT_EVM_INTERFACE_CONTRACT,
|
||||
] as const satisfies readonly ToolContract[];
|
||||
|
||||
@@ -5,7 +5,7 @@ import { snapshotEnvironment } from "../process/snapshotEnvironment.js";
|
||||
import { createPeResourcesService } from "../composition/binaryDiagnostics.js";
|
||||
import { registerPeResourcesTool } from "./registerPeResourcesTool.js";
|
||||
import type { EvmInterfaceService } from "../application/evm/EvmInterfaceService.js";
|
||||
import { createEvmInterfaceService } from "../composition/evm.js";
|
||||
import { evmInterfaceModule } from "../composition/evm.js";
|
||||
import { registerEvmTools } from "./registerEvmTools.js";
|
||||
import { registerRecordedCrashTools } from "./registerRecordedCrashTools.js";
|
||||
import { createRecordedCrashService } from "../composition/binaryDiagnostics.js";
|
||||
@@ -242,7 +242,7 @@ export const createServer = (
|
||||
const environment = snapshotEnvironment(options.environment ?? process.env);
|
||||
const delivery = selectToolResultDelivery(environment, options.delivery);
|
||||
const evmInterface =
|
||||
options.evmInterface ?? createEvmInterfaceService(environment);
|
||||
options.evmInterface ?? evmInterfaceModule.create(environment);
|
||||
const webSourceLocation =
|
||||
options.webSourceLocation ?? createWebSourceLocationService(environment);
|
||||
const webModuleTrace =
|
||||
@@ -372,6 +372,7 @@ export const createServer = (
|
||||
toolContext,
|
||||
android,
|
||||
wasmArtifact,
|
||||
evmInterface,
|
||||
jeb,
|
||||
firmwareAnalysis,
|
||||
);
|
||||
@@ -449,6 +450,7 @@ const registerConfiguredAnalysisTools = (
|
||||
}: ServerToolContext,
|
||||
android: AndroidAnalysisPort,
|
||||
wasmArtifact: Pick<WasmArtifactService, "inspect" | "close">,
|
||||
evmInterface: EvmInterfaceService,
|
||||
jeb: JebAnalysisPort,
|
||||
firmwareAnalysis: FirmwareAnalysisService,
|
||||
): void => {
|
||||
@@ -505,7 +507,7 @@ const registerConfiguredAnalysisTools = (
|
||||
);
|
||||
registerEvmTools(
|
||||
server,
|
||||
options.evmInterface ?? createEvmInterfaceService(environment),
|
||||
evmInterface,
|
||||
toolLogger,
|
||||
recordEvidence,
|
||||
withAdmittedAnalysis,
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
|
||||
|
||||
import type { EvmInterfaceService } from "../application/evm/EvmInterfaceService.js";
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import { toolContract } from "../contracts/toolContracts.js";
|
||||
import { evmInterfaceModule } from "../composition/evm.js";
|
||||
import type { Logger } from "pino";
|
||||
import type { WithAdmittedAnalysis } from "./analysisAdmission.js";
|
||||
import { createEvidenceToolHandler } from "./contractToolHandler.js";
|
||||
@@ -16,7 +16,7 @@ export const registerEvmTools = (
|
||||
recordEvidence?: EvidenceWriter["recordEvidence"],
|
||||
withAdmittedAnalysis?: WithAdmittedAnalysis,
|
||||
): void => {
|
||||
const contract = toolContract("inspect_evm_interface");
|
||||
const contract = evmInterfaceModule.contract;
|
||||
const handler = createEvidenceToolHandler(
|
||||
server,
|
||||
(input, options) => service.inspect(input, options),
|
||||
|
||||
@@ -1,12 +1,25 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { expect, it, onTestFinished } from "vitest";
|
||||
import { expect, it, onTestFinished, vi } from "vitest";
|
||||
import { EvmInterfaceService } from "../../../src/application/evm/EvmInterfaceService.js";
|
||||
import { WasmArtifactService } from "../../../src/application/wasm/WasmArtifactService.js";
|
||||
import { toolContract } from "../../../src/contracts/toolContracts.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
} from "../../../src/domain/analysisErrorCore.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { ok } from "../../../src/domain/result.js";
|
||||
import { err, ok } from "../../../src/domain/result.js";
|
||||
import { silentLogger } from "../../../src/logger.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import { registerEvmTools } from "../../../src/server/registerEvmTools.js";
|
||||
import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";
|
||||
import {
|
||||
createDeferred,
|
||||
createTestBinarySession,
|
||||
} from "../../fixtures/binarySession.js";
|
||||
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
|
||||
import { wasmArtifactExecution } from "../../fixtures/wasm/artifact.js";
|
||||
import {
|
||||
evmInterfaceFixture,
|
||||
evmInterfaceExecution,
|
||||
@@ -54,6 +67,14 @@ it("advertises exact valid schemas and records inline EVM interface evidence wit
|
||||
approval: true,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(() => registerEvmTools(server, service, silentLogger)).toThrow(
|
||||
/inspect_evm_interface.*already registered/,
|
||||
);
|
||||
expect(
|
||||
(await client.listTools()).tools.filter(
|
||||
(tool) => tool.name === "inspect_evm_interface",
|
||||
),
|
||||
).toHaveLength(1);
|
||||
const response = await client.callTool({
|
||||
name: "inspect_evm_interface",
|
||||
arguments: { path: value.artifact.path, encoding: "hex" },
|
||||
@@ -80,3 +101,151 @@ it("advertises exact valid schemas and records inline EVM interface evidence wit
|
||||
).isError,
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it.each(["unavailable", "incompatible-output"])(
|
||||
"preserves a healthy WASM peer and explicit EVM failure: %s",
|
||||
async (scenario) => {
|
||||
const value = evmInterfaceFixture();
|
||||
const inspect = vi.fn(() =>
|
||||
Promise.resolve(
|
||||
scenario === "unavailable"
|
||||
? err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"fixture-evm",
|
||||
"inspect_evm_interface",
|
||||
"selected engine unavailable",
|
||||
),
|
||||
)
|
||||
: ok(
|
||||
evmInterfaceExecution({
|
||||
...value,
|
||||
artifact: { ...value.artifact, encoding: "raw" },
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const harness = await createApplicationMcpHarness({
|
||||
serverOptions: {
|
||||
evmInterface: new EvmInterfaceService({ inspect }),
|
||||
wasmArtifact: new WasmArtifactService({
|
||||
close: () => Promise.resolve(),
|
||||
inspect: () => Promise.resolve(ok(wasmArtifactExecution())),
|
||||
}),
|
||||
},
|
||||
});
|
||||
onTestFinished(harness.close);
|
||||
const invalid = await harness.client.callTool({
|
||||
name: "inspect_evm_interface",
|
||||
arguments: { path: value.artifact.path, encoding: "hex", approval: true },
|
||||
});
|
||||
expect(invalid.isError).toBe(true);
|
||||
expect(inspect).not.toHaveBeenCalled();
|
||||
const failure = await harness.client.callTool({
|
||||
name: "inspect_evm_interface",
|
||||
arguments: { path: value.artifact.path, encoding: "hex" },
|
||||
});
|
||||
expect(parseMcpToolError(failure).error.code).toBe(
|
||||
scenario === "unavailable"
|
||||
? "capability_unavailable"
|
||||
: "unreadable_output",
|
||||
);
|
||||
const peer = await harness.client.callTool({
|
||||
name: "inspect_wasm_artifact",
|
||||
arguments: { path: "/artifacts/module.wasm" },
|
||||
});
|
||||
expect(peer.isError).not.toBe(true);
|
||||
const parsed = toolContract("inspect_wasm_artifact").outputSchema.parse(
|
||||
peer.structuredContent,
|
||||
);
|
||||
const evidence = parseEvidence(parsed);
|
||||
expect(harness.session.evidenceById(evidence.evidence_id)).toEqual(
|
||||
evidence,
|
||||
);
|
||||
await harness.client.ping();
|
||||
},
|
||||
);
|
||||
|
||||
it("retains the injected EVM owner and retries failed cleanup on server shutdown", async () => {
|
||||
const close = vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(new Error("retained EVM worker"))
|
||||
.mockResolvedValue(undefined);
|
||||
const service = new EvmInterfaceService({
|
||||
close,
|
||||
inspect: () => Promise.resolve(ok(evmInterfaceExecution())),
|
||||
});
|
||||
const session = createTestBinarySession(() => {
|
||||
throw new Error("deep provider must not start");
|
||||
});
|
||||
const server = createServer(
|
||||
{ kind: "session", session },
|
||||
{ evmInterface: service },
|
||||
);
|
||||
const client = new Client({ name: "evm-cleanup-retry", version: "1" });
|
||||
const [a, b] = InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(b);
|
||||
await client.connect(a);
|
||||
const response = await client.callTool({
|
||||
name: "inspect_evm_interface",
|
||||
arguments: { path: "/artifacts/source-owned.hex", encoding: "hex" },
|
||||
});
|
||||
expect(response.isError).not.toBe(true);
|
||||
await expect(server.close()).rejects.toThrow("REA session cleanup failed");
|
||||
await server.close();
|
||||
expect(close).toHaveBeenCalledTimes(2);
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("settles the admitted EVM operation after SDK cancellation and accepts a subsequent request", async () => {
|
||||
const entered = createDeferred<void>();
|
||||
const stopped = createDeferred<void>();
|
||||
let invocations = 0;
|
||||
const harness = await createApplicationMcpHarness({
|
||||
serverOptions: {
|
||||
evmInterface: new EvmInterfaceService({
|
||||
inspect: async (_input, options) => {
|
||||
if (invocations++ > 0) return ok(evmInterfaceExecution());
|
||||
const signal = options?.signal;
|
||||
if (signal === undefined)
|
||||
throw new Error("MCP request omitted cancellation signal");
|
||||
const aborted = new Promise<void>((resolve) => {
|
||||
if (signal.aborted) resolve();
|
||||
else
|
||||
signal.addEventListener("abort", () => resolve(), { once: true });
|
||||
});
|
||||
entered.resolve();
|
||||
await aborted;
|
||||
stopped.resolve();
|
||||
return err(new AnalysisCancelledError("inspect_evm_interface"));
|
||||
},
|
||||
}),
|
||||
},
|
||||
});
|
||||
onTestFinished(harness.close);
|
||||
const controller = new AbortController();
|
||||
const input = {
|
||||
name: "inspect_evm_interface",
|
||||
arguments: { path: "/artifacts/source-owned.hex", encoding: "hex" },
|
||||
};
|
||||
const cancellation = harness.client
|
||||
.callTool(input, { signal: controller.signal })
|
||||
.then(
|
||||
() => "completed",
|
||||
(error: unknown) => error,
|
||||
);
|
||||
await entered.promise;
|
||||
controller.abort(new Error("SDK EVM cancellation verification"));
|
||||
expect(await cancellation).toMatchObject({
|
||||
message: expect.stringContaining("SDK EVM cancellation verification"),
|
||||
code: "REQUEST_TIMEOUT",
|
||||
});
|
||||
await stopped.promise;
|
||||
await harness.client.ping();
|
||||
expect((await harness.client.callTool(input)).isError).not.toBe(true);
|
||||
expect(invocations).toBe(2);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user