Files
reverse-engineering-anything/tests/acceptance/managedMemberRecovery.test.ts
T
morluto 858ff73880 perf(tests): give MCP test clients the shared lazy schema validation (#10960)
* perf(tests): give MCP test clients the shared lazy schema validation

The MCP SDK client compiles every listed tool's output schema on its
first tool call. With the SDK's default Ajv options, REA's catalog costs
gigabytes of allocation per client (inspect_analysis_view alone: 1.7 s and
~500 MiB retained), so native MCP files peaked at 1-2 GiB per worker.

tests/fixtures/mcpSchemaValidation already owns lazy, reference-preserving
validation. Route the native MCP, process-boundary and shared harness
clients through it, share compiled validators across clients in a worker
(bounded LRU keyed by schema text), and add a counted architecture guard so
default-validation test clients cannot spread; the remaining copies are the
baseline.

* fix(guards): read call arguments past parentheses inside string literals

* perf(tests): give MCP boundary test clients the shared schema validation (#11022)

* perf(tests): give MCP boundary test clients the shared schema validation

* perf(tests): give the remaining MCP test clients the shared schema validation (#11025)

* fix(guards): read an MCP client's validator option from parsed code

The default-validation counter searched each new Client(...) call's text for jsonSchemaValidator, so an inline comment, a string literal or a client name naming the option hid a default client. Parse the source with @babel/parser and count NewExpressions of Client whose object-literal arguments have no jsonSchemaValidator property; a source that does not parse counts every textual call. The guard reads raw test sources, and the generated-child-script allowlist entry, which no longer counts as a call, is removed.

* fix(guards): read an MCP client's options only from a whole object-literal argument

The default-validation counter skipped files without the text
'new Client(', so a comment between the tokens hid a client, and it took
any depth-two key as an option, so 'enabled ? { jsonSchemaValidator } : {}'
passed while its false branch uses the SDK default. The skip now only
requires the name Client, and the validator counts only when it is a key
of an object literal that is a whole argument; anything else counts as the
default.
2026-11-15 21:53:53 -05:00

195 lines
7.3 KiB
TypeScript

import { fileIdentity } from "../fixtures/evidenceSubject.js";
import { canonicalOutputSchema } from "../fixtures/canonicalOutputSchema.js";
import { artifactMcpCall } from "../../scripts/lib/artifact-e2e.mjs";
import { createHash } from "node:crypto";
import { unlink, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { tmpdir } from "node:os";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect } from "vitest";
import { parseEvidence } from "../../src/domain/evidence.js";
import { managedMemberInspectionSchema } from "../../src/domain/managed/managedArtifact.js";
import {
analysisViewResultSchema,
managedMemberSummaryViewResultSchema,
} from "../../src/domain/analysisView/analysisViewResult.js";
import { buildManagedMemberCapacityFixture } from "../fixtures/managedMemberCapacity.js";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
import { cliTest } from "../support/cli/cliFixture.js";
import { createMcpSchemaValidation } from "../fixtures/mcpSchemaValidation.js";
const createTransport = () =>
new StdioClientTransport({
command: process.execPath,
args: [resolve("scripts/rea.mjs"), "mcp"],
cwd: process.cwd(),
env: {
PATH: process.env.PATH ?? "",
REA_LOG_LEVEL: "silent",
...(process.platform === "win32"
? {
SystemRoot: process.env.SystemRoot ?? "",
TEMP: tmpdir(),
TMP: tmpdir(),
}
: {}),
},
stderr: "pipe",
});
cliTest(
"CLI and stdio MCP recover type discovery and preserve partial retained pages",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-managed-member-recovery-");
const path = join(root, "large-method.dll");
const bytes = buildManagedMemberCapacityFixture();
await writeFile(path, bytes);
const sha256 = createHash("sha256").update(bytes).digest("hex");
const transport = createTransport();
transport.stderr?.on("data", () => undefined);
const client = new Client(
{ name: "managed-type-recovery", version: "1" },
{ jsonSchemaValidator: createMcpSchemaValidation() },
);
try {
await client.connect(transport);
const definition = (await client.listTools()).tools.find(
(tool) => tool.name === "inspect_managed_members",
);
const ajv = new Ajv2020({ strict: false, validateFormats: false });
if (definition === undefined)
throw new Error("Managed member schema is absent");
const outputSchema: Record<string, unknown> = canonicalOutputSchema(
definition.name,
);
expect(ajv.validateSchema(definition.inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
const output = await cli.run({
arguments: ["inspect-managed-members", path, "--json"],
});
expect(output.exitCode, output.stderr).toBe(0);
const cliEvidence = parseEvidence(output.json);
const response = await artifactMcpCall(client, {
name: "inspect_managed_members",
arguments: { path },
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
expect(
ajv.validate(outputSchema, response.structuredContent),
JSON.stringify(ajv.errors),
).toBe(true);
const mcpEvidence = parseEvidence(response.structuredContent);
expect(mcpEvidence.normalized_result).toEqual(
cliEvidence.normalized_result,
);
expect(fileIdentity(mcpEvidence.subject).sha256).toBe(sha256);
expect(fileIdentity(cliEvidence.subject).sha256).toBe(sha256);
const report = managedMemberInspectionSchema.parse(
mcpEvidence.normalized_result,
);
expect(report.coverage.state).toBe("partial");
expect(report.types).toHaveLength(3);
expect(report.methods).toEqual([]);
const empty = report.types.find((type) => type.method_list.count === 0);
if (empty === undefined) throw new Error("Missing empty fixture type");
const selectedCli = await cli.run({
arguments: [
"inspect-managed-members",
path,
"--type",
empty.full_name,
"--json",
],
});
expect(selectedCli.exitCode, selectedCli.stderr).toBe(0);
const selected = await artifactMcpCall(client, {
name: "inspect_managed_members",
arguments: { path, type_names: [empty.full_name] },
});
expect(selected.isError).not.toBe(true);
const selectedEvidence = parseEvidence(selected.structuredContent);
expect(selectedEvidence.normalized_result).toEqual(
parseEvidence(selectedCli.json).normalized_result,
);
const selectedReport = managedMemberInspectionSchema.parse(
selectedEvidence.normalized_result,
);
expect(selectedReport).toMatchObject({
coverage: { state: "complete", issues: [] },
selection: { type_names: [empty.full_name], unmatched_type_names: [] },
types: [{ token: empty.token, full_name: empty.full_name }],
methods: [],
});
const summaryReply = await artifactMcpCall(client, {
name: "inspect_managed_members",
arguments: { path, detail: "summary" },
});
expect(summaryReply.isError).not.toBe(true);
const summary = managedMemberSummaryViewResultSchema.parse(
parseEvidence(summaryReply.structuredContent).normalized_result,
);
expect(summary.summary).toMatchObject({
coverage: { state: "partial" },
reported_counts: {
types: 3,
methods: 0,
exported_types: null,
user_strings: null,
},
});
await unlink(path);
for (const collection of ["types", "methods"] as const) {
const reply = await artifactMcpCall(client, {
name: "inspect_analysis_view",
arguments: {
source: {
kind: "retained-evidence",
evidence_id: summary.parent_evidence_id,
},
view: { kind: "managed-members", collection, offset: 0, limit: 10 },
},
});
expect(reply.isError, JSON.stringify(reply)).not.toBe(true);
const page = analysisViewResultSchema.parse(
parseEvidence(reply.structuredContent).normalized_result,
);
if (page.kind !== "managed-members")
throw new Error("Expected managed member page");
expect(page.source_coverage.state).toBe("partial");
expect(page.page.rows).toEqual(
collection === "types" ? report.types : [],
);
}
const unknown = await artifactMcpCall(client, {
name: "inspect_analysis_view",
arguments: {
source: {
kind: "retained-evidence",
evidence_id: summary.parent_evidence_id,
},
view: {
kind: "managed-members",
collection: "exported_types",
offset: 0,
limit: 10,
},
},
});
expect(unknown.isError).toBe(true);
expect(JSON.stringify(unknown)).toContain(
"did not examine exported_types",
);
} finally {
try {
await client.close();
} finally {
await transport.close();
}
}
},
);