feat: add evidence-backed process investigations

This commit is contained in:
morluto
2026-07-12 20:36:00 +08:00
parent 9f60348d1b
commit cc8681a856
53 changed files with 2774 additions and 290 deletions
+19 -2
View File
@@ -22,7 +22,24 @@ describe("binary session", () => {
const operations: string[] = [];
const provider: AnalysisProvider = {
identity: () => ({ id: "fixture", name: "Fixture", version: "1" }),
capabilities: () => ["fixture-analysis"],
capabilities: () => [
{
operation: "fixture-analysis",
version: 1,
available: true,
pagination: "none",
exhaustive: true,
effects: {
mutatesArtifact: false,
launchesProcess: false,
mayShowUi: false,
mayAccessNetwork: false,
mayWriteFilesystem: false,
requiresPrivileges: false,
},
limitations: [],
},
],
createClient: () => ({
execute: (operation) => {
operations.push(operation);
@@ -38,7 +55,7 @@ describe("binary session", () => {
value: "fixture_operation",
});
expect(provider.identity().id).toBe("fixture");
expect(provider.capabilities()).toEqual(["fixture-analysis"]);
expect(provider.capabilities()[0]?.operation).toBe("fixture-analysis");
expect(operations).toEqual(["health", "fixture_operation"]);
await session.close();
});
+25 -3
View File
@@ -8,9 +8,12 @@ const bridgeSource = await readFile(
);
describe("Hopper bridge truthfulness", () => {
it("marks unavailable CFG successors instead of returning deceptive empty arrays", () => {
expect(bridgeSource).toContain('"successors": _unavailable(');
expect(bridgeSource).not.toContain('"successors": []');
it("collects CFG successors from Hopper instead of fabricating empty edges", () => {
expect(bridgeSource).toContain("block.getSuccessorCount()");
expect(bridgeSource).toContain("block.getSuccessorAddressAtIndex(index)");
expect(bridgeSource).not.toContain(
"Hopper's public Python API does not expose CFG successor edges",
);
});
it("does not fabricate non-writable and non-executable segment permissions", () => {
@@ -29,4 +32,23 @@ describe("Hopper bridge truthfulness", () => {
"Hopper's public Python API does not classify reference kinds",
);
});
it("scans procedure instructions for comments and typed reference evidence", () => {
expect(bridgeSource).toContain("for address in addresses:");
expect(bridgeSource).toContain("segment.getCommentAtAddress(address)");
expect(bridgeSource).toContain(
"segment.getInlineCommentAtAddress(address)",
);
expect(bridgeSource).toContain('"source_procedure"');
expect(bridgeSource).toContain('"target_procedure"');
expect(bridgeSource).toContain('"outgoing_references"');
expect(bridgeSource).toContain('"referenced_strings"');
expect(bridgeSource).toContain('"referenced_names"');
});
it("supports independent dossier continuation offsets", () => {
expect(bridgeSource).toContain('_offset(params, "pseudocode_offset")');
expect(bridgeSource).toContain('_offset(params, "assembly_offset")');
expect(bridgeSource).toContain('params.get("collection_offset", {})');
});
});
+6
View File
@@ -33,6 +33,12 @@ describe("runtime configuration", () => {
hopperTargetKind: "database",
hopperLoaderArgs: ["-l", "FAT", "--aarch64", "-l", "Mach-O"],
logLevel: "info",
processExecutionPolicy: {
enabled: false,
executableRoots: [],
workingRoots: [],
allowedEnvironment: [],
},
},
});
});
+5 -1
View File
@@ -36,13 +36,17 @@ describe("tool contract surface", () => {
}
});
it("keeps exactly three additive session contracts", () => {
it("keeps exactly seven additive session contracts", () => {
expect(
SESSION_TOOL_CONTRACTS.map(({ name, kind }) => ({ name, kind })),
).toEqual([
{ name: "open_binary", kind: "session" },
{ name: "close_binary", kind: "session" },
{ name: "binary_session", kind: "session" },
{ name: "export_evidence_bundle", kind: "session" },
{ name: "import_evidence_bundle", kind: "session" },
{ name: "capture_process_scenario", kind: "session" },
{ name: "compare_process_captures", kind: "session" },
]);
});
+55 -2
View File
@@ -114,9 +114,11 @@ const fixturePort = (): AnalysisOperationPort => ({
callers: emptyBounded(),
callees: emptyBounded(),
incoming_references: emptyBounded(),
referenced_strings: { available: false, reason: "unsupported" },
referenced_names: { available: false, reason: "unsupported" },
outgoing_references: emptyBounded(),
referenced_strings: emptyBounded(),
referenced_names: emptyBounded(),
basic_blocks: emptyBounded(),
instruction_scan: { scanned: 0, truncated: false },
}),
);
default:
@@ -475,4 +477,55 @@ describe("enhanced MCP tools", () => {
"HopperProtocolError",
);
});
it("rejects incomplete function dossiers at the application boundary", async () => {
const client = await connect({
execute: () =>
Promise.resolve(
ok({
procedure: { address: "0x1", name: "entry" },
pseudocode: { text: "plausible but incomplete" },
}),
),
});
const result = await client.callTool({
name: "analyze_function",
arguments: { procedure: "0x1" },
});
expect(result.isError).toBe(true);
const text = result.content.find((item) => item.type === "text");
expect(text?.type === "text" ? text.text : "").toContain(
"AnalysisProtocolError",
);
});
it("rejects deceptive function dossier collection metadata", async () => {
const malformedPort = fixturePort();
const client = await connect({
execute: async (name, arguments_, options) => {
const result = await malformedPort.execute(name, arguments_, options);
if (!result.ok || name !== "analyze_function") return result;
const dossier = result.value as Record<string, JsonValue>;
return ok({
...dossier,
comments: {
items: [],
total: 0,
returned: 1,
truncated: false,
next_offset: null,
},
});
},
});
const result = await client.callTool({
name: "analyze_function",
arguments: { procedure: "0x1" },
});
expect(result.isError).toBe(true);
const text = result.content.find((item) => item.type === "text");
expect(text?.type === "text" ? text.text : "").toContain(
"AnalysisProtocolError",
);
});
});
+86 -30
View File
@@ -1,8 +1,12 @@
import { describe, expect, it } from "vitest";
import { EvidenceLedger } from "../src/application/EvidenceLedger.js";
import type { BinaryTarget } from "../src/domain/binaryTarget.js";
import { createEvidence, evidenceSchema } from "../src/domain/evidence.js";
import { jsonValueSchema } from "../src/hopper/protocol.js";
import {
createEvidence,
evidenceSchema,
parseEvidence,
} from "../src/domain/evidence.js";
const TARGET: BinaryTarget = {
path: "/tmp/fixture",
@@ -13,44 +17,96 @@ const TARGET: BinaryTarget = {
availableArchitectures: ["arm64"],
loaderArgs: ["-l", "Mach-O", "--aarch64"],
};
const PROVIDER = { id: "fixture", name: "Fixture provider", version: "1" };
describe("analysis evidence", () => {
it("preserves strict JSON inputs and results without timestamps", () => {
const evidence = createEvidence(TARGET, {
it("creates provider-neutral, deterministic Evidence v2", () => {
const observation = {
operation: "procedure_info",
parameters: { procedure: "0x1000", document: null },
parameters: { document: null, procedure: "0x1000" },
result: { name: "main" },
});
redactedRawPayload: { token: "<redacted:token>" },
} as const;
const evidence = createEvidence(TARGET, PROVIDER, observation);
expect(evidenceSchema.parse(evidence)).toEqual(evidence);
expect(jsonValueSchema.parse(evidence)).toEqual(evidence);
expect(parseEvidence(evidence)).toEqual(evidence);
expect(evidence).toMatchObject({
schema_version: 1,
artifact: {
path: "/tmp/fixture",
sha256: "a".repeat(64),
architecture: "arm64",
},
provider: { id: "hopper", version: null },
operation: "procedure_info",
schema_version: 2,
provider: PROVIDER,
subject: { digest: { sha256: "a".repeat(64) } },
confidence: "observed",
limitations: [],
authority: "shipped-artifact",
});
expect(evidence).not.toHaveProperty("timestamp");
expect(evidence).not.toHaveProperty("evidence_id");
expect(evidence.evidence_id).toMatch(/^ev_[a-f0-9]{64}$/u);
expect(evidence.raw_payload_sha256).toMatch(/^[a-f0-9]{64}$/u);
expect(createEvidence(TARGET, PROVIDER, observation)).toEqual(evidence);
});
it("marks missing fixed-target identity as unavailable", () => {
expect(
createEvidence(undefined, {
operation: "health",
parameters: {},
result: null,
}),
).toMatchObject({
artifact: null,
limitations: [
"Artifact identity is unavailable for this fixed-target adapter.",
],
it("excludes local paths and redacted raw payloads from semantic identity", () => {
const observation = {
operation: "health",
parameters: {},
result: true,
redactedRawPayload: { pid: 100 },
} as const;
const first = createEvidence(TARGET, PROVIDER, observation);
const moved = createEvidence(
{ ...TARGET, path: "/other/renamed-fixture" },
PROVIDER,
{ ...observation, redactedRawPayload: { pid: 200 } },
);
expect(moved.evidence_id).toBe(first.evidence_id);
expect(moved.raw_payload_sha256).not.toBe(first.raw_payload_sha256);
});
it("rejects semantic tampering", () => {
const evidence = createEvidence(TARGET, PROVIDER, {
operation: "health",
parameters: {},
result: true,
});
expect(() => parseEvidence({ ...evidence, result: false })).toThrow(
"semantic identifier",
);
});
it("deduplicates and atomically imports bounded bundles", () => {
const evidence = createEvidence(TARGET, PROVIDER, {
operation: "health",
parameters: {},
result: true,
});
const ledger = new EvidenceLedger({ maxRecords: 1 });
expect(ledger.record(evidence)).toBe("added");
expect(ledger.record(evidence)).toBe("duplicate");
const relocated = createEvidence(
{ ...TARGET, path: "/relocated/different-name" },
PROVIDER,
{ operation: "health", parameters: {}, result: true },
);
expect(relocated.evidence_id).toBe(evidence.evidence_id);
expect(ledger.record(relocated)).toBe("duplicate");
expect(ledger.import({ bundle_version: 1, records: [evidence] })).toBe(0);
expect(ledger.export().records).toEqual([evidence]);
ledger.clear();
expect(ledger.export().records).toEqual([]);
});
it("rejects duplicate semantic IDs with conflicting raw payload hashes", () => {
const ledger = new EvidenceLedger({ maxRecords: 2 });
const first = createEvidence(TARGET, PROVIDER, {
operation: "health",
parameters: {},
result: true,
redactedRawPayload: { pid: 1 },
});
const second = createEvidence(TARGET, PROVIDER, {
operation: "health",
parameters: {},
result: true,
redactedRawPayload: { pid: 2 },
});
ledger.record(first);
expect(() => ledger.record(second)).toThrow("Conflicting evidence");
});
});
+4 -4
View File
@@ -85,9 +85,9 @@ describe("full MCP integration with multi-tool sequences", () => {
});
expect(listResult.isError).not.toBe(true);
expect(structured(listResult)).toMatchObject({
artifact: null,
subject: null,
operation: "list_procedures",
provider: { id: "hopper", version: null },
provider: { id: "unidentified", version: null },
result: {
items: [
{ address: "0x1000", value: "main" },
@@ -118,7 +118,7 @@ describe("full MCP integration with multi-tool sequences", () => {
});
});
it("preserves the complete 46-tool inventory with a session", async () => {
it("preserves the complete 50-tool inventory with a session", async () => {
const session = new BinarySession(
(_path) =>
({
@@ -141,7 +141,7 @@ describe("full MCP integration with multi-tool sequences", () => {
await client.connect(clientTransport);
const listed = await client.listTools();
expect(listed.tools).toHaveLength(46);
expect(listed.tools).toHaveLength(50);
const names = listed.tools.map((t) => t.name);
expect(names).toContain("open_binary");
expect(names).toContain("close_binary");
+191
View File
@@ -0,0 +1,191 @@
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { describe, expect, it } from "vitest";
import WebSocket from "ws";
import { startLoopbackReplay } from "../src/application/LoopbackReplay.js";
import {
captureProcessScenario,
probeProcessCaptureCapability,
ProcessCaptureError,
} from "../src/application/ProcessHarness.js";
import {
authorizeProcessScenario,
compareProcessCaptures,
parseProcessScenario,
type ProcessExecutionPolicy,
} from "../src/domain/processCapture.js";
describe("process capture domain", () => {
const base = {
approved: true as const,
executable: "/bin/sh",
working_directory: "/tmp",
};
it("parses bounded scenarios and rejects unordered events", () => {
expect(parseProcessScenario(base).timeout_ms).toBe(30_000);
expect(() =>
parseProcessScenario({
...base,
events: [
{ type: "input", at_ms: 2, data: "a" },
{ type: "input", at_ms: 1, data: "b" },
],
}),
).toThrow(/ordered/);
});
it("refuses paths and environment outside operator policy", () => {
const scenario = parseProcessScenario({
...base,
environment: { TOKEN: "secret" },
});
expect(
authorizeProcessScenario(scenario, {
enabled: true,
executableRoots: ["/bin"],
workingRoots: ["/tmp"],
allowedEnvironment: [],
}),
).toEqual({
allowed: false,
reason: "scenario requests an environment variable not allowed by policy",
});
});
it("never considers truncated captures equivalent", () => {
const capture = {
schema_version: 1 as const,
frames: [],
exit: { code: 0, signal: null },
process_samples: [],
protocol_events: [],
files_before: [],
files_after: [],
truncated: true,
limitations: [],
};
expect(compareProcessCaptures(capture, capture).status).toBe("truncated");
});
});
describe("process capture adapter", () => {
it("serves bounded HTTP and WebSocket replay on loopback", async () => {
const scenario = parseProcessScenario({
approved: true,
executable: "/bin/sh",
working_directory: "/tmp",
replay: {
http: [{ method: "GET", path: "/ready", status: 201, body: "ready" }],
websocket_messages: ["welcome"],
},
});
const replay = await startLoopbackReplay(scenario);
try {
const response = await fetch(`${replay.httpUrl}/ready`);
expect(response.status).toBe(201);
expect(await response.text()).toBe("ready");
const websocketMessage = await new Promise<string>(
(resolveMessage, rejectMessage) => {
const socket = new WebSocket(replay.websocketUrl);
socket.once("message", (value) => {
resolveMessage(value.toString());
socket.close();
});
socket.once("error", rejectMessage);
},
);
expect(websocketMessage).toBe("welcome");
expect(replay.events.map((event) => event.protocol)).toContain(
"websocket",
);
} finally {
await replay.close();
}
});
it("captures PTY, filesystem, descendants, HTTP replay, and redacts environment", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-harness-test-"));
const script = join(root, "fixture.mjs");
await writeFile(
script,
[
'import { writeFile } from "node:fs/promises";',
'import { spawn } from "node:child_process";',
'await writeFile(new URL("result.txt", `file://${process.cwd()}/`), "created");',
"const response = await fetch(`${process.env.REA_REPLAY_HTTP_URL}/probe`);",
"console.log(`reply:${await response.text()}`);",
"console.log(`sensitive:${process.env.SECRET}`);",
'const child = spawn(process.execPath, ["-e", "setTimeout(()=>{}, 150)"], { stdio: "ignore" });',
"await new Promise((resolve) => setTimeout(resolve, 80));",
"child.kill();",
].join("\n"),
);
const policy: ProcessExecutionPolicy = {
enabled: true,
executableRoots: [dirname(process.execPath)],
workingRoots: [root],
allowedEnvironment: ["SECRET"],
};
const scenario = parseProcessScenario({
approved: true,
executable: process.execPath,
arguments: [script],
working_directory: root,
filesystem_roots: [root],
environment: { SECRET: "do-not-record" },
secret_aliases: ["SECRET"],
replay: {
http: [{ method: "GET", path: "/probe", status: 200, body: "ok" }],
},
});
try {
const capability = await probeProcessCaptureCapability();
if (!capability.available) {
expect(capability.reason).toMatch(/native PTY/);
return;
}
const capture = await captureProcessScenario(scenario, policy);
expect(capture.ok).toBe(true);
if (!capture.ok) throw capture.error;
expect(
capture.value.frames.map((frame) => frame.data).join(""),
).toContain("reply:ok");
expect(
capture.value.frames.map((frame) => frame.data).join(""),
).toContain("sensitive:<redacted>");
expect(
capture.value.files_after.some((file) =>
file.path.endsWith("result.txt"),
),
).toBe(true);
expect(
capture.value.protocol_events.some(
(event) => event.protocol === "http" && event.path === "/probe",
),
).toBe(true);
expect(JSON.stringify(capture.value)).not.toContain("do-not-record");
expect(await readFile(join(root, "result.txt"), "utf8")).toBe("created");
} finally {
await rm(root, { recursive: true, force: true });
}
});
it("does not launch when policy denies capture", async () => {
const scenario = parseProcessScenario({
approved: true,
executable: "/bin/sh",
working_directory: "/tmp",
});
const result = await captureProcessScenario(scenario, {
enabled: false,
executableRoots: [],
workingRoots: [],
allowedEnvironment: [],
});
expect(result.ok).toBe(false);
if (result.ok) throw new Error("expected policy refusal");
expect(result.error).toBeInstanceOf(ProcessCaptureError);
});
});
+2 -2
View File
@@ -20,9 +20,9 @@ describe("localized README product facts", () => {
expect(content).toContain("npx -y @morluto/rea setup --yes");
expect(content).toContain("npx -y @morluto/rea doctor");
expect(content).toContain('"args": ["-y", "@morluto/rea", "mcp"]');
expect(content).toContain("Node.js 22");
expect(content).toContain("Node.js 24");
expect(content).toContain("macOS 12");
expect(content).toMatch(/\b46\b/u);
expect(content).toMatch(/\b50\b/u);
expect(content).toMatch(/\b33\b/u);
expect(content).toMatch(/\b10\b/u);
expect(content).toMatch(/\b3\b/u);
+3 -3
View File
@@ -10,7 +10,7 @@ const fixturePath = fileURLToPath(
);
describe("production stdio runtime", () => {
it("starts the built entrypoint, lists 46 tools, calls one, and shuts down", async () => {
it("starts the built entrypoint, lists 50 tools, calls one, and shuts down", async () => {
const transport = new StdioClientTransport({
command: process.execPath,
args: [mainPath],
@@ -32,7 +32,7 @@ describe("production stdio runtime", () => {
try {
await client.connect(transport);
const tools = await client.listTools();
expect(tools.tools).toHaveLength(46);
expect(tools.tools).toHaveLength(50);
const result = await client.callTool({
name: "current_document",
arguments: {},
@@ -78,7 +78,7 @@ describe("production stdio runtime", () => {
try {
await client.connect(transport);
expect((await client.listTools()).tools).toHaveLength(46);
expect((await client.listTools()).tools).toHaveLength(50);
} finally {
await client.close();
await transport.close();
+36 -1
View File
@@ -4,11 +4,13 @@ import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { afterEach, describe, expect, it } from "vitest";
import { z } from "zod";
import { BinarySession } from "../src/application/BinarySession.js";
import type { AnalysisClient } from "../src/application/AnalysisProvider.js";
import { ok } from "../src/domain/result.js";
import { createServer } from "../src/server/createServer.js";
import { evidenceBundleSchema } from "../src/domain/evidenceBundle.js";
const resources: Array<{ close(): Promise<unknown> }> = [];
let directory: string | undefined;
@@ -42,7 +44,17 @@ describe("target-free MCP lifecycle", () => {
});
expect(before.isError).toBe(true);
expect(text(before)).toContain("NoBinaryOpenError");
expect((await mcp.listTools()).tools).toHaveLength(46);
expect((await mcp.listTools()).tools).toHaveLength(50);
const deniedCapture = await mcp.callTool({
name: "capture_process_scenario",
arguments: {
approved: true,
executable: "/bin/sh",
working_directory: "/tmp",
},
});
expect(deniedCapture.isError).toBe(true);
expect(text(deniedCapture)).toContain("process capture is disabled");
expect(
(await mcp.callTool({ name: "open_binary", arguments: { path: first } }))
.isError,
@@ -50,6 +62,20 @@ describe("target-free MCP lifecycle", () => {
expect(
text(await mcp.callTool({ name: "current_document", arguments: {} })),
).toContain("first.hop");
const exported = await mcp.callTool({
name: "export_evidence_bundle",
arguments: {},
});
const bundle = evidenceBundleSchema.parse(structured(exported).result);
expect(bundle.records).toHaveLength(1);
expect(
structured(
await mcp.callTool({
name: "import_evidence_bundle",
arguments: { bundle },
}),
).result,
).toEqual({ imported: 0, total: 1 });
await mcp.callTool({ name: "open_binary", arguments: { path: second } });
expect(closed.some((path) => path.endsWith("first.hop"))).toBe(true);
expect(
@@ -78,3 +104,12 @@ const text = (result: CallToolResult): string => {
if (content?.type !== "text") throw new Error("missing text result");
return content.text;
};
const structured = (result: CallToolResult): Record<string, unknown> => {
if (
typeof result.structuredContent !== "object" ||
result.structuredContent === null
)
throw new Error("missing structured result");
return z.record(z.string(), z.unknown()).parse(result.structuredContent);
};
+7 -3
View File
@@ -8,16 +8,20 @@ import {
} from "../src/contracts/toolContracts.js";
describe("tool contract inventory", () => {
it("publishes 43 analysis contracts and three session tools", () => {
it("publishes 43 analysis contracts and seven session tools", () => {
expect(OFFICIAL_TOOL_CONTRACTS).toHaveLength(33);
expect(ENHANCED_TOOL_CONTRACTS).toHaveLength(10);
expect(SESSION_TOOL_CONTRACTS.map(({ name }) => name)).toEqual([
"open_binary",
"close_binary",
"binary_session",
"export_evidence_bundle",
"import_evidence_bundle",
"capture_process_scenario",
"compare_process_captures",
]);
expect(TOOL_CONTRACTS).toHaveLength(46);
expect(new Set(TOOL_CONTRACTS.map(({ name }) => name)).size).toBe(46);
expect(TOOL_CONTRACTS).toHaveLength(50);
expect(new Set(TOOL_CONTRACTS.map(({ name }) => name)).size).toBe(50);
});
it("retains documented enhanced-tool limits at the input boundary", () => {