feat(analysis): add opt-in retained inventory and WASM views (#2122)

Add opt-in retained inventory and WASM Evidence views with exact nested output contracts and a small static WASM descriptor. Preserve old complete CLI/MCP workflows, producer choices, original authenticated Evidence and cleanup ownership.

Validated with real public applications, genuine old Evidence migration, 123 focused assertions, 11 synchronized description checks and 42 installed-package WABT cases. Detailed generated experiment JSON stays outside the final tree; concise findings and reproduction inputs remain. Main-existing completion/package CI failures are separately attributed and left unchanged.

Refs #2016

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
This commit is contained in:
Ysopwnable
2026-10-12 21:17:52 +08:00
committed by GitHub
co-authored by factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
parent 3159732597
commit 58fb372071
55 changed files with 4322 additions and 235 deletions
+48 -3
View File
@@ -1,10 +1,10 @@
import { apiSurfaceHar } from "../../fixtures/historicalHar.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { createHash } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import { mkdir, unlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
@@ -15,11 +15,56 @@ import {
analysisViewCaptureEvidence,
analysisViewObjectDenseCapture,
} from "../../fixtures/analysisView.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import { ghidraFunctionDossier } from "../../../src/domain/ghidraValues.fixture.js";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import { inspectEvidenceBundle } from "../../../src/application/investigation/InspectEvidenceBundle.js";
cliTest(
"projects portable artifact inventory after the original ZIP is removed",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-inventory-view-cli-");
const archive = join(root, "fixture.zip");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("main.js", new TextReader("console.log('portable');\n"));
await writeFile(archive, await writer.close());
const inspected = await cli.run({
arguments: ["inspect-artifact", archive, "--json"],
});
expect(inspected.exitCode).toBe(0);
const parent = parseEvidence(inspected.json);
await unlink(archive);
const request = join(root, "view.json");
await writeFile(
request,
JSON.stringify({
source: { kind: "inline", evidence: parent },
view: {
kind: "inventory",
collection: "occurrences",
logical_paths: ["main.js"],
},
}),
);
const projected = await cli.run({
arguments: ["inspect-analysis-view", request, "--json"],
});
expect(projected.exitCode).toBe(0);
expect(projected.json).toMatchObject({
operation: "inspect_analysis_view",
evidence_links: [parent.evidence_id],
normalized_result: {
parent_evidence_id: parent.evidence_id,
kind: "inventory",
source_complete: true,
artifact: { path: archive, sha256: parent.subject?.digest.sha256 },
items: [expect.objectContaining({ logical_path: "main.js" })],
coverage: { total: 1, exhausted: true, next_offset: null },
},
});
},
);
cliTest(
"admits portable captures before parsing and preserves capture caveats",
async ({ cli }) => {
@@ -1,8 +1,9 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { readFile, writeFile } from "node:fs/promises";
import { readFile, unlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { Ajv2020 } from "ajv/dist/2020.js";
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { expect, it } from "vitest";
import { z } from "zod";
@@ -12,8 +13,81 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { ArtifactProvider } from "../../../src/artifacts/ArtifactProvider.js";
import { createServer } from "../../../src/server/createServer.js";
import {
createEvidence,
parseEvidence,
type Evidence,
} from "../../../src/domain/evidence.js";
import {
artifactInspectionResultSchema,
createArtifactInspection,
} from "../../../src/domain/artifactInspection.js";
import {
artifactInventoryResultSchema,
type ArtifactInventoryResult,
} from "../../../src/domain/artifactGraph.js";
import {
analysisViewResultSchema,
type AnalysisViewResult,
} from "../../../src/domain/analysisView/analysisView.js";
it("inspects a standalone keyed archive through MCP with original object identities", async () => {
const assertInventorySubjectValidation = async (
client: Client,
source: Evidence,
): Promise<void> => {
const result =
source.operation === "inspect_artifact"
? artifactInspectionResultSchema.parse(source.normalized_result)
.substeps[0]?.evidence.normalized_result
: source.normalized_result;
const inventory = artifactInventoryResultSchema.parse(result);
if (source.subject === null)
throw new Error("Fixture requires a known subject");
for (const target of [
undefined,
{
path: source.subject.local_path,
sha256: inventory.manifest.root_sha256,
format: "file" as const,
},
{
path: source.subject.local_path,
sha256: "f".repeat(64),
format: inventory.manifest.root_format,
},
]) {
const inconsistent = createEvidence(target, source.provider, {
operation: source.operation,
parameters: source.parameters,
result: source.normalized_result,
});
for (const view of [
{ kind: "summary" },
{ kind: "inventory", collection: "nodes", offset: 0, limit: 1 },
]) {
const reply = await client.callTool({
name: "inspect_analysis_view",
arguments: { source: { kind: "inline", evidence: inconsistent }, view },
});
expect(parseMcpToolError(reply)).toMatchObject({
error: {
code: "invalid_request",
details: {
issues: [
{
path: ["source"],
reason: "invalid_value",
message: expect.stringContaining("subject does not match"),
},
],
},
},
});
}
}
};
it("preserves keyed archive identities and rejects inconsistent inventory carrier subjects", async () => {
const directory = await createTestTempDirectory("rea-keyed-mcp-");
const path = join(directory, "archive.plist");
await writeFile(
@@ -99,6 +173,19 @@ it("inspects a standalone keyed archive through MCP with original object identit
},
},
});
const inspected = await client.callTool({
name: "inspect_artifact",
arguments: {},
});
expect(inspected.isError).not.toBe(true);
const parent = parseEvidence(inspected.structuredContent);
const inspection = artifactInspectionResultSchema.parse(
parent.normalized_result,
);
const inventory = inspection.substeps[0]?.evidence;
if (inventory === undefined) throw new Error("Missing inventory Evidence");
await assertInventorySubjectValidation(client, inventory);
await assertInventorySubjectValidation(client, parent);
} finally {
await client.close();
await server.close();
@@ -106,7 +193,201 @@ it("inspects a standalone keyed archive through MCP with original object identit
}
});
it("returns all 520 ZIP file occurrences in one inspect_artifact MCP result", async () => {
const createInventoryViewReader = async (client: Client, parent: Evidence) => {
const advertised = (await client.listTools()).tools.find(
(tool) => tool.name === "inspect_analysis_view",
);
if (advertised?.outputSchema === undefined)
throw new Error("Missing advertised view schemas");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = advertised.inputSchema;
const outputSchema: Record<string, unknown> = advertised.outputSchema;
const validateInput = ajv.compile(inputSchema);
const validateOutput = ajv.compile(outputSchema);
expect(
validateInput({
source: { kind: "retained-evidence", evidence_id: parent.evidence_id },
view: { kind: "inventory", collection: "nodes", logical_paths: [] },
}),
).toBe(false);
const readView = async (
view: Record<string, unknown>,
source = {
kind: "retained-evidence",
evidence_id: parent.evidence_id,
},
) => {
const arguments_ = { source, view };
expect(
validateInput(arguments_),
JSON.stringify(validateInput.errors),
).toBe(true);
const reply = await client.callTool({
name: "inspect_analysis_view",
arguments: arguments_,
});
if (reply.isError)
throw new Error(JSON.stringify(parseMcpToolError(reply)));
expect(
validateOutput(reply.structuredContent),
JSON.stringify(validateOutput.errors),
).toBe(true);
const evidence = parseEvidence(reply.structuredContent);
return {
evidence,
result: analysisViewResultSchema.parse(evidence.normalized_result),
};
};
return readView;
};
const assertHistoricalInventory = async (
client: Client,
input: {
archive: string;
parent: Evidence;
inventoryEvidence: Evidence;
graph: ArtifactInventoryResult;
},
) => {
const { archive, parent, inventoryEvidence, graph } = input;
// Historical records may omit a later inventory field. Input parsing must
// not insert defaults inside that authenticated child Evidence.
const { integrity_contradictions: _contradictions, ...legacyInventory } =
graph;
const legacyTarget = {
path: archive,
sha256: graph.manifest.root_sha256,
format: "zip" as const,
};
const legacySource = createEvidence(
legacyTarget,
inventoryEvidence.provider,
{
operation: "inventory_artifact",
parameters: {},
result: legacyInventory,
},
);
const legacyInspection = createArtifactInspection(legacySource);
expect(legacyInspection.substeps[0]?.evidence).toEqual(legacySource);
expect(
legacyInspection.substeps[0]?.evidence.normalized_result,
).not.toHaveProperty("integrity_contradictions");
const legacyParent = createEvidence(legacyTarget, parent.provider, {
operation: "inspect_artifact",
parameters: {},
result: legacyInspection,
});
const legacyReply = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: { kind: "inline", evidence: legacyParent },
view: { kind: "summary" },
},
});
expect(
legacyReply.isError,
JSON.stringify(legacyReply.structuredContent),
).not.toBe(true);
expect(
parseEvidence(legacyReply.structuredContent).normalized_result,
).toMatchObject({
parent_evidence_id: legacyParent.evidence_id,
summary: {
source_complete: true,
inventory_evidence_ids: [legacySource.evidence_id],
},
});
};
const assertPortableRoundtrip = async (
client: Client,
directory: string,
parent: Evidence,
originalView: AnalysisViewResult,
) => {
const saved = join(directory, "evidence.json");
const exported = await client.callTool({
name: "export_evidence_bundle",
arguments: { path: saved },
});
if (exported.isError)
throw new Error(JSON.stringify(parseMcpToolError(exported)));
const closed = await client.callTool({
name: "close_binary",
arguments: {},
});
if (closed.isError)
throw new Error(JSON.stringify(parseMcpToolError(closed)));
const missing = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: { kind: "retained-evidence", evidence_id: parent.evidence_id },
view: { kind: "summary" },
},
});
expect(parseMcpToolError(missing)).toMatchObject({
error: { details: { reason: "missing" } },
});
const imported = await client.callTool({
name: "import_evidence_bundle",
arguments: { path: saved },
});
if (imported.isError)
throw new Error(JSON.stringify(parseMcpToolError(imported)));
const restored = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: { kind: "retained-evidence", evidence_id: parent.evidence_id },
view: { kind: "summary" },
},
});
if (restored.isError)
throw new Error(JSON.stringify(parseMcpToolError(restored)));
expect(parseEvidence(restored.structuredContent).normalized_result).toEqual(
originalView,
);
};
const assertSummaryDelivery = async (
client: Client,
session: ReturnType<typeof createTestBinarySession>,
complete: Evidence,
) => {
expect(complete.parameters).not.toHaveProperty("detail");
const reply = await client.callTool({
name: "inspect_artifact",
arguments: { detail: "summary" },
});
expect(reply.isError, JSON.stringify(reply.structuredContent)).not.toBe(true);
const projected = parseEvidence(reply.structuredContent);
const view = analysisViewResultSchema.parse(projected.normalized_result);
expect(projected.operation).toBe("inspect_analysis_view");
expect(view.kind).toBe("summary");
const retained = session.evidenceById(view.parent_evidence_id);
if (retained === undefined) throw new Error("Missing complete inspection");
expect(retained.operation).toBe("inspect_artifact");
expect(retained.parameters).toMatchObject({ detail: "summary" });
expect(retained.normalized_result).toEqual(complete.normalized_result);
expect(retained.evidence_id).not.toBe(projected.evidence_id);
const inspection = artifactInspectionResultSchema.parse(
retained.normalized_result,
);
expect(
session.evidenceById(inspection.substeps[0]?.evidence_id ?? ""),
).toEqual(inspection.substeps[0]?.evidence);
const explicit = await client.callTool({
name: "inspect_artifact",
arguments: { detail: "complete" },
});
expect(explicit.isError).not.toBe(true);
expect(parseEvidence(explicit.structuredContent).normalized_result).toEqual(
complete.normalized_result,
);
};
it("keeps complete ZIP output and reads retained inventory views after the source is removed", async () => {
const directory = await createTestTempDirectory("rea-artifact-inline-");
const archive = join(directory, "many.zip");
const writer = new ZipWriter(new Uint8ArrayWriter());
@@ -138,27 +419,154 @@ it("returns all 520 ZIP file occurrences in one inspect_artifact MCP result", as
expect(result.isError, JSON.stringify(result.structuredContent)).not.toBe(
true,
);
const inspection = z
.object({
substeps: z.array(
z.object({
evidence: z.object({
normalized_result: z.object({
occurrences: z.array(z.object({ logical_path: z.string() })),
}),
}),
}),
),
})
.parse(
z
.object({ normalized_result: z.unknown() })
.parse(result.structuredContent).normalized_result,
);
const parent = parseEvidence(result.structuredContent);
await assertSummaryDelivery(client, session, parent);
const parsedInspection = artifactInspectionResultSchema.parse(
parent.normalized_result,
);
const inventoryEvidence = parsedInspection.substeps[0]?.evidence;
if (inventoryEvidence === undefined)
throw new Error("Missing inventory Evidence");
const graph = artifactInventoryResultSchema.parse(
inventoryEvidence.normalized_result,
);
expect(graph.occurrences).toHaveLength(fileCount + 1);
// Follow-ups must use retained source facts, not reopen this archive.
await unlink(archive);
const readView = await createInventoryViewReader(client, parent);
const summary = await readView({ kind: "summary" });
expect(summary.result).toMatchObject({
kind: "summary",
parent_evidence_id: parent.evidence_id,
artifact: { path: archive, sha256: graph.manifest.root_sha256 },
summary: {
manifest: graph.manifest,
source_complete: true,
available_counts: { occurrences: fileCount + 1 },
observed_entry_kind_counts: { file: fileCount + 1 },
inventory_evidence_ids: [inventoryEvidence.evidence_id],
},
});
expect(summary.evidence.evidence_links).toEqual([parent.evidence_id]);
const paths = ["files/0.txt", "files/519.txt", "missing.txt"];
const selected = await readView({
kind: "inventory",
collection: "occurrences",
logical_paths: paths,
offset: 0,
limit: 1,
});
expect(selected.result).toMatchObject({
kind: "inventory",
source_complete: true,
items: graph.occurrences
.filter((row) => paths.includes(row.logical_path))
.slice(0, 1),
coverage: { examined: 1, total: 2, next_offset: 1, exhausted: false },
});
const next = await readView({
kind: "inventory",
collection: "occurrences",
logical_paths: paths,
offset: 1,
limit: 1,
});
expect(next.result).toMatchObject({
coverage: { examined: 1, next_offset: null, exhausted: true },
});
const none = await readView({
kind: "inventory",
collection: "occurrences",
logical_paths: [],
});
expect(none.result).toMatchObject({
items: [],
coverage: { total: 0, exhausted: true },
});
const partial = createEvidence(
{ path: archive, sha256: graph.manifest.root_sha256, format: "zip" },
inventoryEvidence.provider,
{
operation: "inventory_artifact",
parameters: {},
result: { ...graph, occurrences: graph.occurrences.slice(0, 1) },
},
);
const partialReply = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: { kind: "inline", evidence: partial },
view: {
kind: "inventory",
collection: "occurrences",
logical_paths: ["missing.txt"],
},
},
});
expect(
inspection.substeps[0]?.evidence.normalized_result.occurrences,
).toHaveLength(fileCount + 1);
parseEvidence(partialReply.structuredContent).normalized_result,
).toMatchObject({
source_complete: false,
items: [],
unknowns: expect.arrayContaining([
expect.stringContaining("Missing matches do not establish absence"),
]),
});
await assertHistoricalInventory(client, {
archive,
parent,
inventoryEvidence,
graph,
});
await assertPortableRoundtrip(client, directory, parent, summary.result);
} finally {
await Promise.allSettled([client.close(), server.close(), session.close()]);
await client.close();
await server.close();
await session.close();
}
});
it("refuses summary delivery without a retained Evidence owner and preserves complete delivery", async () => {
const directory = await createTestTempDirectory("rea-inventory-fixed-");
const archive = join(directory, "fixture.zip");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("main.js", new TextReader("console.log('fixed');\n"));
await writeFile(archive, await writer.close());
const session = createTestBinarySession(new ArtifactProvider(process.env));
const opened = await session.open(archive);
if (!opened.ok) throw opened.error;
const server = createServer({ kind: "fixed", analysis: session });
const client = new Client({ name: "artifact-fixed-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const summary = await client.callTool({
name: "inspect_artifact",
arguments: { detail: "summary" },
});
expect(parseMcpToolError(summary)).toMatchObject({
error: {
code: "capability_unavailable",
message: expect.stringContaining("does not retain Evidence"),
},
});
const complete = await client.callTool({
name: "inspect_artifact",
arguments: {},
});
expect(complete.isError).not.toBe(true);
expect(
parseEvidence(complete.structuredContent).normalized_result,
).toMatchObject({
substeps: [expect.objectContaining({ operation: "inventory_artifact" })],
});
} finally {
await client.close();
await server.close();
await session.close();
}
});
+1 -1
View File
@@ -281,7 +281,7 @@ describe("target-free MCP workflow", () => {
);
expect(
beforeTools.find(({ name }) => name === "inspect_artifact")?.description,
).toContain("Returns the complete content-addressed artifact graph");
).toMatch(/\breturns the complete content-addressed artifact graph\b/iu);
expect(beforeNames).toContain("open_binary");
expect(beforeNames).toContain("binary_session");
expect(beforeNames).toContain("current_document");
+216 -2
View File
@@ -1,11 +1,14 @@
import type { Client } from "@modelcontextprotocol/client";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it, onTestFinished, vi } from "vitest";
import { readFile, realpath, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { WasmArtifactService } from "../../../src/application/wasm/WasmArtifactService.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import { createHash } from "node:crypto";
import { z } from "zod";
import { createServer } from "../../../src/server/createServer.js";
import { ok } from "../../../src/domain/result.js";
import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
@@ -141,3 +144,214 @@ it("advertises exact valid schemas and records inline WASM interface evidence wi
await harness.close();
expect(close).toHaveBeenCalled();
});
it("reads an oversized completed WASM result through its reported retained reference", async () => {
const text = "(module)\n" + ";;😀\n" + " ".repeat(6 * 1024 * 1024);
const value = {
...wasmArtifactFixture(),
imports: ['(import "env" "memory.with punctuation" (memory 1))'],
exports: ['(export "first" (func 0))', '(export "second" (func 1))'],
wat: {
text,
sha256: createHash("sha256").update(text, "utf8").digest("hex"),
representation: "decoded-wat" as const,
},
};
const service = new WasmArtifactService({
close: () => Promise.resolve(),
inspect: () => Promise.resolve(ok(wasmArtifactExecution(value))),
});
const harness = await createApplicationMcpHarness({
serverOptions: { wasmArtifact: service },
});
onTestFinished(harness.close);
const reply = await harness.client.callTool({
name: "inspect_wasm_artifact",
arguments: { path: value.artifact.path },
});
const reference = z
.object({
details: z.object({
reported_limits: z.object({
evidence_reference: z.object({
kind: z.literal("retained-evidence"),
evidence_id: z.string(),
}),
}),
}),
})
.parse(parseMcpToolError(reply).error).details
.reported_limits.evidence_reference;
const catalog = await harness.client.listTools();
const advertised = catalog.tools.find(
(tool) => tool.name === "inspect_analysis_view",
);
if (advertised?.outputSchema === undefined)
throw new Error("Missing WASM view schemas");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const input: Record<string, unknown> = advertised.inputSchema;
const output: Record<string, unknown> = advertised.outputSchema;
for (const [view, expected] of [
[
{ kind: "summary" },
{
summary: {
validation: "valid",
available_counts: { imports: 1, exports: 2 },
runtime_execution: "not-performed",
network_fetch: "not-performed",
wat: { sha256: value.wat.sha256, code_units: text.length },
},
},
],
[
{ kind: "wasm", facet: "exports", offset: 1, limit: 1 },
{
item: [value.exports[1]],
coverage: { total: 2, next_offset: null, exhausted: true },
},
],
[{ kind: "wasm", facet: "imports" }, { item: value.imports }],
[
{ kind: "wasm", facet: "wat", offset: 0, limit: 16 },
{
item: { text: text.slice(0, 16), unit: "utf16-code-units" },
coverage: { total: text.length, next_offset: 16, exhausted: false },
},
],
] as const) {
const args = { source: reference, view };
expect(ajv.validate(input, args), JSON.stringify(ajv.errors)).toBe(true);
const selected = await harness.client.callTool({
name: "inspect_analysis_view",
arguments: args,
});
expect(
selected.isError,
JSON.stringify(selected.structuredContent),
).not.toBe(true);
expect(
ajv.validate(output, selected.structuredContent),
JSON.stringify(ajv.errors),
).toBe(true);
const evidence = parseEvidence(selected.structuredContent);
expect(evidence.confidence).toBe("derived");
expect(evidence.evidence_links).toEqual([reference.evidence_id]);
expect(evidence.normalized_result).toMatchObject({
parent_evidence_id: reference.evidence_id,
...expected,
});
}
const original = harness.session.evidenceById(reference.evidence_id);
expect(original?.normalized_result).toEqual(value);
const inconsistent = createEvidence(
{
path: value.artifact.path,
sha256: value.artifact.sha256,
format: "file",
},
{ id: "historical-wabt", name: "Historical WABT", version: "1" },
{
operation: "inspect_wasm_artifact",
parameters: {},
result: { ...value, wat: { ...value.wat, sha256: "f".repeat(64) } },
},
);
const invalid = await harness.client.callTool({
name: "inspect_analysis_view",
arguments: {
source: { kind: "inline", evidence: inconsistent },
view: { kind: "summary" },
},
});
expect(parseMcpToolError(invalid)).toMatchObject({
error: {
code: "invalid_request",
details: {
issues: [
{
path: ["source", "normalized_result", "wat", "sha256"],
reason: "invalid_value",
},
],
},
},
});
await harness.client.ping();
});
it("rejects absent or inconsistent WASM source identity before deriving portable views", async () => {
const value = wasmArtifactFixture();
const harness = await createApplicationMcpHarness({
serverOptions: { environment: {} },
});
onTestFinished(harness.close);
for (const target of [
undefined,
{
path: `${value.artifact.path}.other`,
sha256: value.artifact.sha256,
format: "file" as const,
},
{
path: value.artifact.path,
sha256: "f".repeat(64),
format: "file" as const,
},
]) {
const source = createEvidence(
target,
{ id: "historical-wabt", name: "Historical WABT", version: "1" },
{ operation: "inspect_wasm_artifact", parameters: {}, result: value },
);
for (const view of [
{ kind: "summary" },
{ kind: "wasm", facet: "exports", offset: 0, limit: 1 },
]) {
const reply = await harness.client.callTool({
name: "inspect_analysis_view",
arguments: { source: { kind: "inline", evidence: source }, view },
});
expect(parseMcpToolError(reply)).toMatchObject({
error: {
code: "invalid_request",
details: {
issues: [{ path: ["source", "subject"], reason: "invalid_value" }],
},
},
});
}
}
await harness.client.ping();
});
it("retries cleanup of the injected WASM module after server shutdown fails", async () => {
const close = vi
.fn()
.mockRejectedValueOnce(new Error("retained WASM workspace"))
.mockResolvedValue(undefined);
const service = new WasmArtifactService({
close,
inspect: () => Promise.resolve(ok(wasmArtifactExecution())),
});
const session = createTestBinarySession(() => {
throw new Error("No deep provider");
});
const server = createServer(
{ kind: "session", session },
{ wasmArtifact: service },
);
const client = new Client({ name: "wasm-cleanup-retry", version: "1" });
const [a, b] = InMemoryTransport.createLinkedPair();
try {
await server.connect(b);
await client.connect(a);
await expect(server.close()).rejects.toThrow("REA session cleanup failed");
await server.close();
expect(close).toHaveBeenCalledTimes(2);
} finally {
await client.close();
await server.close();
await session.close();
}
});
+16 -11
View File
@@ -1,7 +1,10 @@
import { createHash } from "node:crypto";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
import type { WasmArtifact } from "../../../src/domain/wasm/wasmArtifact.js";
/** Source-owned transport seam; upstream binaries are verified in a separate lane. */
export const wasmArtifactFixture = (path = "/artifacts/module.wasm") => ({
export const wasmArtifactFixture = (
path = "/artifacts/module.wasm",
): WasmArtifact => ({
artifact: { path, sha256: "a".repeat(64), bytes: 8 },
validation: "valid" as const,
sections: [],
@@ -18,16 +21,18 @@ export const wasmArtifactFixture = (path = "/artifacts/module.wasm") => ({
source: "https://github.com/WebAssembly/wabt" as const,
release: "1.0.42" as const,
source_commit: "ff0ef7e0009402740c805a9744c09b05be063e48" as const,
commands: ["wasm-validate", "wasm-objdump", "wasm2wat"].map((tool) => ({
tool,
path: `/tools/${tool}`,
sha256: "b".repeat(64),
version_banner: "1.0.42\n",
arguments:
tool === "wasm-objdump"
? ["-h", "-x", "module.wasm"]
: ["--enable-all", "module.wasm"],
})),
commands: (["wasm-validate", "wasm-objdump", "wasm2wat"] as const).map(
(tool) => ({
tool,
path: `/tools/${tool}`,
sha256: "b".repeat(64),
version_banner: "1.0.42\n",
arguments:
tool === "wasm-objdump"
? ["-h", "-x", "module.wasm"]
: ["--enable-all", "module.wasm"],
}),
),
timeout_ms: 30_000,
output_budget_bytes: 32 * 1024 * 1024,
},