fix(hopper): add bounded analysis recovery

This commit is contained in:
N0zoM1z0
2026-07-24 00:33:29 +09:00
committed by N0zoM1z0
parent 161377a505
commit e0bc7fd973
68 changed files with 1750 additions and 368 deletions
+74
View File
@@ -14,6 +14,7 @@ import {
HopperStartError,
ProviderAdapterError,
} from "../src/domain/errors.js";
import { ProviderCleanupError } from "../src/domain/providerCleanupError.js";
import { err, ok as resultOk } from "../src/domain/result.js";
import { createEvidenceBundle } from "../src/domain/evidenceBundle.js";
import { createAnalysisProfile } from "../src/domain/analysisProfile.js";
@@ -123,6 +124,19 @@ describe("binary session", () => {
},
},
],
requestActivitySnapshots: () => [
{
provider: provider.identity(),
active: {
requestId: 7,
operation: "analyze_function",
elapsedMs: 31_000,
timeoutMs: 30_000,
callerState: "timed_out",
},
queuedRequests: 2,
},
],
close: () => Promise.resolve(),
};
},
@@ -184,6 +198,22 @@ describe("binary session", () => {
],
},
},
analysis_activity: {
status: "timed_out_busy",
providers: [
{
provider: { id: "fixture", name: "Fixture", version: "1" },
active: {
request_id: 7,
operation: "analyze_function",
elapsed_ms: 31_000,
timeout_ms: 30_000,
caller_state: "timed_out",
},
queued_requests: 2,
},
],
},
});
expect(operations).toEqual(["health", "address_name"]);
await session.close();
@@ -724,6 +754,50 @@ describe("binary session", () => {
expect(overlapped).toBe(false);
await session.close();
});
it("clears session state while preserving a typed provider cleanup failure", async () => {
const [first] = await targets();
const cleanupError = new ProviderCleanupError(
"fixture",
["fixture-document"],
{ reason: "shutdown acknowledgement missing" },
);
const session = new BinarySession(() => ({
execute: () => Promise.resolve(ok(null)),
closeWithOutcome: () => Promise.resolve(err(cleanupError)),
close: () => Promise.resolve(),
}));
expect((await session.open(first)).ok).toBe(true);
expect(await session.close()).toEqual(err(cleanupError));
expect(session.status()).toMatchObject({
open: false,
analysis_activity: { status: "not_observed", providers: [] },
});
});
it("does not start a replacement after the active provider cleanup is unconfirmed", async () => {
const [first, second] = await targets();
const cleanupError = new ProviderCleanupError(
"fixture",
["fixture-document"],
{ reason: "shutdown acknowledgement missing" },
);
let created = 0;
const session = new BinarySession(() => {
created += 1;
return {
execute: () => Promise.resolve(ok(null)),
closeWithOutcome: () => Promise.resolve(err(cleanupError)),
close: () => Promise.resolve(),
};
});
expect((await session.open(first)).ok).toBe(true);
expect(await session.open(second)).toEqual(err(cleanupError));
expect(created).toBe(1);
expect(session.status()).toMatchObject({ open: false });
});
});
const client = (fail = false): AnalysisClient => ({
+16
View File
@@ -55,6 +55,22 @@ describe("Hopper bridge truthfulness", () => {
expect(bridgeSource).toContain('params.get("collection_offset", {})');
});
it("provides a raw-instruction fast path without decompilation or global scans", () => {
const start = bridgeSource.indexOf("def _read_function_instructions");
const end = bridgeSource.indexOf("\ndef _analyze_function", start);
const implementation = bridgeSource.slice(start, end);
expect(implementation).toContain("_instruction_addresses(");
expect(implementation).toContain("offset + limit + 1");
expect(implementation).not.toContain("decompile(");
expect(implementation).not.toContain("_search_inventory(");
expect(implementation).not.toContain("_strings(");
expect(implementation).not.toContain("_name_map(");
expect(bridgeSource).toContain(
"pseudo = _pseudocode(document, procedure) or",
);
expect(bridgeSource).toContain("return _pseudocode(document, procedure)");
});
it("projects opaque Hopper locals into an exact provenance-bearing shape", () => {
expect(bridgeSource).toContain("def _procedure_locals(procedure):");
expect(bridgeSource).toContain('"description": str(local)');
+1 -1
View File
@@ -18,7 +18,7 @@ the read-only Ghidra inventory contracts without committing a binary.
`scripts/create-ghidra-windows-fixture.mjs` separately emits a deterministic,
ignored native x86-64 PE application for the controlled Windows Ghidra P0 lane.
The generator and fixed SHA-256 are versioned; the `.exe` is never committed or
executed. `npm run verify:ghidra:windows` uses it to prove all 18 operations,
executed. `npm run verify:ghidra:windows` uses it to prove all 19 operations,
digest linkage, transport, and cleanup on the self-hosted real-Ghidra runner.
The C fixture fixes a known call chain and strings. The version pair fixes an
+1 -1
View File
@@ -546,7 +546,7 @@ describe("enhanced MCP tools", () => {
arguments: { detail: "detailed", limit: 1 },
}),
);
expect(procedureOffsets).toEqual([0, 500]);
expect(procedureOffsets).toEqual([0]);
expect(result).toEqual({
document: "fixture",
detail: "detailed",
+2 -1
View File
@@ -176,7 +176,7 @@ const sessionInfo = ({
timedOut,
}) => ({
name: "REA Ghidra bridge",
bridge_version: 4,
bridge_version: 5,
run_id: sessionRunId,
profile_digest: digest,
provider: { id: "ghidra", version },
@@ -202,6 +202,7 @@ const sessionInfo = ({
"procedure_callers",
"procedure_info",
"procedure_pseudo_code",
"read_function_instructions",
"procedure_references",
"xrefs",
],
+1 -1
View File
@@ -5,7 +5,7 @@ const [socketPath, token, runId, shutdownMode = "acknowledge"] =
const shutdownResult = () => ({
shutdown: true,
analysis_stopped: true,
document_closed: true,
document_closed: shutdownMode !== "unconfirmed",
...(shutdownMode === "cleanup-required" ? { cleanup_required: true } : {}),
});
const enhancedFixtureResult = (method) => {
+1 -1
View File
@@ -156,7 +156,7 @@ describe("GhidraClient", () => {
await expect(client.start()).resolves.toMatchObject({
ok: true,
value: {
bridge_version: 4,
bridge_version: 5,
target: { sha256: TARGET_SHA256 },
},
});
+39 -1
View File
@@ -52,6 +52,19 @@ describe("Ghidra function-analysis boundary values", () => {
collection_offset: { basic_blocks: 0, outgoing_references: 0 },
},
});
expect(
parseGhidraFunctionInput("read_function_instructions", {
procedure: "main",
}),
).toEqual({
ok: true,
value: {
document: null,
procedure: "main",
offset: 0,
limit: 64,
},
});
expect(parseGhidraFunctionInput("xrefs", {})).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
@@ -65,14 +78,39 @@ describe("Ghidra function-analysis boundary values", () => {
});
it("keeps the admitted operation set closed", () => {
expect(GHIDRA_FUNCTION_OPERATIONS).toHaveLength(8);
expect(GHIDRA_FUNCTION_OPERATIONS).toHaveLength(9);
expect(isGhidraFunctionOperation("analyze_function")).toBe(true);
expect(isGhidraFunctionOperation("read_function_instructions")).toBe(true);
expect(isGhidraFunctionOperation("procedure_pseudo_code")).toBe(true);
expect(isGhidraFunctionOperation("list_procedures")).toBe(false);
expect(isGhidraFunctionOperation("set_comment")).toBe(false);
});
it("parses provider-classified function facts and reference kinds", () => {
expect(
parseGhidraFunctionResult("read_function_instructions", {
procedure: ghidraFunctionIdentity(),
instructions: ghidraBounded(["0x401000: push rbp"]),
instructions_scanned: 1,
instruction_scan_truncated: false,
limitations: ["Ghidra-specific instruction text."],
}),
).toMatchObject({ ok: true });
expect(
parseGhidraFunctionResult("read_function_instructions", {
procedure: {
...ghidraFunctionIdentity(),
address: "0X401000",
},
instructions: ghidraBounded(["0x401000: push rbp"]),
instructions_scanned: 1,
instruction_scan_truncated: false,
limitations: ["Ghidra-specific instruction text."],
}),
).toMatchObject({
ok: false,
error: { _tag: "AnalysisOutputError" },
});
expect(
parseGhidraFunctionResult("procedure_info", {
name: "fixture_main",
+14 -4
View File
@@ -306,7 +306,7 @@ const installationHost = (): GhidraInstallationHost => ({
const sessionInfo = (profileDigest: string, targetSha256: string) => ({
name: "REA Ghidra bridge" as const,
bridge_version: 4 as const,
bridge_version: 5 as const,
run_id: "11111111-1111-4111-8111-111111111111",
profile_digest: profileDigest,
provider: { id: "ghidra" as const, version: "12.1.2" },
@@ -430,6 +430,16 @@ const resultBuilders = new Map<GhidraOperation, GhidraResultBuilder>([
}),
],
["procedure_pseudo_code", () => "int fixture_main(void) { return 42; }"],
[
"read_function_instructions",
() => ({
procedure: ghidraFunctionIdentity(),
instructions: ghidraBounded(["0x401000: CALL 0x401020", "0x401005: RET"]),
instructions_scanned: 2,
instruction_scan_truncated: false,
limitations: ["Ghidra-specific instruction text."],
}),
],
[
"procedure_references",
(input, _limit) => ({
@@ -459,12 +469,12 @@ const resultFor = (
};
const page = (items: readonly JsonValue[], limit: number): JsonValue => ({
items: [...items],
items: items.slice(0, limit),
offset: 0,
limit,
total: items.length,
next_offset: null,
has_more: false,
next_offset: items.length > limit ? limit : null,
has_more: items.length > limit,
});
const stringItem = (address: string, value: string): JsonValue => ({
+2 -2
View File
@@ -48,7 +48,7 @@ describe("Ghidra provider", () => {
expect(ghidra.capabilities().map(({ operation }) => operation)).toEqual(
GHIDRA_PROVIDER_TOOL_CONTRACTS.map(({ name }) => name),
);
expect(GHIDRA_PROVIDER_TOOL_CONTRACTS).toHaveLength(18);
expect(GHIDRA_PROVIDER_TOOL_CONTRACTS).toHaveLength(19);
expect(Object.isFrozen(ghidra.capabilities())).toBe(true);
expect(ghidra.capabilities()).toEqual(
expect.arrayContaining([
@@ -389,7 +389,7 @@ describe("Ghidra provider", () => {
const sessionInfo = () => ({
name: "REA Ghidra bridge" as const,
bridge_version: 4 as const,
bridge_version: 5 as const,
run_id: "11111111-1111-4111-8111-111111111111",
profile_digest: "a".repeat(64),
provider: { id: "ghidra" as const, version: "12.1.2" },
+99 -2
View File
@@ -7,6 +7,7 @@ import { afterEach, describe, expect, it } from "vitest";
import { OFFICIAL_TOOL_CONTRACTS } from "../src/contracts/toolContracts.js";
import type { HopperStartupDiagnostic } from "../src/domain/hopperStartupFailure.js";
import { projectAnalysisError } from "../src/domain/errors.js";
import { ok } from "../src/domain/result.js";
import type {
BridgeLauncher,
@@ -106,6 +107,27 @@ class OwnedFixtureLauncher implements BridgeLauncher {
}
}
class UnconfirmedFixtureLauncher implements BridgeLauncher {
launch(session: BridgeSession) {
return Promise.resolve(
ok({
process: spawn(
process.execPath,
[
fixturePath,
session.socketPath,
session.token,
session.runId,
"unconfirmed",
],
{ stdio: ["ignore", "ignore", "pipe"] },
),
ownsProcessLifetime: false,
}),
);
}
}
class CancelThenFixtureLauncher implements BridgeLauncher {
#launches = 0;
@@ -235,10 +257,16 @@ describe("HopperClient", () => {
expect(Buffer.byteLength(launcher.socketPaths[0] ?? "")).toBeLessThan(104);
});
it("parses fragmented health and correlates concurrent responses", async () => {
it("serializes concurrent calls until the active Hopper reply arrives", async () => {
const client = await startClient();
const slow = client.callTool("echo", { label: "slow", delay: 30 });
const fast = client.callTool("echo", { label: "fast", delay: 1 });
let fastSettled = false;
void fast.then(() => {
fastSettled = true;
});
await new Promise((resolve) => setTimeout(resolve, 10));
expect(fastSettled).toBe(false);
await expect(Promise.all([slow, fast])).resolves.toEqual([
{ ok: true, value: { label: "slow", delay: 30 } },
{ ok: true, value: { label: "fast", delay: 1 } },
@@ -250,7 +278,7 @@ describe("HopperClient", () => {
const results = await Promise.all(
OFFICIAL_TOOL_CONTRACTS.map(({ name }) => client.callTool(name, {})),
);
expect(results).toHaveLength(33);
expect(results).toHaveLength(34);
expect(results.every((result) => result.ok)).toBe(true);
});
@@ -312,6 +340,45 @@ describe("HopperClient", () => {
});
});
it("retains timed-out bridge activity until the late reply releases the queue", async () => {
const client = await startClient();
const progress: string[] = [];
const result = await client.callTool(
"echo",
{ delay: 60 },
{
timeoutMs: 5,
progress: {
report: (update) => {
progress.push(update.message);
return Promise.resolve();
},
},
},
);
expect(result).toMatchObject({
ok: false,
error: { _tag: "HopperTimeoutError" },
});
expect(client.requestActivity()).toMatchObject({
operation: "echo",
callerState: "timed_out",
timeoutMs: 5,
});
expect(progress).toEqual(
expect.arrayContaining([
expect.stringContaining("started on Hopper's serial bridge"),
]),
);
await new Promise((resolve) => setTimeout(resolve, 70));
expect(client.requestActivity()).toBeNull();
await expect(client.callTool("echo", { alive: true })).resolves.toEqual({
ok: true,
value: { alive: true },
});
});
it("cancels bridge startup without waiting for the startup timeout", async () => {
const client = new HopperClient({
launcher: new CancelThenFixtureLauncher(),
@@ -441,6 +508,36 @@ describe("HopperClient", () => {
await first;
});
it("reports unconfirmed unowned document cleanup as a typed close failure", async () => {
const client = new HopperClient({
launcher: new UnconfirmedFixtureLauncher(),
startupTimeoutMs: 1_000,
});
clients.push(client);
expect((await client.start()).ok).toBe(true);
const closed = await client.closeWithOutcome();
expect(closed).toMatchObject({
ok: false,
error: {
_tag: "ProviderAdapterError",
cleanupIncomplete: true,
cleanupResources: ["hopper-document"],
},
});
if (!closed.ok)
expect(projectAnalysisError(closed.error)).toMatchObject({
code: "cleanup_incomplete",
details: {
provider_id: "hopper",
operation: "close_binary",
cleanup: "incomplete",
resources: ["hopper-document"],
},
});
});
it("kills only its owned Hopper group and emits sanitized shutdown coordinates", async () => {
const unrelated = spawn(
process.execPath,
+15
View File
@@ -32,6 +32,7 @@ const VALID_INPUTS: Readonly<
procedure_callees: { procedure: "main" },
procedure_callers: { procedure: "main" },
procedure_info: { procedure: "main" },
read_function_instructions: { procedure: "main" },
procedure_references: { procedure: "main" },
procedure_pseudo_code: { procedure: "main" },
resolve_containing_procedure: { address: "0x1000" },
@@ -115,6 +116,20 @@ const outputFor = (name: string): JsonValue => {
found: true,
procedure: { address: "0x1000", name: "main" },
};
if (name === "read_function_instructions")
return {
procedure: { address: "0x1000", name: "main" },
instructions: {
items: ["0x1000: ret"],
total: 1,
returned: 1,
truncated: false,
next_offset: null,
},
instructions_scanned: 1,
instruction_scan_truncated: false,
limitations: ["Provider-specific instruction text."],
};
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(34);
expect(capabilities).toHaveLength(35);
expect(new Set(capabilities.map(({ operation }) => operation)).size).toBe(
capabilities.length,
);
+3 -3
View File
@@ -26,10 +26,10 @@ describe("server and catalog identity", () => {
});
expect(PRODUCT_IDENTITY.packageVersion).toBe(packageJson.version);
expect(SDK_IDENTITY.server).toBe("2.0.0-beta.4");
expect(CLI_COMMAND_NAMES).toHaveLength(58);
expect(new Set(CLI_COMMAND_NAMES).size).toBe(58);
expect(CLI_COMMAND_NAMES).toHaveLength(59);
expect(new Set(CLI_COMMAND_NAMES).size).toBe(59);
expect(CATALOG_IDENTITY.counts).toEqual({
cli_commands: 58,
cli_commands: 59,
mcp_tools: TOOL_CONTRACTS.length,
mcp_prompts: 6,
mcp_resources: 2,
+1 -1
View File
@@ -16,7 +16,7 @@ import { APPLICATION_TOOL_CONTRACTS } from "../src/contracts/applicationToolCont
describe("tool contract inventory", () => {
it("publishes the canonical analysis and session tool inventory", () => {
expect(OFFICIAL_TOOL_CONTRACTS).toHaveLength(33);
expect(OFFICIAL_TOOL_CONTRACTS).toHaveLength(34);
expect(ENHANCED_TOOL_CONTRACTS).toHaveLength(10);
expect(NATIVE_TOOL_CONTRACTS).toHaveLength(5);
expect(ARTIFACT_TOOL_CONTRACTS).toHaveLength(2);