chore: reconcile captured main with PR #2801

This commit is contained in:
morluto
2026-10-13 21:43:32 +08:00
808 changed files with 74776 additions and 5305 deletions
@@ -39,6 +39,8 @@ import {
} from "../../fixtures/analysisView.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { BINARY_LAYOUT_TEST_PROVIDER } from "../../fixtures/binaryDiagnostics/layout.js";
import { wasmArtifactFixture } from "../../fixtures/wasm/artifact.js";
import { evmInterfaceFixture } from "../../fixtures/evm/interface.js";
const connect = async (
binaryLayout?: BinaryLayoutService,
@@ -69,6 +71,12 @@ const connect = async (
it("discovers an oversized native dossier by exact metadata and reads its retained view", async () => {
const { client, session } = await connect();
const advertised = (await client.listTools()).tools.find(
(tool) => tool.name === "inspect_analysis_view",
);
expect(advertised?.description).toContain(
'Native function Evidence requires kind native: view: {kind: "native", facet: "procedure"}',
);
const provider = { id: "ghidra", name: "Ghidra", version: "12.1.4" };
const profile = createAnalysisProfile(provider, { language: "fixture" });
const parent = createEvidence(
@@ -98,6 +106,24 @@ it("discovers an oversized native dossier by exact metadata and reads its retain
const retained = session.recordEvidence(record);
if (!retained.ok) throw retained.error;
}
const unsupportedSummary = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: { kind: "retained-evidence", evidence_id: parent.evidence_id },
view: { kind: "summary" },
},
});
expect(parseMcpToolError(unsupportedSummary).error).toMatchObject({
code: "invalid_request",
details: {
issues: [
{
path: ["view"],
message: "analyze_function Evidence requires a native view.",
},
],
},
});
const broad = await client.callTool({
name: "get_evidence_bundle",
arguments: {},
@@ -286,6 +312,65 @@ it("reports a tampered inline Evidence ID at its full MCP source path", async ()
});
});
it("rejects self-contained WASM and EVM Evidence views when the subject format differs", async () => {
const { client } = await connect();
const wasm = wasmArtifactFixture();
const evm = evmInterfaceFixture();
const cases = [
{
evidence: createEvidence(
{
path: wasm.artifact.path,
format: "elf",
sha256: wasm.artifact.sha256,
},
{ id: "fixture-wabt", name: "WABT", version: "1" },
{
operation: "inspect_wasm_artifact",
parameters: { path: wasm.artifact.path },
result: wasm,
},
),
},
{
evidence: createEvidence(
{
path: evm.artifact.path,
format: "elf",
sha256: evm.artifact.sha256,
},
{ id: "fixture-evm", name: "EVMole", version: "1" },
{
operation: "inspect_evm_interface",
parameters: { path: evm.artifact.path, encoding: "hex" },
result: evm,
},
),
},
] as const;
for (const { evidence } of cases) {
const response = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: { kind: "inline", evidence },
view: { kind: "summary" },
},
});
expect(parseMcpToolError(response).error).toMatchObject({
code: "invalid_request",
details: {
issues: [
expect.objectContaining({
path: ["source", "subject"],
reason: "invalid_value",
}),
],
},
});
}
});
it("admits portable captures before SDK Evidence parsing and preserves capture caveats", async () => {
const { client } = await connect();
const dense = analysisViewCaptureEvidence(analysisViewObjectDenseCapture());
@@ -0,0 +1,295 @@
import { unlink } from "node:fs/promises";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it, onTestFinished, vi } from "vitest";
import { AndroidAnalysisService } from "../../../src/application/android/AndroidAnalysisService.js";
import { inspectAndroidPackage } from "../../../src/application/android/AndroidPackageInspection.js";
import { inspectAnalysisView } from "../../../src/application/analysisView/AnalysisViewService.js";
import { androidResultSchemas } from "../../../src/domain/android/androidAnalysis.js";
import {
androidPackageSummaryViewResultSchema,
analysisViewResultSchema,
} from "../../../src/domain/analysisView/analysisView.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import type { JsonValue } from "../../../src/domain/jsonValue.js";
import { createServer } from "../../../src/server/createServer.js";
import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import {
createJadxProtocolFixture,
verifyJadxFixtureCleanup,
} from "../../fixtures/android/jadx.js";
it.skipIf(process.platform === "win32")(
"retains complete APK Evidence and reads exact manifest without its source or another engine launch",
async () => {
const { provider, apk, launches } =
await createJadxProtocolFixture("large-manifest");
const harness = await createApplicationMcpHarness({
serverOptions: { androidAnalysis: provider },
});
onTestFinished(harness.close);
const { client, session } = harness;
const catalog = (await client.listTools()).tools;
const definition = catalog.find(
(tool) => tool.name === "inspect_android_package",
);
if (definition?.outputSchema === undefined)
throw new Error("Missing APK schema");
const outputSchema: Record<string, unknown> = definition.outputSchema;
const ajv = new Ajv2020({ strict: false, validateFormats: false });
expect(ajv.validateSchema(definition.inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
expect(
ajv.validate(definition.inputSchema, { path: apk, detail: "summary" }),
).toBe(true);
expect(
ajv.validate(
catalog.find((tool) => tool.name === "inspect_android_class")!
.inputSchema,
{
path: apk,
class_name: "fixture.Target",
detail: "summary",
},
),
).toBe(false);
const reply = await client.callTool({
name: "inspect_android_package",
arguments: { path: apk, detail: "summary" },
});
expect(reply.isError).not.toBe(true);
expect(
ajv.validate(outputSchema, reply.structuredContent),
JSON.stringify(ajv.errors),
).toBe(true);
const receipt = parseEvidence(reply.structuredContent);
const view = androidPackageSummaryViewResultSchema.parse(
receipt.normalized_result,
);
const parent = session.evidenceById(view.parent_evidence_id);
if (parent === undefined)
throw new Error("Complete package Evidence not retained");
const report = androidResultSchemas.inspect_android_package.parse(
parent.normalized_result,
);
expect(parent.operation).toBe("inspect_android_package");
expect(parent.parameters).toEqual({ path: apk });
expect(view.artifact.sha256).toBe(parent.subject?.digest.sha256);
expect(view.artifact.sha256).not.toBe(report.engine.artifact_sha256);
expect(receipt.evidence_id).not.toBe(parent.evidence_id);
expect(receipt.evidence_links).toEqual([parent.evidence_id]);
const { manifest, ...declarations } = report;
expect(view.summary).toMatchObject(declarations);
expect(view.summary.manifest).toEqual({
status: manifest.status,
reported_total_bytes: manifest.reported_total_bytes,
text_code_units: manifest.text.length,
text_included: false,
});
expect(receipt.raw_result).toBeNull();
expect(parent.raw_result).not.toBeNull();
for (const detail of [undefined, "complete"]) {
const full = parseEvidence(
(
await client.callTool({
name: "inspect_android_package",
arguments: {
path: apk,
...(detail === undefined ? {} : { detail }),
},
})
).structuredContent,
);
expect(full.operation).toBe("inspect_android_package");
expect(full.normalized_result).toEqual(parent.normalized_result);
expect(full.parameters).toEqual(parent.parameters);
expect(full.raw_result).not.toBeNull();
}
const before = JSON.stringify(parent);
await unlink(apk);
let text = "";
let offset = 0;
do {
const paged = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: {
kind: "retained-evidence",
evidence_id: parent.evidence_id,
},
view: { kind: "android", facet: "manifest", offset, limit: 700000 },
},
});
expect(paged.isError).not.toBe(true);
const page = analysisViewResultSchema.parse(
parseEvidence(paged.structuredContent).normalized_result,
);
if (page.kind !== "android") throw new Error("Unexpected manifest page");
text += page.item.text;
expect(page.item.source_status).toBe(manifest.status);
expect(page.item.reported_total_bytes).toBe(
manifest.reported_total_bytes,
);
offset = page.coverage.next_offset ?? manifest.text.length;
} while (offset < manifest.text.length);
expect(text).toBe(manifest.text);
const portable = inspectAnalysisView({
source: { kind: "inline", evidence: parseEvidence(JSON.parse(before)) },
view: { kind: "summary" },
});
if (!portable.ok) throw portable.error;
expect(portable.value.normalized_result).toEqual(view);
expect(JSON.stringify(session.evidenceById(parent.evidence_id))).toBe(
before,
);
expect(
session
.exportEvidenceBundle()
.records.find((record) => record.evidence_id === parent.evidence_id),
).toEqual(parent);
expect(launches).toHaveLength(1);
await harness.close();
await verifyJadxFixtureCleanup(launches);
},
30000,
);
it("preserves partial/unknown declarations and Unicode text while rejecting missing APK identity and malformed source", () => {
const report = {
engine: {
name: "jadx",
version: null,
artifact_sha256: "b".repeat(64),
source_revision: null,
worker_count: 1,
heap_limit_mib: null,
},
package_name: null,
version_name: null,
version_code: null,
min_sdk: null,
target_sdk: null,
permissions: [],
manifest: { status: "partial", text: "a😀b", reported_total_bytes: null },
class_count: 0,
resource_count: 0,
signature_verification: "not_performed",
};
const evidence = (result: JsonValue = report, hasSubject = true) =>
createEvidence(
hasSubject
? { path: "/original.apk", sha256: "a".repeat(64), format: "apk" }
: undefined,
{ id: "jadx", name: "JADX", version: "0.7.1" },
{
operation: "inspect_android_package",
parameters: {},
result,
limitations: ["Original limit"],
},
);
const parent = evidence();
const source = { kind: "inline", evidence: parent };
const summary = inspectAnalysisView({ source, view: { kind: "summary" } });
if (!summary.ok) throw summary.error;
const overview = androidPackageSummaryViewResultSchema.parse(
summary.value.normalized_result,
);
expect(overview.summary.package_name).toBeNull();
expect(overview.summary.manifest.status).toBe("partial");
expect(overview.limitations).toEqual(parent.limitations);
const page = inspectAnalysisView({
source,
view: { kind: "android", facet: "manifest", offset: 0, limit: 4 },
});
if (!page.ok) throw page.error;
const result = analysisViewResultSchema.parse(page.value.normalized_result);
expect(result).toMatchObject({
kind: "android",
item: {
text: "a😀b",
source_status: "partial",
reported_total_bytes: null,
},
coverage: { exhausted: true },
});
expect(result.unknowns.join(" ")).toContain("partial");
for (const offset of [2])
expect(
inspectAnalysisView({
source,
view: { kind: "android", facet: "manifest", offset, limit: 2 },
}),
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
for (const invalid of [
evidence(report, false),
evidence({ ...report, class_count: -1 }),
])
expect(
inspectAnalysisView({
source: { kind: "inline", evidence: invalid },
view: { kind: "summary" },
}),
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
});
it("rejects unavailable retention, invalid selectors and cancellation before provider execution", async () => {
const execute = vi.fn();
const provider = {
execute,
close: async () => {},
inspectAvailability: vi.fn(),
};
const service = new AndroidAnalysisService(provider);
const retention = { recordEvidence: undefined, evidenceById: undefined };
expect(
await inspectAndroidPackage(
service,
{ path: "/missing.apk", detail: "summary" },
retention,
),
).toMatchObject({
ok: false,
error: { _tag: "AnalysisCapabilityUnavailableError" },
});
expect(
await inspectAndroidPackage(
service,
{ path: "/missing.apk", detail: "other" },
retention,
),
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
expect(
await inspectAndroidPackage(
service,
{ path: "/missing.apk", detail: "summary" },
retention,
{ signal: AbortSignal.abort() },
),
).toMatchObject({ ok: false, error: { _tag: "AnalysisCancelledError" } });
expect(execute).not.toHaveBeenCalled();
const session = createTestBinarySession(() => {
throw new Error("Unexpected deep provider");
});
const server = createServer(
{ kind: "fixed", analysis: session },
{ androidAnalysis: provider },
);
const client = new Client({ name: "android-fixed-summary", version: "1" });
onTestFinished(async () => {
await client.close();
await server.close();
await session.close();
});
const [a, b] = InMemoryTransport.createLinkedPair();
await server.connect(b);
await client.connect(a);
const reply = await client.callTool({
name: "inspect_android_package",
arguments: { path: "/missing.apk", detail: "summary" },
});
expect(parseMcpToolError(reply).error.code).toBe("capability_unavailable");
expect(execute).not.toHaveBeenCalled();
});
@@ -2,6 +2,7 @@ import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import type { Client } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
import { Ajv2020 } from "ajv/dist/2020.js";
import type { AnySchema } from "ajv";
import type { BinarySession } from "../../../src/application/binary/BinarySession.js";
import {
@@ -10,12 +11,143 @@ import {
SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE,
} from "../../../src/contracts/javascript/javascriptApplicationWorkflowExamples.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import {
createJavaScriptApplicationGraph,
createJavaScriptApplicationNode,
} from "../../../src/domain/javascript/javascriptApplicationGraph.js";
import { createJavaScriptSemanticGraph } from "../../../src/domain/javascript/javascriptSemanticGraph.js";
import {
artifactEvidence,
sourceMapReference,
} from "../../../src/domain/javascript/javascriptApplicationGraph.fixture.js";
import {
createApplicationMcpHarness,
type ApplicationMcpHarness,
} from "../../fixtures/applicationMcpHarness.js";
import { createHistoricalSourceGraph } from "../../../src/domain/referenceSourceGraph.js";
async function runUnicodeSourceMapComparison(
harness: ApplicationMcpHarness,
): Promise<void> {
const baseApplication = SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE.application;
const subject = baseApplication.subject;
if (subject === null) throw new Error("Application Evidence has no subject");
const baseResult = javascriptApplicationAnalysisResultSchema.parse(
baseApplication.normalized_result,
);
const baseGraph = baseResult.graph;
const decomposedSource = "cafe\u0301.ts";
const unicodeSourceNode = createJavaScriptApplicationNode({
kind: "source-module",
identity: {
strategy: "source-map-original",
source_root: "../src/",
stability: "source-map-exact",
source_map_sha256: "1".repeat(64),
original_source: decomposedSource,
source_sha256: "3".repeat(64),
},
observations: [
{
label: "decomposed source-map spelling",
source_map_reference: sourceMapReference(
decomposedSource,
"../src/",
"dist/main.js.map",
),
properties: { content_available: true, content_sha256: "3".repeat(64) },
evidence: artifactEvidence("1".repeat(64), "dist/main.js.map"),
},
],
});
const applicationGraph = createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
root_node_ids: [...baseGraph.root_node_ids, unicodeSourceNode.node_id],
nodes: [...baseGraph.nodes, unicodeSourceNode],
edges: baseGraph.edges,
coverage: baseGraph.coverage,
limitations: baseGraph.limitations,
});
const semantic = baseResult.semantic_graph;
const { graph_id: _semanticGraphId, ...semanticInput } = semantic;
const semanticGraph = createJavaScriptSemanticGraph({
...semanticInput,
application_graph_id: applicationGraph.graph_id,
});
const unicodeApplication = createEvidence(
{
path: baseResult.input_path,
sha256: subject.digest.sha256,
format: subject.format,
},
baseApplication.provider,
{
predicateType: baseApplication.predicate_type,
operation: baseApplication.operation,
parameters: baseApplication.parameters,
result: {
...baseResult,
graph: applicationGraph,
semantic_graph: semanticGraph,
},
confidence: baseApplication.confidence,
authority: baseApplication.authority,
limitations: baseApplication.limitations,
evidenceLinks: baseApplication.evidence_links,
},
);
const historicalUnicodePath = "src/caf\u00e9.ts";
const unicodeReference = createHistoricalSourceGraph({
...SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE.reference,
root_sha256: undefined,
entries: SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE.reference.entries.map(
(entry) =>
entry.path === "src/main.ts"
? { ...entry, path: historicalUnicodePath }
: entry,
),
});
const reply = await harness.client.callTool({
name: "compare_source_to_bundle",
arguments: { reference: unicodeReference, application: unicodeApplication },
});
expect(reply.isError).not.toBe(true);
expect(reply.structuredContent).toMatchObject({
normalized_result: {
items: [
{
source_path: historicalUnicodePath,
status: "unknown",
current_node_ids: [],
candidates: [
expect.objectContaining({
confidence: "low",
signals: expect.arrayContaining([
expect.objectContaining({
kind: "unicode-equivalent-path",
source_value: historicalUnicodePath,
current_values: ["src/cafe\u0301.ts"],
}),
]),
}),
],
},
],
},
});
const advertised = (await harness.client.listTools()).tools.find(
({ name }) => name === "compare_source_to_bundle",
);
if (advertised?.outputSchema === undefined)
throw new Error("Comparison tool output schema is missing");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const outputSchema = advertised.outputSchema as AnySchema;
expect(ajv.validateSchema(outputSchema)).toBe(true);
const validateOutput = ajv.compile(outputSchema);
expect(validateOutput(reply.structuredContent)).toBe(true);
}
async function runInlineWorkflowScenarios(
harness: ApplicationMcpHarness,
): Promise<void> {
@@ -92,6 +224,8 @@ async function runInlineWorkflowScenarios(
},
});
await runUnicodeSourceMapComparison(harness);
const referenceWithExclusion = createHistoricalSourceGraph({
...SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE.reference,
root_sha256: undefined,
@@ -0,0 +1,285 @@
import { unlink } from "node:fs/promises";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it, onTestFinished, vi } from "vitest";
import { FlutterBuildAnalysisService } from "../../../src/application/flutter/FlutterBuildAnalysisService.js";
import { inspectDartAot } from "../../../src/application/flutter/DartAotInspection.js";
import { inspectAnalysisView } from "../../../src/application/analysisView/AnalysisViewService.js";
import { createFlutterBuildAnalysisProvider } from "../../../src/composition/flutter.js";
import {
analysisViewResultSchema,
dartAotSummaryViewResultSchema,
} from "../../../src/domain/analysisView/analysisView.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import { flutterResultSchemas } from "../../../src/domain/flutter/flutterBuildAnalysis.js";
import type { JsonValue } from "../../../src/domain/jsonValue.js";
import { aotFixtureImage } from "../../../src/flutter/FlutterBuild.fixture.js";
import { createFlutterApk } from "../../fixtures/flutterApk.js";
import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";
it("honors explicit ABI and old full requests, validates SDK schemas and reuses complete Evidence after APK removal", async () => {
const path = await createFlutterApk("views.apk", [
{ path: "lib/arm64-v8a/libapp.so", bytes: aotFixtureImage() },
{ path: "lib/x86_64/libapp.so", bytes: aotFixtureImage("b".repeat(32)) },
]);
const provider = createFlutterBuildAnalysisProvider();
const execute = vi.spyOn(provider, "execute");
const harness = await createApplicationMcpHarness({
serverOptions: { flutterAnalysis: provider },
});
onTestFinished(harness.close);
const { client, session } = harness;
const catalog = (await client.listTools()).tools;
const definition = catalog.find((tool) => tool.name === "inspect_dart_aot");
if (definition?.outputSchema === undefined)
throw new Error("Missing AOT output schema");
const outputSchema: Record<string, unknown> = definition.outputSchema;
const ajv = new Ajv2020({ strict: false, validateFormats: false });
expect(ajv.validateSchema(definition.inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
expect(
ajv.validate(
catalog.find((tool) => tool.name === "identify_flutter_build")!
.inputSchema,
{ path, detail: "summary" },
),
).toBe(false);
const reply = await client.callTool({
name: "inspect_dart_aot",
arguments: { path, abi: "x86_64", detail: "summary" },
});
expect(reply.isError).not.toBe(true);
expect(
ajv.validate(outputSchema, reply.structuredContent),
JSON.stringify(ajv.errors),
).toBe(true);
const receipt = parseEvidence(reply.structuredContent);
const view = dartAotSummaryViewResultSchema.parse(receipt.normalized_result);
const parent = session.evidenceById(view.parent_evidence_id);
if (parent === undefined)
throw new Error("Complete AOT source was not retained");
const report = flutterResultSchemas.inspect_dart_aot.parse(
parent.normalized_result,
);
expect(report.abi).toBe("x86_64");
expect(report.libapp.snapshot_hash).toBe("b".repeat(32));
expect(parent.parameters).toEqual({ path, abi: "x86_64" });
expect(execute).toHaveBeenLastCalledWith(
{ operation: "inspect_dart_aot", input: { path, abi: "x86_64" } },
expect.anything(),
);
expect(view.summary.libapp).toEqual(report.libapp);
expect(view.summary.target).toEqual(report.target);
expect(view.summary.coverage).toBe(report.coverage);
expect(receipt.evidence_id).not.toBe(parent.evidence_id);
expect(receipt.evidence_links).toEqual([parent.evidence_id]);
for (const detail of [undefined, "complete"]) {
const complete = parseEvidence(
(
await client.callTool({
name: "inspect_dart_aot",
arguments: {
path,
abi: "x86_64",
...(detail === undefined ? {} : { detail }),
},
})
).structuredContent,
);
expect(complete.operation).toBe("inspect_dart_aot");
expect(complete.normalized_result).toEqual(parent.normalized_result);
expect(complete.parameters).toEqual(parent.parameters);
}
const preferred = parseEvidence(
(await client.callTool({ name: "inspect_dart_aot", arguments: { path } }))
.structuredContent,
);
expect(
flutterResultSchemas.inspect_dart_aot.parse(preferred.normalized_result)
.abi,
).toBe("arm64-v8a");
const original = JSON.stringify(parent);
await unlink(path);
const calls = execute.mock.calls.length;
for (const collection of [
"package_uris",
"dart_uris",
"class_like_tokens",
] as const) {
const strings: string[] = [];
let offset = 0;
do {
const reply = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: {
kind: "retained-evidence",
evidence_id: parent.evidence_id,
},
view: { kind: "dart-aot", collection, offset, limit: 1 },
},
});
expect(reply.isError).not.toBe(true);
const page = analysisViewResultSchema.parse(
parseEvidence(reply.structuredContent).normalized_result,
);
if (page.kind !== "dart-aot") throw new Error("Wrong pool page kind");
strings.push(...page.items);
expect(page.libapp).toEqual(report.libapp);
expect(page.source_coverage).toBe(report.coverage);
expect(page.string_pool.coverage).toBe(report.string_pool.coverage);
offset =
page.coverage.next_offset ?? report.string_pool[collection].length;
} while (offset < report.string_pool[collection].length);
expect(strings).toEqual(report.string_pool[collection]);
}
expect(execute).toHaveBeenCalledTimes(calls);
expect(JSON.stringify(session.evidenceById(parent.evidence_id))).toBe(
original,
);
expect(
session
.exportEvidenceBundle()
.records.find((record) => record.evidence_id === parent.evidence_id),
).toEqual(parent);
const portable = inspectAnalysisView({
source: { kind: "inline", evidence: parent },
view: { kind: "summary" },
});
if (!portable.ok) throw portable.error;
expect(portable.value.normalized_result).toEqual(view);
}, 30000);
it("preserves null snapshot facts and pool lower bounds after exhaustion, rejecting malformed and conflicting identities", () => {
const report = {
target: { path: "/source.apk", bytes: 10, sha256: "a".repeat(64) },
abi: "arm64-v8a",
libapp: {
coverage: "partial",
bytes: 1,
sha256: "b".repeat(64),
snapshot_hash: null,
snapshot_hash_candidates: [],
snapshot_hash_sources: 0,
sections: [],
},
string_pool: {
coverage: "partial",
package_uris: ["package:opaque/a.dart"],
package_uri_count_at_least: 1000,
dart_uris: [],
dart_uri_count_at_least: 0,
class_like_tokens: ["incidental"],
class_like_token_count_at_least: 4000,
printable_run_count: 12,
},
coverage: "partial",
};
const evidence = (
result: JsonValue = report,
sha: string | null = "a".repeat(64),
) =>
createEvidence(
sha === null
? undefined
: { path: "/source.apk", sha256: sha, format: "apk" },
{ id: "flutter", name: "Flutter", version: null },
{
operation: "inspect_dart_aot",
parameters: {},
result,
limitations: ["Original uncertainty"],
},
);
for (const parent of [evidence(), evidence(report, null)]) {
const summary = inspectAnalysisView({
source: { kind: "inline", evidence: parent },
view: { kind: "summary" },
});
if (!summary.ok) throw summary.error;
const result = dartAotSummaryViewResultSchema.parse(
summary.value.normalized_result,
);
expect(result.summary.libapp.snapshot_hash).toBeNull();
expect(result.summary.string_pool.package_uri_count_at_least).toBe(1000);
expect(result.summary.string_pool.returned_counts.package_uris).toBe(1);
expect(result.limitations).toEqual(parent.limitations);
const page = inspectAnalysisView({
source: { kind: "inline", evidence: parent },
view: {
kind: "dart-aot",
collection: "package_uris",
offset: 0,
limit: 10,
},
});
if (!page.ok) throw page.error;
expect(page.value.normalized_result).toMatchObject({
kind: "dart-aot",
items: report.string_pool.package_uris,
source_coverage: "partial",
string_pool: { coverage: "partial", package_uri_count_at_least: 1000 },
coverage: { total: 1, exhausted: true },
});
}
expect(
inspectAnalysisView({
source: { kind: "inline", evidence: evidence(report, "c".repeat(64)) },
view: { kind: "summary" },
}),
).toMatchObject({ ok: false, error: { _tag: "EvidenceIntegrityError" } });
expect(
inspectAnalysisView({
source: {
kind: "inline",
evidence: evidence({
...report,
string_pool: {
...report.string_pool,
package_uri_count_at_least: -1,
},
}),
},
view: { kind: "summary" },
}),
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
expect(
inspectAnalysisView({
source: { kind: "inline", evidence: evidence() },
view: { kind: "android", facet: "manifest", offset: 0, limit: 1 },
}),
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
});
it("rejects unavailable retention, invalid delivery and cancellation before producer work", async () => {
const provider = createFlutterBuildAnalysisProvider();
onTestFinished(() => provider.close());
const execute = vi.spyOn(provider, "execute");
const service = new FlutterBuildAnalysisService(provider);
const retention = { recordEvidence: undefined, evidenceById: undefined };
expect(
await inspectDartAot(
service,
{ path: "/missing.apk", abi: "x86_64", detail: "summary" },
retention,
),
).toMatchObject({
ok: false,
error: { _tag: "AnalysisCapabilityUnavailableError" },
});
expect(
await inspectDartAot(
service,
{ path: "/missing.apk", detail: "other" },
retention,
),
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
expect(
await inspectDartAot(
service,
{ path: "/missing.apk", detail: "summary" },
retention,
{ signal: AbortSignal.abort() },
),
).toMatchObject({ ok: false, error: { _tag: "AnalysisCancelledError" } });
expect(execute).not.toHaveBeenCalled();
});
+46
View File
@@ -471,3 +471,49 @@ it("exposes the target-free static JavaScript application workflow", async () =>
const evidenceFor = (value: unknown) => {
return parseEvidence(value);
};
it("reports every unresolved Electron path without starting a provider", async () => {
const root = await createTestTempDirectory("rea-electron-invalid-paths-");
const capture = vi.fn();
const session = createTestBinarySession(() => {
throw new Error("must not start");
});
const server = createServer(
{ kind: "session", session },
{
electronActiveObservation: {
capture,
identity: () => ({ id: "test", name: "test", version: "1" }),
},
},
);
const client = new Client({ name: "electron-path-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server, session);
await server.connect(serverTransport);
await client.connect(clientTransport);
const fields = ["executable_path", "application_path", "application_root"];
const result = await client.callTool({
name: "capture_electron_scenario",
arguments: {
...Object.fromEntries(fields.map((field) => [field, join(root, field)])),
actions: [],
},
});
expect(result.isError).toBe(true);
expect(parseMcpToolError(result)).toMatchObject({
error: {
code: "invalid_request",
details: {
issues: fields.map((field) => ({
path: [field],
reason: "invalid_value",
message: expect.stringContaining("ENOENT"),
})),
},
},
});
expect(capture).not.toHaveBeenCalled();
await client.ping();
});
@@ -144,14 +144,26 @@ describe("enhanced MCP tools", () => {
);
expect(result).toEqual({
document: "fixture",
image_base: "0x1000",
segments: [
{ name: "__TEXT", start: "0x1000", end: "0x1800", length: 2048 },
{ name: "__DATA", start: "0x1800", end: "0x2000", length: 2048 },
{
name: "__TEXT",
start: "0x1000",
end: "0x1800",
length: 2048,
image_base: "0x1000",
},
{
name: "__DATA",
start: "0x1800",
end: "0x2000",
length: 2048,
image_base: "0x1000",
},
],
segment_count: 2,
procedure_count: 2,
string_count: 700,
image_base: "0x1000",
});
});
@@ -0,0 +1,249 @@
import { afterEach, describe, expect, it } from "vitest";
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
import { EnhancedTools } from "../../../src/application/EnhancedTools.js";
import { AnalysisOutputError } from "../../../src/domain/analysisErrorCore.js";
import { err, ok } from "../../../src/domain/result.js";
import { closeEnhancedToolResources, connect } from "./enhancedToolsHarness.js";
afterEach(closeEnhancedToolResources);
const PROVIDER = {
id: "fixture",
name: "Fixture analysis provider",
version: "1",
} as const;
type Coverage = boolean | undefined;
interface Behavior {
/** What the provider reports for the references of each match address. */
readonly coverage?: Readonly<Record<string, Coverage>>;
readonly limitations?: readonly string[];
/** Also report the first string match as a procedure match. */
readonly duplicateProcedure?: boolean;
/** Fail the references read of this address. */
readonly failXrefsOf?: string;
readonly calls?: string[];
}
const containing = (address: string) => ({
query_address: address,
found: false,
procedure: null,
reason: "not_in_procedure",
});
/**
* A provider with two string matches (0x10 and 0x11), each referenced from
* one address (0x20 and 0x21).
*/
const provider = (behavior: Behavior = {}): AnalysisOperationPort => ({
execute: async (name, arguments_) => {
const address = String(arguments_.address);
behavior.calls?.push(`${name}:${address}`);
switch (name) {
case "search_strings":
return ok(
createAnalysisExecution(
[
{ address: "0x10", value: "hello" },
{ address: "0x11", value: "hello again" },
],
PROVIDER,
),
);
case "search_procedures":
return ok(
createAnalysisExecution(
behavior.duplicateProcedure === true
? [{ address: "0x10", value: "hello" }]
: [],
PROVIDER,
),
);
case "xrefs": {
if (address === behavior.failXrefsOf)
return err(new AnalysisOutputError("xrefs", "provider failed"));
const reported = behavior.coverage?.[address];
return ok(
createAnalysisExecution(
[address === "0x10" ? "0x20" : "0x21"],
PROVIDER,
{
limitations: behavior.limitations ?? [],
...(reported === undefined
? {}
: { referencesTruncated: reported }),
},
),
);
}
case "resolve_containing_procedure":
return ok(createAnalysisExecution(containing(address), PROVIDER));
default:
throw new Error(`Unexpected operation: ${name}`);
}
},
});
const expectedTrace = (
residual: readonly string[],
extraMatches: readonly object[] = [],
) => ({
query: "hello",
search_mode: "literal",
matches: [
{ type: "string", address: "0x10", value: "hello" },
{ type: "string", address: "0x11", value: "hello again" },
...extraMatches,
],
references: [
{
target_address: "0x10",
source_address: "0x20",
containing_procedure: containing("0x20"),
},
{
target_address: "0x11",
source_address: "0x21",
containing_procedure: containing("0x21"),
},
...extraMatches.map(() => ({
target_address: "0x10",
source_address: "0x20",
containing_procedure: containing("0x20"),
})),
],
truncated: residual.length > 0,
residual_unknowns: residual,
});
const unknownFor = (address: string) =>
`References to ${address} were truncated by the provider; additional references may exist.`;
const trace = async (analysis: AnalysisOperationPort) => {
const client = await connect(analysis);
const result = await client.callTool({
name: "trace_feature",
arguments: { query: "hello" },
});
expect(result.isError).not.toBe(true);
return result.structuredContent as { normalized_result: unknown };
};
describe("trace_feature reference coverage", () => {
it("marks the trace truncated for the target whose references the provider capped", async () => {
const output = await trace(
provider({ coverage: { "0x10": true, "0x11": false } }),
);
expect(
output.normalized_result,
"the received references are kept and only the capped target is a residual unknown",
).toEqual(expectedTrace([unknownFor("0x10")]));
});
it("does not carry a truncation over to the next target that reports nothing", async () => {
const output = await trace(provider({ coverage: { "0x10": true } }));
expect(output.normalized_result).toEqual(
expectedTrace([unknownFor("0x10")]),
);
});
it("reports a capped target once when it is matched twice", async () => {
const output = await trace(
provider({ coverage: { "0x10": true }, duplicateProcedure: true }),
);
expect(output.normalized_result).toEqual(
expectedTrace(
[unknownFor("0x10")],
[{ type: "procedure", address: "0x10", value: "hello" }],
),
);
});
it("resolves the containing procedure of a repeated reference source once", async () => {
const calls: string[] = [];
const output = await trace(provider({ duplicateProcedure: true, calls }));
expect(
calls.filter((call) => call.startsWith("resolve_containing_procedure:")),
"the source 0x20 is referenced by two matches of the same address and resolved once",
).toEqual([
"resolve_containing_procedure:0x20",
"resolve_containing_procedure:0x21",
]);
expect(
output.normalized_result,
"every reference is still reported with its containing procedure",
).toEqual(
expectedTrace(
[],
[{ type: "procedure", address: "0x10", value: "hello" }],
),
);
});
it("keeps the trace complete when the provider explicitly reports no cap", async () => {
const output = await trace(
provider({ coverage: { "0x10": false, "0x11": false } }),
);
expect(output.normalized_result).toEqual(expectedTrace([]));
});
it("does not change the trace of a provider that reports no coverage", async () => {
const output = await trace(
provider({
limitations: ["Upstream xrefs_to capped results at 1000 references."],
}),
);
expect(
output.normalized_result,
"a limitation text alone never truncates, and an absent field keeps the previous result",
).toEqual(expectedTrace([]));
});
it("never exposes the coverage field in the tool output", async () => {
const output = await trace(
provider({ coverage: { "0x10": true, "0x11": false } }),
);
expect(JSON.stringify(output)).not.toMatch(
/referencesTruncated|references_truncated/,
);
});
it("fails the trace when a references read fails and reads nothing further", async () => {
const calls: string[] = [];
const result = await new EnhancedTools(
provider({ failXrefsOf: "0x10", calls }),
).execute("trace_feature", { query: "hello" });
expect(result.ok).toBe(false);
expect(
calls.filter((call) => call.startsWith("xrefs:")),
"the next target is not read after the failure",
).toEqual(["xrefs:0x10"]);
});
it("stops without reading references when the trace is cancelled", async () => {
const calls: string[] = [];
const controller = new AbortController();
controller.abort();
const result = await new EnhancedTools(provider({ calls })).execute(
"trace_feature",
{ query: "hello" },
controller.signal,
);
expect(result.ok).toBe(false);
expect(calls.filter((call) => call.startsWith("xrefs:"))).toEqual([]);
});
});
@@ -1,10 +1,20 @@
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { ok as resultOk } from "../../../src/domain/result.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it } from "vitest";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { observed } from "../../fixtures/analysisExecution.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { ANALYSIS_SNAPSHOT_TARGET } from "../../../src/domain/analysisSnapshot.fixture.js";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/domain/process/processCaptureExample.js";
import { PROCESS_PROVIDER } from "../../../src/domain/process/processEvidenceProvider.js";
import { createServer } from "../../../src/server/createServer.js";
it("returns the complete session Evidence bundle in the tool result", async () => {
@@ -44,3 +54,251 @@ it("returns the complete session Evidence bundle in the tool result", async () =
await Promise.allSettled([client.close(), server.close(), session.close()]);
}
});
it("rejects bundle field stripping at MCP import without changing retained evidence", async () => {
const root = await createTestTempDirectory("rea-evidence-bundle-mcp-");
const sourceSession = createBundleSourceSession();
const targetSession = createTestBinarySession(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(resultOk(null)),
}));
const source = await connectEvidenceMcp("bundle-source", sourceSession);
const target = await connectEvidenceMcp("bundle-target", targetSession);
const { client: sourceClient } = source;
const { client: targetClient } = target;
const bundlePath = join(root, "exported.json");
const targetExportPath = join(root, "round-trip.json");
try {
const { sourceJson, records, evidenceIndex } = await exportFixtureBundle(
sourceClient,
bundlePath,
);
const initial = structured(
await targetClient.callTool({
name: "get_evidence_bundle",
arguments: {},
}),
).result;
for (const [label, path] of unsupportedBundleFields(evidenceIndex)) {
const candidate = structuredClone(sourceJson);
setPath(candidate, path, "unsupported-metadata");
const malformedPath = join(root, `${label.replaceAll(" ", "-")}.json`);
await writeFile(malformedPath, JSON.stringify(candidate));
const rejected = await targetClient.callTool({
name: "import_evidence_bundle",
arguments: { path: malformedPath },
});
expect(parseMcpToolError(rejected), label).toMatchObject({
error: { code: "evidence_integrity_mismatch" },
});
expect(
structured(
await targetClient.callTool({
name: "get_evidence_bundle",
arguments: {},
}),
).result,
label,
).toEqual(initial);
}
const imported = await targetClient.callTool({
name: "import_evidence_bundle",
arguments: { path: bundlePath },
});
if (imported.isError === true)
throw new Error(JSON.stringify(parseMcpToolError(imported)));
await targetClient.callTool({
name: "export_evidence_bundle",
arguments: { path: targetExportPath },
});
expect(JSON.parse(await readFile(targetExportPath, "utf8"))).toEqual(
sourceJson,
);
const observedRecord = records[evidenceIndex]!;
expect(observedRecord.parameters).toEqual({ caller: { note: "preserve" } });
expect(observedRecord.normalized_result).toEqual({
producer: { extension: "preserve" },
});
expect(object(observedRecord.analysis_profile).parameters).toEqual({
loader: { mode: "full" },
});
} finally {
await Promise.allSettled([
sourceClient.close(),
source.server.close(),
sourceSession.close(),
targetClient.close(),
target.server.close(),
targetSession.close(),
]);
}
});
const createBundleSourceSession = () => {
const provider = { id: "fixture", name: "Fixture", version: "1" };
const evidence = createEvidence(ANALYSIS_SNAPSHOT_TARGET, provider, {
operation: "observe",
parameters: { caller: { note: "preserve" } },
result: { producer: { extension: "preserve" } },
analysisProfile: createAnalysisProfile(provider, {
loader: { mode: "full" },
}),
environment: {
id: "fixture-linux",
platform: "linux",
architecture: "x86_64",
isolation: "process",
},
locations: [{ kind: "address", address: "0x1000" }],
});
const session = createTestBinarySession(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(resultOk(null)),
}));
expect(session.recordEvidence(evidence).ok).toBe(true);
for (const extra of [
createEvidence(ANALYSIS_SNAPSHOT_TARGET, provider, {
operation: "controlled_replay",
parameters: {},
result: { completed: true },
authority: "controlled-replay",
}),
createEvidence(undefined, PROCESS_PROVIDER, {
predicateType: "rea.process-capture",
operation: "capture_process_scenario",
parameters: {},
result: jsonValueSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE),
confidence: "observed",
authority: "controlled-replay",
}),
])
expect(session.recordEvidence(extra).ok).toBe(true);
return session;
};
const exportFixtureBundle = async (
client: Client,
path: string,
): Promise<{
readonly sourceJson: unknown;
readonly records: Record<string, unknown>[];
readonly evidenceIndex: number;
}> => {
const unknown = await client.callTool({
name: "record_unknown",
arguments: {
question: "Does this remain unknown?",
severity: "medium",
domain: "bundle-format",
required_authority: null,
required_confidence: "derived",
required_environment: null,
recommended_probes: [{ operation: "observe", rationale: "Inspect it." }],
relationships: [],
},
});
expect(unknown.isError).not.toBe(true);
const exported = await client.callTool({
name: "export_evidence_bundle",
arguments: { path },
});
expect(exported.isError).not.toBe(true);
const sourceJson = JSON.parse(await readFile(path, "utf8")) as unknown;
const records = array(object(sourceJson).records).map(object);
const evidenceIndex = records.findIndex(
(record) => record.operation === "observe",
);
expect(evidenceIndex).toBeGreaterThanOrEqual(0);
return { sourceJson, records, evidenceIndex };
};
const unsupportedBundleFields = (
evidenceIndex: number,
): readonly [string, readonly (string | number)[]][] => [
["bundle envelope", ["schema_version"]],
["record provider", ["records", evidenceIndex, "provider", "future_field"]],
["provider manifest", ["providers", 0, "future_field"]],
["record subject", ["records", evidenceIndex, "subject", "future_field"]],
[
"subject digest",
["records", evidenceIndex, "subject", "digest", "future_field"],
],
["artifact manifest", ["artifacts", 0, "future_field"]],
[
"record environment",
["records", evidenceIndex, "environment", "future_field"],
],
["environment manifest", ["environments", 0, "future_field"]],
[
"source location",
["records", evidenceIndex, "locations", 0, "future_field"],
],
["scenario manifest", ["scenarios", 0, "future_field"]],
["capture manifest", ["captures", 0, "future_field"]],
[
"analysis profile",
["records", evidenceIndex, "analysis_profile", "future_field"],
],
[
"profile provider",
["records", evidenceIndex, "analysis_profile", "provider", "future_field"],
],
["unknown revision", ["unknowns", 0, "future_field"]],
["unknown probe", ["unknowns", 0, "recommended_probes", 0, "future_field"]],
];
const connectEvidenceMcp = async (
name: string,
session: ReturnType<typeof createTestBinarySession>,
) => {
const server = createServer({ kind: "session", session });
const client = new Client({ name, version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
return { client, server };
};
const object = (value: unknown): Record<string, unknown> => {
if (typeof value !== "object" || value === null || Array.isArray(value))
throw new Error("Expected object in exported Evidence bundle");
return value as Record<string, unknown>;
};
const array = (value: unknown): unknown[] => {
if (!Array.isArray(value))
throw new Error("Expected array in Evidence bundle");
return value;
};
const setPath = (
root: unknown,
path: readonly (string | number)[],
value: unknown,
): void => {
const [last, ...parents] = [...path].reverse();
if (last === undefined) throw new Error("Expected a nonempty bundle path");
const target = parents
.reverse()
.reduce<unknown>(
(current, segment) =>
typeof segment === "number"
? array(current)[segment]
: object(current)[segment],
root,
);
object(target)[String(last)] = value;
};
const structured = (result: Awaited<ReturnType<Client["callTool"]>>) => {
if (result.isError === true) throw parseMcpToolError(result);
if (
typeof result.structuredContent !== "object" ||
result.structuredContent === null
)
throw new Error("Missing structured MCP result");
return result.structuredContent as Record<string, unknown>;
};
@@ -0,0 +1,155 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it, onTestFinished, vi } from "vitest";
import { createEvidence } from "../../../src/domain/evidence.js";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import { OwnedFileHandle } from "../../../src/filesystem/OwnedFileHandle.js";
import { createServer } from "../../../src/server/createServer.js";
import {
createDeferred,
createTestBinarySession,
} from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const connectImportSession = async () => {
const root = await createTestTempDirectory("rea-mcp-import-lifecycle-");
const session = createTestBinarySession(() => {
throw new Error("Evidence import must not start a binary provider");
});
const server = createServer({ kind: "session", session });
const client = new Client({
name: "evidence-import-lifecycle",
version: "1",
});
const readCompleted = createDeferred<void>();
const releaseRead = createDeferred<void>();
const originalFileClose = OwnedFileHandle.prototype.close;
vi.spyOn(OwnedFileHandle.prototype, "close").mockImplementationOnce(
async function (this: OwnedFileHandle) {
await originalFileClose.call(this);
readCompleted.resolve();
await releaseRead.promise;
},
);
const closeStarted = createDeferred<void>();
const originalSessionClose = session.close.bind(session);
const events: string[] = [];
vi.spyOn(session, "close").mockImplementation((...args) => {
const closing = originalSessionClose(...args);
closeStarted.resolve();
return closing.then((result) => {
events.push("close");
return result;
});
});
const originalImport = session.importEvidenceBundle.bind(session);
vi.spyOn(session, "importEvidenceBundle").mockImplementation((bundle) => {
const imported = originalImport(bundle);
events.push("import");
return imported;
});
onTestFinished(async () => {
releaseRead.resolve();
vi.restoreAllMocks();
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const laterImportDispatched = createDeferred<void>();
let importsDispatched = 0;
const send = clientTransport.send.bind(clientTransport);
vi.spyOn(clientTransport, "send").mockImplementation(
async (message, ...args) => {
await send(message, ...args);
if (
"method" in message &&
message.method === "tools/call" &&
message.params?.name === "import_evidence_bundle"
) {
importsDispatched += 1;
if (importsDispatched === 2) laterImportDispatched.resolve();
}
},
);
await server.connect(serverTransport);
await client.connect(clientTransport);
const importBundle = async (operation: string) => {
const record = createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
{ operation, parameters: {}, result: { retained: operation } },
);
const path = join(root, `${operation}.json`);
await writeFile(path, JSON.stringify(createEvidenceBundle([record])));
return client.callTool({
name: "import_evidence_bundle",
arguments: { path },
});
};
return {
client,
session,
events,
importBundle,
readCompleted: readCompleted.promise,
closeStarted: closeStarted.promise,
laterImportDispatched: laterImportDispatched.promise,
releaseRead: () => releaseRead.resolve(),
};
};
it("drains a file import before close_binary clears the session", async () => {
const fixture = await connectImportSession();
const importing = fixture.importBundle("before_close");
await fixture.readCompleted;
const closing = fixture.client.callTool({
name: "close_binary",
arguments: {},
});
await fixture.closeStarted;
await fixture.client.ping();
fixture.releaseRead();
const [imported, closed] = await Promise.all([importing, closing]);
expect(imported.isError, JSON.stringify(imported)).not.toBe(true);
expect(imported.structuredContent).toMatchObject({
result: { imported: 1, unknowns_added: 0, total: 1 },
});
expect(closed.isError, JSON.stringify(closed)).not.toBe(true);
expect(fixture.events).toEqual(["import", "close"]);
expect(fixture.session.exportEvidenceBundle().records).toEqual([]);
await fixture.client.ping();
});
it("admits a later import after close_binary without retaining the earlier bundle", async () => {
const fixture = await connectImportSession();
const earlier = fixture.importBundle("before_close");
await fixture.readCompleted;
const closing = fixture.client.callTool({
name: "close_binary",
arguments: {},
});
await fixture.closeStarted;
const later = fixture.importBundle("after_close");
await fixture.laterImportDispatched;
await fixture.client.ping();
fixture.releaseRead();
const results = await Promise.all([earlier, closing, later]);
for (const result of results)
expect(result.isError, JSON.stringify(result)).not.toBe(true);
expect(results[2]?.structuredContent).toMatchObject({
result: { imported: 1, unknowns_added: 0, total: 1 },
});
expect(fixture.events).toEqual(["import", "close", "import"]);
expect(
fixture.session
.exportEvidenceBundle()
.records.map((record) => record.operation),
).toEqual(["after_close"]);
await fixture.client.ping();
});
@@ -107,6 +107,30 @@ it("advertises exact valid schemas and records inline EVM interface evidence wit
).toBe(true);
});
it("rejects an EVM provider response with a non-file subject before recording Evidence", async () => {
const value = evmInterfaceFixture();
const execution = evmInterfaceExecution(value);
const malformed = {
...execution,
subject: { ...execution.subject, format: "elf" },
} as unknown as typeof execution;
const harness = await createApplicationMcpHarness({
serverOptions: {
evmInterface: new EvmInterfaceService({
inspect: () => Promise.resolve(ok(malformed)),
}),
},
});
onTestFinished(harness.close);
const before = harness.session.exportEvidenceBundle().records.length;
const response = await harness.client.callTool({
name: "inspect_evm_interface",
arguments: { path: value.artifact.path, encoding: "hex" },
});
expect(parseMcpToolError(response).error.code).toBe("unreadable_output");
expect(harness.session.exportEvidenceBundle().records).toHaveLength(before);
});
it.each(["unavailable", "incompatible-output"])(
"preserves a healthy WASM peer and explicit EVM failure: %s",
async (scenario) => {
+3 -1
View File
@@ -46,6 +46,8 @@ it("retains terminal-call qualifications across function views and snapshot repl
limitations: [limitation],
},
],
["procedure_callees", ["0x402000"]],
["procedure_callers", [identity.address]],
["analyze_function", jsonValueSchema.parse(dossier)],
]);
const harness = await connectGhidraMcp(
@@ -81,7 +83,7 @@ it("retains terminal-call qualifications across function views and snapshot repl
});
expect(evidence.limitations, name).toContain(limitation);
expect(evidence.analysis_profile?.parameters).toMatchObject({
function_boundary_observations: "ghidra-terminal-call-limitations-v1",
function_boundary_observations: "ghidra-terminal-call-limitations-v2",
});
const replay = await harness.session.execute(name, evidence.parameters);
if (!replay.ok) throw replay.error;
+3 -1
View File
@@ -95,7 +95,7 @@ export const sessionEvidence = (session: BinarySession, value: unknown) => {
const installationHost = (): GhidraInstallationHost => ({
platform: "linux",
architecture: "x64",
readText: () => "application.version=12.1.4\n",
readText: () => "application.version=12.1.4\napplication.java.min=21\n",
executable: () => true,
probeJava: () => ({
version: "21.0.11",
@@ -263,6 +263,8 @@ const resultFor = (
const functionObservationOperations: ReadonlySet<GhidraOperation> = new Set([
"analyze_function",
"procedure_assembly",
"procedure_callees",
"procedure_callers",
"procedure_info",
"procedure_pseudo_code",
"read_function_instructions",
+1 -1
View File
@@ -99,7 +99,7 @@ class FixtureLauncher implements GhidraLauncher {
const installationHost: GhidraInstallationHost = {
platform: "linux",
architecture: "x64",
readText: () => "application.version=12.1.4\n",
readText: () => "application.version=12.1.4\napplication.java.min=21\n",
executable: () => true,
probeJava: () => ({
version: "21.0.11",
@@ -0,0 +1,121 @@
import { afterEach, expect, it } from "vitest";
import { Ajv2020 } from "ajv/dist/2020.js";
import type { AnySchemaObject } from "ajv";
import {
closeEnhancedToolResources,
connect,
jsonResult,
} from "./enhancedToolsHarness.js";
import { observed as ok } from "../../fixtures/analysisExecution.js";
import type { SegmentSummary } from "../../../src/domain/hopperValues.js";
afterEach(closeEnhancedToolResources);
const segment = {
name: ".text",
start: "0x101000",
end: "0x101100",
readable: true,
writable: false,
executable: true,
image_base: "0x100000",
address_space: "ram",
};
const overviewClient = (segments: SegmentSummary[]) =>
connect({
execute: (name) => {
switch (name) {
case "current_document":
return Promise.resolve(ok("fixture"));
case "list_documents":
return Promise.resolve(ok(["fixture"]));
case "list_segments":
return Promise.resolve(ok(segments));
case "list_procedures":
return Promise.resolve(ok([{ address: "0x101013", value: "entry" }]));
case "list_strings":
return Promise.resolve(ok([]));
default:
throw new Error(`Unexpected operation: ${name}`);
}
},
});
it("preserves observed coordinates and main's optional-string output contract after SDK conversion", async () => {
const client = await overviewClient([segment]);
const schema = (await client.listTools()).tools.find(
({ name }) => name === "binary_overview",
)?.outputSchema;
if (schema === undefined) throw new Error("Missing overview output schema");
const validate = new Ajv2020({ strict: false }).compile(
schema as AnySchemaObject,
);
const response = await client.callTool({
name: "binary_overview",
arguments: {},
});
expect(validate(response.structuredContent)).toBe(true);
expect(jsonResult(response)).toMatchObject({
image_base: "0x100000",
segments: [
{ start: "0x101000", image_base: "0x100000", address_space: "ram" },
],
});
const absent = JSON.parse(JSON.stringify(response.structuredContent));
delete absent.normalized_result.image_base;
expect(validate(absent)).toBe(true);
absent.normalized_result.image_base = null;
expect(validate(absent)).toBe(false);
});
it("omits unreported bases without inventing zero and preserves explicit zero", async () => {
const { image_base: _base, ...unreported } = segment;
const client = await overviewClient([unreported]);
expect(
jsonResult(
await client.callTool({ name: "binary_overview", arguments: {} }),
),
).not.toHaveProperty("image_base");
const zero = await overviewClient([{ ...segment, image_base: "0x0" }]);
expect(
jsonResult(await zero.callTool({ name: "binary_overview", arguments: {} })),
).toMatchObject({ image_base: "0x0" });
});
it("keeps a partially reported base unknown while retaining the reported segment observation", async () => {
const { image_base: _base, ...unreported } = segment;
const client = await overviewClient([
segment,
{ ...unreported, name: ".data" },
]);
const result = jsonResult(
await client.callTool({ name: "binary_overview", arguments: {} }),
);
expect(result).not.toHaveProperty("image_base");
expect(result).toMatchObject({
segments: [{ image_base: "0x100000" }, { name: ".data" }],
});
});
it("retains all conflicting observations after repeated early bases without selecting one", async () => {
const { address_space: _space, ...unreported } = segment;
const client = await overviewClient([
...Array.from({ length: 40 }, () => unreported),
{
...segment,
name: ".data",
start: "other%20space:0x201000",
end: "other%20space:0x201100",
image_base: "0x200000",
address_space: "other space",
},
]);
const result = jsonResult(
await client.callTool({ name: "binary_overview", arguments: {} }),
);
expect(result).not.toHaveProperty("image_base");
expect(result).toHaveProperty("segments.length", 41);
expect(result).toHaveProperty("segments.40.image_base", "0x200000");
expect(result).toHaveProperty("segments.40.address_space", "other space");
expect(result).not.toHaveProperty("segments.0.address_space");
});
@@ -0,0 +1,216 @@
import { silentLogger } from "../../../src/logger.js";
import { copyFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect } from "vitest";
import { z } from "zod";
import { createBinarySession } from "../../../src/composition/binary.js";
import { parseConfig } from "../../../src/config/parseConfig.js";
import { inspectMachoSchema } from "../../../src/domain/native/nativeInspection.js";
import { createServer } from "../../../src/server/createServer.js";
import { thinMach } from "../../../src/domain/binaryTarget.fixture.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { observed } from "../../fixtures/analysisExecution.js";
import { ok } from "../../../src/domain/result.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { mcpTest } from "../../support/mcp/mcpFixture.js";
const evidenceOf = <Schema extends z.ZodType>(schema: Schema) =>
z.object({
evidence_id: z.string(),
parameters: z.record(z.string(), z.unknown()),
normalized_result: schema,
});
const countSchema = z.object({
returned: z.number(),
total: z.number().nullable(),
exhaustive: z.boolean(),
});
const summarySchema = z.object({
kind: z.literal("summary"),
parent_evidence_id: z.string(),
summary: z.object({
uuid: z.string().nullable(),
collections: z.record(z.string(), countSchema),
provenance_count: z.number(),
}),
});
const pageSchema = z.object({
kind: z.literal("macho"),
item: z.array(z.unknown()),
coverage: z.object({ next_offset: z.number().nullable() }),
});
describe.skipIf(process.platform !== "darwin")(
"Mach-O summary delivery through MCP",
() => {
mcpTest(
"retains complete inspect_macho Evidence and pages its exact rows",
async ({ mcp, onTestFinished }) => {
const target = join(
await createTestTempDirectory("rea-macho-summary-mcp-"),
"ls",
);
await copyFile("/bin/ls", target);
const configured = parseConfig({ REA_ANALYSIS_PROVIDER: "auto" });
if (!configured.ok) throw configured.error;
const session = createBinarySession(
configured.value,
silentLogger,
process.env,
);
onTestFinished(async () => {
await session.close();
});
const client = await mcp.connect(
createServer({ kind: "session", session }),
);
const opened = await client.callTool({
name: "open_binary",
arguments: { path: target },
});
expect(opened.isError, JSON.stringify(opened.content)).not.toBe(true);
const complete = await client.callTool({
name: "inspect_macho",
arguments: {},
});
expect(complete.isError, JSON.stringify(complete.content)).not.toBe(
true,
);
const full = evidenceOf(inspectMachoSchema).parse(
complete.structuredContent,
);
// Omitted detail keeps the default Evidence parameters unchanged.
expect(full.parameters).toEqual({});
const summarized = await client.callTool({
name: "inspect_macho",
arguments: { detail: "summary" },
});
expect(summarized.isError, JSON.stringify(summarized.content)).not.toBe(
true,
);
const summary = evidenceOf(summarySchema).parse(
summarized.structuredContent,
).normalized_result;
// Delivery detail never reaches the tools or the source Evidence ID.
expect(summary.parent_evidence_id).toBe(full.evidence_id);
const report = full.normalized_result;
expect(summary.summary.uuid).toBe(report.uuid);
expect(summary.summary.provenance_count).toBe(report.provenance.length);
for (const name of ["imports", "exports", "dependencies"] as const)
expect(summary.summary.collections[name]).toEqual({
returned: report[name].items.length,
total: report[name].total,
exhaustive: report[name].exhaustive,
});
expect(JSON.stringify(summarized.structuredContent)).not.toContain(
report.imports.items[0]?.name ?? "_",
);
// Every facet must reassemble the unparsed complete rows exactly.
const raw = z
.object({ normalized_result: z.record(z.string(), z.unknown()) })
.parse(complete.structuredContent).normalized_result;
const facets = [
"entrypoints",
"architectures",
"build_metadata",
"load_commands",
"dependencies",
"imports",
"exports",
"segments",
"provenance",
] as const;
for (const facet of facets) {
const rows: unknown[] = [];
let offset: number | null = 0;
while (offset !== null) {
const paged = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: {
kind: "retained-evidence",
evidence_id: summary.parent_evidence_id,
},
view: { kind: "macho", facet, offset, limit: 16 },
},
});
expect(paged.isError, JSON.stringify(paged.content)).not.toBe(true);
const page = evidenceOf(pageSchema).parse(
paged.structuredContent,
).normalized_result;
rows.push(...page.item);
offset = page.coverage.next_offset;
}
expect(rows, facet).toEqual(
facet === "provenance"
? raw.provenance
: z.object({ items: z.array(z.unknown()) }).parse(raw[facet])
.items,
);
}
const wrongKind = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: {
kind: "retained-evidence",
evidence_id: summary.parent_evidence_id,
},
view: { kind: "wasm", facet: "exports" },
},
});
expect(wrongKind.isError).toBe(true);
expect(JSON.stringify(wrongKind.content)).toContain(
"Mach-O inspection supports summary and macho views.",
);
},
);
},
);
mcpTest(
"refuses summary delivery before analysis when the server retains no Evidence",
async ({ mcp, onTestFinished }) => {
const target = join(
await createTestTempDirectory("rea-summary-preflight-"),
"tool",
);
await writeFile(target, thinMach(0xfeedfacf, 0x0100000c));
const executed: string[] = [];
const session = createTestBinarySession(() => ({
execute: (operation) => {
executed.push(operation);
return Promise.resolve(observed(null));
},
close: () => Promise.resolve(ok(null)),
}));
onTestFinished(async () => {
await session.close();
});
const opened = await session.open(target);
if (!opened.ok) throw opened.error;
const client = await mcp.connect(
createServer({ kind: "fixed", analysis: session }),
);
const refused = [];
for (const name of ["inspect_macho", "inspect_artifact"])
refused.push(
await client.callTool({ name, arguments: { detail: "summary" } }),
);
// Neither analysis ran only to be discarded by the delivery refusal.
expect(executed.filter((operation) => operation !== "health")).toEqual([]);
for (const result of refused)
expect(parseMcpToolError(result)).toMatchObject({
error: {
code: "capability_unavailable",
message: expect.stringContaining("does not retain Evidence"),
},
});
},
);
+52 -35
View File
@@ -8,42 +8,53 @@ import { Ajv2020 } from "ajv/dist/2020.js";
import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
it("advertises valid target-free packet capture schemas and actionable missing-tool diagnostics", async () => {
const harness = await createApplicationMcpHarness({
serverOptions: { environment: {} },
});
onTestFinished(harness.close);
const tool = (await harness.client.listTools()).tools.find(
({ name }) => name === "inspect_packet_capture",
);
if (tool?.outputSchema === undefined) throw new Error("Capture tool missing");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = tool.inputSchema;
const outputSchema: Record<string, unknown> = tool.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
const input = {
path:
process.platform === "win32" ? "C:\\recording.pcap" : "/recording.pcap",
fields: ["ip.addr"],
};
expect(ajv.validate(inputSchema, input)).toBe(true);
expect(ajv.validate(inputSchema, { ...input, interface: "lo0" })).toBe(false);
const result = await harness.client.callTool({
name: tool.name,
arguments: input,
});
expect(parseMcpToolError(result)).toMatchObject({
error: {
code: "capability_unavailable",
details: {
operation: tool.name,
reason: expect.stringContaining("REA_TSHARK_COMMAND"),
it.each(["inspect_packet_capture", "inspect_packet_fields"])(
"advertises valid target-free schemas and missing-tool diagnostics: %s",
async (name) => {
const harness = await createApplicationMcpHarness({
serverOptions: { environment: {} },
});
onTestFinished(harness.close);
const tool = (await harness.client.listTools()).tools.find(
(tool) => tool.name === name,
);
if (tool?.outputSchema === undefined)
throw new Error("Capture tool missing");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = tool.inputSchema;
const outputSchema: Record<string, unknown> = tool.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
const input =
name === "inspect_packet_fields"
? { query: "usb" }
: {
path:
process.platform === "win32"
? "C:\\recording.pcap"
: "/recording.pcap",
fields: ["ip.addr"],
};
expect(ajv.validate(inputSchema, input)).toBe(true);
expect(ajv.validate(inputSchema, { ...input, interface: "lo0" })).toBe(
false,
);
const result = await harness.client.callTool({
name: tool.name,
arguments: input,
});
expect(parseMcpToolError(result)).toMatchObject({
error: {
code: "capability_unavailable",
details: {
operation: tool.name,
reason: expect.stringContaining("REA_TSHARK_COMMAND"),
},
},
},
});
await harness.client.ping();
});
});
await harness.client.ping();
},
);
it.each(["cancelled", "cleanup"])(
"retains completed Evidence after %s failure",
@@ -78,6 +89,9 @@ it.each(["cancelled", "cleanup"])(
},
);
const packetCapture = new PacketCaptureService({
inspectFields: async () => {
throw new Error("Unexpected field discovery call");
},
inspect: async () => err(failure),
close: async () => {},
});
@@ -120,6 +134,9 @@ it.each(["cancelled", "cleanup"])(
it("rejects oversized selector expansion through the MCP boundary before invoking the provider", async () => {
let calls = 0;
const packetCapture = new PacketCaptureService({
inspectFields: async () => {
throw new Error("Unexpected field discovery call");
},
inspect: async () => {
calls++;
return err(new AnalysisCancelledError("inspect_packet_capture"));
+118
View File
@@ -0,0 +1,118 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it, onTestFinished } from "vitest";
import type { PcapAnalysisPort } from "../../../src/application/pcap/PcapAnalysisPort.js";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
import { assertAdvertisedMcpContracts } from "./mcpContractHarness.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { ok } from "../../../src/domain/result.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
const identity = { id: "pcap", name: "Packet capture analysis", version: null };
const clientIdentity = {
tshark_command: "/usr/bin/tshark",
tshark_source: "path",
tshark_version: "TShark (Wireshark) 4.6.6",
capinfos_command: "/usr/bin/capinfos",
capinfos_source: "path",
capinfos_version: "Capinfos (Wireshark) 4.6.6",
};
it("advertises exact valid pcap schemas and records inline evidence through MCP", async () => {
const provider: PcapAnalysisPort = {
async inspectAvailability() {
return { status: "available", code: null, reason: null, diagnostics: {} };
},
async close() {},
async execute(request) {
if (request.operation === "inspect_pcap_client")
return ok(
createAnalysisExecution({ client: clientIdentity }, identity),
);
return ok(
createAnalysisExecution(
{
client: clientIdentity,
target: {
path: "/captures/session.pcap",
bytes: 23279,
sha256: "a".repeat(64),
},
file_type: "Wireshark/tcpdump/... - pcap",
encapsulation: "Linux cooked-mode capture v2",
packet_count: 50,
capture_start: "2026-10-11 14:13:40.608505",
capture_end: "2026-10-11 14:13:40.981978",
capture_duration_seconds: 0.373473,
snapshot_length: 262144,
endpoints: [
{ address: "192.168.1.100", port: null, packet_count: 30 },
{ address: "8.8.8.8", port: 53, packet_count: 5 },
],
endpoint_count: 2,
dns_queries: [
{
query: "example.com",
response_addresses: ["93.184.216.34"],
response_address_count: 1,
},
],
dns_query_count: 1,
tls_sni_values: ["example.com"],
tls_sni_count: 1,
protocol_distribution: [
{ protocol: "ip:tcp:tls", packet_count: 25 },
{ protocol: "ip:udp:dns", packet_count: 5 },
],
protocol_count: 2,
http_request_uris: ["http://example.com/api"],
http_request_uri_count: 1,
http_uri_redaction_count: 0,
unattributed_dns_addresses: [],
unattributed_dns_address_count: 0,
unattributed_dns_packet_count: 0,
coverage: "complete",
},
identity,
),
);
},
};
const session = createTestBinarySession(() => {
throw new Error("deep provider must not start");
});
const server = createServer(
{ kind: "session", session },
{ pcapAnalysis: provider },
);
onTestFinished(() => server.close());
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
const client = new Client({ name: "pcap-boundary", version: "0.0.0" });
onTestFinished(() => client.close());
await client.connect(clientTransport);
const { tools } = await client.listTools();
assertAdvertisedMcpContracts(
["inspect_pcap_client", "inspect_pcap_capture"],
tools,
);
const inspected = await client.callTool({
name: "inspect_pcap_capture",
arguments: { path: "/captures/session.pcap" },
});
expect(inspected.isError).not.toBe(true);
const text = (inspected.content as { readonly text?: string }[])
.map((part) => part.text ?? "")
.join("");
const evidence = parseEvidence(JSON.parse(text));
expect(evidence.normalized_result).toMatchObject({
packet_count: 50,
tls_sni_values: ["example.com"],
coverage: "complete",
});
});
@@ -252,6 +252,56 @@ it("reports CLI trace specification issues like the MCP trace_spec input", async
});
});
it("rejects a deep trace cycle as an input error through CLI and MCP", async () => {
const events = Array.from({ length: 6000 }, (_, index) => ({
id: `e${String(index)}`,
source: "lifecycle",
exact: { marker: index },
}));
const trace = {
events,
language: {
kind: "partial_order",
happens_before: events.map((event, index) => ({
before: event.id,
after: events[(index + 1) % events.length]!.id,
})),
not_before: events.map((event, index) => ({
event: event.id,
anchor: events[(index + 1) % events.length]!.id,
})),
unordered_groups: [{ events: events.map(({ id }) => id) }],
},
};
const issue = {
path: ["trace_spec", "language"],
message: "happens-before graph must be acyclic",
};
const capture = captureEvidence("left");
const root = await createTestTempDirectory("rea-process-trace-cycle-");
const capturePath = join(root, "capture.json");
const specPath = join(root, "spec.json");
await writeFile(capturePath, JSON.stringify(capture));
await writeFile(specPath, JSON.stringify(trace));
expect(
await compareProcessEvidenceFiles(capturePath, capturePath, specPath),
).toMatchObject({
code: "invalid_request",
details: { issues: [issue] },
});
const client = await connect();
const response = await client.callTool({
name: "compare_process_captures",
arguments: { left: capture, right: capture, trace_spec: trace },
});
expect(response.isError).toBe(true);
expect(response.content).toEqual([
{ type: "text", text: expect.stringContaining(issue.message) },
]);
await client.ping();
});
it("names the side and constraint when Evidence is not a usable capture", async () => {
const client = await connect();
const capture = captureEvidence("right");
@@ -309,7 +309,9 @@ it("separately rejects a tampered digest before admission to any consumer or ses
};
const digestMismatch = /semantic identifier does not match/u;
expect(() => parseEvidence(tampered)).toThrow(digestMismatch);
expect(() => findChangedBehavior([tampered])).toThrow(digestMismatch);
expect(() => findChangedBehavior({ comparisons: [tampered] })).toThrow(
digestMismatch,
);
expect(() => correlateStaticAndRuntime(correlationInput(tampered))).toThrow(
digestMismatch,
);
@@ -336,6 +338,19 @@ it("separately rejects a tampered digest before admission to any consumer or ses
}
});
it("maps malformed changed-behavior Evidence to an invalid request before closure lookup", async () => {
const { client, comparison } = await connectedComparison();
const malformed = { ...comparison, evidence_links: undefined } as unknown;
const response = await client.callTool({
name: "find_changed_behavior",
arguments: { comparisons: [malformed] },
});
expect(response.isError).toBe(true);
expect(parseMcpToolError(response)).toMatchObject({
error: { code: "invalid_request" },
});
});
it("keeps withheld ownership unknown through CLI and MCP comparison", async () => {
const { client, right } = await connectedComparison();
const left = captureEvidence("left", {
@@ -9,76 +9,16 @@ import { createTestBinarySession } from "../../fixtures/binarySession.js";
import type { AnalysisClient } from "../../../src/application/AnalysisProvider.js";
import { compareProcessEvidenceFiles } from "../../../src/application/process/ProcessCli.js";
import { PROCESS_PROVIDER } from "../../../src/domain/process/processEvidenceProvider.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/domain/process/processCaptureExample.js";
import { processTraceCaptureFixture } from "../../../src/domain/process/processCapture.fixture.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
import type { ProcessTraceSpecification } from "../../../src/domain/process/processTraceSpecification.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed as ok } from "../../fixtures/analysisExecution.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const resources: Array<{ close(): Promise<void> }> = [];
const temporaryRoots: string[] = [];
const beforeCheckpoint = {
name: "before",
at_ms: 0,
files: [],
effects: [],
truncated: false,
};
const afterCheckpoint = {
name: "after_settlement",
at_ms: 50,
files: [],
effects: [],
truncated: false,
};
const capture = {
...EMPTY_PROCESS_CAPTURE_EXAMPLE,
event_journal: [
{ capture_order: 0, collection: "filesystem_checkpoints", index: 0 },
{ capture_order: 1, collection: "lifecycle", index: 0 },
{ capture_order: 2, collection: "lifecycle", index: 1 },
{ capture_order: 3, collection: "filesystem_checkpoints", index: 1 },
],
} as const;
const traceSpecification: ProcessTraceSpecification = {
events: [
{
id: "before",
source: "filesystem",
exact: beforeCheckpoint,
cardinality: { kind: "required" },
},
{
id: "exit",
source: "lifecycle",
exact: { event: "exit", ...capture.exit },
cardinality: { kind: "required" },
},
{
id: "settlement",
source: "lifecycle",
exact: { event: "settlement", ...capture.settlement },
cardinality: { kind: "required" },
},
{
id: "after",
source: "filesystem",
exact: afterCheckpoint,
cardinality: { kind: "required" },
},
],
language: {
kind: "finite_traces",
variants: [
{
id: "normal",
trace: ["before", "exit", "settlement", "after"],
},
],
},
};
const { capture, traceSpecification } = processTraceCaptureFixture();
const captureEvidence = (side: "left" | "right") =>
createEvidence(undefined, PROCESS_PROVIDER, {
+208 -23
View File
@@ -1,4 +1,4 @@
import { writeFile } from "node:fs/promises";
import { mkdir, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
@@ -10,7 +10,8 @@ import { createServer } from "../../../src/server/createServer.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import type { AnalysisProvider } from "../../../src/application/AnalysisProvider.js";
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
import { ok } from "../../../src/domain/result.js";
import { ProviderAdapterError } from "../../../src/domain/providerAdapterError.js";
import { err, ok } from "../../../src/domain/result.js";
import { observed } from "../../fixtures/analysisExecution.js";
import {
createCacheProvider,
@@ -18,6 +19,7 @@ import {
} from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { silentLogger } from "../../../src/logger.js";
import { GHIDRA_PROVIDER_IDENTITY } from "../../../src/ghidra/GhidraProviderCapabilities.js";
import type { CallToolResult } from "@modelcontextprotocol/server";
const connect = async (
@@ -50,29 +52,97 @@ const structured = (result: CallToolResult): Record<string, unknown> => {
return z.record(z.string(), z.unknown()).parse(result.structuredContent);
};
it("opens a headerless image when architecture and entry are supplied", async () => {
const root = await createTestTempDirectory("rea-raw-mcp-");
const path = join(root, "ecu.bin");
await writeFile(path, Buffer.from("1eff2fe1", "hex"));
const { client } = await connect();
const opened = await client.callTool({
name: "open_binary",
arguments: {
const withGhidraFixtureIdentity = (
provider: AnalysisProvider,
): AnalysisProvider => {
const identity = { ...GHIDRA_PROVIDER_IDENTITY, version: "12.1.4" };
const profile = createAnalysisProfile(identity, { fixture: true });
return {
...provider,
identity: () => identity,
capabilities: () =>
provider.capabilities().map((capability) => ({
...capability,
provider: identity,
})),
resolveAnalysisProfile: () => Promise.resolve(ok({ profile })),
createClient: (target, _profile, context) => {
const client = provider.createClient(target, profile, context);
return {
...client,
execute: async (operation, parameters, options) => {
const result = await client.execute(operation, parameters, options);
return result.ok
? ok({
...result.value,
provider: identity,
analysisProfile: profile,
})
: result;
},
};
},
};
};
it("keeps 6502 out of detected lifecycle output contracts", () => {
const schema = toolContract("open_binary").outputSchema;
const result = {
path: "/fixture/image.bin",
kind: "executable",
sha256: "a".repeat(64),
architecture: "6502",
};
expect(
schema.safeParse({ result: { ...result, format: "pe" } }).success,
).toBe(false);
expect(
schema.safeParse({
result: { ...result, format: "raw-binary", entry_point: "0x8001" },
}).success,
).toBe(true);
const validateAdvertised = new Ajv2020({ strict: false }).compile(
z.toJSONSchema(schema),
);
expect(validateAdvertised({ result: { ...result, format: "pe" } })).toBe(
false,
);
expect(
validateAdvertised({
result: { ...result, format: "raw-binary", entry_point: "0x8001" },
}),
).toBe(true);
});
it.each([
["arm", "0x08000000", "0x8000000", "1eff2fe1"],
["6502", "0x008001", "0x8001", "a92a60"],
])(
"opens a headerless %s image when architecture and entry are supplied",
async (architecture, entryPoint, canonical, bytes) => {
const root = await createTestTempDirectory("rea-raw-mcp-");
const path = join(root, "ecu.bin");
await writeFile(path, Buffer.from(bytes, "hex"));
const { client } = await connect();
const opened = await client.callTool({
name: "open_binary",
arguments: {
path,
format: "raw-binary",
architecture,
entry_point: entryPoint,
},
});
expect(opened.isError).not.toBe(true);
expect(structured(opened).result).toMatchObject({
path,
format: "raw-binary",
architecture: "arm",
entry_point: "0x08000000",
},
});
expect(opened.isError).not.toBe(true);
expect(structured(opened).result).toMatchObject({
path,
format: "raw-binary",
kind: "executable",
architecture: "arm",
entry_point: "0x8000000",
});
});
kind: "executable",
architecture,
entry_point: canonical,
});
},
);
it("rejects an unaligned AArch64 entry before selecting or starting a provider", async () => {
const root = await createTestTempDirectory("rea-raw-mcp-alignment-");
@@ -217,3 +287,118 @@ it("reuses a canonical raw entry and replaces the session when the entry changes
expect(created).toEqual(["0x8000000", "0x9000000"]);
expect(closed).toEqual(["0x8000000"]);
});
it.skipIf(process.platform !== "win32")(
"does not replay a saved read after switching to a Windows junction",
async () => {
const root = await createTestTempDirectory("rea-raw-mcp-linked-reopen-");
const actual = join(root, "actual");
const linked = join(root, "linked");
await mkdir(actual);
const path = join(actual, "image.bin");
await writeFile(path, Buffer.from("a92a60", "hex"));
await symlink(actual, linked, "junction");
const created: string[] = [];
const executed: string[] = [];
const fixture = createCacheProvider([]);
const { client } = await connect(
withGhidraFixtureIdentity({
...fixture,
createClient: (target) => {
created.push(target.sourcePath ?? target.path);
return {
execute: (operation) => {
if (operation === "address_name")
executed.push(target.sourcePath ?? target.path);
if (
operation === "address_name" &&
target.sourcePath === join(linked, "image.bin")
)
return Promise.resolve(
err(new ProviderAdapterError("fixture", operation)),
);
return Promise.resolve(
observed(operation === "address_name" ? "entry" : null),
);
},
close: () => Promise.resolve(ok(null)),
};
},
}),
);
const linkedPath = join(linked, "image.bin");
for (const requested of [path, linkedPath]) {
const opened = await client.callTool({
name: "open_binary",
arguments: {
path: requested,
format: "raw-binary",
architecture: "6502",
entry_point: "0x8001",
},
});
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
const address = await client.callTool({
name: "address_name",
arguments: { address: "0x8001", document: "image.bin" },
});
expect(address.isError === true, JSON.stringify(address)).toBe(
requested === linkedPath,
);
}
expect(created).toEqual([path, linkedPath]);
expect(executed).toEqual([path, linkedPath]);
},
);
it.skipIf(process.platform !== "win32")(
"reuses saved reads after a fixture admits a noncanonical Windows path",
async () => {
const root = await createTestTempDirectory("rea-raw-mcp-admitted-path-");
const actual = join(root, "actual");
const linked = join(root, "linked");
await mkdir(actual);
const path = join(actual, "image.bin");
await writeFile(path, Buffer.from("a92a60", "hex"));
await symlink(actual, linked, "junction");
const calls: string[] = [];
const fixture = createCacheProvider([]);
// This fixture accepts the alias to isolate cache behavior after admission.
// The real Ghidra verifier checks that a junction itself is rejected.
const { client, session } = await connect(
withGhidraFixtureIdentity({
...fixture,
createClient: () => ({
execute: (operation) => {
if (operation === "address_name") calls.push(operation);
return Promise.resolve(
observed(operation === "health" ? null : "entry"),
);
},
close: () => Promise.resolve(ok(null)),
}),
}),
);
const linkedPath = join(linked, "image.bin");
const opened = await client.callTool({
name: "open_binary",
arguments: {
path: linkedPath,
format: "raw-binary",
architecture: "6502",
entry_point: "0x8001",
},
});
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
expect(session.activeTarget()?.sourcePath).toBe(linkedPath);
expect(session.activeTarget()?.path).toBe(path);
for (const _ of [0, 1]) {
const address = await client.callTool({
name: "address_name",
arguments: { address: "0x8001", document: "image.bin" },
});
expect(address.isError, JSON.stringify(address)).not.toBe(true);
}
expect(calls).toEqual(["address_name"]);
},
);
@@ -3,7 +3,10 @@ import { ok as resultOk } from "../../../src/domain/result.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
import { completeReconstructionCoverageData } from "../../../src/domain/reconstructionCoverage.fixture.js";
import {
completeReconstructionCoverageData,
reconstructionCoverageEvidenceId,
} from "../../../src/domain/reconstructionCoverage.fixture.js";
import { createReconstructionCoverageData } from "../../../src/domain/reconstructionCoverage.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { createServer } from "../../../src/server/createServer.js";
@@ -36,6 +39,42 @@ describe("reconstruction coverage MCP", () => {
boundary_id: boundaryId,
summary: { reasons: 0 },
});
const coverage = currentFixtureCoverage(boundaryId);
const latest = coverage.verifier_results[0];
if (latest === undefined)
throw new Error("Expected fixture verifier result");
const ambiguous = await client.callTool({
name: "evaluate_reconstruction_coverage",
arguments: {
coverage: createReconstructionCoverageData({
...coverage,
verifier_results: [
latest,
{
...latest,
status: "fail",
evidence_ids: [reconstructionCoverageEvidenceId("1")],
},
],
}),
boundary_id: boundaryId,
},
});
expect(ambiguous.isError).not.toBe(true);
expect(ambiguous.structuredContent).toMatchObject({
status: "unknown",
boundary_id: boundaryId,
reasons: [
expect.objectContaining({
code: "verifier-result-ambiguous",
subject_id: "claim.cli.help",
}),
],
evidence_ids: expect.arrayContaining([
reconstructionCoverageEvidenceId("3"),
reconstructionCoverageEvidenceId("1"),
]),
});
const unknown = await client.callTool({
name: "evaluate_reconstruction_coverage",
arguments: {
@@ -34,6 +34,9 @@ import {
} from "../../support/workspace/workspaceFixture.js";
import { z } from "zod";
import { createDeferred } from "../../fixtures/binarySession.js";
import { GoBinaryService } from "../../../src/application/go/GoBinaryService.js";
import { WebNetworkCaptureService } from "../../../src/application/WebNetworkCaptureService.js";
import { AnalysisUnsupportedTargetError } from "../../../src/domain/analysisErrorCore.js";
const resources: Array<{ close(): Promise<void> }> = [];
@@ -334,6 +337,68 @@ it("awaits SQLite cleanup and retries its retained owner after failed server shu
expect(attempts).toBe(2);
});
it("closes the bound Go and web-capture services and retries failed shutdown", async () => {
let goCalls = 0;
let goCloseAttempts = 0;
let captureCloseAttempts = 0;
let cleanupAllowed = false;
const goBinary = new GoBinaryService({
identity: { id: "go-fixture", name: "Go fixture", version: "1" },
inspect: async ({ path }) => {
goCalls += 1;
return err(
new AnalysisUnsupportedTargetError(
"inspect_go_binary",
path,
"fixture rejection",
),
);
},
close: async () => {
goCloseAttempts += 1;
if (!cleanupAllowed) throw new Error("Go cleanup refused");
},
});
const webNetworkCapture = new WebNetworkCaptureService({
inspect: async () => {
throw new Error("No capture inspection requested");
},
close: async () => {
captureCloseAttempts += 1;
if (!cleanupAllowed) throw new Error("Capture cleanup refused");
},
});
const server = createServer(
{ kind: "fixed", analysis: { execute: async () => ok(null) } },
{ goBinary, webNetworkCapture },
);
const client = new Client({ name: "bound-service-lifecycle", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server);
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const result = await client.callTool({
name: "inspect_go_binary",
arguments: { path: "/tmp/go-fixture" },
});
expect(result.isError).toBe(true);
expect(goCalls).toBe(1);
await expect(server.close()).rejects.toBeInstanceOf(AggregateError);
expect(goCloseAttempts).toBe(1);
expect(captureCloseAttempts).toBe(1);
cleanupAllowed = true;
await server.close();
expect(goCloseAttempts).toBe(2);
expect(captureCloseAttempts).toBe(2);
} finally {
cleanupAllowed = true;
}
});
afterEach(async () => {
await Promise.all(
resources.splice(0).map(async (resource) => resource.close()),
+7 -8
View File
@@ -281,7 +281,7 @@ it("pages filtered unknown heads through the public MCP contract", async () => {
supporting_evidence_ids: [],
contradicting_evidence_ids: [],
});
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
}
const defaultPage = structured(
@@ -372,12 +372,11 @@ it("pages filtered unknown heads through the public MCP contract", async () => {
.result as typeof defaultPage;
expect(first).toMatchObject({ total: 3, offset: 0, next_offset: 2 });
expect(first.items).toHaveLength(2);
const second = structured(
await client.callTool({
...request,
arguments: { ...request.arguments, offset: first.next_offset ?? 0 },
}),
).result as typeof defaultPage;
const secondResponse = await client.callTool({
...request,
arguments: { ...request.arguments, offset: first.next_offset ?? 0 },
});
const second = structured(secondResponse).result as typeof defaultPage;
expect(second).toMatchObject({ total: 3, offset: 2, next_offset: null });
expect(second.items).toHaveLength(1);
expect(
@@ -389,7 +388,7 @@ it("pages filtered unknown heads through the public MCP contract", async () => {
);
expect(
toolContract("list_unknowns").outputSchema.safeParse(
(await client.callTool(request)).structuredContent,
secondResponse.structuredContent,
).success,
).toBe(true);
+11 -4
View File
@@ -122,11 +122,18 @@ it("advertises the complete currently available inventory with a session", async
const listed = await client.listTools();
const names = listed.tools.map((t) => t.name);
const sessionTool = listed.tools.find(
({ name }) => name === "binary_session",
);
if (sessionTool === undefined)
throw new Error("Missing advertised binary_session tool");
// Validate this reply with its current advertised schema. The SDK otherwise
// builds output validators for the entire catalog on the first cached call.
const status = structured(
await client.callTool({
name: "binary_session",
arguments: {},
}),
await client.callTool(
{ name: "binary_session", arguments: {} },
{ toolDefinition: sessionTool },
),
);
const inventory = expandToolAvailability(
toolContract("binary_session").outputSchema.parse(status).result
+47 -34
View File
@@ -8,41 +8,51 @@ import { Ajv2020 } from "ajv/dist/2020.js";
import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
it("advertises valid target-free signal decoding schemas and actionable missing-tool diagnostics", async () => {
const harness = await createApplicationMcpHarness({
serverOptions: { environment: {} },
});
onTestFinished(harness.close);
const tool = (await harness.client.listTools()).tools.find(
({ name }) => name === "decode_signal_recording",
);
if (tool?.outputSchema === undefined) throw new Error("Signal tool missing");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = tool.inputSchema;
const outputSchema: Record<string, unknown> = tool.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
const input = {
path: process.platform === "win32" ? "C:\\recording.vcd" : "/recording.vcd",
decoders: "uart",
};
expect(ajv.validate(inputSchema, input)).toBe(true);
expect(ajv.validate(inputSchema, { ...input, driver: "demo" })).toBe(false);
const result = await harness.client.callTool({
name: tool.name,
arguments: input,
});
expect(parseMcpToolError(result)).toMatchObject({
error: {
code: "capability_unavailable",
details: {
operation: tool.name,
reason: expect.stringContaining("REA_SIGROK_COMMAND"),
it.each(["decode_signal_recording", "inspect_signal_decoders"])(
"advertises valid target-free schemas and missing-tool diagnostics: %s",
async (name) => {
const harness = await createApplicationMcpHarness({
serverOptions: { environment: {} },
});
onTestFinished(harness.close);
const tool = (await harness.client.listTools()).tools.find(
(tool) => tool.name === name,
);
if (tool?.outputSchema === undefined)
throw new Error("Signal tool missing");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = tool.inputSchema;
const outputSchema: Record<string, unknown> = tool.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
const input =
name === "inspect_signal_decoders"
? { query: "uart" }
: {
path:
process.platform === "win32"
? "C:\\recording.vcd"
: "/recording.vcd",
decoders: "uart",
};
expect(ajv.validate(inputSchema, input)).toBe(true);
expect(ajv.validate(inputSchema, { ...input, driver: "demo" })).toBe(false);
const result = await harness.client.callTool({
name: tool.name,
arguments: input,
});
expect(parseMcpToolError(result)).toMatchObject({
error: {
code: "capability_unavailable",
details: {
operation: tool.name,
reason: expect.stringContaining("REA_SIGROK_COMMAND"),
},
},
},
});
await harness.client.ping();
});
});
await harness.client.ping();
},
);
it.each(["cancelled", "cleanup"])(
"retains completed Evidence after %s failure",
@@ -77,6 +87,9 @@ it.each(["cancelled", "cleanup"])(
},
);
const signalRecording = new SignalRecordingService({
inspectDecoders: async () => {
throw new Error("Unexpected discovery call");
},
decode: async () => err(failure),
close: async () => {},
});
@@ -213,6 +213,31 @@ it("advertises exact valid schemas and records inline WASM interface evidence wi
expect(close).toHaveBeenCalled();
});
it("rejects a WASM provider response with a non-file subject before recording Evidence", async () => {
const value = wasmArtifactFixture();
const execution = wasmArtifactExecution(value);
const malformed = {
...execution,
subject: { ...execution.subject, format: "elf" },
} as unknown as typeof execution;
const harness = await createApplicationMcpHarness({
serverOptions: {
wasmArtifact: new WasmArtifactService({
close: () => Promise.resolve(),
inspect: () => Promise.resolve(ok(malformed)),
}),
},
});
onTestFinished(harness.close);
const before = harness.session.exportEvidenceBundle().records.length;
const response = await harness.client.callTool({
name: "inspect_wasm_artifact",
arguments: { path: value.artifact.path },
});
expect(parseMcpToolError(response).error.code).toBe("unreadable_output");
expect(harness.session.exportEvidenceBundle().records).toHaveLength(before);
});
it("reads an oversized completed WASM result through its reported retained reference", async () => {
const text = "(module)\n" + ";;😀\n" + " ".repeat(6 * 1024 * 1024);
const value = {