Files
rea/tests/boundary/mcp/nativeMachoSummaryMcp.test.ts
f993d33028 perf(artifacts): add opt-in Interface Builder summary delivery and pages
decode_interface_builder returns the complete object, hierarchy and
connection graph inline. XLD.app's graph is 6.7 MB (about 1.98M o200k
tokens) and Transmission.app's 6.3 MB; over MCP the doubled text and
structured content exceed the default response budget, so an agent got
a resource_constraint error instead of any answer.

Add the established opt-in delivery: omitted or complete detail keeps the
complete result and its Evidence ID, while summary retains the complete
Evidence and returns every decoded document with node-kind,
edge-relation and coverage-status tallies (10k tokens for XLD).
inspect_analysis_view kind interface-builder pages documents, nodes,
edges or coverage; nodes and edges accept an exact decoded document path,
matched against each row's recorded evidence, and an undecoded path is
refused. Decoder truncation stays visible on every page.

Related cleanup, since the new code repeated it a ninth time:
- parseAnalysisViewResult owns parsing a view parent's normalized result
  with the operation's schema and mapping issues into the view source.
- retainedSummaryDelivery owns the preflight/summary hook pair and the
  shared registration options for artifact, native and managed tools.
- openProductionTarget owns the production MCP session test setup.
Duplication drops from 3.02% to 2.98% (threshold 3.0%).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 02:40:06 +08:00

198 lines
7.0 KiB
TypeScript

import { copyFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect } from "vitest";
import { z } from "zod";
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";
import { openProductionTarget } from "../../support/mcp/productionSession.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 client = await openProductionTarget(mcp, onTestFinished, target);
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"),
},
});
},
);