feat(analysis): add bounded memory and call tracing

This commit is contained in:
morluto
2026-07-24 13:14:01 +00:00
parent 205bf1529b
commit 8e7709d35a
21 changed files with 1025 additions and 188 deletions
+50 -1
View File
@@ -213,7 +213,7 @@ describe("enhanced MCP tools", () => {
).toEqual(ENHANCED_TOOL_CONTRACTS.map(({ name }) => name).sort());
});
it("executes all ten tools through production registration", async () => {
it("executes all twelve tools through production registration", async () => {
const client = await connect();
const calls = [
["swift_classes", { pattern: "Fixture" }],
@@ -226,6 +226,8 @@ describe("enhanced MCP tools", () => {
["binary_overview", {}],
["analyze_function", { procedure: "0x1" }],
["trace_feature", { query: "hello", max_operations: 10 }],
["find_code_for_string", { query: "hello", max_operations: 10 }],
["trace_call_path", { start: "0x1", goal: "0x2", max_operations: 10 }],
] as const;
const results = await Promise.all(
calls.map(async ([name, arguments_]) =>
@@ -277,6 +279,53 @@ describe("enhanced MCP tools", () => {
{ target_address: "0x30", source_address: "0x21" },
],
});
expect(results[10]).toMatchObject({
query: "hello",
matches: [{ type: "string", address: "0x30", value: "hello" }],
truncated: false,
});
expect(results[11]).toMatchObject({
start: "0x1",
goal: "0x2",
direction: "forward",
goal_status: "reached",
traversal_path: ["0x1", "0x2"],
nodes: [
{ address: "0x1", depth: 0 },
{ address: "0x2", depth: 1 },
],
truncated: false,
});
});
it("returns Evidence IDs and explicit call-path frontiers at limits", async () => {
const client = await connect();
const result = await client.callTool({
name: "trace_call_path",
arguments: {
start: "0x1",
goal: "0x3",
max_nodes: 1,
max_operations: 10,
},
});
expect(result.isError).not.toBe(true);
expect(result.structuredContent).toMatchObject({
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
result: {
goal_status: "not_reached",
nodes: [{ address: "0x1", depth: 0 }],
frontier: ["0x2"],
truncated: true,
residual_unknowns: [expect.stringContaining("reached the node limit")],
limits: {
max_nodes: 1,
nodes_visited: 1,
operations_used: 1,
},
},
});
});
it("bounds batch concurrency at the parsed maximum of 20", async () => {
+2 -5
View File
@@ -7,11 +7,8 @@ import sys
def _load_bridge(path):
source = Path(path).read_text(encoding="utf-8")
prefix, marker, suffix = source.rpartition("\n_run()")
if not marker or suffix.strip():
raise RuntimeError("bridge entrypoint shape changed")
namespace = {"__file__": path}
exec(compile(prefix, path, "exec"), namespace)
namespace = {"__file__": path, "__name__": "rea_hopper_bridge"}
exec(compile(source, path, "exec"), namespace)
return namespace
+10
View File
@@ -8,6 +8,14 @@ const shutdownResult = () => ({
document_closed: shutdownMode !== "unconfirmed",
...(shutdownMode === "cleanup-required" ? { cleanup_required: true } : {}),
});
const capabilityUnavailableResult = (id) => ({
id,
error: {
code: -32000,
message: "fixture API is unavailable",
type: "capability_unavailable",
},
});
const enhancedFixtureResult = (method) => {
switch (method) {
case "list_segments":
@@ -153,6 +161,8 @@ const server = createServer((socket) => {
type: "bridge_exception",
},
});
} else if (request.method === "capability_unavailable") {
send(capabilityUnavailableResult(request.id));
} else if (request.method === "current_document") {
send({ id: request.id, result: "fixture" });
} else if (enhancedFixtureResult(request.method) !== undefined) {
+92
View File
@@ -0,0 +1,92 @@
"""Exercise the Hopper bridge facade without importing Hopper globals."""
import json
from pathlib import Path
import sys
class FakeDocument:
def __init__(self):
self.analysis_active = True
def getDocumentName(self):
return "fixture"
def getExecutableFilePath(self):
return "/tmp/rea-hopper-facade-fixture"
def getDatabaseFilePath(self):
return None
def backgroundProcessActive(self):
return self.analysis_active
def getCurrentAddress(self):
return 0x401000
class FakeDocumentProvider:
document = FakeDocument()
@classmethod
def getAllDocuments(cls):
return [cls.document]
@classmethod
def getCurrentDocument(cls):
return cls.document
def load_bridge(path):
namespace = {
"__file__": path,
"__name__": "rea_hopper_bridge",
}
source = Path(path).read_text(encoding="utf-8")
exec(compile(source, path, "exec"), namespace)
return namespace
def main():
bridge = load_bridge(sys.argv[1])
unavailable = None
try:
bridge["_api"]()
except Exception as error:
unavailable = {
"type": type(error).__name__,
"diagnostic_type": bridge["_diagnostic_type"](error),
}
bridge["REA_TARGET_PATH"] = "/tmp/rea-hopper-facade-fixture"
bridge["_configure_hopper_api"](FakeDocumentProvider)
current = bridge["_dispatch"]("current_document", {})
current_address = bridge["_dispatch"]("current_address", {})
selected = bridge["_session_document"]().getDocumentName()
analysis_guard = None
try:
bridge["_dispatch"]("list_procedures", {"offset": 0, "limit": 1})
except Exception as error:
analysis_guard = {
"type": type(error).__name__,
"diagnostic_type": bridge["_diagnostic_type"](error),
"message": str(error),
}
print(
json.dumps(
{
"imported_without_hopper": unavailable,
"current_document": current,
"current_address": current_address,
"session_document": selected,
"analysis_guard": analysis_guard,
},
sort_keys=True,
)
)
if __name__ == "__main__":
main()
+45
View File
@@ -0,0 +1,45 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { describe, expect, it } from "vitest";
import { z } from "zod";
const execute = promisify(execFile);
const bridgePath = new URL("../bridge/hopper_bridge.py", import.meta.url);
const probePath = new URL(
"./fixtures/hopperBridgeFacadeProbe.py",
import.meta.url,
);
const probeResultSchema = z.strictObject({
imported_without_hopper: z.strictObject({
type: z.literal("CapabilityUnavailableError"),
diagnostic_type: z.literal("capability_unavailable"),
}),
current_document: z.literal("fixture"),
current_address: z.literal("0x401000"),
session_document: z.literal("fixture"),
analysis_guard: z.strictObject({
type: z.literal("CapabilityUnavailableError"),
diagnostic_type: z.literal("capability_unavailable"),
message: z.string(),
}),
});
describe("Hopper API facade", () => {
it("imports without Hopper globals and gates exhaustive work during analysis", async () => {
const { stdout } = await execute(
"python3",
[probePath.pathname, bridgePath.pathname],
{
encoding: "utf8",
timeout: 3_000,
maxBuffer: 1_024 * 1_024,
},
);
const result = probeResultSchema.parse(JSON.parse(stdout));
expect(result.analysis_guard.message).toContain(
"requires completed Hopper background analysis",
);
});
});
+14 -1
View File
@@ -278,7 +278,7 @@ describe("HopperClient", () => {
const results = await Promise.all(
OFFICIAL_TOOL_CONTRACTS.map(({ name }) => client.callTool(name, {})),
);
expect(results).toHaveLength(34);
expect(results).toHaveLength(36);
expect(results.every((result) => result.ok)).toBe(true);
});
@@ -317,6 +317,19 @@ describe("HopperClient", () => {
});
});
it("projects a missing bridge API as typed capability unavailability", async () => {
const client = await startClient();
const result = await client.callTool("capability_unavailable");
expect(result.ok).toBe(false);
if (!result.ok)
expect(result.error).toMatchObject({
_tag: "AnalysisCapabilityUnavailableError",
providerId: "hopper",
operation: "capability_unavailable",
reason: "fixture API is unavailable",
});
});
it("cancels and ignores late responses without corrupting the session", async () => {
const client = await startClient();
const controller = new AbortController();
+20
View File
@@ -50,6 +50,26 @@ describe("Hopper provider discovery", () => {
code: "architecture_unsupported",
});
});
it("advertises the exact bounded byte-read limit", () => {
const capabilities = provider(process.execPath).capabilities();
expect(
capabilities.find(({ operation }) => operation === "read_bytes"),
).toMatchObject({
available: true,
pagination: "none",
limits: {
maxResults: null,
maxPayloadBytes: 4_096,
timeoutMs: null,
},
});
expect(
capabilities.find(
({ operation }) => operation === "address_to_file_offset",
),
).toMatchObject({ available: true, pagination: "none" });
});
});
const provider = (launcherPath: string): HopperProvider => {
+12
View File
@@ -33,6 +33,8 @@ const VALID_INPUTS: Readonly<
procedure_callers: { procedure: "main" },
procedure_info: { procedure: "main" },
read_function_instructions: { procedure: "main" },
read_bytes: { address: "0x1000", length: 4 },
address_to_file_offset: { address: "0x1000" },
procedure_references: { procedure: "main" },
procedure_pseudo_code: { procedure: "main" },
resolve_containing_procedure: { address: "0x1000" },
@@ -130,6 +132,16 @@ const outputFor = (name: string): JsonValue => {
instruction_scan_truncated: false,
limitations: ["Provider-specific instruction text."],
};
if (name === "read_bytes")
return {
address: "0x1000",
requested_bytes: 4,
returned_bytes: 4,
bytes_hex: "c3c3c3c3",
complete: true,
};
if (name === "address_to_file_offset")
return { address: "0x1000", file_offset: 0 };
if (name === "procedure_references")
return {
procedure: { address: "0x1000", name: "main" },
+1 -1
View File
@@ -78,7 +78,7 @@ describe("provider-neutral architecture", () => {
if (!config.ok) return;
const provider = new HopperProvider(config.value, silentLogger);
const capabilities = provider.capabilities();
expect(capabilities).toHaveLength(35);
expect(capabilities).toHaveLength(37);
expect(new Set(capabilities.map(({ operation }) => operation)).size).toBe(
capabilities.length,
);