refactor: return complete tool results inline
This commit is contained in:
@@ -63,7 +63,7 @@ async function runInlineEvidenceScenarios(
|
||||
expect(traced.isError).not.toBe(true);
|
||||
expect(traced.structuredContent).toMatchObject({
|
||||
result: {
|
||||
schema_version: 1,
|
||||
source_graph_id: expect.any(String),
|
||||
coverage: { status: expect.any(String) },
|
||||
},
|
||||
});
|
||||
|
||||
@@ -10,7 +10,6 @@ import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
import { analyzeJavaScriptApplication } from "../../../src/application/JavaScriptApplicationService.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascriptApplicationAnalysis.js";
|
||||
import { permissionAuthorityForRoot } from "../../fixtures/permissionAuthority.js";
|
||||
|
||||
describe("application workflow MCP parity", () => {
|
||||
it("compares exact parser export shapes through full Evidence and session IDs", async () => {
|
||||
@@ -28,19 +27,12 @@ describe("application workflow MCP parity", () => {
|
||||
join(rightRoot, "parser.mjs"),
|
||||
),
|
||||
]);
|
||||
const authority = await permissionAuthorityForRoot(
|
||||
root,
|
||||
["investigation_input"],
|
||||
["investigation_input"],
|
||||
);
|
||||
const [left, right] = await Promise.all([
|
||||
analyzeJavaScriptApplication(authority, {
|
||||
analyzeJavaScriptApplication({
|
||||
input_path: leftRoot,
|
||||
approved: true,
|
||||
}),
|
||||
analyzeJavaScriptApplication(authority, {
|
||||
analyzeJavaScriptApplication({
|
||||
input_path: rightRoot,
|
||||
approved: true,
|
||||
}),
|
||||
]);
|
||||
if (!left.ok) throw left.error;
|
||||
@@ -107,8 +99,6 @@ describe("application workflow MCP parity", () => {
|
||||
const analyzed = javascriptApplicationAnalysisResultSchema.parse(
|
||||
left.value.normalized_result,
|
||||
);
|
||||
if (analyzed.schema_version !== 2)
|
||||
throw new TypeError("Expected semantic application Evidence");
|
||||
const seed = analyzed.semantic_graph.relations[0]?.source_node_id;
|
||||
if (seed === undefined)
|
||||
throw new TypeError("Expected at least one semantic relation");
|
||||
|
||||
@@ -19,7 +19,6 @@ import {
|
||||
serializeEvidenceBundle,
|
||||
} from "../../../src/domain/evidenceBundle.js";
|
||||
import { analyzeJavaScriptApplication } from "../../../src/application/JavaScriptApplicationService.js";
|
||||
import { permissionAuthorityForRoot } from "../../fixtures/permissionAuthority.js";
|
||||
import { REPLAY_MACHINE_RUN_EXAMPLE } from "../../../src/contracts/replayMachineExample.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascriptApplicationAnalysis.js";
|
||||
|
||||
@@ -43,7 +42,7 @@ describe("application workflow CLI parity", () => {
|
||||
]);
|
||||
expect(traced).toMatchObject({
|
||||
operation: "trace_application_feature",
|
||||
normalized_result: { schema_version: 1 },
|
||||
normalized_result: { source_evidence_id: expect.any(String) },
|
||||
});
|
||||
|
||||
const root = await createTestTempDirectory("rea-application-cli-");
|
||||
@@ -86,21 +85,13 @@ describe("application workflow CLI parity", () => {
|
||||
join(root, "app.js"),
|
||||
"function add(value) { return value + 1; } add(2);",
|
||||
);
|
||||
const authority = await permissionAuthorityForRoot(
|
||||
root,
|
||||
["investigation_input"],
|
||||
["investigation_input"],
|
||||
);
|
||||
const analyzed = await analyzeJavaScriptApplication(authority, {
|
||||
const analyzed = await analyzeJavaScriptApplication({
|
||||
input_path: root,
|
||||
approved: true,
|
||||
});
|
||||
if (!analyzed.ok) throw analyzed.error;
|
||||
const result = javascriptApplicationAnalysisResultSchema.parse(
|
||||
analyzed.value.normalized_result,
|
||||
);
|
||||
if (result.schema_version !== 2)
|
||||
throw new TypeError("Expected semantic application Evidence");
|
||||
const seed = result.semantic_graph.relations[0]?.source_node_id;
|
||||
if (seed === undefined)
|
||||
throw new TypeError("Expected at least one semantic relation");
|
||||
@@ -163,7 +154,7 @@ describe("application workflow CLI Evidence resolution", () => {
|
||||
);
|
||||
expect(traced).toMatchObject({
|
||||
operation: "trace_application_feature",
|
||||
normalized_result: { schema_version: 1 },
|
||||
normalized_result: { source_evidence_id: expect.any(String) },
|
||||
});
|
||||
|
||||
const compared = await runCli(
|
||||
@@ -244,19 +235,12 @@ describe("application workflow CLI export Evidence", () => {
|
||||
join(rightRoot, "parser.mjs"),
|
||||
),
|
||||
]);
|
||||
const authority = await permissionAuthorityForRoot(
|
||||
root,
|
||||
["investigation_input"],
|
||||
["investigation_input"],
|
||||
);
|
||||
const [left, right] = await Promise.all([
|
||||
analyzeJavaScriptApplication(authority, {
|
||||
analyzeJavaScriptApplication({
|
||||
input_path: leftRoot,
|
||||
approved: true,
|
||||
}),
|
||||
analyzeJavaScriptApplication(authority, {
|
||||
analyzeJavaScriptApplication({
|
||||
input_path: rightRoot,
|
||||
approved: true,
|
||||
}),
|
||||
]);
|
||||
if (!left.ok) throw left.error;
|
||||
|
||||
@@ -20,7 +20,6 @@ import {
|
||||
buildSyntheticJavaScriptApplicationGraph,
|
||||
} from "../../../src/domain/javascriptApplicationGraph.fixture.js";
|
||||
import { writeVersionedJavaScriptApplicationFixtures } from "../../fixtures/javascriptArtifactApplication.js";
|
||||
import { permissionAuthorityForRoot } from "../../fixtures/permissionAuthority.js";
|
||||
|
||||
const temporary: string[] = [];
|
||||
|
||||
@@ -62,7 +61,6 @@ describe("JavaScript application workflows", () => {
|
||||
case_sensitive: false,
|
||||
},
|
||||
direction: "outgoing",
|
||||
limits: traceLimits(),
|
||||
});
|
||||
|
||||
expect(() =>
|
||||
@@ -94,7 +92,7 @@ describe("JavaScript application workflows", () => {
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps no-match and bounded frontiers explicit", () => {
|
||||
it("keeps no-match explicit and traces the full reachable graph", () => {
|
||||
const graph = buildSyntheticJavaScriptApplicationGraph();
|
||||
const noMatch = traceApplicationFeature({
|
||||
sourceEvidenceId: `ev_${"a".repeat(64)}`,
|
||||
@@ -107,7 +105,6 @@ describe("JavaScript application workflows", () => {
|
||||
case_sensitive: false,
|
||||
},
|
||||
direction: "both",
|
||||
limits: traceLimits(),
|
||||
});
|
||||
expect(noMatch).toMatchObject({
|
||||
graph: null,
|
||||
@@ -115,7 +112,7 @@ describe("JavaScript application workflows", () => {
|
||||
summary: { matched_seeds: 0 },
|
||||
});
|
||||
|
||||
const bounded = traceApplicationFeature({
|
||||
const complete = traceApplicationFeature({
|
||||
sourceEvidenceId: `ev_${"a".repeat(64)}`,
|
||||
graph,
|
||||
nativeEvidence: [],
|
||||
@@ -126,11 +123,11 @@ describe("JavaScript application workflows", () => {
|
||||
case_sensitive: false,
|
||||
},
|
||||
direction: "outgoing",
|
||||
limits: { ...traceLimits(), max_depth: 1 },
|
||||
});
|
||||
expect(bounded.coverage).toMatchObject({ status: "truncated" });
|
||||
expect(bounded.coverage.omitted_nodes).toBeGreaterThan(0);
|
||||
expect(bounded.summary.native_handoffs).toBe(0);
|
||||
expect(complete.coverage.status).toBe("complete-within-source");
|
||||
expect(complete.coverage.total_seed_matches).toBe(1);
|
||||
expect(complete.graph?.nodes.length).toBeGreaterThan(1);
|
||||
expect(complete.coverage).not.toHaveProperty("omitted_nodes");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -140,8 +137,8 @@ describe("JavaScript application comparison workflows", () => {
|
||||
temporary.push(root);
|
||||
const fixtures = await writeVersionedJavaScriptApplicationFixtures(root);
|
||||
const [left, right] = await Promise.all([
|
||||
analyzeFixture(fixtures.left, true),
|
||||
analyzeFixture(fixtures.right, true),
|
||||
analyzeFixture(fixtures.left),
|
||||
analyzeFixture(fixtures.right),
|
||||
]);
|
||||
const compared = compareApplicationVersionsEvidence({ left, right });
|
||||
if (!compared.ok) throw compared.error;
|
||||
@@ -199,8 +196,8 @@ describe("JavaScript application comparison workflows", () => {
|
||||
temporary.push(root);
|
||||
const fixtures = await writeVersionedJavaScriptApplicationFixtures(root);
|
||||
const [left, right] = await Promise.all([
|
||||
analyzeFixture(fixtures.left, true),
|
||||
analyzeFixture(fixtures.right, true),
|
||||
analyzeFixture(fixtures.left),
|
||||
analyzeFixture(fixtures.right),
|
||||
]);
|
||||
const compared = compareApplicationVersionsEvidence({ left, right });
|
||||
if (!compared.ok) throw compared.error;
|
||||
@@ -227,7 +224,6 @@ describe("JavaScript application comparison workflows", () => {
|
||||
if (rootNode === undefined) throw new Error("Synthetic graph root missing");
|
||||
const partial = createJavaScriptApplicationGraph({
|
||||
schema: "JavaScriptApplicationGraph",
|
||||
schema_version: 1,
|
||||
root_node_ids: [rootNode.node_id],
|
||||
nodes: [rootNode],
|
||||
edges: [],
|
||||
@@ -273,24 +269,9 @@ describe("JavaScript application comparison workflows", () => {
|
||||
});
|
||||
});
|
||||
|
||||
const traceLimits = () => ({
|
||||
max_seed_matches: 25,
|
||||
max_depth: 12,
|
||||
max_nodes: 2_000,
|
||||
max_edges: 4_000,
|
||||
max_paths: 100,
|
||||
});
|
||||
|
||||
const analyzeFixture = async (root: string, sourceMaps = false) => {
|
||||
const authority = await permissionAuthorityForRoot(
|
||||
root,
|
||||
["investigation_input"],
|
||||
["investigation_input"],
|
||||
);
|
||||
const result = await analyzeJavaScriptApplication(authority, {
|
||||
const analyzeFixture = async (root: string) => {
|
||||
const result = await analyzeJavaScriptApplication({
|
||||
input_path: root,
|
||||
approved: true,
|
||||
source_map_read_approved: sourceMaps,
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
return result.value;
|
||||
|
||||
@@ -19,7 +19,7 @@ const expectAvailableToolInventory = async (client: Client): Promise<void> => {
|
||||
const listed = await client.listTools();
|
||||
const status = await client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: { detail: "full" },
|
||||
arguments: {},
|
||||
});
|
||||
const availability = z
|
||||
.object({
|
||||
|
||||
@@ -9,6 +9,22 @@ import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
|
||||
import { describeBrowser, trackBrowser } from "./cdpBrowserProvider.support.js";
|
||||
|
||||
describeBrowser("CdpBrowserProvider: discovery authorization 1", () => {
|
||||
it("returns every approved page target inline", async () => {
|
||||
const browser = await startFakeCdpBrowser({ additionalPageCount: 205 });
|
||||
trackBrowser(browser);
|
||||
const listed = await new CdpBrowserProvider().listTargets(
|
||||
listBrowserTargetsInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
approved: true,
|
||||
}),
|
||||
);
|
||||
if (!listed.ok) throw listed.error;
|
||||
expect(listed.value.targets).toHaveLength(206);
|
||||
expect(listed.value.targets[0]?.target_id).toBe("allowed-page");
|
||||
expect(listed.value.targets.at(-1)?.target_id).toBe("allowed-page-0204");
|
||||
});
|
||||
|
||||
it("lists only exact-origin pages and sanitizes URLs", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
trackBrowser(browser);
|
||||
@@ -22,7 +38,7 @@ describeBrowser("CdpBrowserProvider: discovery authorization 1", () => {
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.targets.items).toEqual([
|
||||
expect(result.value.targets).toEqual([
|
||||
expect.objectContaining({
|
||||
target_id: "allowed-page",
|
||||
origin: browser.allowedOrigin,
|
||||
@@ -60,7 +76,7 @@ describeBrowser("CdpBrowserProvider: discovery authorization 1", () => {
|
||||
listBrowserTargetsInputSchema.parse(input),
|
||||
);
|
||||
if (!listed.ok) throw listed.error;
|
||||
expect(listed.value.targets.items[0]?.title).toBe(expected);
|
||||
expect(listed.value.targets[0]?.title).toBe(expected);
|
||||
|
||||
const inspected = await provider.inspectPage(
|
||||
inspectWebPageInputSchema.parse({ ...input, observation_ms: 0 }),
|
||||
@@ -90,9 +106,10 @@ describeBrowser("CdpBrowserProvider: discovery authorization 1", () => {
|
||||
}),
|
||||
);
|
||||
if (!listed.ok) throw listed.error;
|
||||
expect(
|
||||
listed.value.targets.items.map(({ target_id }) => target_id),
|
||||
).toEqual(["allowed-page", "allowed-page-with-socket"]);
|
||||
expect(listed.value.targets.map(({ target_id }) => target_id)).toEqual([
|
||||
"allowed-page",
|
||||
"allowed-page-with-socket",
|
||||
]);
|
||||
expect(listed.value.limitations).toContain(
|
||||
"1 otherwise allowed page target(s) lacked a validated direct CDP WebSocket and were excluded.",
|
||||
);
|
||||
|
||||
@@ -29,6 +29,27 @@ afterEach(async () => {
|
||||
});
|
||||
|
||||
describe("CdpElectronProvider target access", () => {
|
||||
it("returns every approved Electron page target inline", async () => {
|
||||
const root = await electronFixture();
|
||||
const index = join(root, "index.html");
|
||||
const browser = await startFakeCdpBrowser({
|
||||
electronFileUrl: pathToFileURL(index).href,
|
||||
additionalElectronPageCount: 205,
|
||||
});
|
||||
browsers.push(browser);
|
||||
const listed = await new CdpElectronProvider().listTargets(
|
||||
listElectronTargetsInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_file_roots: [root],
|
||||
approved: true,
|
||||
}),
|
||||
);
|
||||
if (!listed.ok) throw listed.error;
|
||||
expect(listed.value.targets).toHaveLength(206);
|
||||
expect(listed.value.targets[0]?.target_id).toBe("electron-page");
|
||||
expect(listed.value.targets.at(-1)?.target_id).toBe("electron-page-0204");
|
||||
});
|
||||
|
||||
it("lists and inspects only canonical file targets beneath approved roots", async () => {
|
||||
const root = await electronFixture();
|
||||
const index = join(root, "index.html");
|
||||
@@ -46,7 +67,7 @@ describe("CdpElectronProvider target access", () => {
|
||||
}),
|
||||
);
|
||||
if (!listed.ok) throw listed.error;
|
||||
expect(listed.value.targets.items).toEqual([
|
||||
expect(listed.value.targets).toEqual([
|
||||
expect.objectContaining({
|
||||
target_id: "electron-page",
|
||||
file_path: index,
|
||||
|
||||
@@ -27,6 +27,28 @@ import { startFakeV8Inspector } from "../../fixtures/fakeV8Inspector.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
describe("passive V8 Inspector provider", () => {
|
||||
test("returns every approved Inspector target inline", async () => {
|
||||
const fixture = await runtimeFixture();
|
||||
const fake = await startFakeV8Inspector({
|
||||
targetUrl: pathToFileURL(fixture.entry).href,
|
||||
additionalTargetCount: 205,
|
||||
});
|
||||
try {
|
||||
const listed = await new V8InspectorProvider().listTargets({
|
||||
inspector_endpoint: fake.endpoint,
|
||||
allowed_file_roots: [fixture.root],
|
||||
allowed_origins: [],
|
||||
approved: true,
|
||||
});
|
||||
expect(listed.ok).toBe(true);
|
||||
if (!listed.ok) return;
|
||||
expect(listed.value.targets).toHaveLength(206);
|
||||
expect(listed.value.targets[0]?.target_id).toBe(fake.targetId);
|
||||
} finally {
|
||||
await fake.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("filters target locations and never retains the excluded path", async () => {
|
||||
const fixture = await runtimeFixture();
|
||||
const outside = await temporaryFile("outside.js");
|
||||
@@ -40,12 +62,10 @@ describe("passive V8 Inspector provider", () => {
|
||||
allowed_file_roots: [fixture.root],
|
||||
allowed_origins: [],
|
||||
approved: true,
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.value.targets.total).toBe(1);
|
||||
expect(result.value.targets).toHaveLength(1);
|
||||
expect(result.value.excluded.outside_file_roots).toBe(1);
|
||||
expect(JSON.stringify(result.value)).not.toContain(outside);
|
||||
} finally {
|
||||
@@ -106,13 +126,10 @@ describe("passive V8 Inspector provider", () => {
|
||||
allowed_file_roots: [fixture.root],
|
||||
allowed_origins: [],
|
||||
approved: true,
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
});
|
||||
expect(listed.ok).toBe(true);
|
||||
if (!listed.ok) return;
|
||||
expect(listed.value.targets.total).toBe(0);
|
||||
expect(listed.value.targets.items).toEqual([]);
|
||||
expect(listed.value.targets).toEqual([]);
|
||||
|
||||
const observed = await provider.observe(
|
||||
observeInput(
|
||||
@@ -224,8 +241,6 @@ describe("passive V8 Inspector evidence", () => {
|
||||
allowed_file_roots: [fixture.root],
|
||||
allowed_origins: [],
|
||||
approved: true,
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
},
|
||||
);
|
||||
expect(listed.ok).toBe(true);
|
||||
@@ -338,7 +353,6 @@ const runtimeObservation = (
|
||||
targetPath: string,
|
||||
scriptPath: string,
|
||||
): JavaScriptRuntimeObservation => ({
|
||||
schema_version: 1,
|
||||
runtime: {
|
||||
product: "node.js/v24.4.1",
|
||||
protocol_version: "1.3",
|
||||
|
||||
@@ -42,7 +42,7 @@ describe("browser CLI parity", () => {
|
||||
operation: "list_browser_targets",
|
||||
provider: { id: "rea-cdp-browser" },
|
||||
normalized_result: {
|
||||
targets: { items: [{ target_id: "allowed-page" }] },
|
||||
targets: [{ target_id: "allowed-page" }],
|
||||
},
|
||||
});
|
||||
const inspected = await runCli(
|
||||
@@ -358,7 +358,6 @@ const completeScenarioCapture = () => {
|
||||
completeness,
|
||||
});
|
||||
return {
|
||||
schema_version: 1,
|
||||
browser: {
|
||||
mode: "connect",
|
||||
process_ownership: "external",
|
||||
|
||||
@@ -135,7 +135,7 @@ describe("compiled CLI output boundary", () => {
|
||||
'code: VALIDATION_ERROR\nmessage: "REA could not read the command arguments. Run `rea --help`, correct the arguments, then try again."\n',
|
||||
});
|
||||
const json = await cli.run({
|
||||
arguments: ["--full-output", "--json", "analyze"],
|
||||
arguments: ["--json", "analyze"],
|
||||
});
|
||||
expect(json).toMatchObject({
|
||||
exitCode: 1,
|
||||
@@ -154,7 +154,7 @@ describe("compiled CLI output boundary", () => {
|
||||
);
|
||||
|
||||
workspaceCliTest(
|
||||
"preserves artifact diagnostics in ordinary and full JSON output",
|
||||
"preserves artifact diagnostics in JSON output",
|
||||
async ({ cli, workspace }) => {
|
||||
const source = workspace.path("source");
|
||||
await mkdir(source);
|
||||
@@ -163,17 +163,15 @@ describe("compiled CLI output boundary", () => {
|
||||
await createPackageWithOptions(source, archive, { unpack: "*.js" });
|
||||
await writeFile(join(`${archive}.unpacked`, "main.js"), "changed();\n");
|
||||
|
||||
for (const flags of [["--json"], ["--full-output", "--json"]]) {
|
||||
const result = await cli.run({
|
||||
arguments: [...flags, "inventory-artifact", archive],
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
const output = JSON.stringify(result.json);
|
||||
expect(output).toContain('"logical_path":"main.js"');
|
||||
expect(output).toMatch(/"declared_sha256":"[a-f0-9]{64}"/u);
|
||||
expect(output).toMatch(/"calculated_sha256":"[a-f0-9]{64}"/u);
|
||||
expect(output).toContain('"unpacked":true');
|
||||
}
|
||||
const result = await cli.run({
|
||||
arguments: ["--json", "inventory-artifact", archive],
|
||||
});
|
||||
expect(result.exitCode).toBe(1);
|
||||
const output = JSON.stringify(result.json);
|
||||
expect(output).toContain('"logical_path":"main.js"');
|
||||
expect(output).toMatch(/"declared_sha256":"[a-f0-9]{64}"/u);
|
||||
expect(output).toMatch(/"calculated_sha256":"[a-f0-9]{64}"/u);
|
||||
expect(output).toContain('"unpacked":true');
|
||||
},
|
||||
CLI_INTEGRATION_TIMEOUT_MS,
|
||||
);
|
||||
@@ -187,7 +185,6 @@ describe("compiled CLI output boundary", () => {
|
||||
["--format", "yaml"],
|
||||
["--format", "md"],
|
||||
["--format", "jsonl"],
|
||||
["--full-output", "--json"],
|
||||
["--filter-output", "category", "--json"],
|
||||
["--token-limit", "5", "--json"],
|
||||
["--token-count", "--json"],
|
||||
|
||||
@@ -57,7 +57,7 @@ describe("Electron CLI parity", () => {
|
||||
expect(listed).toMatchObject({
|
||||
operation: "list_electron_targets",
|
||||
normalized_result: {
|
||||
targets: { items: [{ target_id: "electron-page" }] },
|
||||
targets: [{ target_id: "electron-page" }],
|
||||
},
|
||||
});
|
||||
const inspected = await runCli(
|
||||
@@ -91,11 +91,10 @@ describe("Electron CLI parity", () => {
|
||||
await writeElectronBoundaryFixture(root);
|
||||
const environment = {
|
||||
...process.env,
|
||||
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([root]),
|
||||
};
|
||||
|
||||
const analyzed = await runCli(
|
||||
["analyze-javascript-application", root, "--approved", "--json"],
|
||||
["analyze-javascript-application", root, "--json"],
|
||||
environment,
|
||||
);
|
||||
|
||||
@@ -125,7 +124,6 @@ describe("Electron CLI artifact behavior", () => {
|
||||
await writeElectronBoundaryFixture(root);
|
||||
const environment = {
|
||||
...process.env,
|
||||
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([root]),
|
||||
};
|
||||
|
||||
const analyzed = await runCli(
|
||||
@@ -134,7 +132,6 @@ describe("Electron CLI artifact behavior", () => {
|
||||
"json",
|
||||
"analyze-javascript-application",
|
||||
root,
|
||||
"--approved",
|
||||
"--artifact-format",
|
||||
"directory",
|
||||
],
|
||||
@@ -150,20 +147,16 @@ describe("Electron CLI artifact behavior", () => {
|
||||
);
|
||||
|
||||
it(
|
||||
"routes generic approved analysis of a directory to static JavaScript",
|
||||
"routes generic directory analysis to static JavaScript",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory("rea-electron-routed-cli-");
|
||||
temporary.push(root);
|
||||
await writeElectronBoundaryFixture(root);
|
||||
const environment = {
|
||||
...process.env,
|
||||
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([root]),
|
||||
};
|
||||
|
||||
const analyzed = await runCli(
|
||||
["analyze", root, "--approved", "--json"],
|
||||
environment,
|
||||
);
|
||||
const analyzed = await runCli(["analyze", root, "--json"], environment);
|
||||
|
||||
expect(analyzed).toMatchObject({
|
||||
operation: "analyze_javascript_application",
|
||||
@@ -177,39 +170,6 @@ describe("Electron CLI artifact behavior", () => {
|
||||
},
|
||||
INTEGRATION_TEST_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it(
|
||||
"requires explicit approval before generic JavaScript analysis",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory(
|
||||
"rea-electron-unapproved-cli-",
|
||||
);
|
||||
temporary.push(root);
|
||||
await writeElectronBoundaryFixture(root);
|
||||
const environment = {
|
||||
...process.env,
|
||||
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([root]),
|
||||
};
|
||||
|
||||
const denied = await runCli(["analyze", root, "--json"], environment);
|
||||
|
||||
expect(denied).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "analyze_javascript_application",
|
||||
issues: [
|
||||
{
|
||||
path: ["approved"],
|
||||
reason: "invalid_value",
|
||||
expected: [true],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(denied).not.toHaveProperty("details.candidate_ids");
|
||||
},
|
||||
INTEGRATION_TEST_TIMEOUT_MS,
|
||||
);
|
||||
});
|
||||
|
||||
describe("Electron CLI runtime reconciliation", () => {
|
||||
@@ -232,7 +192,6 @@ describe("Electron CLI runtime reconciliation", () => {
|
||||
operation: "reconcile_javascript_runtime",
|
||||
provider: { id: "rea-javascript-runtime-reconciliation" },
|
||||
normalized_result: {
|
||||
schema_version: 1,
|
||||
summary: { runtime_scripts: 1, matched: 1 },
|
||||
source_map_authority: { used_for_primary_matching: false },
|
||||
},
|
||||
|
||||
@@ -60,7 +60,7 @@ describe("JavaScript runtime observation CLI parity", () => {
|
||||
operation: "list_javascript_runtime_targets",
|
||||
provider: { id: "rea-v8-inspector" },
|
||||
normalized_result: {
|
||||
targets: { items: [{ target_id: inspector.targetId }] },
|
||||
targets: [{ target_id: inspector.targetId }],
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -134,15 +134,15 @@ describe("process CLI errors", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("explains unsupported and unrelated capture evidence", async () => {
|
||||
it("rejects unrelated capture evidence", async () => {
|
||||
const root = await fixture();
|
||||
const legacy = join(root, "legacy.json");
|
||||
const invalidCapture = join(root, "invalid-capture.json");
|
||||
const unrelated = join(root, "unrelated.json");
|
||||
await writeFile(
|
||||
legacy,
|
||||
invalidCapture,
|
||||
JSON.stringify(
|
||||
createEvidence(undefined, PROCESS_PROVIDER, {
|
||||
predicateType: "rea.process-capture/v3",
|
||||
predicateType: "rea.process-capture/other",
|
||||
operation: "capture_process_scenario",
|
||||
parameters: {},
|
||||
result: {},
|
||||
@@ -161,14 +161,12 @@ describe("process CLI errors", () => {
|
||||
),
|
||||
);
|
||||
|
||||
const legacyResult = await compareProcessEvidenceFiles(legacy, legacy);
|
||||
expect(legacyResult).toMatchObject({
|
||||
expect(
|
||||
await compareProcessEvidenceFiles(invalidCapture, invalidCapture),
|
||||
).toMatchObject({
|
||||
error: "Process command failed",
|
||||
category: "invalid_input",
|
||||
});
|
||||
expect(JSON.stringify(legacyResult)).toContain(
|
||||
"Process Capture v3 is unsupported",
|
||||
);
|
||||
expect(await compareProcessEvidenceFiles(unrelated, unrelated)).toEqual({
|
||||
error: "Process command failed",
|
||||
category: "invalid_input",
|
||||
|
||||
@@ -3,7 +3,6 @@ import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
@@ -24,8 +23,6 @@ import { V8_INSPECTOR_PROVIDER_IDENTITY } from "../../../src/browser/V8Inspector
|
||||
import { CLI_COMMAND_NAMES } from "../../../src/cliCommandNames.js";
|
||||
import { createCli } from "../../../src/cli.js";
|
||||
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
|
||||
import { analysisSnapshotSchema } from "../../../src/domain/analysisSnapshot.js";
|
||||
import { investigationWorkspaceSchema } from "../../../src/domain/investigationWorkspace.js";
|
||||
import {
|
||||
HOPPER_PROVIDER_IDENTITY,
|
||||
HOPPER_PROVIDER_TOOL_CONTRACTS,
|
||||
@@ -150,19 +147,6 @@ describe("canonical product catalog", () => {
|
||||
expect(catalog.runtime_catalog.digests.providers_sha256).toBe(
|
||||
providerCatalogDigest(catalog.providers),
|
||||
);
|
||||
expect(
|
||||
z.toJSONSchema(analysisSnapshotSchema).properties?.snapshot_version,
|
||||
).toMatchObject({
|
||||
const: catalog.schemas.find(({ id }) => id === "analysis_snapshot")
|
||||
?.version,
|
||||
});
|
||||
expect(
|
||||
z.toJSONSchema(investigationWorkspaceSchema).properties
|
||||
?.workspace_version,
|
||||
).toMatchObject({
|
||||
const: catalog.schemas.find(({ id }) => id === "investigation_workspace")
|
||||
?.version,
|
||||
});
|
||||
expect(
|
||||
JSON.parse(await readFile("docs/product-catalog.json", "utf8")),
|
||||
).toEqual(catalog);
|
||||
@@ -207,7 +191,7 @@ describe("canonical CLI catalog", () => {
|
||||
});
|
||||
|
||||
describe("canonical product catalog drift", () => {
|
||||
it("reports tool-family, setup-client, and schema fact drift", async () => {
|
||||
it("reports tool-family and setup-client fact drift", async () => {
|
||||
const catalog = await createProductCatalog(root);
|
||||
const firstFamily = catalog.tools.families[0];
|
||||
if (firstFamily === undefined) throw new TypeError("Missing tool family");
|
||||
@@ -229,20 +213,12 @@ describe("canonical product catalog drift", () => {
|
||||
configuration: "managed",
|
||||
},
|
||||
],
|
||||
schemas: catalog.schemas.map((schema) =>
|
||||
schema.id === "process_capture"
|
||||
? { ...schema, version: Number(schema.version) + 1 }
|
||||
: schema,
|
||||
),
|
||||
};
|
||||
const issues = await documentationFactIssues(root, drifted);
|
||||
expect(issues.some((issue) => issue.includes("tool family counts"))).toBe(
|
||||
true,
|
||||
);
|
||||
expect(issues.some((issue) => issue.includes("Future Client"))).toBe(true);
|
||||
expect(issues.some((issue) => issue.includes("Process Capture v5"))).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("changes the provider projection digest when provider facts drift", async () => {
|
||||
|
||||
@@ -13,11 +13,9 @@ describe("reconstruction obligation ledger CLI parity", () => {
|
||||
evidence_bundle: createEvidenceBundle([]),
|
||||
reviewed_obligations: [],
|
||||
manifest: {
|
||||
schema_version: 1,
|
||||
bindings: [],
|
||||
contradictions: [],
|
||||
},
|
||||
limits: { max_obligations: 100 },
|
||||
page: { offset: 0, limit: 50 },
|
||||
};
|
||||
const { stdout } = await execute(
|
||||
|
||||
@@ -5,10 +5,7 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
paginateArtifactInventory,
|
||||
scanArtifactInventory,
|
||||
} from "../../../src/application/ArtifactInventory.js";
|
||||
import { scanArtifactInventory } from "../../../src/application/ArtifactInventory.js";
|
||||
|
||||
const LIMITS = {
|
||||
maxEntries: 10,
|
||||
@@ -20,37 +17,18 @@ const LIMITS = {
|
||||
} as const;
|
||||
|
||||
describe("artifact inventory snapshot", () => {
|
||||
it("projects every page from the same completed scan", async () => {
|
||||
it("retains the complete scan after the source directory changes", async () => {
|
||||
const root = await createTestTempDirectory("rea-inventory-snapshot-");
|
||||
await writeFile(join(root, "a.txt"), "a");
|
||||
await writeFile(join(root, "b.txt"), "b");
|
||||
const snapshot = await scanArtifactInventory(root, LIMITS);
|
||||
|
||||
await rm(join(root, "b.txt"));
|
||||
const first = paginateArtifactInventory(snapshot, {
|
||||
nodeOffset: 0,
|
||||
nodeLimit: 1,
|
||||
occurrenceOffset: 0,
|
||||
occurrenceLimit: 2,
|
||||
edgeOffset: 0,
|
||||
edgeLimit: 1,
|
||||
});
|
||||
const second = paginateArtifactInventory(snapshot, {
|
||||
nodeOffset: 1,
|
||||
nodeLimit: 10,
|
||||
occurrenceOffset: 2,
|
||||
occurrenceLimit: 2,
|
||||
edgeOffset: 1,
|
||||
edgeLimit: 10,
|
||||
});
|
||||
|
||||
expect(first.manifest).toEqual(second.manifest);
|
||||
expect(
|
||||
[...first.occurrences.items, ...second.occurrences.items].map(
|
||||
({ logical_path: path }) => path,
|
||||
),
|
||||
).toEqual([".", "a.txt", "b.txt"]);
|
||||
expect(first.occurrences.total).toBe(3);
|
||||
expect(second.occurrences.total).toBe(3);
|
||||
expect(snapshot.occurrences.map(({ logical_path: path }) => path)).toEqual([
|
||||
".",
|
||||
"a.txt",
|
||||
"b.txt",
|
||||
]);
|
||||
expect(snapshot.manifest.occurrence_count).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -17,15 +17,11 @@ const LIMITS = {
|
||||
} as const;
|
||||
|
||||
describe("authorized artifact inventory", () => {
|
||||
it("uses a valid input root when another configured root is missing", async () => {
|
||||
it("scans a local artifact without configured input roots", async () => {
|
||||
const root = await createTestTempDirectory("rea-artifact-roots-");
|
||||
const path = join(root, "artifact.js");
|
||||
await writeFile(path, "export const value = 1;\n");
|
||||
const inventory = await scanAuthorizedArtifactInventory(
|
||||
path,
|
||||
[join(root, "missing"), root],
|
||||
LIMITS,
|
||||
);
|
||||
const inventory = await scanAuthorizedArtifactInventory(path, LIMITS);
|
||||
expect(inventory.manifest.root_format).toBe("javascript-bundle");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -96,7 +96,7 @@ describe("persistent cross-version investigation workspace", () => {
|
||||
const completed = await runCrossVersionInvestigation(
|
||||
input,
|
||||
policy(directory),
|
||||
{ inputRoots: [directory] },
|
||||
{},
|
||||
);
|
||||
if (!completed.ok) throw completed.error;
|
||||
|
||||
@@ -116,7 +116,7 @@ describe("persistent cross-version investigation workspace", () => {
|
||||
const completed = await runCrossVersionInvestigation(
|
||||
input,
|
||||
policy(directory),
|
||||
{ inputRoots: [directory] },
|
||||
{},
|
||||
);
|
||||
if (!completed.ok) throw completed.error;
|
||||
const run = completed.value.workspace.runs[0];
|
||||
@@ -162,7 +162,7 @@ describe("persistent cross-version investigation workspace", () => {
|
||||
replay_run_id: partialRun.run_id,
|
||||
},
|
||||
policy(directory),
|
||||
{ inputRoots: [], authorizeInputRead: replayAuthorization },
|
||||
{},
|
||||
),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
@@ -176,7 +176,7 @@ describe("persistent cross-version investigation workspace", () => {
|
||||
const resumed = await runCrossVersionInvestigation(
|
||||
{ ...input, workspace_path: resumePath },
|
||||
policy(directory),
|
||||
{ inputRoots: [directory] },
|
||||
{},
|
||||
);
|
||||
expect(resumed).toMatchObject({
|
||||
ok: true,
|
||||
@@ -192,9 +192,11 @@ describe("persistent cross-version investigation workspace", () => {
|
||||
describe("persistent investigation workspace history", () => {
|
||||
it("appends a changed-content run without replacing earlier Evidence", async () => {
|
||||
const { directory, right, input } = await fixture();
|
||||
const first = await runCrossVersionInvestigation(input, policy(directory), {
|
||||
inputRoots: [directory],
|
||||
});
|
||||
const first = await runCrossVersionInvestigation(
|
||||
input,
|
||||
policy(directory),
|
||||
{},
|
||||
);
|
||||
if (!first.ok) throw first.error;
|
||||
const firstRun = first.value.workspace.runs[0];
|
||||
if (firstRun === undefined || firstRun.result_evidence_id === null)
|
||||
@@ -204,7 +206,7 @@ describe("persistent investigation workspace history", () => {
|
||||
const second = await runCrossVersionInvestigation(
|
||||
input,
|
||||
policy(directory),
|
||||
{ inputRoots: [directory] },
|
||||
{},
|
||||
);
|
||||
expect(second).toMatchObject({
|
||||
ok: true,
|
||||
@@ -251,7 +253,7 @@ describe("persistent investigation workspace history", () => {
|
||||
const strict = await runCrossVersionInvestigation(
|
||||
crossVersionInvestigationInputSchema.parse(base),
|
||||
policy(directory),
|
||||
{ inputRoots: [directory] },
|
||||
{},
|
||||
);
|
||||
expect(strict).toMatchObject({
|
||||
ok: false,
|
||||
@@ -268,7 +270,7 @@ describe("persistent investigation workspace history", () => {
|
||||
const continued = await runCrossVersionInvestigation(
|
||||
continuedInput,
|
||||
policy(directory),
|
||||
{ inputRoots: [directory], integrityContinueEnabled: true },
|
||||
{ integrityContinueEnabled: true },
|
||||
);
|
||||
expect(continued).toMatchObject({
|
||||
ok: true,
|
||||
@@ -289,7 +291,6 @@ describe("persistent investigation workspace history", () => {
|
||||
).toMatchObject({ status: "contradiction" });
|
||||
await expect(
|
||||
runCrossVersionInvestigation(continuedInput, policy(directory), {
|
||||
inputRoots: [directory],
|
||||
integrityContinueEnabled: true,
|
||||
}),
|
||||
).resolves.toMatchObject({ ok: true, value: { reused: true } });
|
||||
@@ -299,9 +300,11 @@ describe("persistent investigation workspace history", () => {
|
||||
workspace_path: continuedInput.workspace_path,
|
||||
});
|
||||
await expect(
|
||||
runCrossVersionInvestigation(strictAfterContinuation, policy(directory), {
|
||||
inputRoots: [directory],
|
||||
}),
|
||||
runCrossVersionInvestigation(
|
||||
strictAfterContinuation,
|
||||
policy(directory),
|
||||
{},
|
||||
),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "ArtifactOperationError", reason: "integrity" },
|
||||
|
||||
@@ -55,9 +55,7 @@ describe("persistent cross-version investigation workspace", () => {
|
||||
mode: 0o600,
|
||||
});
|
||||
expect(
|
||||
await runCrossVersionInvestigation(input, policy(directory), {
|
||||
inputRoots: [directory],
|
||||
}),
|
||||
await runCrossVersionInvestigation(input, policy(directory), {}),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "InvestigationWorkspaceError", reason: "locked" },
|
||||
@@ -65,9 +63,7 @@ describe("persistent cross-version investigation workspace", () => {
|
||||
await rm(`${path}.lock`);
|
||||
await writeFile(`${path}.lock`, "occupied\n", { mode: 0o600 });
|
||||
expect(
|
||||
await runCrossVersionInvestigation(input, policy(directory), {
|
||||
inputRoots: [directory],
|
||||
}),
|
||||
await runCrossVersionInvestigation(input, policy(directory), {}),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "InvestigationWorkspaceError", reason: "locked" },
|
||||
@@ -77,7 +73,7 @@ describe("persistent cross-version investigation workspace", () => {
|
||||
const completed = await runCrossVersionInvestigation(
|
||||
input,
|
||||
policy(directory),
|
||||
{ inputRoots: [directory] },
|
||||
{},
|
||||
);
|
||||
if (!completed.ok) throw completed.error;
|
||||
await expect(stat(`${path}.lock`)).rejects.toMatchObject({
|
||||
@@ -87,7 +83,7 @@ describe("persistent cross-version investigation workspace", () => {
|
||||
await runCrossVersionInvestigation(
|
||||
{ ...input, expected_workspace_revision: 2 },
|
||||
policy(directory),
|
||||
{ inputRoots: [directory] },
|
||||
{},
|
||||
),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
@@ -116,7 +112,7 @@ describe("persistent cross-version investigation workspace", () => {
|
||||
await runCrossVersionInvestigation(
|
||||
{ ...input, workspace_path: cancelledPath },
|
||||
policy(directory),
|
||||
{ inputRoots: [directory], signal: controller.signal },
|
||||
{ signal: controller.signal },
|
||||
),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
@@ -129,9 +125,7 @@ describe("persistent cross-version investigation workspace", () => {
|
||||
const approved = join(directory, "approved");
|
||||
await mkdir(approved);
|
||||
expect(
|
||||
await runCrossVersionInvestigation(input, policy(approved), {
|
||||
inputRoots: [directory],
|
||||
}),
|
||||
await runCrossVersionInvestigation(input, policy(approved), {}),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
@@ -148,26 +142,11 @@ describe("persistent cross-version investigation workspace", () => {
|
||||
await runCrossVersionInvestigation(
|
||||
{ ...input, workspace_path: escaped },
|
||||
policy(approved),
|
||||
{ inputRoots: [directory] },
|
||||
{},
|
||||
),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "InvestigationWorkspaceError", reason: "not-file" },
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects artifact inputs outside independently approved roots", async () => {
|
||||
const { directory, input, path } = await fixture();
|
||||
const approvedInputs = join(directory, "approved-inputs");
|
||||
await mkdir(approvedInputs);
|
||||
expect(
|
||||
await runCrossVersionInvestigation(input, policy(directory), {
|
||||
inputRoots: [approvedInputs],
|
||||
}),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "ArtifactOperationError", reason: "path" },
|
||||
});
|
||||
await expect(stat(path)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,7 +2,7 @@ import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
|
||||
import { createHash } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import canonicalize from "canonicalize";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
@@ -21,7 +21,6 @@ import {
|
||||
parseInvestigationWorkspace,
|
||||
serializeInvestigationWorkspace,
|
||||
} from "../../../src/domain/investigationWorkspace.js";
|
||||
import { ok } from "../../../src/domain/result.js";
|
||||
|
||||
const digestCanonical = (value: unknown): string => {
|
||||
const encoded = canonicalize(value);
|
||||
@@ -65,7 +64,7 @@ describe("persistent cross-version investigation workspace", () => {
|
||||
const completed = await runCrossVersionInvestigation(
|
||||
input,
|
||||
policy(directory),
|
||||
{ inputRoots: [directory] },
|
||||
{},
|
||||
);
|
||||
if (!completed.ok) throw completed.error;
|
||||
const current = completed.value.workspace;
|
||||
@@ -159,7 +158,7 @@ describe("persistent cross-version investigation workspace", () => {
|
||||
runCrossVersionInvestigation(
|
||||
{ ...input, expected_workspace_revision: current.revision },
|
||||
policy(directory),
|
||||
{ inputRoots: [directory] },
|
||||
{},
|
||||
),
|
||||
).resolves.toMatchObject({ ok: true, value: { reused: true } });
|
||||
await expect(
|
||||
@@ -172,7 +171,7 @@ describe("persistent cross-version investigation workspace", () => {
|
||||
},
|
||||
},
|
||||
policy(directory),
|
||||
{ inputRoots: [directory] },
|
||||
{},
|
||||
),
|
||||
).resolves.toMatchObject({ ok: true, value: { reused: false } });
|
||||
});
|
||||
@@ -181,9 +180,11 @@ describe("persistent cross-version investigation workspace", () => {
|
||||
describe("persistent investigation workspace reuse", () => {
|
||||
it("checkpoints, validates, and reuses a completed deterministic run", async () => {
|
||||
const { directory, path, input } = await fixture();
|
||||
const first = await runCrossVersionInvestigation(input, policy(directory), {
|
||||
inputRoots: [directory],
|
||||
});
|
||||
const first = await runCrossVersionInvestigation(
|
||||
input,
|
||||
policy(directory),
|
||||
{},
|
||||
);
|
||||
expect(first).toMatchObject({
|
||||
ok: true,
|
||||
value: { reused: false, workspace: { revision: 3 } },
|
||||
@@ -212,7 +213,7 @@ describe("persistent investigation workspace reuse", () => {
|
||||
const second = await runCrossVersionInvestigation(
|
||||
input,
|
||||
policy(directory),
|
||||
{ inputRoots: [directory] },
|
||||
{},
|
||||
);
|
||||
expect(second).toMatchObject({
|
||||
ok: true,
|
||||
@@ -235,12 +236,8 @@ describe("persistent investigation workspace reuse", () => {
|
||||
workspace_path: join(directory, "repeated-workspace.json"),
|
||||
});
|
||||
const [first, repeated] = await Promise.all([
|
||||
runCrossVersionInvestigation(input, policy(directory), {
|
||||
inputRoots: [directory],
|
||||
}),
|
||||
runCrossVersionInvestigation(repeatedInput, policy(directory), {
|
||||
inputRoots: [directory],
|
||||
}),
|
||||
runCrossVersionInvestigation(input, policy(directory), {}),
|
||||
runCrossVersionInvestigation(repeatedInput, policy(directory), {}),
|
||||
]);
|
||||
if (!first.ok) throw first.error;
|
||||
if (!repeated.ok) throw repeated.error;
|
||||
@@ -293,21 +290,16 @@ describe("persistent investigation workspace replay", () => {
|
||||
const completed = await runCrossVersionInvestigation(
|
||||
input,
|
||||
policy(directory),
|
||||
{ inputRoots: [directory] },
|
||||
{},
|
||||
);
|
||||
if (!completed.ok) throw completed.error;
|
||||
const run = completed.value.workspace.runs[0];
|
||||
if (run === undefined || run.comparison_evidence_id === null)
|
||||
throw new Error("missing completed run");
|
||||
|
||||
const defaultAuthorization = vi.fn(() => Promise.resolve(ok(null)));
|
||||
await expect(
|
||||
runCrossVersionInvestigation(input, policy(directory), {
|
||||
inputRoots: [directory],
|
||||
authorizeInputRead: defaultAuthorization,
|
||||
}),
|
||||
runCrossVersionInvestigation(input, policy(directory), {}),
|
||||
).resolves.toMatchObject({ ok: true, value: { reused: true } });
|
||||
expect(defaultAuthorization).toHaveBeenCalledOnce();
|
||||
|
||||
const inconsistentRun = investigationRunSchema.parse({
|
||||
...run,
|
||||
@@ -335,7 +327,7 @@ describe("persistent investigation workspace replay", () => {
|
||||
replay_run_id: run.run_id,
|
||||
},
|
||||
policy(directory),
|
||||
{ inputRoots: [] },
|
||||
{},
|
||||
),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
@@ -346,7 +338,6 @@ describe("persistent investigation workspace replay", () => {
|
||||
rm(left, { recursive: true, force: true }),
|
||||
rm(right, { recursive: true, force: true }),
|
||||
]);
|
||||
const replayAuthorization = vi.fn(() => Promise.resolve(ok(null)));
|
||||
await expect(
|
||||
runCrossVersionInvestigation(
|
||||
{
|
||||
@@ -355,7 +346,7 @@ describe("persistent investigation workspace replay", () => {
|
||||
replay_run_id: run.run_id,
|
||||
},
|
||||
policy(directory),
|
||||
{ inputRoots: [], authorizeInputRead: replayAuthorization },
|
||||
{},
|
||||
),
|
||||
).resolves.toMatchObject({
|
||||
ok: true,
|
||||
@@ -365,7 +356,6 @@ describe("persistent investigation workspace replay", () => {
|
||||
workspace: { revision: completed.value.workspace.revision },
|
||||
},
|
||||
});
|
||||
expect(replayAuthorization).not.toHaveBeenCalled();
|
||||
|
||||
for (const replayInput of [
|
||||
{ ...input, replay_run_id: `run_${"f".repeat(64)}` },
|
||||
@@ -377,10 +367,7 @@ describe("persistent investigation workspace replay", () => {
|
||||
},
|
||||
])
|
||||
await expect(
|
||||
runCrossVersionInvestigation(replayInput, policy(directory), {
|
||||
inputRoots: [],
|
||||
authorizeInputRead: replayAuthorization,
|
||||
}),
|
||||
runCrossVersionInvestigation(replayInput, policy(directory), {}),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
@@ -388,6 +375,5 @@ describe("persistent investigation workspace replay", () => {
|
||||
reason: "revision-conflict",
|
||||
},
|
||||
});
|
||||
expect(replayAuthorization).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -19,54 +19,22 @@ import {
|
||||
} from "../../../src/artifacts/ArtifactReader.js";
|
||||
import { writeJavaScriptArtifactFixture } from "../../fixtures/javascriptArtifactApplication.js";
|
||||
|
||||
it("discovers source maps without reading them until separately approved", async () => {
|
||||
it("reads local source maps as part of static artifact analysis", async () => {
|
||||
const root = await fixtureDirectory();
|
||||
const unapproved = await reconstructJavaScriptArtifact({
|
||||
input_path: root,
|
||||
source_map_read_approved: false,
|
||||
});
|
||||
const approved = await reconstructJavaScriptArtifact({
|
||||
input_path: root,
|
||||
source_map_read_approved: true,
|
||||
});
|
||||
const result = await reconstructJavaScriptArtifact({ input_path: root });
|
||||
|
||||
expect(unapproved.graph.nodes.some(({ kind }) => kind === "source-map")).toBe(
|
||||
expect(result.graph.nodes.some(({ kind }) => kind === "source-map")).toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
unapproved.graph.nodes.some(({ kind }) => kind === "source-module"),
|
||||
).toBe(false);
|
||||
expect(unapproved.graph.coverage).toMatchObject({
|
||||
status: "partial",
|
||||
truncated: false,
|
||||
omitted_count: null,
|
||||
});
|
||||
expect(unapproved.statistics.policy_filtered_text_files).toBe(1);
|
||||
expect(unapproved.graph.nodes).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
kind: "unknown",
|
||||
observations: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
properties: expect.objectContaining({
|
||||
operation: "parse-local-source-map",
|
||||
}),
|
||||
evidence: expect.objectContaining({ state: "unavailable" }),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
]),
|
||||
expect(result.graph.nodes.some(({ kind }) => kind === "source-module")).toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
approved.graph.nodes.some(({ kind }) => kind === "source-module"),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("reports text and AST limits as truncation instead of absence", async () => {
|
||||
const root = await fixtureDirectory();
|
||||
const result = await reconstructJavaScriptArtifact({
|
||||
input_path: root,
|
||||
source_map_read_approved: true,
|
||||
limits: {
|
||||
max_text_file_bytes: 128,
|
||||
max_total_text_bytes: 1_024,
|
||||
@@ -163,7 +131,6 @@ it("keeps malformed JavaScript, package metadata, and source maps as explicit un
|
||||
|
||||
const result = await reconstructJavaScriptArtifact({
|
||||
input_path: root,
|
||||
source_map_read_approved: true,
|
||||
});
|
||||
const unknownOperations = result.graph.nodes
|
||||
.filter(({ kind }) => kind === "unknown")
|
||||
@@ -213,7 +180,6 @@ it("applies one source-map source budget across every local map", async () => {
|
||||
|
||||
const result = await reconstructJavaScriptArtifact({
|
||||
input_path: root,
|
||||
source_map_read_approved: true,
|
||||
limits: { max_source_map_sources: 3 },
|
||||
});
|
||||
|
||||
@@ -297,12 +263,12 @@ it("preserves cancellation and explicit format diagnostics", async () => {
|
||||
reason: "format",
|
||||
message: expect.stringContaining(root),
|
||||
});
|
||||
expect(() =>
|
||||
expect(
|
||||
javascriptArtifactReconstructionInputSchema.parse({
|
||||
input_path: root,
|
||||
limits: { max_entries: 100_000 },
|
||||
}),
|
||||
).toThrow(/graph contract/iu);
|
||||
}).limits.max_entries,
|
||||
).toBe(100_000);
|
||||
});
|
||||
|
||||
class TraversalReader implements ArtifactReader {
|
||||
|
||||
@@ -13,7 +13,6 @@ import {
|
||||
createJavaScriptApplicationGraph,
|
||||
createJavaScriptApplicationNode,
|
||||
} from "../../../src/domain/javascriptApplicationGraph.js";
|
||||
import { permissionAuthorityForRoot } from "../../fixtures/permissionAuthority.js";
|
||||
|
||||
describe("JavaScript export return-shape comparison", () => {
|
||||
it("reports exactly the heading depth addition from source-owned parser fixtures", async () => {
|
||||
@@ -194,7 +193,6 @@ describe("JavaScript export return-shape selection", () => {
|
||||
});
|
||||
const ambiguousGraph = createJavaScriptApplicationGraph({
|
||||
schema: "JavaScriptApplicationGraph",
|
||||
schema_version: 1,
|
||||
root_node_ids: left.graph.root_node_ids,
|
||||
nodes: [...left.graph.nodes, duplicate],
|
||||
edges: left.graph.edges,
|
||||
@@ -271,14 +269,8 @@ const compare = (
|
||||
});
|
||||
|
||||
const analyzeGraph = async (root: string) => {
|
||||
const authority = await permissionAuthorityForRoot(
|
||||
root,
|
||||
["investigation_input"],
|
||||
["investigation_input"],
|
||||
);
|
||||
const result = await analyzeJavaScriptApplication(authority, {
|
||||
const result = await analyzeJavaScriptApplication({
|
||||
input_path: root,
|
||||
approved: true,
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
return parseApplicationGraphEvidence(result.value);
|
||||
|
||||
@@ -234,7 +234,7 @@ const inspect = (
|
||||
) => {
|
||||
const target = managedPeFixtureTarget(bytes, path);
|
||||
const result = inspectManagedMembersBytes(bytes, target, limits);
|
||||
const method = result.methods.items[0];
|
||||
const method = result.methods[0];
|
||||
if (method === undefined) throw new Error("fixture has no method");
|
||||
return {
|
||||
result,
|
||||
|
||||
@@ -235,7 +235,6 @@ const dependenciesFor = (root: string, onExecute: () => void) => {
|
||||
execute: async (prepared) => {
|
||||
onExecute();
|
||||
return {
|
||||
schema_version: 1,
|
||||
plan_digest: prepared.publicPlan.plan_digest,
|
||||
outcomes: [
|
||||
{
|
||||
|
||||
@@ -53,11 +53,7 @@ describe("runtime identification", () => {
|
||||
await writeFile(path, await writer.close());
|
||||
|
||||
const inventory = parseEvidence(
|
||||
await runProviderAnalysis(path, "inventory_artifact", {
|
||||
node_limit: 100,
|
||||
occurrence_limit: 100,
|
||||
edge_limit: 100,
|
||||
}),
|
||||
await runProviderAnalysis(path, "inventory_artifact", {}),
|
||||
);
|
||||
const first = identifyRuntimes({ inventory_evidence: [inventory] });
|
||||
const second = identifyRuntimes({ inventory_evidence: [inventory] });
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
|
||||
import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import { ArtifactProvider } from "../../../src/artifacts/ArtifactProvider.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
|
||||
it("returns every artifact occurrence in one MCP call", async () => {
|
||||
const directory = await createTestTempDirectory("rea-artifact-inline-");
|
||||
const archive = join(directory, "many.zip");
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
const fileCount = 520;
|
||||
for (let index = 0; index < fileCount; index += 1) {
|
||||
await writer.add(
|
||||
`files/${String(index)}.txt`,
|
||||
new TextReader(`file-${String(index)}`),
|
||||
);
|
||||
}
|
||||
await writeFile(archive, await writer.close());
|
||||
|
||||
const session = createTestBinarySession(new ArtifactProvider());
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({ name: "artifact-inline-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const opened = await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: archive },
|
||||
});
|
||||
expect(opened.isError).not.toBe(true);
|
||||
const result = await client.callTool({
|
||||
name: "inventory_artifact",
|
||||
arguments: {},
|
||||
});
|
||||
expect(result.isError, JSON.stringify(result.structuredContent)).not.toBe(
|
||||
true,
|
||||
);
|
||||
const inventory = z
|
||||
.object({
|
||||
occurrences: z.object({
|
||||
items: z.array(z.object({ logical_path: z.string() })),
|
||||
total: z.number(),
|
||||
}),
|
||||
})
|
||||
.parse(
|
||||
z.object({ result: z.unknown() }).parse(result.structuredContent)
|
||||
.result,
|
||||
);
|
||||
expect(inventory.occurrences.items).toHaveLength(fileCount + 1);
|
||||
expect(inventory.occurrences.total).toBe(fileCount + 1);
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close(), session.close()]);
|
||||
}
|
||||
});
|
||||
@@ -12,7 +12,6 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import { ArtifactProvider } from "../../../src/artifacts/ArtifactProvider.js";
|
||||
import { ARTIFACT_COMPARISON_EXAMPLE } from "../../../src/contracts/artifactComparisonExample.js";
|
||||
import { evidenceBundleSchema } from "../../../src/domain/evidenceBundle.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
@@ -99,6 +98,7 @@ const artifactInventoryResultSchema = z.object({
|
||||
items: z.array(
|
||||
z.object({ logical_path: z.string(), hash_status: z.string() }),
|
||||
),
|
||||
total: z.number(),
|
||||
}),
|
||||
integrity_contradictions: z.array(
|
||||
z.object({
|
||||
@@ -144,18 +144,6 @@ it("records an approved mismatch, preserves verified siblings, and never reports
|
||||
name: "open_binary",
|
||||
arguments: { path: archive },
|
||||
});
|
||||
const limited = await client.callTool({
|
||||
name: "inventory_artifact",
|
||||
arguments: {
|
||||
integrity_policy: "record-and-continue",
|
||||
integrity_continue_approved: true,
|
||||
max_integrity_mismatches: 1,
|
||||
},
|
||||
});
|
||||
expect(limited).toMatchObject({
|
||||
isError: true,
|
||||
structuredContent: { error: { code: "truncated" } },
|
||||
});
|
||||
const result = await client.callTool({
|
||||
name: "inventory_artifact",
|
||||
arguments: {
|
||||
@@ -163,7 +151,9 @@ it("records an approved mismatch, preserves verified siblings, and never reports
|
||||
integrity_continue_approved: true,
|
||||
},
|
||||
});
|
||||
expect(result.isError).not.toBe(true);
|
||||
expect(result.isError, JSON.stringify(result.structuredContent)).not.toBe(
|
||||
true,
|
||||
);
|
||||
const compact = compactResult(result.structuredContent);
|
||||
const evidence = session.evidenceById(compact.evidence_id);
|
||||
if (evidence === undefined) throw new Error("missing inventory Evidence");
|
||||
@@ -275,7 +265,12 @@ it("rejects altered payloads that reuse session Evidence IDs", async () => {
|
||||
},
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
expect(session.exportEvidenceBundle().records).toHaveLength(2);
|
||||
expect(
|
||||
session.evidenceById(ARTIFACT_COMPARISON_EXAMPLE.left.evidence_id),
|
||||
).toBeDefined();
|
||||
expect(
|
||||
session.evidenceById(ARTIFACT_COMPARISON_EXAMPLE.right.evidence_id),
|
||||
).toBeDefined();
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close(), session.close()]);
|
||||
}
|
||||
@@ -302,13 +297,18 @@ it("rejects comparison Evidence that is not owned by the session", async () => {
|
||||
arguments: ARTIFACT_COMPARISON_EXAMPLE,
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
expect(session.exportEvidenceBundle().records).toEqual([]);
|
||||
expect(
|
||||
session.evidenceById(ARTIFACT_COMPARISON_EXAMPLE.left.evidence_id),
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
session.evidenceById(ARTIFACT_COMPARISON_EXAMPLE.right.evidence_id),
|
||||
).toBeUndefined();
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close(), session.close()]);
|
||||
}
|
||||
});
|
||||
|
||||
it("opens archives without Hopper, compares them, and exports linked evidence", async () => {
|
||||
it("returns full artifact graphs inline and compares changed inventories", async () => {
|
||||
const directory = await createTestTempDirectory("rea-artifact-mcp-");
|
||||
const archive = join(directory, "fixture.ipa");
|
||||
const changedArchive = join(directory, "changed.ipa");
|
||||
@@ -336,7 +336,7 @@ it("opens archives without Hopper, compares them, and exports linked evidence",
|
||||
expect(opened.isError).not.toBe(true);
|
||||
const inspected = await client.callTool({
|
||||
name: "inspect_artifact",
|
||||
arguments: { max_observations: 1, max_relationships: 1 },
|
||||
arguments: {},
|
||||
});
|
||||
expect(inspected.isError).not.toBe(true);
|
||||
const inspectionResult = compactResult(inspected.structuredContent);
|
||||
@@ -354,10 +354,9 @@ it("opens archives without Hopper, compares them, and exports linked evidence",
|
||||
}),
|
||||
),
|
||||
coverage: z.object({
|
||||
status: z.literal("truncated"),
|
||||
status: z.literal("complete-within-substeps"),
|
||||
substeps_completed: z.literal(1),
|
||||
}),
|
||||
unexplored_branches: z.array(z.object({ reason: z.string() })),
|
||||
})
|
||||
.parse(inspectionResult.result);
|
||||
expect(inspection.substeps).toHaveLength(1);
|
||||
@@ -367,11 +366,6 @@ it("opens archives without Hopper, compares them, and exports linked evidence",
|
||||
expect(inspectionEvidence.evidence_links).toEqual([
|
||||
inspection.substeps[0]?.evidence_id,
|
||||
]);
|
||||
expect(inspection.unexplored_branches).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ reason: "page-limit" }),
|
||||
]),
|
||||
);
|
||||
const inventory = await client.callTool({
|
||||
name: "inventory_artifact",
|
||||
arguments: {},
|
||||
@@ -384,9 +378,22 @@ it("opens archives without Hopper, compares them, and exports linked evidence",
|
||||
provider: { id: "rea-artifact-graph" },
|
||||
subject: { format: "ipa" },
|
||||
});
|
||||
expect(inventoryResult.result).toMatchObject({
|
||||
manifest: { root_format: "ipa" },
|
||||
});
|
||||
expect(
|
||||
z
|
||||
.object({
|
||||
manifest: z.object({ root_format: z.literal("ipa") }),
|
||||
occurrences: z.object({
|
||||
items: z.array(z.object({ logical_path: z.string() })),
|
||||
}),
|
||||
})
|
||||
.parse(inventoryResult.result).occurrences.items,
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
logical_path: "Payload/Fixture.app/main.js",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
const openedChanged = await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: changedArchive },
|
||||
@@ -421,32 +428,11 @@ it("opens archives without Hopper, compares them, and exports linked evidence",
|
||||
result: {
|
||||
items: [
|
||||
expect.objectContaining({
|
||||
unknown: expect.objectContaining({
|
||||
domain: "artifact-comparison",
|
||||
}),
|
||||
domain: "artifact-comparison",
|
||||
}),
|
||||
],
|
||||
},
|
||||
});
|
||||
const snapshotted = await client.callTool({
|
||||
name: "snapshot_evidence_bundle",
|
||||
arguments: {},
|
||||
});
|
||||
const bundleUri = z
|
||||
.object({ result: z.object({ bundle_uri: z.string() }) })
|
||||
.parse(snapshotted.structuredContent).result.bundle_uri;
|
||||
const bundleResource = await client.readResource({ uri: bundleUri });
|
||||
const bundle = evidenceBundleSchema.parse(
|
||||
JSON.parse(
|
||||
z.object({ text: z.string() }).parse(bundleResource.contents[0]).text,
|
||||
),
|
||||
);
|
||||
expect(bundle.records).toHaveLength(6);
|
||||
expect(bundle.artifacts).toContainEqual({
|
||||
digest: { sha256: evidence.subject?.digest.sha256 },
|
||||
format: "ipa",
|
||||
architecture: null,
|
||||
});
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close(), session.close()]);
|
||||
}
|
||||
@@ -457,6 +443,5 @@ const compactResult = (value: unknown) =>
|
||||
.object({
|
||||
result: z.unknown(),
|
||||
evidence_id: z.string(),
|
||||
evidence_uri: z.string(),
|
||||
})
|
||||
.parse(value);
|
||||
|
||||
@@ -53,7 +53,7 @@ it(
|
||||
);
|
||||
const status = await connected.client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: { detail: "full" },
|
||||
arguments: {},
|
||||
});
|
||||
expect(status.structuredContent).toMatchObject({
|
||||
result: {
|
||||
@@ -77,7 +77,7 @@ it(
|
||||
expect(listed.isError).not.toBe(true);
|
||||
expect(listed.structuredContent).toMatchObject({
|
||||
result: {
|
||||
targets: { items: [{ target_id: "allowed-page" }] },
|
||||
targets: [{ target_id: "allowed-page" }],
|
||||
},
|
||||
});
|
||||
const unapprovedSourceCapture = await connected.client.callTool({
|
||||
@@ -246,12 +246,10 @@ const verifySessionAndComparisonTools = async (
|
||||
result: { status: "identical", changed_pixels: 0 },
|
||||
});
|
||||
const evidenceId = evidenceIdOf(inspected.structuredContent);
|
||||
const evidence = await connected.client.readResource({
|
||||
uri: `rea://evidence/${evidenceId}`,
|
||||
expect(inspected.structuredContent).toMatchObject({
|
||||
evidence_id: evidenceId,
|
||||
result: expect.any(Object),
|
||||
});
|
||||
expect(evidence.contents[0]).toEqual(
|
||||
expect.objectContaining({ text: expect.stringContaining(evidenceId) }),
|
||||
);
|
||||
};
|
||||
|
||||
it("denies origins outside the administrator ceiling before CDP attach", async () => {
|
||||
|
||||
@@ -75,7 +75,6 @@ const captureFor = (scenario: BrowserScenario): BrowserScenarioCapture => {
|
||||
},
|
||||
});
|
||||
return browserScenarioCaptureSchema.parse({
|
||||
schema_version: 1,
|
||||
browser: {
|
||||
mode: scenario.browser.mode,
|
||||
process_ownership: "provider-owned",
|
||||
@@ -108,7 +107,6 @@ const captureFor = (scenario: BrowserScenario): BrowserScenarioCapture => {
|
||||
};
|
||||
|
||||
const scenario = (origin = "https://app.example.test") => ({
|
||||
schema_version: 1,
|
||||
browser: {
|
||||
mode: "launch",
|
||||
executable_path: process.execPath,
|
||||
|
||||
@@ -72,7 +72,6 @@ describe("bundle comparison MCP integration", () => {
|
||||
expect(result.structuredContent).toMatchObject({
|
||||
result: { status: "changed" },
|
||||
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
|
||||
evidence_uri: expect.stringMatching(/^rea:\/\/evidence\/ev_/u),
|
||||
});
|
||||
} finally {
|
||||
await connected.close();
|
||||
|
||||
@@ -58,7 +58,6 @@ it("exposes root-confined Electron discovery and inspection as Evidence v2", asy
|
||||
REA_ELECTRON_OBSERVE_ENABLED: "true",
|
||||
REA_ELECTRON_CDP_ENDPOINTS_JSON: JSON.stringify([browser.endpoint]),
|
||||
REA_ELECTRON_FILE_ROOTS_JSON: JSON.stringify([root]),
|
||||
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([root]),
|
||||
});
|
||||
if (!config.ok) throw config.error;
|
||||
const authority = await loadConfiguredPermissionAuthority(config.value);
|
||||
@@ -95,7 +94,7 @@ it("exposes root-confined Electron discovery and inspection as Evidence v2", asy
|
||||
expect(listed.isError).not.toBe(true);
|
||||
expect(listed.structuredContent).toMatchObject({
|
||||
result: {
|
||||
targets: { items: [{ target_id: "electron-page" }] },
|
||||
targets: [{ target_id: "electron-page" }],
|
||||
},
|
||||
});
|
||||
const inspected = await client.callTool({
|
||||
@@ -112,7 +111,7 @@ it("exposes root-confined Electron discovery and inspection as Evidence v2", asy
|
||||
});
|
||||
const analyzed = await client.callTool({
|
||||
name: "analyze_javascript_application",
|
||||
arguments: { input_path: root, approved: true, detail: "full" },
|
||||
arguments: { input_path: root },
|
||||
});
|
||||
expect(analyzed.isError).not.toBe(true);
|
||||
expect(analyzed.structuredContent).toMatchObject({
|
||||
@@ -122,7 +121,7 @@ it("exposes root-confined Electron discovery and inspection as Evidence v2", asy
|
||||
expect(analysisText).toBeDefined();
|
||||
if (analysisText?.type !== "text")
|
||||
throw new TypeError("Missing JavaScript analysis text projection");
|
||||
expect(analysisText.text).not.toContain('"nodes":[');
|
||||
expect(analysisText.text).toContain('"nodes":[');
|
||||
const reconciled = await client.callTool({
|
||||
name: "reconcile_javascript_runtime",
|
||||
arguments: {
|
||||
@@ -242,7 +241,6 @@ it("exposes active Electron scenarios through the separately granted MCP boundar
|
||||
const captured = await client.callTool({
|
||||
name: "capture_electron_scenario",
|
||||
arguments: {
|
||||
schema_version: 1,
|
||||
executable_path: process.execPath,
|
||||
application_path: join(aliasedRoot, "main.js"),
|
||||
application_root: aliasedRoot,
|
||||
@@ -292,9 +290,7 @@ it("exposes the target-free static JavaScript application workflow", async () =>
|
||||
const root = await createTestTempDirectory("rea-electron-static-mcp-");
|
||||
temporary.push(root);
|
||||
await writeElectronBoundaryFixture(root);
|
||||
const config = parseConfig({
|
||||
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([root]),
|
||||
});
|
||||
const config = parseConfig({});
|
||||
if (!config.ok) throw config.error;
|
||||
const authority = await loadConfiguredPermissionAuthority(config.value);
|
||||
if (!authority.ok) throw authority.error;
|
||||
@@ -322,7 +318,7 @@ it("exposes the target-free static JavaScript application workflow", async () =>
|
||||
|
||||
const analyzed = await client.callTool({
|
||||
name: "analyze_javascript_application",
|
||||
arguments: { input_path: root, approved: true },
|
||||
arguments: { input_path: root },
|
||||
});
|
||||
|
||||
expect(analyzed.isError).not.toBe(true);
|
||||
@@ -330,9 +326,7 @@ it("exposes the target-free static JavaScript application workflow", async () =>
|
||||
.object({
|
||||
evidence_id: z.string(),
|
||||
result: z.object({
|
||||
schema_version: z.literal(2),
|
||||
input_path: z.string(),
|
||||
unknowns: z.array(z.string()),
|
||||
summary: z.object({
|
||||
browser_windows: z.number(),
|
||||
context_bridge_apis: z.number(),
|
||||
@@ -340,19 +334,19 @@ it("exposes the target-free static JavaScript application workflow", async () =>
|
||||
}),
|
||||
graph: z.object({
|
||||
graph_id: z.string(),
|
||||
node_count: z.number(),
|
||||
edge_count: z.number(),
|
||||
top_findings: z.array(z.unknown()),
|
||||
pages: z.object({ nodes: z.string(), edges: z.string() }),
|
||||
nodes: z.array(z.unknown()),
|
||||
edges: z.array(z.unknown()),
|
||||
}),
|
||||
semantic_graph: z.object({
|
||||
graph_id: z.string(),
|
||||
nodes: z.number(),
|
||||
relations: z.number(),
|
||||
unknown_frontiers: z.number(),
|
||||
query_tool: z.literal("trace_javascript_semantics"),
|
||||
nodes: z.array(z.unknown()),
|
||||
relations: z.array(z.unknown()),
|
||||
}),
|
||||
}),
|
||||
evidence: z.object({
|
||||
operation: z.literal("analyze_javascript_application"),
|
||||
parameters: z.object({ format: z.string() }),
|
||||
}),
|
||||
})
|
||||
.parse(analyzed.structuredContent);
|
||||
expect(projected.result).toMatchObject({
|
||||
@@ -363,83 +357,9 @@ it("exposes the target-free static JavaScript application workflow", async () =>
|
||||
ipc: { paired_renderer_transmissions: 4 },
|
||||
},
|
||||
});
|
||||
expect(projected.result.graph.node_count).toBeGreaterThan(0);
|
||||
expect(projected.result.semantic_graph.nodes).toBeGreaterThan(0);
|
||||
expect(JSON.stringify(analyzed.structuredContent)).not.toContain('"nodes":[');
|
||||
|
||||
const nodePage = await client.readResource({
|
||||
uri: projected.result.graph.pages.nodes,
|
||||
});
|
||||
const nodeContent = nodePage.contents[0];
|
||||
if (nodeContent === undefined || !("text" in nodeContent))
|
||||
throw new TypeError("Missing JavaScript application graph node page");
|
||||
expect(JSON.parse(nodeContent.text)).toMatchObject({
|
||||
evidence_id: projected.evidence_id,
|
||||
graph_id: projected.result.graph.graph_id,
|
||||
collection: "nodes",
|
||||
items: expect.any(Array),
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
});
|
||||
});
|
||||
|
||||
it("reports an unconfigured investigation ceiling before static analysis", async () => {
|
||||
const root = await createTestTempDirectory("rea-electron-denied-mcp-");
|
||||
temporary.push(root);
|
||||
await writeElectronBoundaryFixture(root);
|
||||
const config = parseConfig({});
|
||||
if (!config.ok) throw config.error;
|
||||
const authority = await loadConfiguredPermissionAuthority(config.value);
|
||||
if (!authority.ok) throw authority.error;
|
||||
const session = createTestBinarySession(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(session, session, {
|
||||
permissionAuthority: authority.value,
|
||||
});
|
||||
const client = new Client({
|
||||
name: "electron-denied-mcp-test",
|
||||
version: "1",
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server, session);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
|
||||
const status = await client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: {
|
||||
detail: "capabilities",
|
||||
capability_family: "electron-provider",
|
||||
limit: 100,
|
||||
},
|
||||
});
|
||||
expect(status.structuredContent).toMatchObject({
|
||||
result: {
|
||||
capabilities: {
|
||||
items: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: "analyze_javascript_application",
|
||||
available: false,
|
||||
reason: "policy_disabled",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
name: "reconcile_javascript_runtime",
|
||||
available: true,
|
||||
reason: "available",
|
||||
}),
|
||||
]),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
(await client.listTools()).tools.some(
|
||||
({ name }) => name === "analyze_javascript_application",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(projected.result.graph.nodes.length).toBeGreaterThan(0);
|
||||
expect(projected.result.semantic_graph.nodes.length).toBeGreaterThan(0);
|
||||
expect(projected.evidence.operation).toBe("analyze_javascript_application");
|
||||
});
|
||||
|
||||
const evidenceFor = (session: BinarySession, value: unknown) => {
|
||||
|
||||
@@ -25,24 +25,18 @@ const PROCEDURES = {
|
||||
"0x6": "prefix_TtOther",
|
||||
};
|
||||
|
||||
const page = (values: Readonly<Record<string, string>>) => ({
|
||||
items: Object.entries(values).map(([address, value]) => ({ address, value })),
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: Object.keys(values).length,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
});
|
||||
const inventory = (values: Readonly<Record<string, string>>) =>
|
||||
Object.entries(values).map(([address, value]) => ({ address, value }));
|
||||
|
||||
const fixturePort = (): AnalysisOperationPort => ({
|
||||
execute: (name, arguments_) => {
|
||||
switch (name) {
|
||||
case "list_procedures":
|
||||
return Promise.resolve(ok(page(PROCEDURES)));
|
||||
return Promise.resolve(ok(inventory(PROCEDURES)));
|
||||
case "list_names":
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
page({
|
||||
inventory({
|
||||
"0x10": "_OBJC_CLASS_$_Fixture",
|
||||
"0x11": "_OBJC_CLASS_$_Fixture",
|
||||
"0x12": "_OBJC_PROTOCOL_$_FixtureDelegate",
|
||||
@@ -93,7 +87,11 @@ const fixturePort = (): AnalysisOperationPort => ({
|
||||
case "list_documents":
|
||||
return Promise.resolve(ok(["fixture"]));
|
||||
case "list_strings":
|
||||
return Promise.resolve(ok(page({ "0x30": "hello" })));
|
||||
return Promise.resolve(ok(inventory({ "0x30": "hello" })));
|
||||
case "search_strings":
|
||||
return Promise.resolve(ok(inventory({ "0x30": "hello" })));
|
||||
case "search_procedures":
|
||||
return Promise.resolve(ok(inventory({})));
|
||||
case "analyze_function":
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
@@ -103,29 +101,16 @@ const fixturePort = (): AnalysisOperationPort => ({
|
||||
signature: null,
|
||||
locals: [],
|
||||
},
|
||||
pseudocode: {
|
||||
text: "return 0;",
|
||||
total_chars: 9,
|
||||
returned_chars: 9,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
assembly: {
|
||||
items: [],
|
||||
total: 0,
|
||||
returned: 0,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
comments: emptyBounded(),
|
||||
callers: emptyBounded(),
|
||||
callees: emptyBounded(),
|
||||
incoming_references: emptyBounded(),
|
||||
outgoing_references: emptyBounded(),
|
||||
referenced_strings: emptyBounded(),
|
||||
referenced_names: emptyBounded(),
|
||||
basic_blocks: emptyBounded(),
|
||||
instruction_scan: { scanned: 0, truncated: false },
|
||||
pseudocode: "return 0;",
|
||||
assembly: [],
|
||||
comments: [],
|
||||
callers: [],
|
||||
callees: [],
|
||||
incoming_references: [],
|
||||
outgoing_references: [],
|
||||
referenced_strings: [],
|
||||
referenced_names: [],
|
||||
basic_blocks: [],
|
||||
}),
|
||||
);
|
||||
default:
|
||||
@@ -134,14 +119,6 @@ const fixturePort = (): AnalysisOperationPort => ({
|
||||
},
|
||||
});
|
||||
|
||||
const emptyBounded = () => ({
|
||||
items: [],
|
||||
total: 0,
|
||||
returned: 0,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
});
|
||||
|
||||
const resources: Array<{ close(): Promise<void> }> = [];
|
||||
|
||||
afterEach(async () => {
|
||||
@@ -218,15 +195,15 @@ describe("enhanced MCP tools", () => {
|
||||
["get_objc_classes", { pattern: "Fixture" }],
|
||||
["get_objc_protocols", {}],
|
||||
["batch_decompile", { addresses: ["0x1", "0x2"] }],
|
||||
["get_call_graph", { address: "0x1", direction: "forward", depth: 2 }],
|
||||
["get_call_graph", { address: "0x1", direction: "forward" }],
|
||||
["analyze_swift_types", {}],
|
||||
["find_xrefs_to_name", { name: "entry" }],
|
||||
["binary_overview", {}],
|
||||
["analyze_function", { procedure: "0x1" }],
|
||||
["inspect_native_api", { 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 }],
|
||||
["trace_feature", { query: "hello" }],
|
||||
["find_code_for_string", { query: "hello" }],
|
||||
["trace_call_path", { start: "0x1", goal: "0x2" }],
|
||||
] as const;
|
||||
const results = await Promise.all(
|
||||
calls.map(async ([name, arguments_]) =>
|
||||
@@ -267,7 +244,7 @@ describe("enhanced MCP tools", () => {
|
||||
});
|
||||
expect(results[8]).toMatchObject({
|
||||
procedure: { address: "0x1", name: "entry" },
|
||||
pseudocode: { text: "return 0;" },
|
||||
pseudocode: "return 0;",
|
||||
});
|
||||
expect(results[9]).toMatchObject({
|
||||
procedure: { address: "0x1", name: "entry" },
|
||||
|
||||
@@ -17,24 +17,18 @@ const PROCEDURES = {
|
||||
"0x6": "prefix_TtOther",
|
||||
};
|
||||
|
||||
const page = (values: Readonly<Record<string, string>>) => ({
|
||||
items: Object.entries(values).map(([address, value]) => ({ address, value })),
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: Object.keys(values).length,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
});
|
||||
const inventory = (values: Readonly<Record<string, string>>) =>
|
||||
Object.entries(values).map(([address, value]) => ({ address, value }));
|
||||
|
||||
const fixturePort = (): AnalysisOperationPort => ({
|
||||
execute: (name, arguments_) => {
|
||||
switch (name) {
|
||||
case "list_procedures":
|
||||
return Promise.resolve(ok(page(PROCEDURES)));
|
||||
return Promise.resolve(ok(inventory(PROCEDURES)));
|
||||
case "list_names":
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
page({
|
||||
inventory({
|
||||
"0x10": "_OBJC_CLASS_$_Fixture",
|
||||
"0x11": "_OBJC_CLASS_$_Fixture",
|
||||
"0x12": "_OBJC_PROTOCOL_$_FixtureDelegate",
|
||||
@@ -85,7 +79,7 @@ const fixturePort = (): AnalysisOperationPort => ({
|
||||
case "list_documents":
|
||||
return Promise.resolve(ok(["fixture"]));
|
||||
case "list_strings":
|
||||
return Promise.resolve(ok(page({ "0x30": "hello" })));
|
||||
return Promise.resolve(ok(inventory({ "0x30": "hello" })));
|
||||
case "analyze_function":
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
@@ -154,15 +148,13 @@ const connect = async (analysis: AnalysisOperationPort = fixturePort()) => {
|
||||
};
|
||||
|
||||
describe("enhanced MCP tools", () => {
|
||||
it("returns Evidence IDs and explicit call-path frontiers at limits", async () => {
|
||||
it("returns Evidence IDs and a complete call path", 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,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -170,19 +162,12 @@ describe("enhanced MCP tools", () => {
|
||||
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.arrayContaining([
|
||||
expect.stringContaining("reached the node limit"),
|
||||
expect.stringContaining("reached the edge limit"),
|
||||
goal_status: "reached",
|
||||
nodes: expect.arrayContaining([
|
||||
expect.objectContaining({ address: "0x1" }),
|
||||
expect.objectContaining({ address: "0x3" }),
|
||||
]),
|
||||
limits: {
|
||||
max_nodes: 1,
|
||||
nodes_visited: 1,
|
||||
operations_used: 1,
|
||||
},
|
||||
truncated: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -22,24 +22,18 @@ const PROCEDURES = {
|
||||
"0x6": "prefix_TtOther",
|
||||
};
|
||||
|
||||
const page = (values: Readonly<Record<string, string>>) => ({
|
||||
items: Object.entries(values).map(([address, value]) => ({ address, value })),
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: Object.keys(values).length,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
});
|
||||
const inventory = (values: Readonly<Record<string, string>>) =>
|
||||
Object.entries(values).map(([address, value]) => ({ address, value }));
|
||||
|
||||
const fixturePort = (): AnalysisOperationPort => ({
|
||||
execute: (name, arguments_) => {
|
||||
switch (name) {
|
||||
case "list_procedures":
|
||||
return Promise.resolve(ok(page(PROCEDURES)));
|
||||
return Promise.resolve(ok(inventory(PROCEDURES)));
|
||||
case "list_names":
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
page({
|
||||
inventory({
|
||||
"0x10": "_OBJC_CLASS_$_Fixture",
|
||||
"0x11": "_OBJC_CLASS_$_Fixture",
|
||||
"0x12": "_OBJC_PROTOCOL_$_FixtureDelegate",
|
||||
@@ -90,7 +84,7 @@ const fixturePort = (): AnalysisOperationPort => ({
|
||||
case "list_documents":
|
||||
return Promise.resolve(ok(["fixture"]));
|
||||
case "list_strings":
|
||||
return Promise.resolve(ok(page({ "0x30": "hello" })));
|
||||
return Promise.resolve(ok(inventory({ "0x30": "hello" })));
|
||||
case "analyze_function":
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
@@ -195,13 +189,12 @@ describe("enhanced MCP tools", () => {
|
||||
execute: (name) =>
|
||||
name === "procedure_callees"
|
||||
? Promise.resolve(err(new AnalysisOutputError(name, "failed")))
|
||||
: Promise.resolve(ok(page({}))),
|
||||
: Promise.resolve(ok(inventory({}))),
|
||||
});
|
||||
|
||||
const graph = await tools.execute("get_call_graph", {
|
||||
address: "0x1",
|
||||
direction: "forward",
|
||||
depth: 1,
|
||||
});
|
||||
const unresolved = await tools.execute("find_xrefs_to_name", {
|
||||
name: "missing",
|
||||
@@ -233,53 +226,72 @@ describe("enhanced MCP tools", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("follows procedure pagination for whole-binary workflows", async () => {
|
||||
const offsets: number[] = [];
|
||||
const client = await connect({
|
||||
execute: (_name, arguments_) => {
|
||||
const offset = arguments_.offset;
|
||||
offsets.push(typeof offset === "number" ? offset : 0);
|
||||
it("traverses the complete reachable call graph and stops at cycles", async () => {
|
||||
const calls: string[] = [];
|
||||
const tools = new EnhancedTools({
|
||||
execute: (name, arguments_) => {
|
||||
if (name !== "procedure_callees") return Promise.resolve(ok([]));
|
||||
const address = String(arguments_.procedure);
|
||||
calls.push(address);
|
||||
const next = Number.parseInt(address.slice(2), 16) + 1;
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
items: [
|
||||
{
|
||||
address: offset === 500 ? "0x2" : "0x1",
|
||||
value: offset === 500 ? "_TtC4Last" : "_TtC5First",
|
||||
},
|
||||
],
|
||||
offset: typeof offset === "number" ? offset : 0,
|
||||
limit: 500,
|
||||
total: 2,
|
||||
next_offset: offset === 500 ? null : 500,
|
||||
has_more: offset !== 500,
|
||||
}),
|
||||
ok(next <= 8 ? [`0x${next.toString(16)}`] : ["0x2"]),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
const result = await tools.execute("get_call_graph", {
|
||||
address: "0x1",
|
||||
direction: "forward",
|
||||
});
|
||||
|
||||
expect(calls).toEqual([
|
||||
"0x1",
|
||||
"0x2",
|
||||
"0x3",
|
||||
"0x4",
|
||||
"0x5",
|
||||
"0x6",
|
||||
"0x7",
|
||||
"0x8",
|
||||
]);
|
||||
expect(result).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
"0": [{ address: "0x1", calls: ["0x2"], status: "ok" }],
|
||||
"7": [{ address: "0x8", calls: ["0x2"], status: "ok" }],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("uses every procedure in one complete inventory", async () => {
|
||||
const calls: string[] = [];
|
||||
const client = await connect({
|
||||
execute: (name) => {
|
||||
calls.push(name);
|
||||
return Promise.resolve(
|
||||
ok([
|
||||
{ address: "0x1", value: "_TtC5First" },
|
||||
{ address: "0x2", value: "_TtC4Last" },
|
||||
]),
|
||||
);
|
||||
},
|
||||
});
|
||||
const result = jsonResult(
|
||||
await client.callTool({ name: "swift_classes", arguments: {} }),
|
||||
);
|
||||
expect(offsets).toEqual([0, 500]);
|
||||
expect(calls).toEqual(["list_procedures"]);
|
||||
expect(result).toMatchObject({ count: 2 });
|
||||
});
|
||||
|
||||
it("does not start another page after cancellation", async () => {
|
||||
it("returns cancellation when a complete inventory call is cancelled", async () => {
|
||||
const controller = new AbortController();
|
||||
let calls = 0;
|
||||
const analysis: AnalysisOperationPort = {
|
||||
execute: () => {
|
||||
calls += 1;
|
||||
controller.abort();
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
items: [{ address: "0x1", value: "_TtC5First" }],
|
||||
offset: 0,
|
||||
limit: 500,
|
||||
total: 2,
|
||||
next_offset: 500,
|
||||
has_more: true,
|
||||
}),
|
||||
);
|
||||
return Promise.resolve(ok([{ address: "0x1", value: "_TtC5First" }]));
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
+33
-68
@@ -19,24 +19,18 @@ const PROCEDURES = {
|
||||
"0x6": "prefix_TtOther",
|
||||
};
|
||||
|
||||
const page = (values: Readonly<Record<string, string>>) => ({
|
||||
items: Object.entries(values).map(([address, value]) => ({ address, value })),
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: Object.keys(values).length,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
});
|
||||
const inventory = (values: Readonly<Record<string, string>>) =>
|
||||
Object.entries(values).map(([address, value]) => ({ address, value }));
|
||||
|
||||
const fixturePort = (): AnalysisOperationPort => ({
|
||||
execute: (name, arguments_) => {
|
||||
switch (name) {
|
||||
case "list_procedures":
|
||||
return Promise.resolve(ok(page(PROCEDURES)));
|
||||
return Promise.resolve(ok(inventory(PROCEDURES)));
|
||||
case "list_names":
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
page({
|
||||
inventory({
|
||||
"0x10": "_OBJC_CLASS_$_Fixture",
|
||||
"0x11": "_OBJC_CLASS_$_Fixture",
|
||||
"0x12": "_OBJC_PROTOCOL_$_FixtureDelegate",
|
||||
@@ -87,7 +81,7 @@ const fixturePort = (): AnalysisOperationPort => ({
|
||||
case "list_documents":
|
||||
return Promise.resolve(ok(["fixture"]));
|
||||
case "list_strings":
|
||||
return Promise.resolve(ok(page({ "0x30": "hello" })));
|
||||
return Promise.resolve(ok(inventory({ "0x30": "hello" })));
|
||||
case "analyze_function":
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
@@ -187,43 +181,31 @@ const jsonResult = (result: CallToolResult): JsonValue => {
|
||||
};
|
||||
|
||||
describe("enhanced MCP tools", () => {
|
||||
it("follows name pagination for exhaustive Objective-C discovery", async () => {
|
||||
const offsets: number[] = [];
|
||||
it("discovers every Objective-C class from one complete inventory", async () => {
|
||||
const calls: string[] = [];
|
||||
const client = await connect({
|
||||
execute: (name, arguments_) => {
|
||||
execute: (name) => {
|
||||
expect(name).toBe("list_names");
|
||||
const offset =
|
||||
typeof arguments_.offset === "number" ? arguments_.offset : 0;
|
||||
offsets.push(offset);
|
||||
calls.push(name);
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
items: [
|
||||
{
|
||||
address: offset === 500 ? "0x2" : "0x1",
|
||||
value:
|
||||
offset === 500 ? "_OBJC_CLASS_$_Last" : "_OBJC_CLASS_$_First",
|
||||
},
|
||||
],
|
||||
offset,
|
||||
limit: 500,
|
||||
total: 2,
|
||||
next_offset: offset === 500 ? null : 500,
|
||||
has_more: offset !== 500,
|
||||
}),
|
||||
ok([
|
||||
{ address: "0x1", value: "_OBJC_CLASS_$_First" },
|
||||
{ address: "0x2", value: "_OBJC_CLASS_$_Last" },
|
||||
]),
|
||||
);
|
||||
},
|
||||
});
|
||||
const result = jsonResult(
|
||||
await client.callTool({ name: "get_objc_classes", arguments: {} }),
|
||||
);
|
||||
expect(offsets).toEqual([0, 500]);
|
||||
expect(calls).toEqual(["list_names"]);
|
||||
expect(result).toMatchObject({ count: 2 });
|
||||
});
|
||||
|
||||
it("honors overview detail and limit while reporting exhaustive totals", async () => {
|
||||
const procedureOffsets: number[] = [];
|
||||
it("returns the complete overview inline with exhaustive totals", async () => {
|
||||
const inventoryCalls: string[] = [];
|
||||
const client = await connect({
|
||||
execute: (name, arguments_) => {
|
||||
execute: (name) => {
|
||||
switch (name) {
|
||||
case "list_segments":
|
||||
return Promise.resolve(
|
||||
@@ -235,34 +217,22 @@ describe("enhanced MCP tools", () => {
|
||||
case "list_documents":
|
||||
return Promise.resolve(ok(["fixture"]));
|
||||
case "list_strings":
|
||||
inventoryCalls.push(name);
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
items: [{ address: "0x30", value: "first page only" }],
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: 700,
|
||||
next_offset: 100,
|
||||
has_more: true,
|
||||
}),
|
||||
ok(
|
||||
Array.from({ length: 700 }, (_, index) => ({
|
||||
address: `0x${(0x30 + index).toString(16)}`,
|
||||
value: `string-${index}`,
|
||||
})),
|
||||
),
|
||||
);
|
||||
case "list_procedures": {
|
||||
const offset =
|
||||
typeof arguments_.offset === "number" ? arguments_.offset : 0;
|
||||
procedureOffsets.push(offset);
|
||||
inventoryCalls.push(name);
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
items: [
|
||||
{
|
||||
address: offset === 500 ? "0x2" : "0x1",
|
||||
value: offset === 500 ? "last" : "first",
|
||||
},
|
||||
],
|
||||
offset,
|
||||
limit: 500,
|
||||
total: 2,
|
||||
next_offset: offset === 500 ? null : 500,
|
||||
has_more: offset !== 500,
|
||||
}),
|
||||
ok([
|
||||
{ address: "0x1", value: "first" },
|
||||
{ address: "0x2", value: "last" },
|
||||
]),
|
||||
);
|
||||
}
|
||||
default:
|
||||
@@ -273,15 +243,15 @@ describe("enhanced MCP tools", () => {
|
||||
const result = jsonResult(
|
||||
await client.callTool({
|
||||
name: "binary_overview",
|
||||
arguments: { detail: "detailed", limit: 1 },
|
||||
arguments: {},
|
||||
}),
|
||||
);
|
||||
expect(procedureOffsets).toEqual([0]);
|
||||
expect(inventoryCalls).toEqual(["list_procedures", "list_strings"]);
|
||||
expect(result).toEqual({
|
||||
document: "fixture",
|
||||
detail: "detailed",
|
||||
segments: [
|
||||
{ name: "__TEXT", start: "0x1000", end: "0x1800", length: 2048 },
|
||||
{ name: "__DATA", start: "0x1800", end: "0x2000", length: 2048 },
|
||||
],
|
||||
segment_count: 2,
|
||||
procedure_count: 2,
|
||||
@@ -289,17 +259,12 @@ describe("enhanced MCP tools", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects non-advancing pagination metadata", async () => {
|
||||
it("rejects paginated provider output", async () => {
|
||||
const client = await connect({
|
||||
execute: () =>
|
||||
Promise.resolve(
|
||||
ok({
|
||||
items: [{ address: "0x1", value: "_TtC5First" }],
|
||||
offset: 0,
|
||||
limit: 500,
|
||||
total: 2,
|
||||
next_offset: 0,
|
||||
has_more: true,
|
||||
}),
|
||||
),
|
||||
});
|
||||
+18
-51
@@ -14,24 +14,18 @@ const PROCEDURES = {
|
||||
"0x6": "prefix_TtOther",
|
||||
};
|
||||
|
||||
const page = (values: Readonly<Record<string, string>>) => ({
|
||||
items: Object.entries(values).map(([address, value]) => ({ address, value })),
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: Object.keys(values).length,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
});
|
||||
const inventory = (values: Readonly<Record<string, string>>) =>
|
||||
Object.entries(values).map(([address, value]) => ({ address, value }));
|
||||
|
||||
const fixturePort = (): AnalysisOperationPort => ({
|
||||
execute: (name, arguments_) => {
|
||||
switch (name) {
|
||||
case "list_procedures":
|
||||
return Promise.resolve(ok(page(PROCEDURES)));
|
||||
return Promise.resolve(ok(inventory(PROCEDURES)));
|
||||
case "list_names":
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
page({
|
||||
inventory({
|
||||
"0x10": "_OBJC_CLASS_$_Fixture",
|
||||
"0x11": "_OBJC_CLASS_$_Fixture",
|
||||
"0x12": "_OBJC_PROTOCOL_$_FixtureDelegate",
|
||||
@@ -82,7 +76,7 @@ const fixturePort = (): AnalysisOperationPort => ({
|
||||
case "list_documents":
|
||||
return Promise.resolve(ok(["fixture"]));
|
||||
case "list_strings":
|
||||
return Promise.resolve(ok(page({ "0x30": "hello" })));
|
||||
return Promise.resolve(ok(inventory({ "0x30": "hello" })));
|
||||
case "analyze_function":
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
@@ -92,29 +86,16 @@ const fixturePort = (): AnalysisOperationPort => ({
|
||||
signature: null,
|
||||
locals: [],
|
||||
},
|
||||
pseudocode: {
|
||||
text: "return 0;",
|
||||
total_chars: 9,
|
||||
returned_chars: 9,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
assembly: {
|
||||
items: [],
|
||||
total: 0,
|
||||
returned: 0,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
comments: emptyBounded(),
|
||||
callers: emptyBounded(),
|
||||
callees: emptyBounded(),
|
||||
incoming_references: emptyBounded(),
|
||||
outgoing_references: emptyBounded(),
|
||||
referenced_strings: emptyBounded(),
|
||||
referenced_names: emptyBounded(),
|
||||
basic_blocks: emptyBounded(),
|
||||
instruction_scan: { scanned: 0, truncated: false },
|
||||
pseudocode: "return 0;",
|
||||
assembly: [],
|
||||
comments: [],
|
||||
callers: [],
|
||||
callees: [],
|
||||
incoming_references: [],
|
||||
outgoing_references: [],
|
||||
referenced_strings: [],
|
||||
referenced_names: [],
|
||||
basic_blocks: [],
|
||||
}),
|
||||
);
|
||||
default:
|
||||
@@ -123,14 +104,6 @@ const fixturePort = (): AnalysisOperationPort => ({
|
||||
},
|
||||
});
|
||||
|
||||
const emptyBounded = () => ({
|
||||
items: [],
|
||||
total: 0,
|
||||
returned: 0,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
});
|
||||
|
||||
const resources: Array<{ close(): Promise<void> }> = [];
|
||||
|
||||
afterEach(async () => {
|
||||
@@ -208,7 +181,7 @@ describe("enhanced MCP tools", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts a final dossier page whose total exceeds returned", async () => {
|
||||
it("rejects legacy paged collection wrappers", async () => {
|
||||
const malformedPort = fixturePort();
|
||||
const client = await connect({
|
||||
execute: async (name, arguments_, options) => {
|
||||
@@ -223,13 +196,7 @@ describe("enhanced MCP tools", () => {
|
||||
return result;
|
||||
return ok({
|
||||
...dossier,
|
||||
callers: {
|
||||
items: [],
|
||||
total: 1,
|
||||
returned: 0,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
callers: { items: [], total: 1, returned: 0 },
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -237,6 +204,6 @@ describe("enhanced MCP tools", () => {
|
||||
name: "analyze_function",
|
||||
arguments: { procedure: "0x1" },
|
||||
});
|
||||
expect(result.isError).not.toBe(true);
|
||||
expect(result.isError).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
+12
-89
@@ -1,12 +1,7 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import type { CallToolResult } from "@modelcontextprotocol/server";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
|
||||
import {
|
||||
jsonValueSchema,
|
||||
type JsonValue,
|
||||
} from "../../../src/domain/jsonValue.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
@@ -19,24 +14,18 @@ const PROCEDURES = {
|
||||
"0x6": "prefix_TtOther",
|
||||
};
|
||||
|
||||
const page = (values: Readonly<Record<string, string>>) => ({
|
||||
items: Object.entries(values).map(([address, value]) => ({ address, value })),
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: Object.keys(values).length,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
});
|
||||
const inventory = (values: Readonly<Record<string, string>>) =>
|
||||
Object.entries(values).map(([address, value]) => ({ address, value }));
|
||||
|
||||
const fixturePort = (): AnalysisOperationPort => ({
|
||||
execute: (name, arguments_) => {
|
||||
switch (name) {
|
||||
case "list_procedures":
|
||||
return Promise.resolve(ok(page(PROCEDURES)));
|
||||
return Promise.resolve(ok(inventory(PROCEDURES)));
|
||||
case "list_names":
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
page({
|
||||
inventory({
|
||||
"0x10": "_OBJC_CLASS_$_Fixture",
|
||||
"0x11": "_OBJC_CLASS_$_Fixture",
|
||||
"0x12": "_OBJC_PROTOCOL_$_FixtureDelegate",
|
||||
@@ -87,7 +76,10 @@ const fixturePort = (): AnalysisOperationPort => ({
|
||||
case "list_documents":
|
||||
return Promise.resolve(ok(["fixture"]));
|
||||
case "list_strings":
|
||||
return Promise.resolve(ok(page({ "0x30": "hello" })));
|
||||
return Promise.resolve(ok(inventory({ "0x30": "hello" })));
|
||||
case "search_strings":
|
||||
case "search_procedures":
|
||||
return Promise.resolve(ok(inventory({ "0x1": "needle" })));
|
||||
case "analyze_function":
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
@@ -155,80 +147,17 @@ const connect = async (analysis: AnalysisOperationPort = fixturePort()) => {
|
||||
return client;
|
||||
};
|
||||
|
||||
const jsonResult = (result: CallToolResult): JsonValue => {
|
||||
if (result.structuredContent === undefined)
|
||||
throw new Error("Tool result omitted structured content");
|
||||
const structured = jsonValueSchema.safeParse(result.structuredContent);
|
||||
if (!structured.success)
|
||||
throw new Error("Tool structured result was not JSON");
|
||||
if (
|
||||
typeof structured.data === "object" &&
|
||||
structured.data !== null &&
|
||||
!Array.isArray(structured.data) &&
|
||||
"normalized_result" in structured.data
|
||||
) {
|
||||
return structured.data.normalized_result ?? null;
|
||||
}
|
||||
if (
|
||||
typeof structured.data === "object" &&
|
||||
structured.data !== null &&
|
||||
!Array.isArray(structured.data) &&
|
||||
"evidence_id" in structured.data &&
|
||||
"result" in structured.data
|
||||
)
|
||||
return structured.data.result ?? null;
|
||||
const text = result.content.find((item) => item.type === "text");
|
||||
if (text?.type !== "text")
|
||||
throw new Error("Tool result omitted text content");
|
||||
const decoded: unknown = JSON.parse(text.text);
|
||||
const parsed = jsonValueSchema.safeParse(decoded);
|
||||
if (!parsed.success) throw new Error("Tool result was not JSON");
|
||||
return parsed.data;
|
||||
};
|
||||
|
||||
describe("enhanced MCP tools", () => {
|
||||
it("stops trace_feature at its explicit operation budget", async () => {
|
||||
let operations = 0;
|
||||
const client = await connect({
|
||||
execute: () => {
|
||||
operations += 1;
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
items: [{ address: "0x1", value: "needle" }],
|
||||
offset: 0,
|
||||
limit: 500,
|
||||
total: 2,
|
||||
next_offset: 1,
|
||||
has_more: true,
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
const result = jsonResult(
|
||||
await client.callTool({
|
||||
name: "trace_feature",
|
||||
arguments: { query: "needle", max_operations: 1 },
|
||||
}),
|
||||
);
|
||||
expect(operations).toBe(1);
|
||||
expect(result).toMatchObject({
|
||||
operations_used: 1,
|
||||
operation_budget: 1,
|
||||
truncated: true,
|
||||
});
|
||||
expect(JSON.stringify(result)).toContain("operation budget");
|
||||
});
|
||||
|
||||
it("lets the SDK reject misspelled and out-of-range inputs", async () => {
|
||||
describe("enhanced MCP input validation", () => {
|
||||
it("lets the SDK reject misspelled tool inputs", async () => {
|
||||
const client = await connect();
|
||||
const valid = await client.callTool({
|
||||
name: "trace_feature",
|
||||
arguments: { query: "needle", max_operations: 1 },
|
||||
arguments: { query: "needle" },
|
||||
});
|
||||
expect(valid.isError).not.toBe(true);
|
||||
const misspelled = await client.callTool({
|
||||
name: "trace_feature",
|
||||
arguments: { query: "needle", max_operatons: 1 },
|
||||
arguments: { query: "needle", unrecognized_option: true },
|
||||
});
|
||||
expect(misspelled.isError).toBe(true);
|
||||
expect(misspelled.structuredContent).toBeUndefined();
|
||||
@@ -241,12 +170,6 @@ describe("enhanced MCP tools", () => {
|
||||
});
|
||||
expect(nestedMisspelled.isError).toBe(true);
|
||||
expect(nestedMisspelled.structuredContent).toBeUndefined();
|
||||
const bounded = await client.callTool({
|
||||
name: "trace_feature",
|
||||
arguments: { query: "needle", max_operations: 101 },
|
||||
});
|
||||
expect(bounded.isError).toBe(true);
|
||||
expect(bounded.structuredContent).toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns a typed tool error for malformed Hopper boundary values", async () => {
|
||||
@@ -0,0 +1,45 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
|
||||
it("returns the complete session Evidence bundle in the tool result", async () => {
|
||||
const evidence = createEvidence(
|
||||
undefined,
|
||||
{ id: "fixture", name: "Fixture", version: "1" },
|
||||
{ operation: "observe", parameters: {}, result: { value: "seen" } },
|
||||
);
|
||||
const session = createTestBinarySession(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
expect(session.recordEvidence(evidence).ok).toBe(true);
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({ name: "inline-evidence-bundle", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const result = await client.callTool({
|
||||
name: "get_evidence_bundle",
|
||||
arguments: {},
|
||||
});
|
||||
expect(result.structuredContent).toMatchObject({
|
||||
result: {
|
||||
records: [
|
||||
{
|
||||
evidence_id: evidence.evidence_id,
|
||||
normalized_result: { value: "seen" },
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await Promise.allSettled([client.close(), server.close(), session.close()]);
|
||||
}
|
||||
});
|
||||
@@ -1,128 +0,0 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import type { CallToolResult } from "@modelcontextprotocol/server";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import { createPermissionPolicy } from "../../../src/domain/permissionPolicy.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
|
||||
const structured = (result: CallToolResult): Record<string, unknown> => {
|
||||
if (result.structuredContent === undefined)
|
||||
throw new Error("expected structured MCP content");
|
||||
return result.structuredContent as Record<string, unknown>;
|
||||
};
|
||||
|
||||
const createSession = () =>
|
||||
createTestBinarySession(() => ({
|
||||
health: () => Promise.resolve(),
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
|
||||
describe("evidence bundle release", () => {
|
||||
it("notifies snapshot observers and invalidates the retained URI", async () => {
|
||||
const session = createSession();
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({ name: "release-test", version: "1" });
|
||||
const bundleUpdated = new Promise<string>((resolve) => {
|
||||
client.setNotificationHandler(
|
||||
"notifications/resources/updated",
|
||||
(notice) => {
|
||||
if (notice.params.uri.startsWith("rea://evidence-bundle/"))
|
||||
resolve(notice.params.uri);
|
||||
},
|
||||
);
|
||||
});
|
||||
let updates = 0;
|
||||
session.onAnalysisSnapshotChanged(() => {
|
||||
updates += 1;
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const snapshot = z
|
||||
.object({
|
||||
result: z.object({
|
||||
bundle_uri: z.string(),
|
||||
bundle_digest: z.string(),
|
||||
}),
|
||||
})
|
||||
.parse(
|
||||
structured(
|
||||
await client.callTool({
|
||||
name: "snapshot_evidence_bundle",
|
||||
arguments: {},
|
||||
}),
|
||||
),
|
||||
).result;
|
||||
expect(
|
||||
structured(
|
||||
await client.callTool({
|
||||
name: "release_evidence_bundle",
|
||||
arguments: { bundle_digest: snapshot.bundle_digest },
|
||||
}),
|
||||
).result,
|
||||
).toEqual({
|
||||
bundle_digest: snapshot.bundle_digest,
|
||||
released: true,
|
||||
});
|
||||
expect(updates).toBe(1);
|
||||
await expect(bundleUpdated).resolves.toBe(snapshot.bundle_uri);
|
||||
await expect(
|
||||
client.readResource({ uri: snapshot.bundle_uri }),
|
||||
).rejects.toThrow(/not found/iu);
|
||||
} finally {
|
||||
await Promise.allSettled([
|
||||
client.close(),
|
||||
server.close(),
|
||||
session.close(),
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
it("requires evidence-write permission before releasing a bundle", async () => {
|
||||
const session = createSession();
|
||||
const server = createServer(session, session, {
|
||||
permissionAuthority: new PermissionAuthority(createPermissionPolicy([])),
|
||||
});
|
||||
const client = new Client({
|
||||
name: "release-permission-test",
|
||||
version: "1",
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const snapshot = z
|
||||
.object({ result: z.object({ bundle_digest: z.string() }) })
|
||||
.parse(
|
||||
structured(
|
||||
await client.callTool({
|
||||
name: "snapshot_evidence_bundle",
|
||||
arguments: {},
|
||||
}),
|
||||
),
|
||||
).result;
|
||||
const release = await client.callTool({
|
||||
name: "release_evidence_bundle",
|
||||
arguments: { bundle_digest: snapshot.bundle_digest },
|
||||
});
|
||||
expect(release.isError).toBe(true);
|
||||
expect(
|
||||
session.retainedEvidenceBundle(snapshot.bundle_digest),
|
||||
).toBeDefined();
|
||||
} finally {
|
||||
await Promise.allSettled([
|
||||
client.close(),
|
||||
server.close(),
|
||||
session.close(),
|
||||
]);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,322 +0,0 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import type { BinarySession } from "../../../src/application/BinarySession.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
|
||||
import { createInvestigationWorkspace } from "../../../src/domain/investigationWorkspace.js";
|
||||
import { createResidualUnknown } from "../../../src/domain/residualUnknown.js";
|
||||
|
||||
const provider = { id: "fixture", name: "Fixture", version: "1" };
|
||||
|
||||
interface ResourceFixture {
|
||||
readonly evidence: ReturnType<typeof createEvidence>;
|
||||
readonly capture: ReturnType<typeof createEvidence>;
|
||||
readonly workspace: ReturnType<typeof createInvestigationWorkspace>;
|
||||
readonly unknown: ReturnType<BinarySession["recordUnknown"]>;
|
||||
}
|
||||
|
||||
function seedResourceFixture(session: BinarySession): ResourceFixture {
|
||||
const evidence = createEvidence(undefined, provider, {
|
||||
operation: "resource_probe",
|
||||
parameters: {},
|
||||
result: { observed: true },
|
||||
});
|
||||
session.recordEvidence(evidence);
|
||||
const capture = createEvidence(undefined, provider, {
|
||||
operation: "capture_process_scenario",
|
||||
parameters: {},
|
||||
result: {
|
||||
frames: [{ sequence: 0, at_ms: 0, data: "ready" }],
|
||||
protocol_events: [],
|
||||
replay_transitions: [],
|
||||
},
|
||||
});
|
||||
session.recordEvidence(capture);
|
||||
const workspace = createInvestigationWorkspace(
|
||||
"resource test",
|
||||
createEvidenceBundle([]),
|
||||
[],
|
||||
);
|
||||
session.retainInvestigationWorkspace(workspace);
|
||||
const unknown = session.recordUnknown({
|
||||
approved: true,
|
||||
question: "Was every branch observed?",
|
||||
severity: "medium",
|
||||
domain: "control-flow",
|
||||
supporting_evidence_ids: [evidence.evidence_id],
|
||||
contradicting_evidence_ids: [],
|
||||
required_authority: "controlled-replay",
|
||||
required_confidence: "observed",
|
||||
required_environment: null,
|
||||
recommended_probes: [],
|
||||
relationships: [],
|
||||
});
|
||||
expect(unknown.ok).toBe(true);
|
||||
return { evidence, capture, workspace, unknown };
|
||||
}
|
||||
|
||||
async function verifyResourceProtocol(
|
||||
client: Client,
|
||||
fixture: ResourceFixture,
|
||||
): Promise<void> {
|
||||
const { evidence, capture, workspace, unknown } = fixture;
|
||||
const templates = await client.listResourceTemplates();
|
||||
expect(templates.resourceTemplates).toContainEqual(
|
||||
expect.objectContaining({ uriTemplate: "rea://evidence/{evidenceId}" }),
|
||||
);
|
||||
expect(
|
||||
templates.resourceTemplates.map(({ uriTemplate }) => uriTemplate),
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
"rea://artifact/{manifestId}/{collection}",
|
||||
"rea://function/{targetSha256}/{address}",
|
||||
"rea://evidence-bundle/{bundleDigest}",
|
||||
"rea://workspace/{workspaceId}/revision/{revision}",
|
||||
]),
|
||||
);
|
||||
expect(templates.resourceTemplates).toContainEqual(
|
||||
expect.objectContaining({
|
||||
uriTemplate: "rea://evidence/{evidenceId}/section/{section}",
|
||||
}),
|
||||
);
|
||||
const listed = await client.listResources();
|
||||
expect(listed.resources).toContainEqual(
|
||||
expect.objectContaining({ uri: "rea://snapshot/current" }),
|
||||
);
|
||||
expect(listed.resources).not.toContainEqual(
|
||||
expect.objectContaining({
|
||||
uri: `rea://evidence/${evidence.evidence_id}`,
|
||||
}),
|
||||
);
|
||||
const read = await client.readResource({
|
||||
uri: `rea://evidence/${evidence.evidence_id}`,
|
||||
});
|
||||
expect(read.contents).toEqual([
|
||||
expect.objectContaining({
|
||||
uri: `rea://evidence/${evidence.evidence_id}`,
|
||||
mimeType: "application/json",
|
||||
text: expect.stringContaining(evidence.evidence_id),
|
||||
}),
|
||||
]);
|
||||
const firstSnapshot = await client.callTool({
|
||||
name: "snapshot_evidence_bundle",
|
||||
arguments: {},
|
||||
});
|
||||
const secondSnapshot = await client.callTool({
|
||||
name: "snapshot_evidence_bundle",
|
||||
arguments: {},
|
||||
});
|
||||
expect(secondSnapshot.structuredContent).toEqual(
|
||||
firstSnapshot.structuredContent,
|
||||
);
|
||||
expect(firstSnapshot.content).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: "text",
|
||||
text: expect.stringContaining("Copy the opaque URI exactly"),
|
||||
}),
|
||||
);
|
||||
const bundleUri = z
|
||||
.object({ result: z.object({ bundle_uri: z.string() }) })
|
||||
.parse(firstSnapshot.structuredContent).result.bundle_uri;
|
||||
const retainedBundle = await client.readResource({ uri: bundleUri });
|
||||
expect(retainedBundle.contents[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
uri: bundleUri,
|
||||
text: expect.stringContaining(evidence.evidence_id),
|
||||
}),
|
||||
);
|
||||
const terminal = await client.readResource({
|
||||
uri: `rea://evidence/${capture.evidence_id}/section/terminal`,
|
||||
});
|
||||
const workspaceResource = await client.readResource({
|
||||
uri: `rea://workspace/${workspace.workspace_id}/revision/${String(workspace.revision)}`,
|
||||
});
|
||||
expect(workspaceResource.contents[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
text: expect.stringContaining(workspace.revision_digest),
|
||||
}),
|
||||
);
|
||||
expect(terminal.contents[0]).toEqual(
|
||||
expect.objectContaining({ text: expect.stringContaining("ready") }),
|
||||
);
|
||||
if (unknown.ok) {
|
||||
const unknownResource = await client.readResource({
|
||||
uri: `rea://unknown/${unknown.value.unknown_id}`,
|
||||
});
|
||||
expect(unknownResource.contents[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
text: expect.stringContaining(unknown.value.revision_digest),
|
||||
}),
|
||||
);
|
||||
}
|
||||
await expect(
|
||||
client.readResource({ uri: `rea://evidence/ev_${"0".repeat(64)}` }),
|
||||
).rejects.toThrow(/not found/iu);
|
||||
}
|
||||
|
||||
describe("evidence MCP resources", () => {
|
||||
it("publishes mutable snapshot changes for every Evidence mutation", () => {
|
||||
const session = createTestBinarySession(() => ({
|
||||
health: () => Promise.resolve(),
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
let updates = 0;
|
||||
session.onAnalysisSnapshotChanged(() => {
|
||||
updates += 1;
|
||||
});
|
||||
const first = createEvidence(undefined, provider, {
|
||||
operation: "notification_probe",
|
||||
parameters: {},
|
||||
result: 1,
|
||||
});
|
||||
expect(session.recordEvidence(first)).toEqual({ ok: true, value: "added" });
|
||||
expect(session.recordEvidence(first)).toEqual({
|
||||
ok: true,
|
||||
value: "duplicate",
|
||||
});
|
||||
const importedUnknown = createResidualUnknown(
|
||||
{
|
||||
approved: true,
|
||||
question: "Does an imported unknown publish a snapshot update?",
|
||||
severity: "low",
|
||||
domain: "notifications",
|
||||
supporting_evidence_ids: [first.evidence_id],
|
||||
contradicting_evidence_ids: [],
|
||||
required_authority: "controlled-replay",
|
||||
required_confidence: "observed",
|
||||
required_environment: null,
|
||||
recommended_probes: [],
|
||||
relationships: [],
|
||||
},
|
||||
first.evidence_id,
|
||||
first.subject?.digest.sha256 ?? null,
|
||||
);
|
||||
expect(
|
||||
session.importEvidenceBundle(
|
||||
createEvidenceBundle([first], [importedUnknown]),
|
||||
),
|
||||
).toEqual({ ok: true, value: 0 });
|
||||
const imported = createEvidence(undefined, provider, {
|
||||
operation: "import_notification_probe",
|
||||
parameters: {},
|
||||
result: 2,
|
||||
});
|
||||
expect(
|
||||
session.importEvidenceBundle(createEvidenceBundle([imported])),
|
||||
).toEqual({ ok: true, value: 1 });
|
||||
expect(
|
||||
session.recordUnknown({
|
||||
approved: true,
|
||||
question: "Does mutation publish a snapshot update?",
|
||||
severity: "low",
|
||||
domain: "notifications",
|
||||
supporting_evidence_ids: [first.evidence_id],
|
||||
contradicting_evidence_ids: [],
|
||||
required_authority: "controlled-replay",
|
||||
required_confidence: "observed",
|
||||
required_environment: null,
|
||||
recommended_probes: [],
|
||||
relationships: [],
|
||||
}).ok,
|
||||
).toBe(true);
|
||||
expect(updates).toBe(4);
|
||||
});
|
||||
|
||||
it("contains observer failures after committing a mutation", () => {
|
||||
const session = createTestBinarySession(() => ({
|
||||
health: () => Promise.resolve(),
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
session.onAnalysisSnapshotChanged(() => {
|
||||
throw new Error("fixture observer failure");
|
||||
});
|
||||
expect(() =>
|
||||
session.recordEvidence(
|
||||
createEvidence(undefined, provider, {
|
||||
operation: "observer_failure_probe",
|
||||
parameters: {},
|
||||
result: true,
|
||||
}),
|
||||
),
|
||||
).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("evidence bundle resources", () => {
|
||||
it("retains bundles without eviction and rejects a seventeenth digest", () => {
|
||||
const session = createTestBinarySession(() => ({
|
||||
health: () => Promise.resolve(),
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const first = session.snapshotEvidenceBundle();
|
||||
expect(first.ok).toBe(true);
|
||||
for (let index = 0; index < 15; index += 1) {
|
||||
session.recordEvidence(
|
||||
createEvidence(undefined, provider, {
|
||||
operation: `retention_probe_${String(index)}`,
|
||||
parameters: {},
|
||||
result: index,
|
||||
}),
|
||||
);
|
||||
expect(session.snapshotEvidenceBundle().ok).toBe(true);
|
||||
}
|
||||
session.recordEvidence(
|
||||
createEvidence(undefined, provider, {
|
||||
operation: "retention_probe_overflow",
|
||||
parameters: {},
|
||||
result: true,
|
||||
}),
|
||||
);
|
||||
expect(session.snapshotEvidenceBundle()).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "EvidenceLimitError", limit: "records", maximum: 16 },
|
||||
});
|
||||
if (first.ok) {
|
||||
expect(session.retainedEvidenceBundle(first.value.bundleDigest)).toEqual(
|
||||
expect.any(String),
|
||||
);
|
||||
expect(session.releaseEvidenceBundle(first.value.bundleDigest)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(session.releaseEvidenceBundle(first.value.bundleDigest)).toBe(
|
||||
false,
|
||||
);
|
||||
expect(session.snapshotEvidenceBundle().ok).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("lists and reads only evidence owned by the current session", async () => {
|
||||
const session = createTestBinarySession(() => ({
|
||||
health: () => Promise.resolve(),
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const fixture = seedResourceFixture(session);
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({
|
||||
name: "evidence-resource-test",
|
||||
version: "1",
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
await verifyResourceProtocol(client, fixture);
|
||||
} finally {
|
||||
await Promise.allSettled([
|
||||
client.close(),
|
||||
server.close(),
|
||||
session.close(),
|
||||
]);
|
||||
}
|
||||
}, 10_000);
|
||||
});
|
||||
@@ -33,8 +33,8 @@ describe("function comparison MCP integration", () => {
|
||||
const result = await client.callTool({
|
||||
name: "compare_functions",
|
||||
arguments: {
|
||||
left_evidence_ids: [FUNCTION_COMPARISON_EXAMPLE.left.evidence_id],
|
||||
right_evidence_ids: [FUNCTION_COMPARISON_EXAMPLE.right.evidence_id],
|
||||
left_evidence_id: FUNCTION_COMPARISON_EXAMPLE.left.evidence_id,
|
||||
right_evidence_id: FUNCTION_COMPARISON_EXAMPLE.right.evidence_id,
|
||||
unknown_registry_approved: true,
|
||||
},
|
||||
});
|
||||
@@ -42,7 +42,6 @@ describe("function comparison MCP integration", () => {
|
||||
expect(result.structuredContent).toMatchObject({
|
||||
result: { status: expect.any(String) },
|
||||
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
|
||||
evidence_uri: expect.stringMatching(/^rea:\/\/evidence\/ev_/u),
|
||||
});
|
||||
const unknowns = await client.callTool({
|
||||
name: "list_unknowns",
|
||||
@@ -52,15 +51,13 @@ describe("function comparison MCP integration", () => {
|
||||
result: {
|
||||
items: [
|
||||
expect.objectContaining({
|
||||
unknown: expect.objectContaining({
|
||||
domain: "function-comparison",
|
||||
recommended_probes: [
|
||||
expect.objectContaining({
|
||||
rationale:
|
||||
"Capture complete dossiers for both functions under the same target context and analysis limits.",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
domain: "function-comparison",
|
||||
recommended_probes: [
|
||||
expect.objectContaining({
|
||||
rationale:
|
||||
"Capture complete dossiers for both functions under the same target context.",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
@@ -90,8 +87,8 @@ describe("function comparison MCP integration", () => {
|
||||
const result = await client.callTool({
|
||||
name: "compare_functions",
|
||||
arguments: {
|
||||
left_evidence_ids: [FUNCTION_COMPARISON_EXAMPLE.left.evidence_id],
|
||||
right_evidence_ids: [FUNCTION_COMPARISON_EXAMPLE.right.evidence_id],
|
||||
left_evidence_id: FUNCTION_COMPARISON_EXAMPLE.left.evidence_id,
|
||||
right_evidence_id: FUNCTION_COMPARISON_EXAMPLE.right.evidence_id,
|
||||
},
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
@@ -135,8 +132,8 @@ describe("function comparison MCP integration", () => {
|
||||
const result = await client.callTool({
|
||||
name: "compare_functions",
|
||||
arguments: {
|
||||
left_evidence_ids: [wrong.evidence_id],
|
||||
right_evidence_ids: [FUNCTION_COMPARISON_EXAMPLE.right.evidence_id],
|
||||
left_evidence_id: wrong.evidence_id,
|
||||
right_evidence_id: FUNCTION_COMPARISON_EXAMPLE.right.evidence_id,
|
||||
},
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
|
||||
@@ -26,23 +26,17 @@ describe("Ghidra MCP evidence parity", () => {
|
||||
analyzer_preset: "ghidra-default",
|
||||
},
|
||||
},
|
||||
normalized_result: {
|
||||
items: [
|
||||
{
|
||||
address: "0x401000",
|
||||
value: "fixture_main",
|
||||
procedure: {
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
},
|
||||
normalized_result: [
|
||||
{
|
||||
address: "0x401000",
|
||||
value: "fixture_main",
|
||||
procedure: {
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
},
|
||||
raw_result: {
|
||||
items: [{ value_truncated: false }],
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const mcpOverview = sessionEvidence(
|
||||
@@ -50,13 +44,13 @@ describe("Ghidra MCP evidence parity", () => {
|
||||
(
|
||||
await mcp.callTool({
|
||||
name: "binary_overview",
|
||||
arguments: { detail: "detailed", limit: 5 },
|
||||
arguments: {},
|
||||
})
|
||||
).structuredContent,
|
||||
);
|
||||
const directOverview = await new EnhancedTools(session).execute(
|
||||
"binary_overview",
|
||||
{ detail: "detailed", limit: 5 },
|
||||
{},
|
||||
);
|
||||
expect(directOverview.ok).toBe(true);
|
||||
if (!directOverview.ok) return;
|
||||
@@ -97,7 +91,7 @@ describe("Ghidra MCP evidence parity", () => {
|
||||
(
|
||||
await mcp.callTool({
|
||||
name: "analyze_function",
|
||||
arguments: { procedure: "fixture_main", include_assembly: true },
|
||||
arguments: { procedure: "fixture_main" },
|
||||
})
|
||||
).structuredContent,
|
||||
);
|
||||
@@ -114,17 +108,12 @@ describe("Ghidra MCP evidence parity", () => {
|
||||
provenance: "ghidra-function-manager",
|
||||
},
|
||||
},
|
||||
pseudocode: { truncated: false },
|
||||
outgoing_references: {
|
||||
items: [
|
||||
{
|
||||
kind: {
|
||||
available: true,
|
||||
provenance: "ghidra-reference-manager",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
pseudocode: "int fixture_main(void) { return 42; }",
|
||||
outgoing_references: [
|
||||
{
|
||||
kind: { available: true, provenance: "ghidra-reference-manager" },
|
||||
},
|
||||
],
|
||||
limitations: expect.arrayContaining([
|
||||
expect.stringContaining("indirect flows without target addresses"),
|
||||
expect.stringContaining(
|
||||
@@ -138,7 +127,7 @@ describe("Ghidra MCP evidence parity", () => {
|
||||
});
|
||||
const directAnalyzed = await new EnhancedTools(session).execute(
|
||||
"analyze_function",
|
||||
{ procedure: "fixture_main", include_assembly: true },
|
||||
{ procedure: "fixture_main" },
|
||||
);
|
||||
expect(directAnalyzed.ok).toBe(true);
|
||||
if (!directAnalyzed.ok) return;
|
||||
|
||||
@@ -16,7 +16,6 @@ import { GHIDRA_SESSION_CAPABILITIES } from "../../../src/ghidra/GhidraSessionVa
|
||||
import { silentLogger } from "../../../src/logger.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import {
|
||||
ghidraBounded,
|
||||
ghidraFunctionClassification,
|
||||
ghidraFunctionDossier,
|
||||
ghidraFunctionIdentity,
|
||||
@@ -139,33 +138,24 @@ const resultBuilders = new Map<GhidraOperation, GhidraResultBuilder>([
|
||||
["list_documents", () => ["fixture"]],
|
||||
[
|
||||
"list_procedures",
|
||||
(_input, limit) =>
|
||||
page(
|
||||
[
|
||||
{
|
||||
address: "0x401000",
|
||||
value: "fixture_main",
|
||||
value_truncated: false,
|
||||
procedure: {
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
},
|
||||
},
|
||||
],
|
||||
limit,
|
||||
),
|
||||
() => [
|
||||
{
|
||||
address: "0x401000",
|
||||
value: "fixture_main",
|
||||
procedure: {
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
},
|
||||
},
|
||||
],
|
||||
],
|
||||
[
|
||||
"list_strings",
|
||||
(_input, limit) =>
|
||||
page(
|
||||
[
|
||||
stringItem("0x402000", "inventory fixture"),
|
||||
stringItem("0x402020", "external fixture"),
|
||||
],
|
||||
limit,
|
||||
),
|
||||
() => [
|
||||
stringItem("0x402000", "inventory fixture"),
|
||||
stringItem("0x402020", "external fixture"),
|
||||
],
|
||||
],
|
||||
[
|
||||
"list_segments",
|
||||
@@ -189,27 +179,22 @@ const resultBuilders = new Map<GhidraOperation, GhidraResultBuilder>([
|
||||
],
|
||||
[
|
||||
"list_names",
|
||||
(_input, limit) =>
|
||||
page(
|
||||
[
|
||||
{
|
||||
address: "0x401000",
|
||||
value: "fixture_main",
|
||||
value_truncated: false,
|
||||
symbol: {
|
||||
primary: true,
|
||||
dynamic: false,
|
||||
external: false,
|
||||
type: "function",
|
||||
source: "user_defined",
|
||||
},
|
||||
},
|
||||
],
|
||||
limit,
|
||||
),
|
||||
() => [
|
||||
{
|
||||
address: "0x401000",
|
||||
value: "fixture_main",
|
||||
symbol: {
|
||||
primary: true,
|
||||
dynamic: false,
|
||||
external: false,
|
||||
type: "function",
|
||||
source: "user_defined",
|
||||
},
|
||||
},
|
||||
],
|
||||
],
|
||||
["search_procedures", (_input, limit) => page([], limit)],
|
||||
["search_strings", (_input, limit) => page([], limit)],
|
||||
["search_procedures", () => []],
|
||||
["search_strings", () => []],
|
||||
["address_name", () => "fixture_main"],
|
||||
["procedure_address", () => "0x401000"],
|
||||
[
|
||||
@@ -240,9 +225,7 @@ const resultBuilders = new Map<GhidraOperation, GhidraResultBuilder>([
|
||||
"read_function_instructions",
|
||||
() => ({
|
||||
procedure: ghidraFunctionIdentity(),
|
||||
instructions: ghidraBounded(["0x401000: CALL 0x401020", "0x401005: RET"]),
|
||||
instructions_scanned: 2,
|
||||
instruction_scan_truncated: false,
|
||||
instructions: ["0x401000: CALL 0x401020", "0x401005: RET"],
|
||||
limitations: ["Ghidra-specific instruction text."],
|
||||
}),
|
||||
],
|
||||
@@ -251,9 +234,7 @@ const resultBuilders = new Map<GhidraOperation, GhidraResultBuilder>([
|
||||
(input, _limit) => ({
|
||||
procedure: ghidraFunctionIdentity(),
|
||||
direction: input.direction ?? "outgoing",
|
||||
references: ghidraBounded([ghidraReferenceEdge()]),
|
||||
instructions_scanned: 2,
|
||||
instruction_scan_truncated: false,
|
||||
references: [ghidraReferenceEdge()],
|
||||
}),
|
||||
],
|
||||
["xrefs", () => ["0x401001"]],
|
||||
@@ -271,26 +252,15 @@ const resultFor = (
|
||||
operation: GhidraOperation,
|
||||
input: Readonly<Record<string, JsonValue>>,
|
||||
): JsonValue => {
|
||||
const limit = typeof input.limit === "number" ? input.limit : 100;
|
||||
const builder = resultBuilders.get(operation);
|
||||
if (builder === undefined)
|
||||
throw new TypeError(`Unexpected Ghidra operation: ${operation}`);
|
||||
return builder(input, limit);
|
||||
return builder(input, typeof input.limit === "number" ? input.limit : 100);
|
||||
};
|
||||
|
||||
const page = (items: readonly JsonValue[], limit: number): JsonValue => ({
|
||||
items: items.slice(0, limit),
|
||||
offset: 0,
|
||||
limit,
|
||||
total: items.length,
|
||||
next_offset: items.length > limit ? limit : null,
|
||||
has_more: items.length > limit,
|
||||
});
|
||||
|
||||
const stringItem = (address: string, value: string): JsonValue => ({
|
||||
address,
|
||||
value,
|
||||
value_truncated: false,
|
||||
string: {
|
||||
encoding: "UTF-8",
|
||||
termination: "present_or_not_required",
|
||||
|
||||
@@ -63,20 +63,18 @@ describe("Ghidra MCP native API evidence", () => {
|
||||
result: {
|
||||
items: [
|
||||
{
|
||||
unknown: {
|
||||
status: "open",
|
||||
domain: "native-api",
|
||||
question: expect.stringContaining(
|
||||
"additional data sources or targets",
|
||||
),
|
||||
supporting_evidence_ids: [approvedInspection.evidence_id],
|
||||
recommended_probes: [
|
||||
{
|
||||
operation: "inspect_native_api",
|
||||
rationale: expect.stringContaining("ABI probe"),
|
||||
},
|
||||
],
|
||||
},
|
||||
status: "open",
|
||||
domain: "native-api",
|
||||
question: expect.stringContaining(
|
||||
"additional data sources or targets",
|
||||
),
|
||||
supporting_evidence_ids: [approvedInspection.evidence_id],
|
||||
recommended_probes: [
|
||||
{
|
||||
operation: "inspect_native_api",
|
||||
rationale: expect.stringContaining("ABI probe"),
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -27,7 +27,7 @@ describe("Ghidra MCP capability routing", () => {
|
||||
|
||||
const status = await mcp.callTool({
|
||||
name: "binary_session",
|
||||
arguments: { detail: "full" },
|
||||
arguments: {},
|
||||
});
|
||||
expect(status.structuredContent).toMatchObject({
|
||||
result: {
|
||||
|
||||
@@ -75,7 +75,7 @@ it("builds a zero-hop exact-address path with dossier citations", async () => {
|
||||
normalized_result: {
|
||||
status: "found",
|
||||
shortest_hops: 0,
|
||||
paths: { total: 1 },
|
||||
paths: [expect.objectContaining({ hops: 0 })],
|
||||
},
|
||||
evidence_links: [FUNCTION_COMPARISON_EXAMPLE.left.evidence_id],
|
||||
});
|
||||
@@ -104,13 +104,7 @@ it("records a safe unresolved call-path question", async () => {
|
||||
parameters: base.parameters,
|
||||
result: jsonValueSchema.parse({
|
||||
...jsonObjectSchema.parse(base.normalized_result),
|
||||
callees: {
|
||||
items: [{ address: "0x2000", name: "next" }],
|
||||
total: 1,
|
||||
returned: 1,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
callees: [{ address: "0x2000", name: "next" }],
|
||||
}),
|
||||
rawResult: base.raw_result,
|
||||
confidence: base.confidence,
|
||||
@@ -175,7 +169,7 @@ it("records an explicit non-causal static/runtime hypothesis", async () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("records a safe unresolved static/runtime question", async () => {
|
||||
it("uses inline assembly observations without recording a false unknown", async () => {
|
||||
const { session, server, client } = await connected();
|
||||
for (const evidence of [
|
||||
FUNCTION_COMPARISON_EXAMPLE.left,
|
||||
@@ -209,11 +203,7 @@ it("records a safe unresolved static/runtime question", async () => {
|
||||
expect(response.isError).not.toBe(true);
|
||||
expect(
|
||||
session.listUnknowns({ domain: "static-runtime-correlation" }),
|
||||
).toMatchObject([
|
||||
{
|
||||
question: "Does runtime behavior match the available static analysis?",
|
||||
},
|
||||
]);
|
||||
).toEqual([]);
|
||||
} finally {
|
||||
await close(session, server, client);
|
||||
}
|
||||
|
||||
@@ -107,26 +107,9 @@ it("runs and reuses a persistent cross-version workspace", async () => {
|
||||
ok: true,
|
||||
value: { revision: 3, runs: [{ status: "complete" }] },
|
||||
});
|
||||
expect(first.content).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: "resource_link",
|
||||
uri: expect.stringMatching(
|
||||
/^rea:\/\/workspace\/ws_[a-f0-9]{64}\/revision\/3$/u,
|
||||
),
|
||||
}),
|
||||
expect(firstEvidence.normalized_result).toHaveProperty(
|
||||
"investigation_run.workspace_id",
|
||||
);
|
||||
const retainedWorkspace = session.investigationWorkspaces()[0];
|
||||
expect(retainedWorkspace).toBeDefined();
|
||||
if (retainedWorkspace !== undefined) {
|
||||
const resource = await client.readResource({
|
||||
uri: `rea://workspace/${retainedWorkspace.workspace_id}/revision/${String(retainedWorkspace.revision)}`,
|
||||
});
|
||||
expect(resource.contents[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
text: expect.stringContaining(retainedWorkspace.revision_digest),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const second = await client.callTool({
|
||||
name: "find_changed_behavior",
|
||||
@@ -166,7 +149,7 @@ it("replays a complete workspace without write authority", async () => {
|
||||
},
|
||||
};
|
||||
const writer = await investigationAuthority(directory, true);
|
||||
const initial = await connected(filePolicy, [directory], writer);
|
||||
const initial = await connected(filePolicy, writer);
|
||||
try {
|
||||
const created = await initial.client.callTool({
|
||||
name: "find_changed_behavior",
|
||||
@@ -178,7 +161,7 @@ it("replays a complete workspace without write authority", async () => {
|
||||
}
|
||||
|
||||
const reader = await investigationAuthority(directory, false);
|
||||
const replay = await connected(filePolicy, [directory], reader);
|
||||
const replay = await connected(filePolicy, reader);
|
||||
try {
|
||||
const cached = await replay.client.callTool({
|
||||
name: "find_changed_behavior",
|
||||
@@ -229,7 +212,7 @@ it("defers input permission for an explicit replay with deleted inputs", async (
|
||||
options: { page_size: 500, change_limit: 100 },
|
||||
};
|
||||
const writer = await investigationAuthority(directory, true);
|
||||
const initial = await connected(filePolicy, [directory], writer);
|
||||
const initial = await connected(filePolicy, writer);
|
||||
let runId: string | undefined;
|
||||
try {
|
||||
const created = await initial.client.callTool({
|
||||
@@ -256,14 +239,10 @@ it("defers input permission for an explicit replay with deleted inputs", async (
|
||||
]);
|
||||
const workspaceOnly = await permissionAuthorityForRoot(
|
||||
directory,
|
||||
[
|
||||
"investigation_workspace_read",
|
||||
"investigation_workspace_write",
|
||||
"investigation_input",
|
||||
],
|
||||
["investigation_workspace_read", "investigation_workspace_write"],
|
||||
["investigation_workspace_read"],
|
||||
);
|
||||
const replay = await connected(filePolicy, [], workspaceOnly);
|
||||
const replay = await connected(filePolicy, workspaceOnly);
|
||||
try {
|
||||
const cached = await replay.client.callTool({
|
||||
name: "find_changed_behavior",
|
||||
@@ -284,49 +263,8 @@ it("defers input permission for an explicit replay with deleted inputs", async (
|
||||
}
|
||||
});
|
||||
|
||||
it("refuses automatic artifact reads outside operator-approved roots", async () => {
|
||||
const directory = await createTestTempDirectory("rea-investigation-mcp-");
|
||||
const approvedInputs = join(directory, "approved-inputs");
|
||||
const outsideInputs = join(directory, "outside-inputs");
|
||||
const evidenceRoot = join(directory, "evidence");
|
||||
await Promise.all([
|
||||
mkdir(approvedInputs),
|
||||
mkdir(outsideInputs),
|
||||
mkdir(evidenceRoot),
|
||||
]);
|
||||
const left = join(outsideInputs, "left");
|
||||
const right = join(outsideInputs, "right");
|
||||
await Promise.all([mkdir(left), mkdir(right)]);
|
||||
const { session, server, client } = await connected(
|
||||
evidencePolicy(evidenceRoot),
|
||||
[approvedInputs],
|
||||
);
|
||||
try {
|
||||
const response = await client.callTool({
|
||||
name: "find_changed_behavior",
|
||||
arguments: {
|
||||
investigation_run: {
|
||||
approved: true,
|
||||
workspace_path: join(evidenceRoot, "workspace.json"),
|
||||
left_path: left,
|
||||
right_path: right,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(response.isError).toBe(true);
|
||||
expect(response.content[0]).toEqual({
|
||||
type: "text",
|
||||
text: JSON.stringify(response.structuredContent),
|
||||
});
|
||||
} finally {
|
||||
await close(session, server, client);
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
const connected = async (
|
||||
evidenceFilePolicy?: EvidenceFilePolicy,
|
||||
investigationInputRoots: readonly string[] = evidenceFilePolicy?.roots ?? [],
|
||||
permissionAuthority?: PermissionAuthority,
|
||||
) => {
|
||||
const session = createTestBinarySession(() => ({
|
||||
@@ -335,12 +273,7 @@ const connected = async (
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(session, session, {
|
||||
...(evidenceFilePolicy === undefined
|
||||
? {}
|
||||
: {
|
||||
evidenceFilePolicy,
|
||||
investigationInputRoots,
|
||||
}),
|
||||
...(evidenceFilePolicy === undefined ? {} : { evidenceFilePolicy }),
|
||||
...(permissionAuthority === undefined ? {} : { permissionAuthority }),
|
||||
});
|
||||
const client = new Client({ name: "investigation-test", version: "1" });
|
||||
@@ -374,14 +307,9 @@ const investigationAuthority = async (
|
||||
): Promise<PermissionAuthority> =>
|
||||
permissionAuthorityForRoot(
|
||||
root,
|
||||
["investigation_workspace_read", "investigation_workspace_write"],
|
||||
[
|
||||
"investigation_workspace_read",
|
||||
"investigation_workspace_write",
|
||||
"investigation_input",
|
||||
],
|
||||
[
|
||||
"investigation_workspace_read",
|
||||
"investigation_input",
|
||||
...(includeWrite ? (["investigation_workspace_write"] as const) : []),
|
||||
],
|
||||
);
|
||||
|
||||
@@ -78,7 +78,7 @@ describe("JavaScript runtime observation MCP tools", () => {
|
||||
expect(listed.isError).not.toBe(true);
|
||||
expect(listed.structuredContent).toMatchObject({
|
||||
result: {
|
||||
targets: { items: [{ target_id: inspector.targetId }] },
|
||||
targets: [{ target_id: inspector.targetId }],
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -121,13 +121,11 @@ const verifyManagedCatalogAndNativeWorkflow = async (
|
||||
MANAGED_NATIVE_VERIFICATION_EXAMPLE.native_observations.map(
|
||||
({ evidence_id: evidenceId }) => evidenceId,
|
||||
),
|
||||
limits: MANAGED_NATIVE_VERIFICATION_EXAMPLE.limits,
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(verified).toMatchObject({
|
||||
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
|
||||
evidence_uri: expect.stringMatching(/^rea:\/\/evidence\/ev_/u),
|
||||
result: {
|
||||
summary: { verified: 1 },
|
||||
algorithm: { token_to_address_mapping: "not-inferred" },
|
||||
@@ -163,13 +161,13 @@ const inspectManagedStaticWorkflow = async (
|
||||
const inspected = structured(
|
||||
await client.callTool({
|
||||
name: "inspect_managed_artifact",
|
||||
arguments: { path, reference_limit: 1 },
|
||||
arguments: { path },
|
||||
}),
|
||||
);
|
||||
expect(inspected).toMatchObject({
|
||||
result: {
|
||||
classification: { status: "managed", runtime_family: "modern-dotnet" },
|
||||
references: { limit: 1 },
|
||||
references: [expect.objectContaining({ name: "System.Runtime" })],
|
||||
},
|
||||
});
|
||||
const members = sessionEvidence(
|
||||
@@ -177,7 +175,7 @@ const inspectManagedStaticWorkflow = async (
|
||||
structured(
|
||||
await client.callTool({
|
||||
name: "inspect_managed_members",
|
||||
arguments: { method_limit: 1 },
|
||||
arguments: {},
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -187,22 +185,26 @@ const inspectManagedStaticWorkflow = async (
|
||||
subject: { local_path: path, format: "pe" },
|
||||
normalized_result: {
|
||||
identity_scope: { token_identity: "build-local" },
|
||||
methods: { total: 1, returned: 1 },
|
||||
call_edges: { total: 1 },
|
||||
field_accesses: { total: 1 },
|
||||
methods: [expect.objectContaining({ token: expect.any(String) })],
|
||||
call_edges: [
|
||||
expect.objectContaining({ target_token: expect.any(String) }),
|
||||
],
|
||||
field_accesses: [
|
||||
expect.objectContaining({ field_token: expect.any(String) }),
|
||||
],
|
||||
},
|
||||
});
|
||||
const boundaries = structured(
|
||||
await client.callTool({
|
||||
name: "inspect_managed_native_boundaries",
|
||||
arguments: { import_limit: 1 },
|
||||
arguments: {},
|
||||
}),
|
||||
);
|
||||
expect(boundaries).toMatchObject({
|
||||
result: {
|
||||
identity_scope: { token_identity: "build-local" },
|
||||
pinvoke_imports: { total: 0, limit: 1 },
|
||||
native_implementations: { total: 0 },
|
||||
pinvoke_imports: [],
|
||||
native_implementations: [],
|
||||
},
|
||||
});
|
||||
return members;
|
||||
@@ -210,19 +212,17 @@ const inspectManagedStaticWorkflow = async (
|
||||
|
||||
const methodFrom = (members: Record<string, unknown>) =>
|
||||
z
|
||||
.object({
|
||||
items: z.array(
|
||||
z.object({
|
||||
token: z.string(),
|
||||
signature: z.object({ raw_sha256: z.string() }),
|
||||
body: z.object({ normalized_il_sha256: z.string().nullable() }),
|
||||
}),
|
||||
),
|
||||
})
|
||||
.array(
|
||||
z.object({
|
||||
token: z.string(),
|
||||
signature: z.object({ raw_sha256: z.string() }),
|
||||
body: z.object({ normalized_il_sha256: z.string().nullable() }),
|
||||
}),
|
||||
)
|
||||
.parse(
|
||||
z.record(z.string(), z.unknown()).parse(members.normalized_result)
|
||||
.methods,
|
||||
).items[0];
|
||||
)[0];
|
||||
|
||||
const verifyManagedComparisonAndReconstruction = async (
|
||||
client: Client,
|
||||
@@ -239,7 +239,7 @@ const verifyManagedComparisonAndReconstruction = async (
|
||||
structured(
|
||||
await client.callTool({
|
||||
name: "inspect_managed_members",
|
||||
arguments: { method_limit: 1 },
|
||||
arguments: {},
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -251,11 +251,6 @@ const verifyManagedComparisonAndReconstruction = async (
|
||||
arguments: {
|
||||
left_evidence_id: members.evidence_id,
|
||||
right_evidence_id: right.evidence_id,
|
||||
limits: {
|
||||
max_method_matches: 100,
|
||||
max_field_matches: 100,
|
||||
max_candidates: 10,
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -74,18 +74,11 @@ const connect = async (analysis: AnalysisOperationPort) => {
|
||||
return client;
|
||||
};
|
||||
|
||||
const page: JsonValue = {
|
||||
items: [],
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: 0,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
};
|
||||
const inventory: JsonValue = [];
|
||||
|
||||
const outputFor = (name: string): JsonValue => {
|
||||
if (["list_procedures", "list_names", "list_strings"].includes(name))
|
||||
return page;
|
||||
return inventory;
|
||||
if (["address_name", "comment", "inline_comment"].includes(name)) return null;
|
||||
if (["procedure_callees", "procedure_callers", "xrefs"].includes(name))
|
||||
return [];
|
||||
@@ -102,7 +95,7 @@ const outputFor = (name: string): JsonValue => {
|
||||
)
|
||||
return true;
|
||||
if (name === "set_addresses_names") return { "0x1000": true };
|
||||
if (["search_procedures", "search_strings"].includes(name)) return page;
|
||||
if (["search_procedures", "search_strings"].includes(name)) return inventory;
|
||||
if (name === "procedure_info")
|
||||
return {
|
||||
name: "main",
|
||||
@@ -121,15 +114,7 @@ const outputFor = (name: string): JsonValue => {
|
||||
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,
|
||||
instructions: ["0x1000: ret"],
|
||||
limitations: ["Provider-specific instruction text."],
|
||||
};
|
||||
if (name === "read_bytes")
|
||||
@@ -146,15 +131,7 @@ const outputFor = (name: string): JsonValue => {
|
||||
return {
|
||||
procedure: { address: "0x1000", name: "main" },
|
||||
direction: "outgoing",
|
||||
references: {
|
||||
items: [],
|
||||
total: 0,
|
||||
returned: 0,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
instructions_scanned: 1,
|
||||
instruction_scan_truncated: false,
|
||||
references: [],
|
||||
};
|
||||
return name.includes("address") ? "0x1000" : "fixture";
|
||||
};
|
||||
@@ -191,11 +168,6 @@ describe("official Hopper proxy tools", () => {
|
||||
arguments: VALID_INPUTS[contract.name],
|
||||
});
|
||||
expect(result.isError).not.toBe(true);
|
||||
expect(result.content).not.toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ type: "resource_link" }),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
expect(invocations.map(({ name }) => name)).toEqual(
|
||||
@@ -213,8 +185,6 @@ describe("official Hopper proxy tools", () => {
|
||||
pattern: "main",
|
||||
mode: "literal",
|
||||
case_sensitive: false,
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
document: null,
|
||||
});
|
||||
});
|
||||
@@ -233,4 +203,72 @@ describe("official Hopper proxy tools", () => {
|
||||
text: JSON.stringify(result.structuredContent),
|
||||
});
|
||||
});
|
||||
|
||||
it("returns every procedure inline without caller-authored page calls", async () => {
|
||||
const invocations: Invocation[] = [];
|
||||
const client = await connect({
|
||||
execute: (name, arguments_) => {
|
||||
invocations.push({ name, arguments_ });
|
||||
return Promise.resolve(
|
||||
ok([
|
||||
{ address: "0x1", value: "procedure" },
|
||||
{ address: "0x2", value: "procedure" },
|
||||
]),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
const result = await client.callTool({
|
||||
name: "list_procedures",
|
||||
arguments: {},
|
||||
});
|
||||
|
||||
expect(result.structuredContent).toMatchObject({
|
||||
result: [
|
||||
{ address: "0x1", value: "procedure" },
|
||||
{ address: "0x2", value: "procedure" },
|
||||
],
|
||||
});
|
||||
expect(invocations).toHaveLength(1);
|
||||
expect(invocations[0]?.arguments_).toEqual({ document: null });
|
||||
expect(
|
||||
(await client.listTools()).tools.find(
|
||||
({ name }) => name === "list_procedures",
|
||||
)?.inputSchema,
|
||||
).not.toHaveProperty("properties.offset");
|
||||
});
|
||||
|
||||
it("returns every search match inline in one provider call", async () => {
|
||||
const invocations: Invocation[] = [];
|
||||
const client = await connect({
|
||||
execute: (name, arguments_) => {
|
||||
invocations.push({ name, arguments_ });
|
||||
return Promise.resolve(
|
||||
ok([
|
||||
{ address: "0x1", value: "coffee" },
|
||||
{ address: "0x2", value: "coffee" },
|
||||
]),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
const result = await client.callTool({
|
||||
name: "search_strings",
|
||||
arguments: { pattern: "coffee" },
|
||||
});
|
||||
|
||||
expect(result.structuredContent).toMatchObject({
|
||||
result: [
|
||||
{ address: "0x1", value: "coffee" },
|
||||
{ address: "0x2", value: "coffee" },
|
||||
],
|
||||
});
|
||||
expect(invocations).toHaveLength(1);
|
||||
expect(invocations[0]?.arguments_).toMatchObject({ pattern: "coffee" });
|
||||
expect(
|
||||
(await client.listTools()).tools.find(
|
||||
({ name }) => name === "search_strings",
|
||||
)?.inputSchema,
|
||||
).not.toHaveProperty("properties.offset");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -70,21 +70,15 @@ describe("process-capture MCP elicitation handshake", () => {
|
||||
});
|
||||
try {
|
||||
await client.connect(clientTransport);
|
||||
const identity = await client.readResource({
|
||||
uri: "rea://server/identity",
|
||||
});
|
||||
const identityContent = identity.contents[0];
|
||||
if (identityContent === undefined || !("text" in identityContent))
|
||||
throw new Error("missing modern server identity resource");
|
||||
expect(JSON.parse(identityContent.text)).toMatchObject({
|
||||
client: { name: "process-elicit", version: "1" },
|
||||
});
|
||||
const status = await client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: { detail: "full" },
|
||||
arguments: {},
|
||||
});
|
||||
expect(status.structuredContent).toMatchObject({
|
||||
result: {
|
||||
server_identity: {
|
||||
client: { name: "process-elicit", version: "1" },
|
||||
},
|
||||
client_features: {
|
||||
elicitation_form: true,
|
||||
elicitation_url: false,
|
||||
|
||||
@@ -82,7 +82,7 @@ const traceSpecification: ProcessTraceSpecification = {
|
||||
|
||||
const captureEvidence = (side: "left" | "right") =>
|
||||
createEvidence(undefined, PROCESS_PROVIDER, {
|
||||
predicateType: "rea.process-capture/v4",
|
||||
predicateType: "rea.process-capture",
|
||||
operation: "capture_process_scenario",
|
||||
parameters: { side },
|
||||
result: jsonValueSchema.parse(capture),
|
||||
|
||||
@@ -21,7 +21,7 @@ afterEach(async () => {
|
||||
});
|
||||
|
||||
describe("guided prompt completion from live analysis", () => {
|
||||
it("reads live documents and paged procedures without ambiguous names", async () => {
|
||||
it("reads live documents and complete procedures without ambiguous names", async () => {
|
||||
const requests: Array<Readonly<Record<string, unknown>>> = [];
|
||||
const session = createTestBinarySession(() => client(requests));
|
||||
directory = await createTestTempDirectory("rea-prompt-completion-");
|
||||
@@ -39,10 +39,7 @@ describe("guided prompt completion from live analysis", () => {
|
||||
arguments: { document: "App" },
|
||||
}),
|
||||
).toEqual(["0x1000", "0x2000", "0x3000", "0x4000", "tail", "unique"]);
|
||||
expect(requests).toEqual([
|
||||
{ offset: 0, limit: 500, document: "App" },
|
||||
{ offset: 2, limit: 500, document: "App" },
|
||||
]);
|
||||
expect(requests).toEqual([{ document: "App" }]);
|
||||
expect(await completion.complete("provider", "uni")).toEqual([
|
||||
"unidentified",
|
||||
]);
|
||||
@@ -62,7 +59,7 @@ describe("guided prompt completion from investigation records", () => {
|
||||
const invalidCapture = createEvidence(undefined, fixtureProvider, {
|
||||
operation: "capture_process_scenario",
|
||||
parameters: {},
|
||||
result: { schema_version: 4 },
|
||||
result: {},
|
||||
confidence: "observed",
|
||||
authority: "controlled-replay",
|
||||
environment: fixtureEnvironment,
|
||||
@@ -156,65 +153,24 @@ describe("guided prompt completion from investigation records", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("guided prompt completion validation and limits", () => {
|
||||
it("does not offer procedure names from an incomplete discovery", async () => {
|
||||
let calls = 0;
|
||||
const completion = createPromptCompletionSource({
|
||||
execute() {
|
||||
calls += 1;
|
||||
return Promise.resolve(
|
||||
observed(
|
||||
calls === 1
|
||||
? page(0, [{ address: "0x1000", value: "possibly_ambiguous" }], 1)
|
||||
: null,
|
||||
),
|
||||
);
|
||||
},
|
||||
});
|
||||
expect(await completion.complete("procedure", "")).toEqual(["0x1000"]);
|
||||
});
|
||||
|
||||
it("bounds procedure scans and rejects non-advancing continuation metadata", async () => {
|
||||
describe("guided prompt completion from complete inventories", () => {
|
||||
it("reads every procedure in one provider call", async () => {
|
||||
let calls = 0;
|
||||
const procedures = Array.from({ length: 6_000 }, (_, address) => ({
|
||||
address: `0x${address.toString(16).padStart(8, "0")}`,
|
||||
value: `procedure_${String(address)}`,
|
||||
}));
|
||||
const bounded = createPromptCompletionSource({
|
||||
execute(_operation, parameters) {
|
||||
calls += 1;
|
||||
const offset = Number(parameters.offset);
|
||||
const items = Array.from({ length: 500 }, (_, index) => {
|
||||
const address = offset + index;
|
||||
return {
|
||||
address: `0x${address.toString(16).padStart(8, "0")}`,
|
||||
value: `procedure_${String(address)}`,
|
||||
};
|
||||
});
|
||||
return Promise.resolve(
|
||||
observed({
|
||||
items,
|
||||
offset,
|
||||
limit: 500,
|
||||
total: 6_000,
|
||||
next_offset: offset + 500,
|
||||
has_more: true,
|
||||
}),
|
||||
);
|
||||
expect(parameters).toEqual({});
|
||||
return Promise.resolve(observed(procedures));
|
||||
},
|
||||
});
|
||||
const values = await bounded.complete("procedure", "");
|
||||
expect(calls).toBe(10);
|
||||
expect(values).toHaveLength(5_000);
|
||||
expect(values.every((value) => value.startsWith("0x"))).toBe(true);
|
||||
|
||||
let nonAdvancingCalls = 0;
|
||||
const nonAdvancing = createPromptCompletionSource({
|
||||
execute() {
|
||||
nonAdvancingCalls += 1;
|
||||
return Promise.resolve(
|
||||
observed(page(0, [{ address: "0x5000", value: "unsafe_name" }], 0)),
|
||||
);
|
||||
},
|
||||
});
|
||||
expect(await nonAdvancing.complete("procedure", "")).toEqual(["0x5000"]);
|
||||
expect(nonAdvancingCalls).toBe(1);
|
||||
expect(calls).toBe(1);
|
||||
expect(values).toHaveLength(12_000);
|
||||
expect(values).toContain("0x00000000");
|
||||
});
|
||||
|
||||
it("normalizes Unicode prefixes while preserving distinct exact identifiers", async () => {
|
||||
@@ -258,43 +214,16 @@ const client = (
|
||||
return Promise.resolve(observed(["AppTests", "App", "App"]));
|
||||
if (operation === "list_procedures") {
|
||||
requests.push(parameters);
|
||||
const offset = parameters.offset;
|
||||
return Promise.resolve(
|
||||
observed(
|
||||
offset === 0
|
||||
? page(
|
||||
0,
|
||||
[
|
||||
{ address: "0x1000", value: "duplicate" },
|
||||
{ address: "0x2000", value: "unique" },
|
||||
],
|
||||
2,
|
||||
)
|
||||
: page(
|
||||
2,
|
||||
[
|
||||
{ address: "0x3000", value: "duplicate" },
|
||||
{ address: "0x4000", value: "tail" },
|
||||
],
|
||||
null,
|
||||
),
|
||||
),
|
||||
observed([
|
||||
{ address: "0x1000", value: "duplicate" },
|
||||
{ address: "0x2000", value: "unique" },
|
||||
{ address: "0x3000", value: "duplicate" },
|
||||
{ address: "0x4000", value: "tail" },
|
||||
]),
|
||||
);
|
||||
}
|
||||
return Promise.resolve(observed(null));
|
||||
},
|
||||
close: () => Promise.resolve(),
|
||||
});
|
||||
|
||||
const page = (
|
||||
offset: number,
|
||||
items: readonly { readonly address: string; readonly value: string }[],
|
||||
nextOffset: number | null,
|
||||
) => ({
|
||||
items,
|
||||
offset,
|
||||
limit: 500,
|
||||
total: 4,
|
||||
next_offset: nextOffset,
|
||||
has_more: nextOffset !== null,
|
||||
});
|
||||
|
||||
@@ -376,19 +376,12 @@ const lifecycleClient = (
|
||||
if (operation === "list_procedures") {
|
||||
requests.push(parameters);
|
||||
return Promise.resolve(
|
||||
observed({
|
||||
items: [
|
||||
{
|
||||
address: target === "first" ? "0x1000" : "0x2000",
|
||||
value: `${target}-procedure`,
|
||||
},
|
||||
],
|
||||
offset: 0,
|
||||
limit: 500,
|
||||
total: 1,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
}),
|
||||
observed([
|
||||
{
|
||||
address: target === "first" ? "0x1000" : "0x2000",
|
||||
value: `${target}-procedure`,
|
||||
},
|
||||
]),
|
||||
);
|
||||
}
|
||||
return Promise.resolve(observed(null));
|
||||
|
||||
@@ -57,7 +57,7 @@ describe("provider selection over MCP", () => {
|
||||
const before = structured(
|
||||
await mcp.callTool({
|
||||
name: "binary_session",
|
||||
arguments: { detail: "full" },
|
||||
arguments: {},
|
||||
}),
|
||||
);
|
||||
expect(before.result).toMatchObject({
|
||||
@@ -124,7 +124,7 @@ describe("provider selection over MCP", () => {
|
||||
const status = structured(
|
||||
await mcp.callTool({
|
||||
name: "binary_session",
|
||||
arguments: { detail: "full" },
|
||||
arguments: {},
|
||||
}),
|
||||
);
|
||||
expect(status.result).toMatchObject({
|
||||
@@ -157,7 +157,7 @@ describe("provider selection over MCP", () => {
|
||||
structured(
|
||||
await mcp.callTool({
|
||||
name: "binary_session",
|
||||
arguments: { detail: "full" },
|
||||
arguments: {},
|
||||
}),
|
||||
).result,
|
||||
).toMatchObject({
|
||||
@@ -192,7 +192,6 @@ const candidate = (id: string, starts: string[]): AnalysisProviderCandidate => {
|
||||
ok({
|
||||
profile: createAnalysisProfile(
|
||||
{ id, name: identity.name, version: "1" },
|
||||
1,
|
||||
{ fixture: id },
|
||||
),
|
||||
compatibility: {},
|
||||
@@ -219,8 +218,6 @@ const candidate = (id: string, starts: string[]): AnalysisProviderCandidate => {
|
||||
const capability = (provider: ProviderIdentity): CapabilityDescriptor => ({
|
||||
provider,
|
||||
operation: "address_name",
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: true,
|
||||
reason: null,
|
||||
pagination: "none",
|
||||
|
||||
@@ -65,16 +65,10 @@ describe("reconstruction coverage MCP parity", () => {
|
||||
revision: 1,
|
||||
revision_sha256: workspace.revision_sha256,
|
||||
});
|
||||
const resourceUri = `rea://reconstruction-coverage/${workspace.workspace_id}/revision/1`;
|
||||
expect(committed.content).toContainEqual(
|
||||
expect.objectContaining({ type: "resource_link", uri: resourceUri }),
|
||||
);
|
||||
const resource = await client.readResource({ uri: resourceUri });
|
||||
expect(resource.contents[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
text: expect.stringContaining(workspace.revision_sha256),
|
||||
}),
|
||||
);
|
||||
expect(committed.structuredContent).toMatchObject({
|
||||
workspace_id: workspace.workspace_id,
|
||||
revision_sha256: workspace.revision_sha256,
|
||||
});
|
||||
const queried = await client.callTool({
|
||||
name: "query_reconstruction_coverage",
|
||||
arguments: {
|
||||
|
||||
@@ -7,7 +7,7 @@ import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
describe("reconstruction obligation ledger MCP parity", () => {
|
||||
it("builds an Evidence-backed page and exposes the retained resource", async () => {
|
||||
it("returns an Evidence-backed page inline", async () => {
|
||||
const session = createTestBinarySession(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
@@ -25,44 +25,24 @@ describe("reconstruction obligation ledger MCP parity", () => {
|
||||
evidence_bundle: createEvidenceBundle([]),
|
||||
reviewed_obligations: [],
|
||||
manifest: {
|
||||
schema_version: 1,
|
||||
bindings: [],
|
||||
contradictions: [],
|
||||
},
|
||||
limits: { max_obligations: 100 },
|
||||
page: { offset: 0, limit: 50 },
|
||||
},
|
||||
});
|
||||
expect(result.isError).not.toBe(true);
|
||||
expect(result.structuredContent).toMatchObject({
|
||||
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
|
||||
evidence_uri: expect.stringMatching(
|
||||
/^rea:\/\/evidence\/ev_[a-f0-9]{64}$/u,
|
||||
),
|
||||
result: {
|
||||
schema: "ReconstructionObligationLedger",
|
||||
status: "unknown",
|
||||
summary: { total: 0 },
|
||||
},
|
||||
});
|
||||
const evidence = result.structuredContent;
|
||||
if (
|
||||
evidence === undefined ||
|
||||
evidence === null ||
|
||||
typeof evidence !== "object" ||
|
||||
!("evidence_id" in evidence) ||
|
||||
typeof evidence.evidence_id !== "string"
|
||||
)
|
||||
throw new TypeError("Missing obligation ledger Evidence ID");
|
||||
const resource = await client.readResource({
|
||||
uri: `rea://evidence/${evidence.evidence_id}/reconstruction-obligation-ledger`,
|
||||
});
|
||||
expect(resource.contents[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
text: expect.stringContaining(
|
||||
'"schema": "ReconstructionObligationLedger"',
|
||||
),
|
||||
}),
|
||||
expect(result.structuredContent).toHaveProperty(
|
||||
"result.schema",
|
||||
"ReconstructionObligationLedger",
|
||||
);
|
||||
} finally {
|
||||
await client.close();
|
||||
|
||||
@@ -7,7 +7,7 @@ import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
describe("reconstruction readiness MCP parity", () => {
|
||||
it("returns a passing compact result and retains the full report resource", async () => {
|
||||
it("returns the complete passing report inline", async () => {
|
||||
const session = createTestBinarySession(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
@@ -30,31 +30,13 @@ describe("reconstruction readiness MCP parity", () => {
|
||||
schema: "ReconstructionReadinessReport",
|
||||
status: "pass",
|
||||
summary: { passed_required_stages: 9 },
|
||||
report_resource_uri: expect.stringMatching(
|
||||
/^rea:\/\/evidence\/ev_[a-f0-9]{64}\/reconstruction-readiness-report$/u,
|
||||
),
|
||||
stages: expect.arrayContaining([expect.any(Object)]),
|
||||
},
|
||||
});
|
||||
expect(result.structuredContent).not.toHaveProperty("result.snapshot");
|
||||
expect(result.structuredContent).not.toHaveProperty("result.stages");
|
||||
const content = result.structuredContent;
|
||||
if (
|
||||
content === undefined ||
|
||||
content === null ||
|
||||
typeof content !== "object" ||
|
||||
!("evidence_id" in content) ||
|
||||
typeof content.evidence_id !== "string"
|
||||
)
|
||||
throw new TypeError("Missing readiness Evidence ID");
|
||||
const resource = await client.readResource({
|
||||
uri: `rea://evidence/${content.evidence_id}/reconstruction-readiness-report`,
|
||||
});
|
||||
expect(resource.contents[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
text: expect.stringContaining(
|
||||
'"schema": "ReconstructionReadinessReport"',
|
||||
),
|
||||
}),
|
||||
expect(result.structuredContent).toHaveProperty("result.snapshot");
|
||||
expect(result.structuredContent).toHaveProperty("result.stages");
|
||||
expect(result.structuredContent).not.toHaveProperty(
|
||||
"result.report_resource_uri",
|
||||
);
|
||||
} finally {
|
||||
await client.close();
|
||||
|
||||
@@ -27,7 +27,6 @@ describe("direct replay machine MCP parity", () => {
|
||||
expect(result).toMatchObject({
|
||||
structuredContent: {
|
||||
result: {
|
||||
schema_version: 1,
|
||||
final_state: "complete",
|
||||
terminal: true,
|
||||
decisions: [{ outcome: "matched", transition_sequence: 0 }],
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
import { PACKAGE_METADATA } from "../../../src/generatedPackageMetadata.js";
|
||||
import { PRODUCT_IDENTITY, SDK_IDENTITY } from "../../../src/identity.js";
|
||||
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
|
||||
import { TOOL_KINDS } from "../../../src/contracts/toolContractTypes.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { createServerIdentity } from "../../../src/serverIdentity.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
@@ -26,8 +25,6 @@ const availabilityProvider = (): AnalysisProvider => {
|
||||
const capability: CapabilityDescriptor = {
|
||||
provider: identity,
|
||||
operation: "current_address",
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: true,
|
||||
reason: null,
|
||||
pagination: "none",
|
||||
@@ -118,8 +115,6 @@ describe("server and catalog identity", () => {
|
||||
cli_commands: 68,
|
||||
mcp_tools: TOOL_CONTRACTS.length,
|
||||
mcp_prompts: 6,
|
||||
mcp_resources: 2,
|
||||
mcp_resource_templates: 11,
|
||||
});
|
||||
expect(CATALOG_IDENTITY.digests.combined_sha256).toMatch(/^[a-f0-9]{64}$/u);
|
||||
});
|
||||
@@ -238,7 +233,6 @@ describe("live server identity over MCP", () => {
|
||||
await client.connect(clientTransport);
|
||||
await assertLiveIdentity(client);
|
||||
await assertSessionIdentity(client);
|
||||
await assertCapabilityViews(client);
|
||||
expect(
|
||||
(await client.listTools()).tools.map(({ name }) => name),
|
||||
).toContain("current_address");
|
||||
@@ -269,29 +263,30 @@ const assertLiveIdentity = async (client: Client): Promise<void> => {
|
||||
expect(instructions).toContain(
|
||||
"native binary/database -> open_binary, then binary_overview",
|
||||
);
|
||||
expect(instructions).toContain("Never repeat identical analysis");
|
||||
expect(instructions).toContain("cite Evidence IDs");
|
||||
const resource = await client.readResource({ uri: "rea://server/identity" });
|
||||
const content = resource.contents[0];
|
||||
expect(content).toBeDefined();
|
||||
if (content === undefined || !("text" in content))
|
||||
throw new Error("missing identity resource text");
|
||||
expect(JSON.parse(content.text)).toMatchObject({
|
||||
package: { version: PRODUCT_IDENTITY.packageVersion },
|
||||
server: { version: PRODUCT_IDENTITY.packageVersion },
|
||||
sdk: {
|
||||
server: SDK_IDENTITY.server,
|
||||
client_test: PACKAGE_METADATA.clientSdkVersion,
|
||||
const identity = await client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: {},
|
||||
});
|
||||
expect(identity.structuredContent).toMatchObject({
|
||||
result: {
|
||||
server_identity: {
|
||||
package: { version: PRODUCT_IDENTITY.packageVersion },
|
||||
server: { version: PRODUCT_IDENTITY.packageVersion },
|
||||
sdk: {
|
||||
server: SDK_IDENTITY.server,
|
||||
client_test: PACKAGE_METADATA.clientSdkVersion,
|
||||
},
|
||||
client: null,
|
||||
alignment: { state: "unknown" },
|
||||
},
|
||||
},
|
||||
client: null,
|
||||
alignment: { state: "unknown" },
|
||||
});
|
||||
};
|
||||
|
||||
const assertSessionIdentity = async (client: Client): Promise<void> => {
|
||||
const status = await client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: { detail: "full", expected_package_version: "1.2.0" },
|
||||
arguments: { expected_package_version: "1.2.0" },
|
||||
});
|
||||
expect(status.structuredContent).toMatchObject({
|
||||
result: {
|
||||
@@ -328,11 +323,9 @@ const assertSessionIdentity = async (client: Client): Promise<void> => {
|
||||
}),
|
||||
expect.objectContaining({
|
||||
name: "analyze_javascript_application",
|
||||
available: false,
|
||||
reason: "policy_disabled",
|
||||
remediation: expect.stringContaining(
|
||||
"REA_INVESTIGATION_INPUT_ROOTS_JSON",
|
||||
),
|
||||
available: true,
|
||||
reason: "available",
|
||||
remediation: null,
|
||||
}),
|
||||
]),
|
||||
client_features: {
|
||||
@@ -343,76 +336,4 @@ const assertSessionIdentity = async (client: Client): Promise<void> => {
|
||||
},
|
||||
},
|
||||
});
|
||||
const summary = await client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: { expected_package_version: "1.2.0" },
|
||||
});
|
||||
expect(summary.structuredContent).toMatchObject({
|
||||
result: {
|
||||
view: "summary",
|
||||
open: false,
|
||||
target: null,
|
||||
alignment: { state: "mcp_server_restart_required" },
|
||||
recommended_actions: expect.arrayContaining([
|
||||
"For a supplied target, route by format: ASAR/JavaScript to analyze_javascript_application; archive/package to open_binary(path), then inspect_artifact or inventory_artifact on the active target; managed PE/CLI to inspect_managed_artifact; browser/Electron runtimes to their list-target tools; native binaries to open_binary.",
|
||||
]),
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(summary.structuredContent)).not.toContain(
|
||||
"tool_availability",
|
||||
);
|
||||
};
|
||||
|
||||
const assertCapabilityViews = async (client: Client): Promise<void> => {
|
||||
const capabilities = await client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: {
|
||||
detail: "capabilities",
|
||||
capability_family: "browser-provider",
|
||||
cursor: 0,
|
||||
limit: 1,
|
||||
},
|
||||
});
|
||||
expect(capabilities.structuredContent).toMatchObject({
|
||||
result: {
|
||||
view: "capabilities",
|
||||
capability_family: "browser-provider",
|
||||
capabilities: {
|
||||
items: [expect.objectContaining({ surface: "browser-provider" })],
|
||||
cursor: 0,
|
||||
limit: 1,
|
||||
total: expect.any(Number),
|
||||
next_cursor: expect.any(Number),
|
||||
has_more: true,
|
||||
},
|
||||
client_features: {
|
||||
elicitation_form: false,
|
||||
elicitation_url: false,
|
||||
roots: false,
|
||||
sampling: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
for (const capabilityFamily of TOOL_KINDS) {
|
||||
const familyCapabilities = await client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: {
|
||||
detail: "capabilities",
|
||||
capability_family: capabilityFamily,
|
||||
limit: 100,
|
||||
},
|
||||
});
|
||||
expect(familyCapabilities.structuredContent).toMatchObject({
|
||||
result: {
|
||||
view: "capabilities",
|
||||
capability_family: capabilityFamily,
|
||||
capabilities: {
|
||||
items: expect.arrayContaining([
|
||||
expect.objectContaining({ surface: capabilityFamily }),
|
||||
]),
|
||||
total: expect.any(Number),
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
@@ -116,18 +116,7 @@ it("handles concurrent tool calls without corruption", async () => {
|
||||
execute: (name) => {
|
||||
invocations.push(name);
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
["list_procedures", "list_strings"].includes(name)
|
||||
? {
|
||||
items: [],
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: 0,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
}
|
||||
: [],
|
||||
),
|
||||
ok(["list_procedures", "list_strings"].includes(name) ? [] : []),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -35,8 +35,6 @@ const providerWithCapabilities = (
|
||||
(operation) => ({
|
||||
provider: identity,
|
||||
operation,
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: true,
|
||||
reason: null,
|
||||
pagination: "none",
|
||||
@@ -77,69 +75,6 @@ const structured = (result: CallToolResult): Record<string, unknown> => {
|
||||
return Object.fromEntries(Object.entries(result.structuredContent));
|
||||
};
|
||||
|
||||
it("records approved trace truncation as a deduplicated residual unknown", async () => {
|
||||
const analysis: AnalysisOperationPort = {
|
||||
execute: () =>
|
||||
Promise.resolve(
|
||||
ok({
|
||||
items: [],
|
||||
offset: 0,
|
||||
limit: 500,
|
||||
total: 0,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
}),
|
||||
),
|
||||
};
|
||||
const session = createTestBinarySession(
|
||||
providerWithCapabilities([
|
||||
"list_strings",
|
||||
"list_procedures",
|
||||
"xrefs",
|
||||
"resolve_containing_procedure",
|
||||
]),
|
||||
);
|
||||
const server = createServer(analysis, session);
|
||||
const client = new Client({ name: "unknown-workflow", version: "1.0.0" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server);
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: process.execPath },
|
||||
});
|
||||
|
||||
for (let attempt = 0; attempt < 2; attempt += 1) {
|
||||
const traced = await client.callTool({
|
||||
name: "trace_feature",
|
||||
arguments: {
|
||||
query: "license",
|
||||
max_operations: 1,
|
||||
unknown_registry_approved: true,
|
||||
},
|
||||
});
|
||||
expect(traced.isError).not.toBe(true);
|
||||
}
|
||||
const listed = structured(
|
||||
await client.callTool({ name: "list_unknowns", arguments: {} }),
|
||||
);
|
||||
expect(listed).toMatchObject({
|
||||
result: {
|
||||
items: [
|
||||
{
|
||||
unknown: {
|
||||
status: "open",
|
||||
domain: "control-flow",
|
||||
question: "Investigation reached the operation budget.",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
}, 10_000);
|
||||
|
||||
it("records approved typed capability unavailability without forwarding the flag", async () => {
|
||||
const received: Array<Readonly<Record<string, unknown>>> = [];
|
||||
const analysis: AnalysisOperationPort = {
|
||||
@@ -191,17 +126,15 @@ it("records approved typed capability unavailability without forwarding the flag
|
||||
result: {
|
||||
items: [
|
||||
{
|
||||
unknown: {
|
||||
domain: "analysis-capability",
|
||||
question:
|
||||
"The requested analysis is unavailable for the current target.",
|
||||
recommended_probes: [
|
||||
{
|
||||
rationale:
|
||||
"Choose another analysis or target that can answer this question.",
|
||||
},
|
||||
],
|
||||
},
|
||||
domain: "analysis-capability",
|
||||
question:
|
||||
"The requested analysis is unavailable for the current target.",
|
||||
recommended_probes: [
|
||||
{
|
||||
rationale:
|
||||
"Choose another analysis or target that can answer this question.",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -243,7 +176,7 @@ it("records approved capture disagreement as a contradicted unknown", async () =
|
||||
});
|
||||
const captureEvidence = (capture: typeof left) =>
|
||||
createEvidence(undefined, PROCESS_PROVIDER, {
|
||||
predicateType: "rea.process-capture/v4",
|
||||
predicateType: "rea.process-capture",
|
||||
operation: "capture_process_scenario",
|
||||
parameters: {},
|
||||
result: jsonValueSchema.parse(capture),
|
||||
@@ -291,12 +224,10 @@ it("records approved capture disagreement as a contradicted unknown", async () =
|
||||
result: {
|
||||
items: [
|
||||
{
|
||||
unknown: {
|
||||
status: "contradicted",
|
||||
domain: "process-comparison",
|
||||
question: "Process captures disagree across: interaction, shim",
|
||||
contradicting_evidence_ids: [rightEvidence.evidence_id],
|
||||
},
|
||||
status: "contradicted",
|
||||
domain: "process-comparison",
|
||||
question: "Process captures disagree across: interaction, shim",
|
||||
contradicting_evidence_ids: [rightEvidence.evidence_id],
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -49,17 +49,10 @@ it("executes a realistic workflow: list methods, decompile selected, get xrefs",
|
||||
switch (name) {
|
||||
case "list_procedures":
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
items: [
|
||||
{ address: "0x1000", value: "main" },
|
||||
{ address: "0x2000", value: "helper" },
|
||||
],
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: 2,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
}),
|
||||
ok([
|
||||
{ address: "0x1000", value: "main" },
|
||||
{ address: "0x2000", value: "helper" },
|
||||
]),
|
||||
);
|
||||
case "procedure_pseudo_code":
|
||||
return Promise.resolve(
|
||||
@@ -79,14 +72,10 @@ it("executes a realistic workflow: list methods, decompile selected, get xrefs",
|
||||
});
|
||||
expect(listResult.isError).not.toBe(true);
|
||||
expect(structured(listResult)).toMatchObject({
|
||||
result: {
|
||||
items: [
|
||||
{ address: "0x1000", value: "main" },
|
||||
{ address: "0x2000", value: "helper" },
|
||||
],
|
||||
total: 2,
|
||||
has_more: false,
|
||||
},
|
||||
result: [
|
||||
{ address: "0x1000", value: "main" },
|
||||
{ address: "0x2000", value: "helper" },
|
||||
],
|
||||
});
|
||||
|
||||
const decompileResult = await client.callTool({
|
||||
@@ -138,7 +127,7 @@ it("advertises the complete currently available inventory with a session", async
|
||||
const status = structured(
|
||||
await client.callTool({
|
||||
name: "binary_session",
|
||||
arguments: { detail: "full" },
|
||||
arguments: {},
|
||||
}),
|
||||
);
|
||||
const available = new Set(
|
||||
|
||||
@@ -27,7 +27,6 @@ import {
|
||||
|
||||
const SNAPSHOT_PROFILE = createAnalysisProfile(
|
||||
{ id: "fixture", name: "Fixture analysis provider", version: "1" },
|
||||
1,
|
||||
{ fixture: true },
|
||||
);
|
||||
|
||||
@@ -93,7 +92,7 @@ describe("target-free MCP lifecycle", () => {
|
||||
structured(
|
||||
await mcp.callTool({
|
||||
name: "binary_session",
|
||||
arguments: { detail: "full" },
|
||||
arguments: {},
|
||||
}),
|
||||
),
|
||||
).result,
|
||||
@@ -117,7 +116,7 @@ describe("target-free MCP workflow", () => {
|
||||
const beforeTools = (await mcp.listTools()).tools;
|
||||
const beforeNames = beforeTools.map(({ name }) => name);
|
||||
expect(mcp.getInstructions()).toContain(
|
||||
"archive/package -> open_binary(path), then inspect_artifact/inventory_artifact (active target)",
|
||||
"archive/package -> open_binary(path), then inspect_artifact/inventory_artifact",
|
||||
);
|
||||
expect(
|
||||
beforeTools.find(({ name }) => name === "inventory_artifact")
|
||||
@@ -137,15 +136,17 @@ describe("target-free MCP workflow", () => {
|
||||
structured(
|
||||
await mcp.callTool({
|
||||
name: "binary_session",
|
||||
arguments: { detail: "full" },
|
||||
arguments: {},
|
||||
}),
|
||||
),
|
||||
).toMatchObject({ result: { path: await realpath(first) } });
|
||||
expect(
|
||||
text(await mcp.callTool({ name: "current_document", arguments: {} })),
|
||||
).toContain("first.hop");
|
||||
const { recordedUnknown, changesBeforeMutation } =
|
||||
await snapshotAndRecordUnknown(lifecycle, directory);
|
||||
const { recordedUnknown } = await snapshotAndRecordUnknown(
|
||||
lifecycle,
|
||||
directory,
|
||||
);
|
||||
const resolved = await mcp.callTool({
|
||||
name: "update_unknown",
|
||||
arguments: {
|
||||
@@ -170,8 +171,6 @@ describe("target-free MCP workflow", () => {
|
||||
});
|
||||
expect(resolved.isError).not.toBe(true);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(lifecycle.unknownResourceUpdates()).toBe(1);
|
||||
expect(lifecycle.resourceListChanges()).toBe(changesBeforeMutation);
|
||||
expect(
|
||||
structured(
|
||||
await mcp.callTool({
|
||||
@@ -267,21 +266,19 @@ describe("process residuals over MCP", () => {
|
||||
result: z.object({
|
||||
items: z.array(
|
||||
z.object({
|
||||
unknown: z.object({
|
||||
question: z.string(),
|
||||
domain: z.string(),
|
||||
}),
|
||||
question: z.string(),
|
||||
domain: z.string(),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
})
|
||||
.parse(structured(listedUnknowns)).result.items;
|
||||
expect(listed).toContainEqual({
|
||||
unknown: expect.objectContaining({
|
||||
expect(listed).toContainEqual(
|
||||
expect.objectContaining({
|
||||
question: "Was network behavior fully observed during capture?",
|
||||
domain: "process-network",
|
||||
}),
|
||||
});
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -301,8 +298,6 @@ const provider = (closed: string[]): AnalysisProvider => {
|
||||
const capability: CapabilityDescriptor = {
|
||||
provider: identity,
|
||||
operation: "current_document",
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: true,
|
||||
reason: null,
|
||||
pagination: "none",
|
||||
@@ -341,6 +336,8 @@ const structured = (result: CallToolResult): Record<string, unknown> => {
|
||||
typeof result.structuredContent !== "object" ||
|
||||
result.structuredContent === null
|
||||
)
|
||||
throw new Error("missing structured result");
|
||||
throw new Error(
|
||||
`missing structured result: ${JSON.stringify(result.content)}`,
|
||||
);
|
||||
return z.record(z.string(), z.unknown()).parse(result.structuredContent);
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
@@ -20,7 +20,6 @@ import type { AnalysisProvider } from "../../../src/application/AnalysisProvider
|
||||
|
||||
const SNAPSHOT_PROFILE = createAnalysisProfile(
|
||||
{ id: "fixture", name: "Fixture analysis provider", version: "1" },
|
||||
1,
|
||||
{ fixture: true },
|
||||
);
|
||||
|
||||
@@ -29,8 +28,6 @@ export interface SessionMcpHarness {
|
||||
readonly first: string;
|
||||
readonly second: string;
|
||||
readonly closed: string[];
|
||||
readonly resourceListChanges: () => number;
|
||||
readonly unknownResourceUpdates: () => number;
|
||||
}
|
||||
|
||||
export const createSessionMcpHarness = async (
|
||||
@@ -59,14 +56,6 @@ export const createSessionMcpHarness = async (
|
||||
analysisSnapshotFilePolicy: filePolicy,
|
||||
});
|
||||
const mcp = new Client({ name: "session-test", version: "1.0.0" });
|
||||
let resourceChanges = 0;
|
||||
let unknownUpdates = 0;
|
||||
mcp.setNotificationHandler("notifications/resources/list_changed", () => {
|
||||
resourceChanges += 1;
|
||||
});
|
||||
mcp.setNotificationHandler("notifications/resources/updated", (notice) => {
|
||||
if (notice.params.uri.startsWith("rea://unknown/")) unknownUpdates += 1;
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(mcp, server);
|
||||
@@ -77,8 +66,6 @@ export const createSessionMcpHarness = async (
|
||||
first,
|
||||
second,
|
||||
closed,
|
||||
resourceListChanges: () => resourceChanges,
|
||||
unknownResourceUpdates: () => unknownUpdates,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -87,34 +74,27 @@ export const snapshotAndRecordUnknown = async (
|
||||
root: string,
|
||||
): Promise<{
|
||||
recordedUnknown: { unknown_id: string; revision: number };
|
||||
changesBeforeMutation: number;
|
||||
}> => {
|
||||
const { mcp } = harness;
|
||||
const snapshotted = await mcp.callTool({
|
||||
name: "snapshot_evidence_bundle",
|
||||
name: "get_evidence_bundle",
|
||||
arguments: {},
|
||||
});
|
||||
const snapshotResult = z
|
||||
.object({ result: z.object({ bundle_uri: z.string() }) })
|
||||
.parse(structured(snapshotted)).result;
|
||||
const bundleResource = await mcp.readResource({
|
||||
uri: snapshotResult.bundle_uri,
|
||||
expect(structured(snapshotted).result).toMatchObject({
|
||||
records: expect.any(Array),
|
||||
unknowns: expect.any(Array),
|
||||
});
|
||||
const evidencePath = join(root, "evidence.json");
|
||||
structured(
|
||||
await mcp.callTool({
|
||||
name: "export_evidence_bundle",
|
||||
arguments: { path: evidencePath },
|
||||
}),
|
||||
);
|
||||
const bundle = evidenceBundleSchema.parse(
|
||||
JSON.parse(
|
||||
z.object({ text: z.string() }).parse(bundleResource.contents[0]).text,
|
||||
),
|
||||
JSON.parse(await readFile(evidencePath, "utf8")),
|
||||
);
|
||||
expect(bundle.records).toHaveLength(1);
|
||||
const evidencePath = join(root, "evidence.json");
|
||||
expect(
|
||||
structured(
|
||||
await mcp.callTool({
|
||||
name: "export_evidence_bundle",
|
||||
arguments: { path: evidencePath },
|
||||
}),
|
||||
).result,
|
||||
).toMatchObject({ path: evidencePath, records: 1 });
|
||||
expect(
|
||||
structured(
|
||||
await mcp.callTool({
|
||||
@@ -144,9 +124,6 @@ export const snapshotAndRecordUnknown = async (
|
||||
}),
|
||||
).result,
|
||||
).toEqual({ imported: 1, unknowns_added: 0, total: 2 });
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(harness.resourceListChanges()).toBe(0);
|
||||
const changesBeforeMutation = harness.resourceListChanges();
|
||||
const recordedUnknown = z
|
||||
.object({
|
||||
result: z.object({ unknown_id: z.string(), revision: z.number() }),
|
||||
@@ -170,8 +147,6 @@ export const snapshotAndRecordUnknown = async (
|
||||
),
|
||||
).result;
|
||||
expect(recordedUnknown.revision).toBe(1);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(harness.resourceListChanges()).toBe(changesBeforeMutation);
|
||||
const listedUnknowns = await mcp.callTool({
|
||||
name: "list_unknowns",
|
||||
arguments: {},
|
||||
@@ -182,7 +157,7 @@ export const snapshotAndRecordUnknown = async (
|
||||
.object({ result: z.object({ items: z.array(z.unknown()) }) })
|
||||
.parse(structured(listedUnknowns)).result.items,
|
||||
).toHaveLength(1);
|
||||
return { recordedUnknown, changesBeforeMutation };
|
||||
return { recordedUnknown };
|
||||
};
|
||||
|
||||
const structured = (result: CallToolResult): Record<string, unknown> => {
|
||||
|
||||
@@ -58,16 +58,8 @@ describe("tool registration options", () => {
|
||||
const analyzeFunction = advertised.find(
|
||||
({ name }) => name === "analyze_function",
|
||||
);
|
||||
expect(analyzeFunction?.inputSchema.properties).toMatchObject({
|
||||
include_assembly: {
|
||||
description: "Whether to include assembly in the result.",
|
||||
},
|
||||
max_instructions: {
|
||||
description: "Maximum permitted instructions for this operation.",
|
||||
},
|
||||
pseudocode_offset: {
|
||||
description: "Zero-based index of the first pseudocode to return.",
|
||||
},
|
||||
expect(analyzeFunction?.inputSchema.properties).toEqual({
|
||||
procedure: expect.objectContaining({ type: "string" }),
|
||||
});
|
||||
expect(advertised).toEqual(
|
||||
GENERATED_MCP_TOOL_CATALOG.map((tool) => ({
|
||||
|
||||
@@ -42,7 +42,7 @@ describe("tool result projection", () => {
|
||||
error: {
|
||||
code: "provider_unavailable",
|
||||
details: { failure_code: "unsupported_demo_dialog" },
|
||||
category: "execution_failure",
|
||||
category: "unavailable",
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(result)).not.toContain("expected Hopper");
|
||||
@@ -87,7 +87,7 @@ describe("tool result projection", () => {
|
||||
});
|
||||
expect(JSON.stringify(result)).not.toContain("cookie");
|
||||
});
|
||||
it("links successful evidence only when its session resource exists", () => {
|
||||
it("returns result and complete Evidence context in one call", () => {
|
||||
const evidence = createEvidence(
|
||||
undefined,
|
||||
{ id: "fixture", name: "Fixture", version: "1" },
|
||||
@@ -95,7 +95,6 @@ describe("tool result projection", () => {
|
||||
operation: "fixture",
|
||||
parameters: {},
|
||||
result: { value: "observed" },
|
||||
limitations: [],
|
||||
},
|
||||
);
|
||||
const evidenceContract: ToolContract = {
|
||||
@@ -103,22 +102,27 @@ describe("tool result projection", () => {
|
||||
outputSchema: evidenceResultOf(z.object({ value: z.string() })),
|
||||
};
|
||||
|
||||
expect(
|
||||
toCallToolResult(ok(evidence), evidenceContract).content,
|
||||
).not.toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ type: "resource_link" }),
|
||||
]),
|
||||
);
|
||||
expect(
|
||||
toCallToolResult(ok(evidence), evidenceContract, {
|
||||
evidenceResourcesAvailable: true,
|
||||
}).content,
|
||||
).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: "resource_link",
|
||||
uri: `rea://evidence/${evidence.evidence_id}`,
|
||||
}),
|
||||
);
|
||||
const result = toCallToolResult(ok(evidence), evidenceContract);
|
||||
expect(result.structuredContent).toMatchObject({
|
||||
result: { value: "observed" },
|
||||
evidence_id: evidence.evidence_id,
|
||||
evidence: {
|
||||
provider: { id: "fixture", name: "Fixture", version: "1" },
|
||||
operation: "fixture",
|
||||
predicate_type: "rea.analysis/v2",
|
||||
parameters: {},
|
||||
raw_result: null,
|
||||
confidence: "observed",
|
||||
authority: "shipped-artifact",
|
||||
environment: null,
|
||||
limitations: evidence.limitations,
|
||||
locations: [],
|
||||
evidence_links: [],
|
||||
},
|
||||
});
|
||||
expect(result.content[0]).toMatchObject({
|
||||
type: "text",
|
||||
text: expect.stringContaining('"value":"observed"'),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,7 +12,6 @@ import { analyzeJavaScriptApplication } from "../../../src/application/JavaScrip
|
||||
import { reconcileJavaScriptRuntime } from "../../../src/domain/javascriptRuntimeReconciliation.js";
|
||||
import { inspectElectronPageInputSchema } from "../../../src/domain/electronObservation.js";
|
||||
import { createWebTextArtifact } from "../../../src/domain/webContentArtifact.js";
|
||||
import { permissionAuthorityForRoot } from "../../fixtures/permissionAuthority.js";
|
||||
|
||||
const SOURCE = `const worker = new Worker("./worker.js");\nexport const observed = worker;\n`;
|
||||
const execute = promisify(execFile);
|
||||
@@ -206,14 +205,8 @@ const applicationFixture = async (): Promise<string> => {
|
||||
};
|
||||
|
||||
const analyzeFixture = async (root: string) => {
|
||||
const authority = await permissionAuthorityForRoot(
|
||||
root,
|
||||
["investigation_input"],
|
||||
["investigation_input"],
|
||||
);
|
||||
const result = await analyzeJavaScriptApplication(authority, {
|
||||
const result = await analyzeJavaScriptApplication({
|
||||
input_path: root,
|
||||
approved: true,
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
return result.value;
|
||||
@@ -256,7 +249,6 @@ const electronRuntimeEvidence = (
|
||||
"inspect_electron_page",
|
||||
input,
|
||||
{
|
||||
schema_version: 1,
|
||||
browser: {
|
||||
product: "Electron/fixture",
|
||||
protocol_version: "1.3",
|
||||
|
||||
@@ -141,7 +141,6 @@ it("renders terminal state, records shim invocations, and captures literal check
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.schema_version).toBe(4);
|
||||
expect(result.value.rendered_frames.at(-1)?.lines.join("\n")).toContain(
|
||||
"probe:codex 1.2.3",
|
||||
);
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
let bridgeSource = "";
|
||||
|
||||
beforeAll(async () => {
|
||||
bridgeSource = await readFile(
|
||||
fileURLToPath(
|
||||
new URL(
|
||||
"../../../../bridge/ghidra/ReaGhidraBridge.java",
|
||||
import.meta.url,
|
||||
),
|
||||
),
|
||||
"utf8",
|
||||
);
|
||||
});
|
||||
|
||||
describe("Ghidra bridge truthfulness", () => {
|
||||
it("owns one persistent decompiler interface for the Program lifetime", () => {
|
||||
expect(bridgeSource).toContain("private DecompInterface decompiler;");
|
||||
expect(bridgeSource.match(/new DecompInterface\(\)/gu)).toHaveLength(1);
|
||||
expect(
|
||||
bridgeSource.match(/decompiler\.openProgram\(currentProgram\)/gu),
|
||||
).toHaveLength(1);
|
||||
expect(bridgeSource).toContain("decompiler.dispose()");
|
||||
expect(bridgeSource).toContain("DECOMPILE_TIMEOUT_SECONDS = 30");
|
||||
expect(bridgeSource).toContain(
|
||||
"decompileFunction(\n function,\n DECOMPILE_TIMEOUT_SECONDS",
|
||||
);
|
||||
});
|
||||
|
||||
it("projects references and CFG from public Ghidra models", () => {
|
||||
expect(bridgeSource).toContain("getReferenceManager().getReferencesTo");
|
||||
expect(bridgeSource).toContain(
|
||||
"getReferencesFrom(instruction.getAddress())",
|
||||
);
|
||||
expect(bridgeSource).toContain(
|
||||
"new BasicBlockModel(currentProgram, false)",
|
||||
);
|
||||
expect(bridgeSource).toContain("block.getDestinations(monitor)");
|
||||
expect(bridgeSource).toContain(
|
||||
'result.addProperty("computed", type.isComputed())',
|
||||
);
|
||||
expect(bridgeSource).toContain(
|
||||
'result.addProperty("indirect", type.isIndirect())',
|
||||
);
|
||||
expect(bridgeSource).toContain(
|
||||
'result.addProperty("external", reference.isExternalReference())',
|
||||
);
|
||||
expect(bridgeSource).toContain("reference.isEntryPointReference()");
|
||||
});
|
||||
|
||||
it("keeps function classification and targetless-flow uncertainty explicit", () => {
|
||||
expect(bridgeSource).toContain("function.isThunk()");
|
||||
expect(bridgeSource).toContain("function.isExternal()");
|
||||
expect(bridgeSource).toContain('"ghidra-function-manager"');
|
||||
expect(bridgeSource).toContain(
|
||||
"Unresolved computed or indirect flows without target addresses",
|
||||
);
|
||||
expect(bridgeSource).toContain(
|
||||
"not original source or Hopper-equivalent text",
|
||||
);
|
||||
});
|
||||
|
||||
it("binds the Windows fallback to authenticated IPv4 loopback", () => {
|
||||
expect(bridgeSource).toContain(
|
||||
'descriptor.transport.equals("unix-socket")',
|
||||
);
|
||||
expect(bridgeSource).toContain(
|
||||
'descriptor.transport.equals("authenticated-loopback-tcp")',
|
||||
);
|
||||
expect(bridgeSource).toContain('InetAddress.getByName("127.0.0.1")');
|
||||
expect(bridgeSource).toContain('endpoint.addProperty("host", "127.0.0.1")');
|
||||
expect(bridgeSource).toContain("StandardCopyOption.ATOMIC_MOVE");
|
||||
});
|
||||
|
||||
it("does not admit mutation methods into the Java dispatch", () => {
|
||||
for (const method of [
|
||||
'case "set_comment"',
|
||||
'case "set_address_name"',
|
||||
'case "set_inline_comment"',
|
||||
'case "set_bookmark"',
|
||||
])
|
||||
expect(bridgeSource).not.toContain(method);
|
||||
});
|
||||
});
|
||||
@@ -169,22 +169,16 @@ describe("GhidraClient", () => {
|
||||
await expect(
|
||||
client.callTool("list_procedures", {
|
||||
document: null,
|
||||
offset: 0,
|
||||
limit: 500,
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
items: [
|
||||
{
|
||||
address: "0x1000",
|
||||
value: "fixture_main",
|
||||
procedure: { external: false, thunk: false },
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
has_more: false,
|
||||
},
|
||||
value: [
|
||||
{
|
||||
address: "0x1000",
|
||||
value: "fixture_main",
|
||||
procedure: { external: false, thunk: false },
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
@@ -348,33 +342,6 @@ describe("GhidraClient established requests", () => {
|
||||
activeController.abort();
|
||||
await active;
|
||||
});
|
||||
|
||||
it("bounds the serial per-Program request queue", async () => {
|
||||
const client = clientFor(new FixtureLauncher("hang_tools"), {
|
||||
requestTimeoutMs: 10_000,
|
||||
});
|
||||
await expect(client.start()).resolves.toMatchObject({ ok: true });
|
||||
const controller = new AbortController();
|
||||
const requests = Array.from({ length: 33 }, () =>
|
||||
client.callTool(
|
||||
"procedure_pseudo_code",
|
||||
{ document: null, procedure: "fixture_main" },
|
||||
{ signal: controller.signal },
|
||||
),
|
||||
);
|
||||
const overflow = requests[32];
|
||||
if (overflow === undefined) throw new Error("Queue probe was not created");
|
||||
|
||||
await expect(overflow).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
kind: "protocol",
|
||||
message: expect.stringContaining("32-request limit"),
|
||||
},
|
||||
});
|
||||
controller.abort();
|
||||
await Promise.all(requests.slice(0, 32));
|
||||
});
|
||||
});
|
||||
|
||||
describe("GhidraClient cleanup and diagnostics", () => {
|
||||
|
||||
@@ -1,390 +0,0 @@
|
||||
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
const bridgePath = fileURLToPath(
|
||||
new URL("../../../../bridge/hopper_bridge.py", import.meta.url),
|
||||
);
|
||||
const probePath = fileURLToPath(
|
||||
new URL("../../../fixtures/bridgeRegexProbe.py", import.meta.url),
|
||||
);
|
||||
|
||||
const errorResultSchema = z.object({
|
||||
action: z.enum(["match", "search"]),
|
||||
ok: z.literal(false),
|
||||
type: z.string(),
|
||||
diagnostic_type: z.string(),
|
||||
message: z.string(),
|
||||
});
|
||||
const matchResultSchema = z.object({
|
||||
action: z.literal("match"),
|
||||
ok: z.literal(true),
|
||||
backtracking_paths: z.number().int().positive(),
|
||||
matched: z.boolean(),
|
||||
});
|
||||
const searchResultSchema = z.object({
|
||||
action: z.literal("search"),
|
||||
ok: z.literal(true),
|
||||
result: z.object({
|
||||
items: z.array(
|
||||
z.object({
|
||||
address: z.string(),
|
||||
value: z.string(),
|
||||
value_truncated: z.boolean(),
|
||||
}),
|
||||
),
|
||||
offset: z.number().int().nonnegative(),
|
||||
limit: z.number().int().positive(),
|
||||
total: z.number().int().nonnegative(),
|
||||
next_offset: z.number().int().nonnegative().nullable(),
|
||||
has_more: z.boolean(),
|
||||
}),
|
||||
});
|
||||
const probeResultSchema = z.union([
|
||||
errorResultSchema,
|
||||
matchResultSchema,
|
||||
searchResultSchema,
|
||||
]);
|
||||
type ProbeResult = z.infer<typeof probeResultSchema>;
|
||||
|
||||
type ProbeInput =
|
||||
| {
|
||||
readonly action: "match";
|
||||
readonly pattern: string;
|
||||
readonly value: string;
|
||||
readonly case_sensitive?: boolean;
|
||||
}
|
||||
| {
|
||||
readonly action: "search";
|
||||
readonly items: readonly (readonly [string, string])[];
|
||||
readonly params: Readonly<Record<string, string | number | boolean>>;
|
||||
};
|
||||
|
||||
interface PendingProbe {
|
||||
readonly resolve: (result: ProbeResult) => void;
|
||||
readonly reject: (error: Error) => void;
|
||||
timeout: NodeJS.Timeout | undefined;
|
||||
}
|
||||
|
||||
const PROBE_TIMEOUT_MS = 3_000;
|
||||
const PROBE_BUFFER_LIMIT = 1_024 * 1_024;
|
||||
const pendingProbes: PendingProbe[] = [];
|
||||
let probeProcess: ChildProcessWithoutNullStreams | undefined;
|
||||
let probeStdout = "";
|
||||
let probeStderr = "";
|
||||
let probeFailure: Error | undefined;
|
||||
let stoppingProbe = false;
|
||||
|
||||
const failureWithStderr = (message: string): Error => {
|
||||
const stderr = probeStderr.trim();
|
||||
return new Error(stderr.length === 0 ? message : `${message}: ${stderr}`);
|
||||
};
|
||||
|
||||
const rejectPendingProbes = (error: Error): void => {
|
||||
for (const pending of pendingProbes.splice(0)) {
|
||||
if (pending.timeout !== undefined) clearTimeout(pending.timeout);
|
||||
pending.reject(error);
|
||||
}
|
||||
};
|
||||
|
||||
const failProbeProcess = (error: Error): void => {
|
||||
probeFailure ??= error;
|
||||
rejectPendingProbes(probeFailure);
|
||||
if (
|
||||
!stoppingProbe &&
|
||||
probeProcess?.exitCode === null &&
|
||||
probeProcess.signalCode === null
|
||||
)
|
||||
probeProcess.kill("SIGKILL");
|
||||
};
|
||||
|
||||
const acceptProbeLine = (line: string): void => {
|
||||
const pending = pendingProbes.shift();
|
||||
if (pending === undefined) {
|
||||
failProbeProcess(
|
||||
failureWithStderr("Python probe returned an extra result"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (pending.timeout !== undefined) clearTimeout(pending.timeout);
|
||||
try {
|
||||
const decoded: unknown = JSON.parse(line);
|
||||
pending.resolve(probeResultSchema.parse(decoded));
|
||||
} catch (cause: unknown) {
|
||||
const error =
|
||||
cause instanceof Error
|
||||
? cause
|
||||
: failureWithStderr("Python probe returned an invalid result");
|
||||
pending.reject(error);
|
||||
failProbeProcess(error);
|
||||
}
|
||||
};
|
||||
|
||||
const acceptProbeOutput = (chunk: string): void => {
|
||||
probeStdout += chunk;
|
||||
if (Buffer.byteLength(probeStdout) > PROBE_BUFFER_LIMIT) {
|
||||
failProbeProcess(failureWithStderr("Python probe output exceeded 1 MiB"));
|
||||
return;
|
||||
}
|
||||
let newline = probeStdout.indexOf("\n");
|
||||
while (newline >= 0) {
|
||||
const line = probeStdout.slice(0, newline).replace(/\r$/u, "");
|
||||
probeStdout = probeStdout.slice(newline + 1);
|
||||
acceptProbeLine(line);
|
||||
newline = probeStdout.indexOf("\n");
|
||||
}
|
||||
};
|
||||
|
||||
const startProbeProcess = async (): Promise<void> => {
|
||||
stoppingProbe = false;
|
||||
probeFailure = undefined;
|
||||
probeStdout = "";
|
||||
probeStderr = "";
|
||||
const child = spawn("python3", [probePath, bridgePath], {
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
probeProcess = child;
|
||||
child.stdout.setEncoding("utf8");
|
||||
child.stderr.setEncoding("utf8");
|
||||
child.stdout.on("data", acceptProbeOutput);
|
||||
child.stderr.on("data", (chunk: string) => {
|
||||
probeStderr += chunk;
|
||||
if (Buffer.byteLength(probeStderr) > PROBE_BUFFER_LIMIT)
|
||||
failProbeProcess(new Error("Python probe stderr exceeded 1 MiB"));
|
||||
});
|
||||
child.stdin.on("error", (error) => {
|
||||
if (!stoppingProbe) failProbeProcess(error);
|
||||
});
|
||||
child.on("error", (error) => {
|
||||
if (!stoppingProbe) failProbeProcess(error);
|
||||
});
|
||||
child.on("exit", (code, signal) => {
|
||||
if (!stoppingProbe)
|
||||
failProbeProcess(
|
||||
failureWithStderr(
|
||||
`Python probe exited before responding (code ${String(code)}, signal ${String(signal)})`,
|
||||
),
|
||||
);
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const onSpawn = (): void => {
|
||||
child.off("error", onError);
|
||||
resolve();
|
||||
};
|
||||
const onError = (error: Error): void => {
|
||||
child.off("spawn", onSpawn);
|
||||
reject(error);
|
||||
};
|
||||
child.once("spawn", onSpawn);
|
||||
child.once("error", onError);
|
||||
});
|
||||
};
|
||||
|
||||
const hasExited = (child: ChildProcessWithoutNullStreams): boolean =>
|
||||
child.exitCode !== null || child.signalCode !== null;
|
||||
|
||||
const waitForExit = (
|
||||
child: ChildProcessWithoutNullStreams,
|
||||
timeoutMs: number,
|
||||
): Promise<boolean> => {
|
||||
if (hasExited(child)) return Promise.resolve(true);
|
||||
return new Promise((resolve) => {
|
||||
const onExit = (): void => {
|
||||
clearTimeout(timeout);
|
||||
resolve(true);
|
||||
};
|
||||
const timeout = setTimeout(() => {
|
||||
child.off("exit", onExit);
|
||||
resolve(false);
|
||||
}, timeoutMs);
|
||||
child.once("exit", onExit);
|
||||
});
|
||||
};
|
||||
|
||||
const stopProbeProcess = async (): Promise<void> => {
|
||||
const child = probeProcess;
|
||||
if (child === undefined) return;
|
||||
stoppingProbe = true;
|
||||
rejectPendingProbes(new Error("Python probe stopped before responding"));
|
||||
if (!hasExited(child)) child.stdin.end();
|
||||
if (!(await waitForExit(child, 500))) child.kill("SIGTERM");
|
||||
if (!(await waitForExit(child, 500))) child.kill("SIGKILL");
|
||||
if (!(await waitForExit(child, 500)))
|
||||
throw new Error("Python probe did not stop after SIGKILL");
|
||||
probeProcess = undefined;
|
||||
};
|
||||
|
||||
const probe = (input: ProbeInput): Promise<ProbeResult> => {
|
||||
const child = probeProcess;
|
||||
if (probeFailure !== undefined) return Promise.reject(probeFailure);
|
||||
if (child === undefined || hasExited(child))
|
||||
return Promise.reject(new Error("Python probe is not running"));
|
||||
return new Promise((resolve, reject) => {
|
||||
const pending: PendingProbe = { resolve, reject, timeout: undefined };
|
||||
pending.timeout = setTimeout(() => {
|
||||
failProbeProcess(
|
||||
new Error(
|
||||
`Python probe request timed out after ${String(PROBE_TIMEOUT_MS)} ms`,
|
||||
),
|
||||
);
|
||||
}, PROBE_TIMEOUT_MS);
|
||||
pendingProbes.push(pending);
|
||||
child.stdin.write(`${JSON.stringify(input)}\n`, (error) => {
|
||||
if (error !== null && error !== undefined) failProbeProcess(error);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
beforeAll(startProbeProcess);
|
||||
beforeEach(async () => {
|
||||
if (
|
||||
probeFailure === undefined &&
|
||||
probeProcess !== undefined &&
|
||||
!hasExited(probeProcess)
|
||||
)
|
||||
return;
|
||||
await stopProbeProcess();
|
||||
await startProbeProcess();
|
||||
});
|
||||
afterAll(stopProbeProcess);
|
||||
|
||||
const invalidRequest = (action: "match" | "search", message: string) => ({
|
||||
action,
|
||||
ok: false,
|
||||
type: "ValueError",
|
||||
diagnostic_type: "invalid_request",
|
||||
message,
|
||||
});
|
||||
|
||||
describe("Hopper bridge regex matching", () => {
|
||||
it("accepts useful patterns whose static backtracking budget is bounded", async () => {
|
||||
await expect(
|
||||
probe({
|
||||
action: "match",
|
||||
pattern: String.raw`^rea_(?:main|helper)_[0-9]{1,3}$`,
|
||||
value: "REA_helper_42",
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
action: "match",
|
||||
ok: true,
|
||||
backtracking_paths: 6,
|
||||
matched: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("applies bounded regex matching through deterministic pagination", async () => {
|
||||
await expect(
|
||||
probe({
|
||||
action: "search",
|
||||
items: [
|
||||
["0x1000", "REA_main_1"],
|
||||
["0x2000", "unrelated"],
|
||||
["0x3000", "rea_helper_42"],
|
||||
],
|
||||
params: {
|
||||
pattern: String.raw`^rea_(?:main|helper)_[0-9]{1,3}$`,
|
||||
mode: "regex",
|
||||
case_sensitive: false,
|
||||
offset: 1,
|
||||
limit: 1,
|
||||
},
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
action: "search",
|
||||
ok: true,
|
||||
result: {
|
||||
items: [
|
||||
{
|
||||
address: "0x3000",
|
||||
value: "rea_helper_42",
|
||||
value_truncated: false,
|
||||
},
|
||||
],
|
||||
offset: 1,
|
||||
limit: 1,
|
||||
total: 2,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"lookaround",
|
||||
"(?=a)a",
|
||||
"Regex lookarounds and backreferences are not supported",
|
||||
],
|
||||
[
|
||||
"backreference",
|
||||
String.raw`(a)\1`,
|
||||
"Regex lookarounds and backreferences are not supported",
|
||||
],
|
||||
[
|
||||
"nested repeat",
|
||||
"(a{1,2}){1,2}",
|
||||
"Nested regex repetitions are not supported",
|
||||
],
|
||||
[
|
||||
"unbounded repeat",
|
||||
"a+",
|
||||
"Unbounded or excessive regex repetitions are not supported",
|
||||
],
|
||||
[
|
||||
"excessive repeat",
|
||||
"a{1001}",
|
||||
"Unbounded or excessive regex repetitions are not supported",
|
||||
],
|
||||
])("rejects unsupported %s constructs", async (_name, pattern, message) => {
|
||||
await expect(
|
||||
probe({ action: "match", pattern, value: "aaaa", case_sensitive: true }),
|
||||
).resolves.toEqual(invalidRequest("match", message));
|
||||
});
|
||||
|
||||
it.each(["(", "a{999999999999999999999999}"])(
|
||||
"normalizes parser failure %s through the search boundary",
|
||||
async (pattern) => {
|
||||
await expect(
|
||||
probe({
|
||||
action: "search",
|
||||
items: [],
|
||||
params: { pattern, mode: "regex", offset: 0, limit: 1 },
|
||||
}),
|
||||
).resolves.toEqual(invalidRequest("search", "Invalid regex pattern"));
|
||||
},
|
||||
);
|
||||
|
||||
it("accepts the maximum bounded repeat at the exact work budget", async () => {
|
||||
await expect(
|
||||
probe({
|
||||
action: "match",
|
||||
pattern: "a{1000}",
|
||||
value: "a".repeat(1_000),
|
||||
case_sensitive: true,
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
action: "match",
|
||||
ok: true,
|
||||
backtracking_paths: 1,
|
||||
matched: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts expensive matching just below the cumulative work limit", async () => {
|
||||
await expect(
|
||||
probe({
|
||||
action: "match",
|
||||
pattern: "(?:a|aa){1,8}b",
|
||||
value: "a".repeat(115),
|
||||
case_sensitive: true,
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
action: "match",
|
||||
ok: true,
|
||||
backtracking_paths: 510,
|
||||
matched: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,396 +0,0 @@
|
||||
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
const bridgePath = fileURLToPath(
|
||||
new URL("../../../../bridge/hopper_bridge.py", import.meta.url),
|
||||
);
|
||||
const probePath = fileURLToPath(
|
||||
new URL("../../../fixtures/bridgeRegexProbe.py", import.meta.url),
|
||||
);
|
||||
|
||||
const errorResultSchema = z.object({
|
||||
action: z.enum(["match", "search"]),
|
||||
ok: z.literal(false),
|
||||
type: z.string(),
|
||||
diagnostic_type: z.string(),
|
||||
message: z.string(),
|
||||
});
|
||||
const matchResultSchema = z.object({
|
||||
action: z.literal("match"),
|
||||
ok: z.literal(true),
|
||||
backtracking_paths: z.number().int().positive(),
|
||||
matched: z.boolean(),
|
||||
});
|
||||
const searchResultSchema = z.object({
|
||||
action: z.literal("search"),
|
||||
ok: z.literal(true),
|
||||
result: z.object({
|
||||
items: z.array(
|
||||
z.object({
|
||||
address: z.string(),
|
||||
value: z.string(),
|
||||
value_truncated: z.boolean(),
|
||||
}),
|
||||
),
|
||||
offset: z.number().int().nonnegative(),
|
||||
limit: z.number().int().positive(),
|
||||
total: z.number().int().nonnegative(),
|
||||
next_offset: z.number().int().nonnegative().nullable(),
|
||||
has_more: z.boolean(),
|
||||
}),
|
||||
});
|
||||
const probeResultSchema = z.union([
|
||||
errorResultSchema,
|
||||
matchResultSchema,
|
||||
searchResultSchema,
|
||||
]);
|
||||
type ProbeResult = z.infer<typeof probeResultSchema>;
|
||||
|
||||
type ProbeInput =
|
||||
| {
|
||||
readonly action: "match";
|
||||
readonly pattern: string;
|
||||
readonly value: string;
|
||||
readonly case_sensitive?: boolean;
|
||||
}
|
||||
| {
|
||||
readonly action: "search";
|
||||
readonly items: readonly (readonly [string, string])[];
|
||||
readonly params: Readonly<Record<string, string | number | boolean>>;
|
||||
};
|
||||
|
||||
interface PendingProbe {
|
||||
readonly resolve: (result: ProbeResult) => void;
|
||||
readonly reject: (error: Error) => void;
|
||||
timeout: NodeJS.Timeout | undefined;
|
||||
}
|
||||
|
||||
const PROBE_TIMEOUT_MS = 3_000;
|
||||
const PROBE_BUFFER_LIMIT = 1_024 * 1_024;
|
||||
const pendingProbes: PendingProbe[] = [];
|
||||
let probeProcess: ChildProcessWithoutNullStreams | undefined;
|
||||
let probeStdout = "";
|
||||
let probeStderr = "";
|
||||
let probeFailure: Error | undefined;
|
||||
let stoppingProbe = false;
|
||||
|
||||
const failureWithStderr = (message: string): Error => {
|
||||
const stderr = probeStderr.trim();
|
||||
return new Error(stderr.length === 0 ? message : `${message}: ${stderr}`);
|
||||
};
|
||||
|
||||
const rejectPendingProbes = (error: Error): void => {
|
||||
for (const pending of pendingProbes.splice(0)) {
|
||||
if (pending.timeout !== undefined) clearTimeout(pending.timeout);
|
||||
pending.reject(error);
|
||||
}
|
||||
};
|
||||
|
||||
const failProbeProcess = (error: Error): void => {
|
||||
probeFailure ??= error;
|
||||
rejectPendingProbes(probeFailure);
|
||||
if (
|
||||
!stoppingProbe &&
|
||||
probeProcess?.exitCode === null &&
|
||||
probeProcess.signalCode === null
|
||||
)
|
||||
probeProcess.kill("SIGKILL");
|
||||
};
|
||||
|
||||
const acceptProbeLine = (line: string): void => {
|
||||
const pending = pendingProbes.shift();
|
||||
if (pending === undefined) {
|
||||
failProbeProcess(
|
||||
failureWithStderr("Python probe returned an extra result"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (pending.timeout !== undefined) clearTimeout(pending.timeout);
|
||||
try {
|
||||
const decoded: unknown = JSON.parse(line);
|
||||
pending.resolve(probeResultSchema.parse(decoded));
|
||||
} catch (cause: unknown) {
|
||||
const error =
|
||||
cause instanceof Error
|
||||
? cause
|
||||
: failureWithStderr("Python probe returned an invalid result");
|
||||
pending.reject(error);
|
||||
failProbeProcess(error);
|
||||
}
|
||||
};
|
||||
|
||||
const acceptProbeOutput = (chunk: string): void => {
|
||||
probeStdout += chunk;
|
||||
if (Buffer.byteLength(probeStdout) > PROBE_BUFFER_LIMIT) {
|
||||
failProbeProcess(failureWithStderr("Python probe output exceeded 1 MiB"));
|
||||
return;
|
||||
}
|
||||
let newline = probeStdout.indexOf("\n");
|
||||
while (newline >= 0) {
|
||||
const line = probeStdout.slice(0, newline).replace(/\r$/u, "");
|
||||
probeStdout = probeStdout.slice(newline + 1);
|
||||
acceptProbeLine(line);
|
||||
newline = probeStdout.indexOf("\n");
|
||||
}
|
||||
};
|
||||
|
||||
const startProbeProcess = async (): Promise<void> => {
|
||||
stoppingProbe = false;
|
||||
probeFailure = undefined;
|
||||
probeStdout = "";
|
||||
probeStderr = "";
|
||||
const child = spawn("python3", [probePath, bridgePath], {
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
probeProcess = child;
|
||||
child.stdout.setEncoding("utf8");
|
||||
child.stderr.setEncoding("utf8");
|
||||
child.stdout.on("data", acceptProbeOutput);
|
||||
child.stderr.on("data", (chunk: string) => {
|
||||
probeStderr += chunk;
|
||||
if (Buffer.byteLength(probeStderr) > PROBE_BUFFER_LIMIT)
|
||||
failProbeProcess(new Error("Python probe stderr exceeded 1 MiB"));
|
||||
});
|
||||
child.stdin.on("error", (error) => {
|
||||
if (!stoppingProbe) failProbeProcess(error);
|
||||
});
|
||||
child.on("error", (error) => {
|
||||
if (!stoppingProbe) failProbeProcess(error);
|
||||
});
|
||||
child.on("exit", (code, signal) => {
|
||||
if (!stoppingProbe)
|
||||
failProbeProcess(
|
||||
failureWithStderr(
|
||||
`Python probe exited before responding (code ${String(code)}, signal ${String(signal)})`,
|
||||
),
|
||||
);
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const onSpawn = (): void => {
|
||||
child.off("error", onError);
|
||||
resolve();
|
||||
};
|
||||
const onError = (error: Error): void => {
|
||||
child.off("spawn", onSpawn);
|
||||
reject(error);
|
||||
};
|
||||
child.once("spawn", onSpawn);
|
||||
child.once("error", onError);
|
||||
});
|
||||
};
|
||||
|
||||
const hasExited = (child: ChildProcessWithoutNullStreams): boolean =>
|
||||
child.exitCode !== null || child.signalCode !== null;
|
||||
|
||||
const waitForExit = (
|
||||
child: ChildProcessWithoutNullStreams,
|
||||
timeoutMs: number,
|
||||
): Promise<boolean> => {
|
||||
if (hasExited(child)) return Promise.resolve(true);
|
||||
return new Promise((resolve) => {
|
||||
const onExit = (): void => {
|
||||
clearTimeout(timeout);
|
||||
resolve(true);
|
||||
};
|
||||
const timeout = setTimeout(() => {
|
||||
child.off("exit", onExit);
|
||||
resolve(false);
|
||||
}, timeoutMs);
|
||||
child.once("exit", onExit);
|
||||
});
|
||||
};
|
||||
|
||||
const stopProbeProcess = async (): Promise<void> => {
|
||||
const child = probeProcess;
|
||||
if (child === undefined) return;
|
||||
stoppingProbe = true;
|
||||
rejectPendingProbes(new Error("Python probe stopped before responding"));
|
||||
if (!hasExited(child)) child.stdin.end();
|
||||
if (!(await waitForExit(child, 500))) child.kill("SIGTERM");
|
||||
if (!(await waitForExit(child, 500))) child.kill("SIGKILL");
|
||||
if (!(await waitForExit(child, 500)))
|
||||
throw new Error("Python probe did not stop after SIGKILL");
|
||||
probeProcess = undefined;
|
||||
};
|
||||
|
||||
const probe = (input: ProbeInput): Promise<ProbeResult> => {
|
||||
const child = probeProcess;
|
||||
if (probeFailure !== undefined) return Promise.reject(probeFailure);
|
||||
if (child === undefined || hasExited(child))
|
||||
return Promise.reject(new Error("Python probe is not running"));
|
||||
return new Promise((resolve, reject) => {
|
||||
const pending: PendingProbe = { resolve, reject, timeout: undefined };
|
||||
pending.timeout = setTimeout(() => {
|
||||
failProbeProcess(
|
||||
new Error(
|
||||
`Python probe request timed out after ${String(PROBE_TIMEOUT_MS)} ms`,
|
||||
),
|
||||
);
|
||||
}, PROBE_TIMEOUT_MS);
|
||||
pendingProbes.push(pending);
|
||||
child.stdin.write(`${JSON.stringify(input)}\n`, (error) => {
|
||||
if (error !== null && error !== undefined) failProbeProcess(error);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
beforeAll(startProbeProcess);
|
||||
beforeEach(async () => {
|
||||
if (
|
||||
probeFailure === undefined &&
|
||||
probeProcess !== undefined &&
|
||||
!hasExited(probeProcess)
|
||||
)
|
||||
return;
|
||||
await stopProbeProcess();
|
||||
await startProbeProcess();
|
||||
});
|
||||
afterAll(stopProbeProcess);
|
||||
|
||||
const invalidRequest = (action: "match" | "search", message: string) => ({
|
||||
action,
|
||||
ok: false,
|
||||
type: "ValueError",
|
||||
diagnostic_type: "invalid_request",
|
||||
message,
|
||||
});
|
||||
|
||||
describe("Hopper bridge regex work limits", () => {
|
||||
it("rejects ambiguous bounded repetition before Python regex execution", async () => {
|
||||
await expect(
|
||||
probe({
|
||||
action: "match",
|
||||
pattern: "(a|aa){1,35}b",
|
||||
value: "a".repeat(35),
|
||||
case_sensitive: true,
|
||||
}),
|
||||
).resolves.toEqual(
|
||||
invalidRequest(
|
||||
"match",
|
||||
"Regex exceeds the 10000-path backtracking budget",
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects excessive combinations across adjacent optional atoms", async () => {
|
||||
await expect(
|
||||
probe({
|
||||
action: "match",
|
||||
pattern: `${"a?".repeat(14)}b`,
|
||||
value: "a".repeat(14),
|
||||
case_sensitive: true,
|
||||
}),
|
||||
).resolves.toEqual(
|
||||
invalidRequest(
|
||||
"match",
|
||||
"Regex exceeds the 10000-path backtracking budget",
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it("bounds cumulative work before evaluating a costly candidate", async () => {
|
||||
await expect(
|
||||
probe({
|
||||
action: "match",
|
||||
pattern: "(?:a|aa){1,12}b",
|
||||
value: "a".repeat(4_096),
|
||||
case_sensitive: true,
|
||||
}),
|
||||
).resolves.toEqual(
|
||||
invalidRequest(
|
||||
"match",
|
||||
"Regex search exceeds the 1000000-unit work budget",
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it("applies the regex work budget across the full inventory", async () => {
|
||||
await expect(
|
||||
probe({
|
||||
action: "search",
|
||||
items: [
|
||||
["0x1000", "a".repeat(60)],
|
||||
["0x2000", "a".repeat(60)],
|
||||
],
|
||||
params: {
|
||||
pattern: "(?:a|aa){1,8}b",
|
||||
mode: "regex",
|
||||
case_sensitive: true,
|
||||
offset: 0,
|
||||
limit: 1,
|
||||
},
|
||||
}),
|
||||
).resolves.toEqual(
|
||||
invalidRequest(
|
||||
"search",
|
||||
"Regex search exceeds the 1000000-unit work budget",
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects oversized regex candidates instead of matching a prefix", async () => {
|
||||
await expect(
|
||||
probe({
|
||||
action: "match",
|
||||
pattern: "needle",
|
||||
value: `${"x".repeat(4_096)}needle`,
|
||||
}),
|
||||
).resolves.toEqual(
|
||||
invalidRequest(
|
||||
"match",
|
||||
"Regex candidate exceeds the 4096-character safety limit",
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts a regex candidate at the exact character limit", async () => {
|
||||
await expect(
|
||||
probe({
|
||||
action: "match",
|
||||
pattern: "z$",
|
||||
value: `${"a".repeat(4_095)}z`,
|
||||
case_sensitive: true,
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
action: "match",
|
||||
ok: true,
|
||||
backtracking_paths: 1,
|
||||
matched: true,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
[256, true],
|
||||
[257, false],
|
||||
])("enforces the %i-character pattern boundary", async (length, accepted) => {
|
||||
const pattern = "a".repeat(length);
|
||||
const result = await probe({
|
||||
action: "search",
|
||||
items: [["0x1000", pattern]],
|
||||
params: {
|
||||
pattern,
|
||||
mode: "regex",
|
||||
case_sensitive: true,
|
||||
offset: 0,
|
||||
limit: 1,
|
||||
},
|
||||
});
|
||||
if (accepted) {
|
||||
expect(result).toMatchObject({
|
||||
action: "search",
|
||||
ok: true,
|
||||
result: { total: 1 },
|
||||
});
|
||||
return;
|
||||
}
|
||||
expect(result).toEqual(
|
||||
invalidRequest(
|
||||
"search",
|
||||
"pattern must contain between 1 and 256 characters",
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
+48
-66
@@ -8,59 +8,22 @@ const bridgePath = fileURLToPath(
|
||||
new URL("../../../../bridge/hopper_bridge.py", import.meta.url),
|
||||
);
|
||||
const probePath = fileURLToPath(
|
||||
new URL("../../../fixtures/bridgeRegexProbe.py", import.meta.url),
|
||||
new URL("../../../fixtures/bridgeSearchProbe.py", import.meta.url),
|
||||
);
|
||||
|
||||
const errorResultSchema = z.object({
|
||||
action: z.enum(["match", "search"]),
|
||||
ok: z.literal(false),
|
||||
type: z.string(),
|
||||
diagnostic_type: z.string(),
|
||||
message: z.string(),
|
||||
});
|
||||
const matchResultSchema = z.object({
|
||||
action: z.literal("match"),
|
||||
ok: z.literal(true),
|
||||
backtracking_paths: z.number().int().positive(),
|
||||
matched: z.boolean(),
|
||||
});
|
||||
const searchResultSchema = z.object({
|
||||
action: z.literal("search"),
|
||||
ok: z.literal(true),
|
||||
result: z.object({
|
||||
items: z.array(
|
||||
z.object({
|
||||
address: z.string(),
|
||||
value: z.string(),
|
||||
value_truncated: z.boolean(),
|
||||
}),
|
||||
),
|
||||
offset: z.number().int().nonnegative(),
|
||||
limit: z.number().int().positive(),
|
||||
total: z.number().int().nonnegative(),
|
||||
next_offset: z.number().int().nonnegative().nullable(),
|
||||
has_more: z.boolean(),
|
||||
}),
|
||||
result: z.array(z.object({ address: z.string(), value: z.string() })),
|
||||
});
|
||||
const probeResultSchema = z.union([
|
||||
errorResultSchema,
|
||||
matchResultSchema,
|
||||
searchResultSchema,
|
||||
]);
|
||||
const probeResultSchema = searchResultSchema;
|
||||
type ProbeResult = z.infer<typeof probeResultSchema>;
|
||||
|
||||
type ProbeInput =
|
||||
| {
|
||||
readonly action: "match";
|
||||
readonly pattern: string;
|
||||
readonly value: string;
|
||||
readonly case_sensitive?: boolean;
|
||||
}
|
||||
| {
|
||||
readonly action: "search";
|
||||
readonly items: readonly (readonly [string, string])[];
|
||||
readonly params: Readonly<Record<string, string | number | boolean>>;
|
||||
};
|
||||
type ProbeInput = {
|
||||
readonly action: "search";
|
||||
readonly items: readonly (readonly [string, string])[];
|
||||
readonly params: Readonly<Record<string, string | number | boolean>>;
|
||||
};
|
||||
|
||||
interface PendingProbe {
|
||||
readonly resolve: (result: ProbeResult) => void;
|
||||
@@ -250,29 +213,48 @@ beforeEach(async () => {
|
||||
});
|
||||
afterAll(stopProbeProcess);
|
||||
|
||||
describe("Hopper bridge literal bounds", () => {
|
||||
it("keeps literal matching exhaustive while bounding returned text", async () => {
|
||||
const result = await probe({
|
||||
action: "search",
|
||||
items: [["0x1000", `${"x".repeat(4_096)}needle`]],
|
||||
params: {
|
||||
pattern: "needle",
|
||||
mode: "literal",
|
||||
case_sensitive: true,
|
||||
offset: 0,
|
||||
limit: 1,
|
||||
},
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
describe("Hopper bridge search", () => {
|
||||
it("returns matching literal values in deterministic order", async () => {
|
||||
await expect(
|
||||
probe({
|
||||
action: "search",
|
||||
items: [
|
||||
["0x1000", "REA_main_1"],
|
||||
["0x2000", "unrelated"],
|
||||
["0x3000", "rea_helper_42"],
|
||||
],
|
||||
params: {
|
||||
pattern: "REA",
|
||||
mode: "literal",
|
||||
case_sensitive: false,
|
||||
},
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
action: "search",
|
||||
ok: true,
|
||||
result: {
|
||||
total: 1,
|
||||
has_more: false,
|
||||
items: [{ address: "0x1000", value_truncated: true }],
|
||||
},
|
||||
result: [
|
||||
{ address: "0x1000", value: "REA_main_1" },
|
||||
{ address: "0x3000", value: "rea_helper_42" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("returns the complete value for a long literal match", async () => {
|
||||
const value = `${"x".repeat(4_096)}needle`;
|
||||
await expect(
|
||||
probe({
|
||||
action: "search",
|
||||
items: [["0x1000", value]],
|
||||
params: {
|
||||
pattern: "needle",
|
||||
mode: "literal",
|
||||
case_sensitive: true,
|
||||
},
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
action: "search",
|
||||
ok: true,
|
||||
result: [{ address: "0x1000", value }],
|
||||
});
|
||||
if (result.action === "search" && result.ok)
|
||||
expect(result.result.items[0]?.value).toHaveLength(4_096);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { HopperApplicationLauncher } from "../../../../src/hopper/BridgeLauncher.js";
|
||||
|
||||
describe("Hopper target leases in the launcher", () => {
|
||||
it("reports an active target owner without launching another document", async () => {
|
||||
let leaseChecks = 0;
|
||||
const launcher = new HopperApplicationLauncher(
|
||||
{
|
||||
launcherPath:
|
||||
"/Applications/Hopper Disassembler.app/Contents/MacOS/hopper",
|
||||
targetPath: "/target",
|
||||
targetKind: "executable",
|
||||
loaderArgs: [],
|
||||
bridgeScriptPath: "/rea/hopper_bridge.py",
|
||||
launchMode: "native",
|
||||
},
|
||||
{
|
||||
platform: "darwin",
|
||||
acquireTargetLease: async () => {
|
||||
leaseChecks += 1;
|
||||
return {
|
||||
acquired: false,
|
||||
owner: { runId: "owning-session", processId: 17 },
|
||||
};
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const result = await launcher.launch({
|
||||
directory: "/tmp/rea-launch-test",
|
||||
socketPath: "/tmp/rea-launch-test/bridge.sock",
|
||||
token: "token",
|
||||
runId: "new-session",
|
||||
});
|
||||
|
||||
expect(leaseChecks).toBe(1);
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "HopperStartError",
|
||||
ownerRunId: "owning-session",
|
||||
userMessage: expect.stringContaining("owning-session"),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("releases a target lease when bridge setup fails", async () => {
|
||||
let releases = 0;
|
||||
const launcher = new HopperApplicationLauncher(
|
||||
{
|
||||
launcherPath: "/unused/hopper",
|
||||
targetPath: "/target",
|
||||
targetKind: "executable",
|
||||
loaderArgs: [],
|
||||
bridgeScriptPath: "/rea/hopper_bridge.py",
|
||||
launchMode: "native",
|
||||
},
|
||||
{
|
||||
platform: "darwin",
|
||||
acquireTargetLease: async () => ({
|
||||
acquired: true,
|
||||
lease: { release: async () => void (releases += 1) },
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
const result = await launcher.launch({
|
||||
directory: "/missing/rea-launch-test",
|
||||
socketPath: "/missing/rea-launch-test/bridge.sock",
|
||||
token: "token",
|
||||
runId: "failed-session",
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
expect(releases).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -1,140 +0,0 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const bridgeSource = await readFile(
|
||||
new URL("../../../../bridge/hopper_bridge.py", import.meta.url),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
describe("Hopper bridge truthfulness", () => {
|
||||
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", () => {
|
||||
expect(bridgeSource).toContain('"writable": None');
|
||||
expect(bridgeSource).toContain('"executable": None');
|
||||
expect(bridgeSource).toContain('"readable": None');
|
||||
expect(bridgeSource).toContain("permission_limitation = _unavailable(");
|
||||
expect(bridgeSource).toContain('"permissions": permission_limitation');
|
||||
expect(bridgeSource).toContain('"provenance": "hopper-public-python-api"');
|
||||
expect(bridgeSource).not.toContain('"writable": False');
|
||||
expect(bridgeSource).not.toContain('"executable": False');
|
||||
});
|
||||
|
||||
it("uses Hopper containment and raw-reference APIs without inferring kinds", () => {
|
||||
expect(bridgeSource).toContain("segment.getProcedureAtAddress(address)");
|
||||
expect(bridgeSource).toContain("segment.getReferencesFromAddress(address)");
|
||||
expect(bridgeSource).toContain("segment.getReferencesOfAddress(address)");
|
||||
expect(bridgeSource).toContain(
|
||||
"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", {})');
|
||||
});
|
||||
|
||||
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)');
|
||||
expect(bridgeSource).not.toContain(
|
||||
"_json_safe(procedure.getLocalVariableList())",
|
||||
);
|
||||
});
|
||||
|
||||
it("stops background analysis and closes the session-owned document", () => {
|
||||
expect(bridgeSource).toContain("def _session_document():");
|
||||
expect(bridgeSource).toContain("os.path.realpath(REA_TARGET_PATH)");
|
||||
expect(bridgeSource).toContain("document.getExecutableFilePath()");
|
||||
expect(bridgeSource).toContain("document.getDatabaseFilePath()");
|
||||
expect(bridgeSource).toContain("document.backgroundProcessActive()");
|
||||
expect(bridgeSource).toContain("document.requestBackgroundProcessStop()");
|
||||
expect(bridgeSource).toContain(
|
||||
'if method == "shutdown" and REA_OWNS_PROCESS_LIFETIME:',
|
||||
);
|
||||
expect(bridgeSource).toContain('"cleanup_required": True');
|
||||
expect(bridgeSource).toContain(
|
||||
'method in ("shutdown", "shutdown_document")',
|
||||
);
|
||||
expect(bridgeSource).toContain("document.waitForBackgroundProcessToEnd()");
|
||||
expect(bridgeSource).toContain("document.closeDocument()");
|
||||
expect(bridgeSource).toContain(
|
||||
"document_closed = _session_document() is None",
|
||||
);
|
||||
});
|
||||
|
||||
it("invalidates cached search inventories in both rename paths", () => {
|
||||
const singleRenameStart = bridgeSource.indexOf(
|
||||
'if method == "set_address_name":',
|
||||
);
|
||||
const bulkRenameStart = bridgeSource.indexOf(
|
||||
'if method == "set_addresses_names":',
|
||||
singleRenameStart,
|
||||
);
|
||||
const nextMethodStart = bridgeSource.indexOf(
|
||||
'if method in ("set_comment", "set_inline_comment"):',
|
||||
bulkRenameStart,
|
||||
);
|
||||
expect(singleRenameStart).toBeGreaterThan(-1);
|
||||
expect(bulkRenameStart).toBeGreaterThan(singleRenameStart);
|
||||
expect(nextMethodStart).toBeGreaterThan(bulkRenameStart);
|
||||
expect(bridgeSource.slice(singleRenameStart, bulkRenameStart)).toContain(
|
||||
"_invalidate_search_inventory(document)",
|
||||
);
|
||||
expect(bridgeSource.slice(bulkRenameStart, nextMethodStart)).toContain(
|
||||
"_invalidate_search_inventory(document)",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns deterministic addresses for direct procedure relationships", () => {
|
||||
expect(bridgeSource).toContain(
|
||||
"_hex(item.getEntryPoint()) for item in procedure.getAllCallerProcedures()",
|
||||
);
|
||||
expect(bridgeSource).toContain(
|
||||
"_hex(item.getEntryPoint()) for item in procedure.getAllCalleeProcedures()",
|
||||
);
|
||||
expect(bridgeSource).not.toContain(
|
||||
"_procedure_name(item) for item in procedure.getAllCallerProcedures()",
|
||||
);
|
||||
expect(bridgeSource).not.toContain(
|
||||
"_procedure_name(item) for item in procedure.getAllCalleeProcedures()",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -21,7 +21,13 @@ const probeResultSchema = z.strictObject({
|
||||
}),
|
||||
current_document: z.literal("fixture"),
|
||||
current_address: z.literal("0x401000"),
|
||||
session_document: z.literal("fixture"),
|
||||
session_document_reused: z.literal(true),
|
||||
shared_document_shutdown: z.strictObject({
|
||||
shutdown: z.literal(true),
|
||||
analysis_stopped: z.literal(false),
|
||||
document_closed: z.literal(false),
|
||||
document_retained: z.literal(true),
|
||||
}),
|
||||
analysis_guard: z.strictObject({
|
||||
type: z.literal("CapabilityUnavailableError"),
|
||||
diagnostic_type: z.literal("capability_unavailable"),
|
||||
|
||||
@@ -153,7 +153,17 @@ describe("HopperClient protocol", () => {
|
||||
const client = await startClient();
|
||||
const result = await client.callTool(method);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error._tag).toBe(expectedTag);
|
||||
if (!result.ok) {
|
||||
expect(result.error._tag).toBe(expectedTag);
|
||||
if (result.error._tag === "HopperRemoteError")
|
||||
expect(result.error).toMatchObject({ operation: method, requestId: 2 });
|
||||
if (result.error._tag === "HopperTimeoutError")
|
||||
expect(result.error).toMatchObject({
|
||||
operation: method,
|
||||
requestId: 2,
|
||||
providerState: "busy",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves a sanitized bridge exception diagnostic", async () => {
|
||||
|
||||
@@ -237,9 +237,7 @@ describe("HopperClient startup failures", () => {
|
||||
if (result.ok) return;
|
||||
|
||||
const projected = projectAnalysisError(result.error);
|
||||
expect(projected.message).toContain(
|
||||
"rea doctor --provider hopper --detail full --json",
|
||||
);
|
||||
expect(projected.message).toContain("rea doctor --provider hopper --json");
|
||||
expect(projected.message).toContain("UI or license prompt");
|
||||
expect(projected.message).toContain("close stale Hopper sessions");
|
||||
expect(projected.details).toMatchObject({
|
||||
|
||||
@@ -16,9 +16,7 @@ describe("managed direct-analysis path boundary", () => {
|
||||
await writeFile(path, buildManagedPeFixture());
|
||||
|
||||
const evidence = parseEvidence(
|
||||
await runProviderAnalysis(path, "inspect_managed_artifact", {
|
||||
reference_limit: 1,
|
||||
}),
|
||||
await runProviderAnalysis(path, "inspect_managed_artifact", {}),
|
||||
);
|
||||
expect(evidence).toMatchObject({
|
||||
operation: "inspect_managed_artifact",
|
||||
@@ -26,7 +24,7 @@ describe("managed direct-analysis path boundary", () => {
|
||||
subject: { local_path: path, format: "pe" },
|
||||
normalized_result: {
|
||||
classification: { status: "managed", runtime_family: "modern-dotnet" },
|
||||
references: { limit: 1 },
|
||||
references: [expect.objectContaining({ name: "System.Runtime" })],
|
||||
},
|
||||
});
|
||||
|
||||
@@ -39,7 +37,7 @@ describe("managed direct-analysis path boundary", () => {
|
||||
subject: { local_path: path, format: "pe" },
|
||||
normalized_result: {
|
||||
identity_scope: { token_identity: "build-local" },
|
||||
methods: { total: 1 },
|
||||
methods: [expect.objectContaining({ token: expect.any(String) })],
|
||||
},
|
||||
});
|
||||
|
||||
@@ -52,7 +50,7 @@ describe("managed direct-analysis path boundary", () => {
|
||||
subject: { local_path: path, format: "pe" },
|
||||
normalized_result: {
|
||||
identity_scope: { token_identity: "build-local" },
|
||||
pinvoke_imports: { total: 0 },
|
||||
pinvoke_imports: [],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,10 +7,7 @@ import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js
|
||||
|
||||
import { compareManagedMemberPaths } from "../../../../src/application/ManagedMemberComparisonService.js";
|
||||
import { managedMemberComparisonResultSchema } from "../../../../src/domain/managedMemberComparison.js";
|
||||
import {
|
||||
buildManagedPeFixture,
|
||||
MANAGED_MEMBER_PATH_FIXTURE_LIMITS,
|
||||
} from "../../../../src/dotnet/ManagedPe.fixture.js";
|
||||
import { buildManagedPeFixture } from "../../../../src/dotnet/ManagedPe.fixture.js";
|
||||
|
||||
describe("managed member comparison path workflow", () => {
|
||||
it("compares two local paths and returns derived Evidence", async () => {
|
||||
@@ -26,12 +23,6 @@ describe("managed member comparison path workflow", () => {
|
||||
const result = await compareManagedMemberPaths({
|
||||
leftPath,
|
||||
rightPath,
|
||||
memberLimits: MANAGED_MEMBER_PATH_FIXTURE_LIMITS,
|
||||
comparisonLimits: {
|
||||
max_method_matches: 100,
|
||||
max_field_matches: 100,
|
||||
max_candidates: 10,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
|
||||
@@ -41,9 +41,9 @@ describe("managed static provider path boundary", () => {
|
||||
if (!members.ok) return;
|
||||
expect(asManagedMemberResult(members.value)).toMatchObject({
|
||||
artifact: { path, sha256: parsed.value.sha256, format: "pe" },
|
||||
methods: { total: 1 },
|
||||
call_edges: { total: 1 },
|
||||
field_accesses: { total: 1 },
|
||||
methods: [expect.objectContaining({ token: "0x06000001" })],
|
||||
call_edges: [expect.objectContaining({ target_name: ".ctor" })],
|
||||
field_accesses: [expect.objectContaining({ field_name: "counter" })],
|
||||
});
|
||||
|
||||
const boundaries = await client.execute(
|
||||
@@ -54,9 +54,9 @@ describe("managed static provider path boundary", () => {
|
||||
if (!boundaries.ok) return;
|
||||
expect(asManagedNativeBoundaryResult(boundaries.value)).toMatchObject({
|
||||
artifact: { path, sha256: parsed.value.sha256, format: "pe" },
|
||||
module_refs: { total: 0 },
|
||||
pinvoke_imports: { total: 0 },
|
||||
native_implementations: { total: 0 },
|
||||
module_refs: [],
|
||||
pinvoke_imports: [],
|
||||
native_implementations: [],
|
||||
});
|
||||
|
||||
const cancelled = new AbortController();
|
||||
|
||||
@@ -9,10 +9,7 @@ import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js
|
||||
|
||||
import { runProviderAnalysis } from "../../../../src/application/DirectAnalysis.js";
|
||||
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
|
||||
import {
|
||||
artifactInspectionInputSchema,
|
||||
artifactInventoryInputSchema,
|
||||
} from "../../../../src/contracts/artifactToolContracts.js";
|
||||
import { artifactInspectionInputSchema } from "../../../../src/contracts/artifactToolContracts.js";
|
||||
import { artifactInventoryResultSchema } from "../../../../src/domain/artifactGraph.js";
|
||||
import { artifactInspectionResultSchema } from "../../../../src/domain/artifactInspection.js";
|
||||
import type { BinaryTarget } from "../../../../src/domain/binaryTarget.js";
|
||||
@@ -20,7 +17,7 @@ import { parseBinaryTarget } from "../../../../src/application/BinaryTargetResol
|
||||
import { parseEvidence } from "../../../../src/domain/evidence.js";
|
||||
|
||||
describe("artifact archive inventory", () => {
|
||||
it("streams ZIP and official ASAR inventories within shared limits", async () => {
|
||||
it("returns complete ZIP and official ASAR inventories inline", async () => {
|
||||
const root = await createTestTempDirectory("rea-containers-");
|
||||
const zipPath = join(root, "fixture.apk");
|
||||
const zipWriter = new ZipWriter(new Uint8ArrayWriter());
|
||||
@@ -44,10 +41,7 @@ describe("artifact archive inventory", () => {
|
||||
subject: { format: "apk" },
|
||||
});
|
||||
const inspectionEvidence = parseEvidence(
|
||||
await runProviderAnalysis(zipPath, "inspect_artifact", {
|
||||
max_observations: 2,
|
||||
max_relationships: 1,
|
||||
}),
|
||||
await runProviderAnalysis(zipPath, "inspect_artifact", {}),
|
||||
);
|
||||
const inspection = artifactInspectionResultSchema.parse(
|
||||
inspectionEvidence.normalized_result,
|
||||
@@ -60,7 +54,7 @@ describe("artifact archive inventory", () => {
|
||||
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
|
||||
},
|
||||
],
|
||||
coverage: { status: "truncated", substeps_completed: 1 },
|
||||
coverage: { status: "complete-within-substeps", substeps_completed: 1 },
|
||||
});
|
||||
expect(inspectionEvidence.evidence_links).toEqual(
|
||||
inspection.evidence_links,
|
||||
@@ -115,7 +109,7 @@ describe("artifact archive inventory", () => {
|
||||
);
|
||||
const corrupted = await new ArtifactProvider()
|
||||
.createClient(target(unpackedPath, "asar"))
|
||||
.execute("inventory_artifact", artifactInventoryInputSchema.parse({}));
|
||||
.execute("inventory_artifact", {});
|
||||
expect(corrupted).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
@@ -137,14 +131,9 @@ describe("artifact archive inventory", () => {
|
||||
});
|
||||
});
|
||||
const inventory = async (targetValue: BinaryTarget) => {
|
||||
const result = await new ArtifactProvider().createClient(targetValue).execute(
|
||||
"inventory_artifact",
|
||||
artifactInventoryInputSchema.parse({
|
||||
node_limit: 500,
|
||||
occurrence_limit: 500,
|
||||
edge_limit: 500,
|
||||
}),
|
||||
);
|
||||
const result = await new ArtifactProvider()
|
||||
.createClient(targetValue)
|
||||
.execute("inventory_artifact", {});
|
||||
if (!result.ok) throw result.error;
|
||||
return artifactInventoryResultSchema.parse(result.value.result);
|
||||
};
|
||||
|
||||
@@ -12,10 +12,8 @@ import {
|
||||
normalizeArtifactPath,
|
||||
} from "../../../../src/artifacts/ArtifactPaths.js";
|
||||
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
|
||||
import {
|
||||
artifactExtractionInputSchema,
|
||||
artifactInventoryInputSchema,
|
||||
} from "../../../../src/contracts/artifactToolContracts.js";
|
||||
import { ArtifactReaderFailure } from "../../../../src/artifacts/ArtifactReader.js";
|
||||
import { artifactExtractionInputSchema } from "../../../../src/contracts/artifactToolContracts.js";
|
||||
import { artifactInventoryResultSchema } from "../../../../src/domain/artifactGraph.js";
|
||||
import type { BinaryTarget } from "../../../../src/domain/binaryTarget.js";
|
||||
import { parseBinaryTarget } from "../../../../src/application/BinaryTargetResolver.js";
|
||||
@@ -74,11 +72,7 @@ describe("artifact archive safety", () => {
|
||||
);
|
||||
expect(
|
||||
parseEvidence(
|
||||
await runProviderAnalysis(path, "inventory_artifact", {
|
||||
node_limit: 10,
|
||||
occurrence_limit: 10,
|
||||
edge_limit: 10,
|
||||
}),
|
||||
await runProviderAnalysis(path, "inventory_artifact", {}),
|
||||
),
|
||||
).toMatchObject({
|
||||
operation: "inventory_artifact",
|
||||
@@ -87,24 +81,39 @@ describe("artifact archive safety", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects unsafe, colliding, and over-ratio entries", async () => {
|
||||
expect(() => normalizeArtifactPath("../escape", limits())).toThrow(
|
||||
/normalized/u,
|
||||
);
|
||||
it("rejects unsafe paths, collisions, and default compression bombs", async () => {
|
||||
let unsafePathError: unknown;
|
||||
try {
|
||||
normalizeArtifactPath("../escape", limits());
|
||||
} catch (error: unknown) {
|
||||
unsafePathError = error;
|
||||
}
|
||||
expect(unsafePathError).toBeInstanceOf(ArtifactReaderFailure);
|
||||
expect(unsafePathError).toMatchObject({
|
||||
reason: "path",
|
||||
message: "Artifact path is not normalized",
|
||||
});
|
||||
const registry = new ArtifactPathRegistry();
|
||||
registry.add("A.js", "file");
|
||||
expect(() => registry.add("a.js", "file")).toThrow(/collision/u);
|
||||
let collisionError: unknown;
|
||||
try {
|
||||
registry.add("a.js", "file");
|
||||
} catch (error: unknown) {
|
||||
collisionError = error;
|
||||
}
|
||||
expect(collisionError).toBeInstanceOf(ArtifactReaderFailure);
|
||||
expect(collisionError).toMatchObject({
|
||||
reason: "path",
|
||||
message: "Artifact path collision: a.js",
|
||||
});
|
||||
|
||||
const root = await createTestTempDirectory("rea-bomb-");
|
||||
const zipPath = join(root, "bomb.zip");
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
await writer.add("zeros", new TextReader("0".repeat(100_000)));
|
||||
await writer.add("zeros", new TextReader("0".repeat(10_000_000)));
|
||||
await writeFile(zipPath, await writer.close());
|
||||
const client = new ArtifactProvider().createClient(target(zipPath, "zip"));
|
||||
const result = await client.execute(
|
||||
"inventory_artifact",
|
||||
artifactInventoryInputSchema.parse({ max_compression_ratio: 2 }),
|
||||
);
|
||||
const result = await client.execute("inventory_artifact", {});
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "ArtifactOperationError", reason: "limit" },
|
||||
@@ -112,14 +121,9 @@ describe("artifact archive safety", () => {
|
||||
});
|
||||
});
|
||||
const inventory = async (targetValue: BinaryTarget) => {
|
||||
const result = await new ArtifactProvider().createClient(targetValue).execute(
|
||||
"inventory_artifact",
|
||||
artifactInventoryInputSchema.parse({
|
||||
node_limit: 500,
|
||||
occurrence_limit: 500,
|
||||
edge_limit: 500,
|
||||
}),
|
||||
);
|
||||
const result = await new ArtifactProvider()
|
||||
.createClient(targetValue)
|
||||
.execute("inventory_artifact", {});
|
||||
if (!result.ok) throw result.error;
|
||||
return artifactInventoryResultSchema.parse(result.value.result);
|
||||
};
|
||||
|
||||
@@ -6,7 +6,6 @@ import { describe, expect, it } from "vitest";
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
|
||||
import { artifactInventoryInputSchema } from "../../../../src/contracts/artifactToolContracts.js";
|
||||
import { artifactInventoryResultSchema } from "../../../../src/domain/artifactGraph.js";
|
||||
import type { BinaryTarget } from "../../../../src/domain/binaryTarget.js";
|
||||
|
||||
@@ -33,11 +32,7 @@ describe("artifact directory inventory", () => {
|
||||
const client = new ArtifactProvider().createClient(
|
||||
target(app, "directory"),
|
||||
);
|
||||
const input = artifactInventoryInputSchema.parse({
|
||||
node_limit: 500,
|
||||
occurrence_limit: 500,
|
||||
edge_limit: 500,
|
||||
});
|
||||
const input = {};
|
||||
const first = await client.execute("inventory_artifact", input);
|
||||
const second = await client.execute("inventory_artifact", input);
|
||||
expect(first.ok).toBe(true);
|
||||
|
||||
@@ -6,10 +6,7 @@ import { describe, expect, it } from "vitest";
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
|
||||
import {
|
||||
artifactExtractionInputSchema,
|
||||
artifactInventoryInputSchema,
|
||||
} from "../../../../src/contracts/artifactToolContracts.js";
|
||||
import { artifactExtractionInputSchema } from "../../../../src/contracts/artifactToolContracts.js";
|
||||
import {
|
||||
artifactExtractionResultSchema,
|
||||
artifactInventoryResultSchema,
|
||||
@@ -110,20 +107,17 @@ describe("artifact extraction", () => {
|
||||
ok: false,
|
||||
error: { _tag: "ArtifactOperationError", reason: "path" },
|
||||
});
|
||||
expect(await readdir(root)).not.toEqual(
|
||||
expect.arrayContaining([expect.stringMatching(/^\.output\.rea-/u)]),
|
||||
);
|
||||
expect((await readdir(root)).sort()).toEqual([
|
||||
"output",
|
||||
"relocated-output",
|
||||
"source",
|
||||
]);
|
||||
});
|
||||
});
|
||||
const inventory = async (targetValue: BinaryTarget) => {
|
||||
const result = await new ArtifactProvider().createClient(targetValue).execute(
|
||||
"inventory_artifact",
|
||||
artifactInventoryInputSchema.parse({
|
||||
node_limit: 500,
|
||||
occurrence_limit: 500,
|
||||
edge_limit: 500,
|
||||
}),
|
||||
);
|
||||
const result = await new ArtifactProvider()
|
||||
.createClient(targetValue)
|
||||
.execute("inventory_artifact", {});
|
||||
if (!result.ok) throw result.error;
|
||||
return artifactInventoryResultSchema.parse(result.value.result);
|
||||
};
|
||||
|
||||
+2
-55
@@ -5,54 +5,12 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
|
||||
import { MachOSliceArtifactReader } from "../../../../src/artifacts/MachOSliceArtifactReader.js";
|
||||
import { artifactInventoryInputSchema } from "../../../../src/contracts/artifactToolContracts.js";
|
||||
import { artifactInventoryResultSchema } from "../../../../src/domain/artifactGraph.js";
|
||||
import type { BinaryTarget } from "../../../../src/domain/binaryTarget.js";
|
||||
import { ok } from "../../../../src/domain/result.js";
|
||||
import type { NativeCommandRunner } from "../../../../src/native/CommandRunner.js";
|
||||
|
||||
describe("artifact pagination and slices", () => {
|
||||
it("paginates wide graphs without changing manifest identity", async () => {
|
||||
const root = await createTestTempDirectory("rea-wide-");
|
||||
await Promise.all(
|
||||
Array.from({ length: 520 }, async (_, index) =>
|
||||
writeFile(
|
||||
join(root, `file-${String(index).padStart(4, "0")}.txt`),
|
||||
`${index}`,
|
||||
),
|
||||
),
|
||||
);
|
||||
const client = new ArtifactProvider().createClient(
|
||||
target(root, "directory"),
|
||||
);
|
||||
const [first, secondPage] = await Promise.all([
|
||||
client.execute(
|
||||
"inventory_artifact",
|
||||
artifactInventoryInputSchema.parse({ occurrence_limit: 500 }),
|
||||
),
|
||||
client.execute(
|
||||
"inventory_artifact",
|
||||
artifactInventoryInputSchema.parse({
|
||||
occurrence_offset: 500,
|
||||
occurrence_limit: 500,
|
||||
}),
|
||||
),
|
||||
]);
|
||||
expect(first.ok && secondPage.ok).toBe(true);
|
||||
if (!first.ok || !secondPage.ok) return;
|
||||
const left = artifactInventoryResultSchema.parse(first.value.result);
|
||||
const right = artifactInventoryResultSchema.parse(secondPage.value.result);
|
||||
expect(left.manifest).toEqual(right.manifest);
|
||||
expect(left.occurrences).toMatchObject({ total: 521, next_offset: 500 });
|
||||
expect(right.occurrences).toMatchObject({
|
||||
offset: 500,
|
||||
next_offset: null,
|
||||
});
|
||||
}, 15_000);
|
||||
|
||||
it("uses bounded native lipo metadata for universal slice ranges", async () => {
|
||||
describe("artifact Mach-O slices", () => {
|
||||
it("uses lipo metadata to read universal slice ranges", async () => {
|
||||
const root = await createTestTempDirectory("rea-slices-");
|
||||
const binary = join(root, "fat");
|
||||
await writeFile(binary, Buffer.from("0123456789abcdef"));
|
||||
@@ -103,14 +61,3 @@ describe("artifact pagination and slices", () => {
|
||||
expect(reader.provenance()[0]?.tool).toBe("lipo");
|
||||
});
|
||||
});
|
||||
|
||||
const target = (
|
||||
path: string,
|
||||
format: Extract<BinaryTarget, { kind: "archive" }>["format"] | "directory",
|
||||
): BinaryTarget => ({
|
||||
path,
|
||||
sourcePath: path,
|
||||
sha256: "0".repeat(64),
|
||||
kind: "archive",
|
||||
format: format === "directory" ? "asar" : format,
|
||||
});
|
||||
@@ -133,7 +133,6 @@ const input = (
|
||||
|
||||
const completedRunner = (): JavaScriptReplayRunner => ({
|
||||
execute: async (prepared) => ({
|
||||
schema_version: 1,
|
||||
plan_digest: prepared.publicPlan.plan_digest,
|
||||
outcomes: [
|
||||
{
|
||||
@@ -403,7 +402,6 @@ describe("controlled JavaScript replay cancellation and export", () => {
|
||||
it("projects an observed cancelled termination through the shared error algebra", async () => {
|
||||
const execute = vi.fn<JavaScriptReplayRunner["execute"]>(
|
||||
async (prepared) => ({
|
||||
schema_version: 1,
|
||||
plan_digest: prepared.publicPlan.plan_digest,
|
||||
outcomes: [
|
||||
{
|
||||
|
||||
@@ -42,11 +42,7 @@ describe("Android application projection", () => {
|
||||
await writeFile(path, await writer.close());
|
||||
|
||||
const inventory = parseEvidence(
|
||||
await runProviderAnalysis(path, "inventory_artifact", {
|
||||
node_limit: 500,
|
||||
occurrence_limit: 500,
|
||||
edge_limit: 500,
|
||||
}),
|
||||
await runProviderAnalysis(path, "inventory_artifact", {}),
|
||||
);
|
||||
const first = projectAndroidApplicationEvidence({
|
||||
inventory_evidence: [inventory],
|
||||
|
||||
@@ -49,11 +49,7 @@ describe("Apple application projection", () => {
|
||||
await writeFile(path, await writer.close());
|
||||
|
||||
const inventory = parseEvidence(
|
||||
await runProviderAnalysis(path, "inventory_artifact", {
|
||||
node_limit: 500,
|
||||
occurrence_limit: 500,
|
||||
edge_limit: 500,
|
||||
}),
|
||||
await runProviderAnalysis(path, "inventory_artifact", {}),
|
||||
);
|
||||
const first = projectAppleApplicationEvidence({
|
||||
inventory_evidence: [inventory],
|
||||
|
||||
@@ -14,8 +14,6 @@ const nonHopperProvider = (operations: string[]): AnalysisProvider => {
|
||||
{
|
||||
provider: { id: "fixture", name: "Fixture", version: "1" },
|
||||
operation: "address_name",
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: true,
|
||||
reason: null,
|
||||
pagination: "none",
|
||||
@@ -134,7 +132,6 @@ describe("binary session", () => {
|
||||
observation: {
|
||||
status: "verified",
|
||||
observed_at: "2026-07-22T10:00:00.000Z",
|
||||
schema_version: 1,
|
||||
launcher_pid: 100,
|
||||
launcher_parent_pid: 1,
|
||||
process_group_id: 100,
|
||||
|
||||
-1
@@ -89,7 +89,6 @@ describe("binary session", () => {
|
||||
name: identity.name,
|
||||
version: identity.version ?? "fixture-unresolved",
|
||||
},
|
||||
1,
|
||||
{ fixture: "different-profile" },
|
||||
),
|
||||
compatibility: {},
|
||||
|
||||
+2
-1
@@ -34,7 +34,8 @@ describe("binary session", () => {
|
||||
expect.objectContaining({
|
||||
operation: "address_name",
|
||||
available: false,
|
||||
reason: "Provider became unavailable during this session.",
|
||||
reason:
|
||||
"ProviderAdapterError: Provider fixture adapter failed during address_name",
|
||||
}),
|
||||
]),
|
||||
});
|
||||
|
||||
-2
@@ -28,8 +28,6 @@ describe("binary session", () => {
|
||||
{
|
||||
provider: { id: "partial", name: "Partial", version: "1" },
|
||||
operation: "address_name",
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: false,
|
||||
reason: "fixture intentionally omits symbol lookup",
|
||||
pagination: "none",
|
||||
|
||||
@@ -200,8 +200,6 @@ const capability = (
|
||||
): CapabilityDescriptor => ({
|
||||
provider: providerIdentity,
|
||||
operation,
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: true,
|
||||
reason: null,
|
||||
pagination: "none",
|
||||
|
||||
@@ -45,10 +45,9 @@ describe("cross-version inventory", () => {
|
||||
const calls: string[] = [];
|
||||
const controller = new AbortController();
|
||||
const scanner: VersionInventoryScanner = (...arguments_) => {
|
||||
const [path, roots, limits, options] = arguments_;
|
||||
const [path, limits, options] = arguments_;
|
||||
if (options === undefined) throw new Error("Expected scanner options");
|
||||
calls.push(path);
|
||||
expect(roots).toEqual([root]);
|
||||
expect(limits).toBe(LIMITS);
|
||||
expect(options.signal).toBe(controller.signal);
|
||||
expect(options.integrity).toBe(INTEGRITY);
|
||||
@@ -59,7 +58,6 @@ describe("cross-version inventory", () => {
|
||||
{
|
||||
leftPath: "left",
|
||||
rightPath: "right",
|
||||
inputRoots: [root],
|
||||
limits: LIMITS,
|
||||
signal: controller.signal,
|
||||
integrity: INTEGRITY,
|
||||
@@ -87,7 +85,6 @@ describe("cross-version inventory", () => {
|
||||
{
|
||||
leftPath: "left",
|
||||
rightPath: "right",
|
||||
inputRoots: ["/approved"],
|
||||
limits: LIMITS,
|
||||
integrity: INTEGRITY,
|
||||
},
|
||||
|
||||
@@ -71,13 +71,6 @@ describe("managed application graph projection", () => {
|
||||
managed_artifact: artifactEvidence,
|
||||
managed_members: memberEvidence,
|
||||
managed_native_boundaries: boundaryEvidence,
|
||||
limits: {
|
||||
max_types: 100,
|
||||
max_methods: 100,
|
||||
max_fields: 100,
|
||||
max_pinvoke_imports: 100,
|
||||
max_native_implementations: 100,
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
@@ -154,15 +147,10 @@ describe("managed application graph projection", () => {
|
||||
case_sensitive: true,
|
||||
},
|
||||
direction: "incoming",
|
||||
limits: {
|
||||
max_seed_matches: 5,
|
||||
max_depth: 4,
|
||||
max_nodes: 50,
|
||||
max_edges: 100,
|
||||
max_paths: 10,
|
||||
},
|
||||
});
|
||||
expect(trace.ok).toBe(true);
|
||||
expect(trace.ok, trace.ok ? undefined : JSON.stringify(trace.error)).toBe(
|
||||
true,
|
||||
);
|
||||
if (!trace.ok) throw new Error("trace failed");
|
||||
expect(trace.value.normalized_result).toMatchObject({
|
||||
source_evidence_id: parsed.evidence_id,
|
||||
@@ -172,7 +160,7 @@ describe("managed application graph projection", () => {
|
||||
});
|
||||
|
||||
describe("managed application graph coverage", () => {
|
||||
it("preserves source-page omissions in graph and per-fact coverage", () => {
|
||||
it("preserves partial parser coverage in graph and per-fact coverage", () => {
|
||||
const bytes = buildManagedPeFixture();
|
||||
const binary = managedPeFixtureTarget(bytes, "/fixture/ManagedInterop.exe");
|
||||
const members = inspectManagedMembersBytes(
|
||||
@@ -180,76 +168,8 @@ describe("managed application graph coverage", () => {
|
||||
binary,
|
||||
MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
);
|
||||
const partialMembers = {
|
||||
...members,
|
||||
methods: {
|
||||
...members.methods,
|
||||
total: 2,
|
||||
returned: 1,
|
||||
dropped: 1,
|
||||
complete: false,
|
||||
},
|
||||
};
|
||||
const memberEvidence = createEvidence(binary, MANAGED_STATIC_PROVIDER, {
|
||||
operation: "inspect_managed_members",
|
||||
parameters: {},
|
||||
result: partialMembers,
|
||||
rawResult: null,
|
||||
limitations: partialMembers.limitations,
|
||||
locations: [{ kind: "artifact-path", path: binary.path }],
|
||||
});
|
||||
|
||||
const evidence = projectManagedApplicationGraphEvidence({
|
||||
managed_members: memberEvidence,
|
||||
limits: {
|
||||
max_types: 100,
|
||||
max_methods: 100,
|
||||
max_fields: 100,
|
||||
max_pinvoke_imports: 100,
|
||||
max_native_implementations: 100,
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
evidence.ok,
|
||||
evidence.ok
|
||||
? undefined
|
||||
: `${JSON.stringify(evidence.error)} cause=${String(evidence.error.cause)}`,
|
||||
).toBe(true);
|
||||
if (!evidence.ok) throw new Error("projection failed");
|
||||
const result = managedApplicationGraphResultSchema.parse(
|
||||
parseEvidence(evidence.value).normalized_result,
|
||||
);
|
||||
const graph = parseJavaScriptApplicationGraph(result.graph);
|
||||
expect(result.coverage).toMatchObject({
|
||||
status: "truncated",
|
||||
omitted_types: 0,
|
||||
omitted_methods: 1,
|
||||
omitted_fields: 0,
|
||||
});
|
||||
expect(graph.coverage).toMatchObject({
|
||||
status: "partial",
|
||||
truncated: true,
|
||||
omitted_count: 1,
|
||||
});
|
||||
const method = graph.nodes.find(({ kind }) => kind === "managed-method");
|
||||
expect(method?.observations[0]?.evidence.coverage).toMatchObject({
|
||||
status: "partial",
|
||||
truncated: true,
|
||||
omitted_count: 1,
|
||||
});
|
||||
expect(
|
||||
graph.edges.find(
|
||||
({ target_node_id }) => target_node_id === method?.node_id,
|
||||
)?.evidence.coverage,
|
||||
).toMatchObject({
|
||||
status: "partial",
|
||||
truncated: true,
|
||||
omitted_count: 1,
|
||||
});
|
||||
|
||||
const parserPartialMembers = {
|
||||
...partialMembers,
|
||||
...members,
|
||||
coverage: {
|
||||
state: "partial" as const,
|
||||
issues: [
|
||||
@@ -275,13 +195,6 @@ describe("managed application graph coverage", () => {
|
||||
);
|
||||
const parserPartialProjection = projectManagedApplicationGraphEvidence({
|
||||
managed_members: parserPartialEvidence,
|
||||
limits: {
|
||||
max_types: 100,
|
||||
max_methods: 100,
|
||||
max_fields: 100,
|
||||
max_pinvoke_imports: 100,
|
||||
max_native_implementations: 100,
|
||||
},
|
||||
});
|
||||
|
||||
expect(parserPartialProjection.ok).toBe(true);
|
||||
@@ -292,7 +205,6 @@ describe("managed application graph coverage", () => {
|
||||
);
|
||||
expect(parserPartialResult.coverage).toMatchObject({
|
||||
status: "partial",
|
||||
omitted_methods: 1,
|
||||
});
|
||||
expect(parserPartialResult.graph.coverage).toEqual({
|
||||
status: "partial",
|
||||
|
||||
@@ -219,7 +219,6 @@ const deepProvider = (id: string): DeepProviderFixture => {
|
||||
ok({
|
||||
profile: createAnalysisProfile(
|
||||
{ id, name: identity.name, version: "1" },
|
||||
1,
|
||||
{ provider: id },
|
||||
),
|
||||
compatibility: {},
|
||||
@@ -295,8 +294,6 @@ const capability = (
|
||||
): CapabilityDescriptor => ({
|
||||
provider,
|
||||
operation,
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: true,
|
||||
reason: null,
|
||||
pagination: "none",
|
||||
|
||||
@@ -1,49 +1,41 @@
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { analyzeJavaScriptApplication } from "../../../src/application/JavaScriptApplicationService.js";
|
||||
import { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
|
||||
import { reconstructJavaScriptArtifact } from "../../../src/application/JavaScriptArtifactReconstruction.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { parseJavaScriptApplicationGraph } from "../../../src/domain/javascriptApplicationGraph.js";
|
||||
import { analyzeJavaScriptApplicationInputSchema } from "../../../src/domain/javascriptApplicationAnalysis.js";
|
||||
import { createPermissionPolicy } from "../../../src/domain/permissionPolicy.js";
|
||||
import { writeElectronBoundaryFixture } from "../../fixtures/electronBoundaryApplication.js";
|
||||
|
||||
describe("static Electron application analysis", () => {
|
||||
it("requires explicit approval, an absolute path, and graph-safe combined bounds", () => {
|
||||
it("accepts a caller path and caller-selected analysis bounds", () => {
|
||||
expect(
|
||||
analyzeJavaScriptApplicationInputSchema.safeParse({
|
||||
input_path: "relative/app.asar",
|
||||
approved: true,
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
analyzeJavaScriptApplicationInputSchema.safeParse({
|
||||
input_path: "/tmp/app.asar",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
).toBe(true);
|
||||
expect(
|
||||
analyzeJavaScriptApplicationInputSchema.safeParse({
|
||||
input_path: "/tmp/app.asar",
|
||||
approved: true,
|
||||
limits: {
|
||||
max_entries: 100_000,
|
||||
max_findings: 200_000,
|
||||
},
|
||||
}).success,
|
||||
).toBe(false);
|
||||
).toBe(true);
|
||||
expect(
|
||||
analyzeJavaScriptApplicationInputSchema.parse({
|
||||
input_path: "/tmp/app.asar",
|
||||
approved: true,
|
||||
}),
|
||||
).toMatchObject({
|
||||
format: "auto",
|
||||
source_map_read_approved: false,
|
||||
limits: { max_findings: 8_000 },
|
||||
});
|
||||
});
|
||||
@@ -65,42 +57,27 @@ describe("static Electron application analysis", () => {
|
||||
expectElectronBoundaries(graph);
|
||||
});
|
||||
|
||||
it("returns Evidence v2 only after exact investigation-input authorization", async () => {
|
||||
it("analyzes the selected local application directory directly", async () => {
|
||||
const root = await fixtureDirectory();
|
||||
const authority = permissionAuthority(root);
|
||||
|
||||
const result = await analyzeJavaScriptApplication(authority, {
|
||||
const result = await analyzeJavaScriptApplication({
|
||||
input_path: root,
|
||||
approved: true,
|
||||
});
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
const evidence = parseEvidence(result.value);
|
||||
expect(evidence).toMatchObject({
|
||||
operation: "analyze_javascript_application",
|
||||
predicate_type: "rea.javascript-application-analysis/v2",
|
||||
predicate_type: "rea.javascript-application-analysis",
|
||||
provider: { id: "rea-javascript-application" },
|
||||
authority: "shipped-artifact",
|
||||
confidence: "derived",
|
||||
subject: { local_path: root, format: "directory" },
|
||||
normalized_result: {
|
||||
schema_version: 2,
|
||||
input_path: root,
|
||||
summary: { browser_windows: 3 },
|
||||
},
|
||||
});
|
||||
|
||||
const denied = await analyzeJavaScriptApplication(
|
||||
permissionAuthority(root),
|
||||
{
|
||||
input_path: join(root, ".."),
|
||||
approved: true,
|
||||
},
|
||||
);
|
||||
expect(denied).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "PermissionRequiredError" },
|
||||
});
|
||||
});
|
||||
|
||||
it("returns a tagged cancellation without executing application code", async () => {
|
||||
@@ -110,8 +87,7 @@ describe("static Electron application analysis", () => {
|
||||
Reflect.deleteProperty(globalThis, "__rea_electron_fixture_executed");
|
||||
|
||||
const result = await analyzeJavaScriptApplication(
|
||||
permissionAuthority(root),
|
||||
{ input_path: root, approved: true },
|
||||
{ input_path: root },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
|
||||
@@ -313,28 +289,3 @@ const fixtureDirectory = async (): Promise<string> => {
|
||||
await writeElectronBoundaryFixture(root);
|
||||
return root;
|
||||
};
|
||||
|
||||
const permissionAuthority = (root: string): PermissionAuthority =>
|
||||
new PermissionAuthority(
|
||||
createPermissionPolicy(
|
||||
[scope(root)],
|
||||
[
|
||||
{
|
||||
...scope(root),
|
||||
grant_id: "test:investigation-input",
|
||||
lifetime: "session",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
},
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
const scope = (root: string) => ({
|
||||
capability: "investigation_input" as const,
|
||||
roots: [root],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none" as const,
|
||||
mount: false,
|
||||
});
|
||||
|
||||
@@ -9,7 +9,7 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { reconstructJavaScriptArtifact } from "../../../src/application/JavaScriptArtifactReconstruction.js";
|
||||
import { scanArtifactInventory } from "../../../src/application/ArtifactInventory.js";
|
||||
import { parseJavaScriptApplicationGraph } from "../../../src/domain/javascriptApplicationGraph.js";
|
||||
import { javaScriptApplicationAnalysisResultV2Schema } from "../../../src/domain/javascriptApplicationAnalysis.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascriptApplicationAnalysis.js";
|
||||
import { createJavaScriptSemanticGraph } from "../../../src/domain/javascriptSemanticGraph.js";
|
||||
import { parseJavaScriptSemanticGraph } from "../../../src/domain/javascriptSemanticGraphSerialization.js";
|
||||
import { writeJavaScriptArtifactFixture } from "../../fixtures/javascriptArtifactApplication.js";
|
||||
@@ -20,7 +20,6 @@ it("reconstructs package, Electron roles, Webpack/Rspack modules, and cross-laye
|
||||
|
||||
const result = await reconstructJavaScriptArtifact({
|
||||
input_path: root,
|
||||
source_map_read_approved: true,
|
||||
});
|
||||
const graph = parseJavaScriptApplicationGraph(result.graph);
|
||||
const semanticGraph = parseJavaScriptSemanticGraph(result.semantic_graph);
|
||||
@@ -31,7 +30,6 @@ it("reconstructs package, Electron roles, Webpack/Rspack modules, and cross-laye
|
||||
modules: 4,
|
||||
parse_failures: 0,
|
||||
omitted_text_files: 0,
|
||||
policy_filtered_text_files: 0,
|
||||
});
|
||||
expect(graph.nodes.map(({ kind }) => kind)).toEqual(
|
||||
expect.arrayContaining([
|
||||
@@ -111,12 +109,10 @@ it("produces deterministic ASAR graphs with unpacked native linkage and complete
|
||||
const first = await reconstructJavaScriptArtifact({
|
||||
input_path: archive,
|
||||
format: "asar",
|
||||
source_map_read_approved: true,
|
||||
});
|
||||
const second = await reconstructJavaScriptArtifact({
|
||||
input_path: archive,
|
||||
format: "asar",
|
||||
source_map_read_approved: true,
|
||||
});
|
||||
|
||||
expect(first.graph).toEqual(second.graph);
|
||||
@@ -191,7 +187,6 @@ it("keeps ASAR analysis usable when unpacked native companion bytes are absent",
|
||||
const result = await reconstructJavaScriptArtifact({
|
||||
input_path: archive,
|
||||
format: "asar",
|
||||
source_map_read_approved: true,
|
||||
});
|
||||
|
||||
expect(result.statistics.parsed_javascript_files).toBeGreaterThan(0);
|
||||
@@ -214,7 +209,6 @@ it("recurses into filesystem-backed ASAR containers without losing container-rel
|
||||
|
||||
const result = await reconstructJavaScriptArtifact({
|
||||
input_path: outer,
|
||||
source_map_read_approved: true,
|
||||
});
|
||||
|
||||
expect(result.statistics.nested_asar_containers).toBe(1);
|
||||
@@ -257,9 +251,8 @@ const assertSemanticLinks = (
|
||||
});
|
||||
const { electron_summary: summary, ...analysisResult } = result;
|
||||
expect(() =>
|
||||
javaScriptApplicationAnalysisResultV2Schema.parse({
|
||||
javascriptApplicationAnalysisResultSchema.parse({
|
||||
...analysisResult,
|
||||
schema_version: 2,
|
||||
summary,
|
||||
semantic_graph: mismatchedSemanticGraph,
|
||||
}),
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user