chore(native): reconcile compact reference verification with main

This commit is contained in:
N0zoM1z0
2026-10-10 15:20:09 +08:00
81 changed files with 2377 additions and 397 deletions
@@ -0,0 +1,76 @@
import { expect } from "vitest";
import {
verifyJavaScriptReturnShapes,
type JavaScriptReturnFields,
} from "../../fixtures/javascriptReturnShapes.js";
import { cliTest } from "../../support/cli/cliFixture.js";
const source = [
"export function inline() { const shared = { x: 1, keep: 7 }; for (const t of [shared]) t.x = 2; return { x: shared.x, keep: shared.keep }; }",
"export function named() { const shared = { x: 1 }; const arr = [shared]; for (const t of arr) t.x = 2; return shared.x; }",
"export function declaredVar() { const shared = { x: 1 }; for (var t of [shared]) t.x = 2; return shared.x; }",
"export function assigned() { const shared = { x: 1 }; let t; for (t of [shared]) t.x = 2; return shared.x; }",
"export function assignedDestructured() { const shared = { x: 1 }; let t; for ({child: t} of [{child: shared}]) t.x = 2; return shared.x; }",
"export function declaredVarDestructured() { const shared = { x: 1 }; for (var {child: t} of [{child: shared}]) t.x = 2; return shared.x; }",
"export function memberTarget() { const shared = { x: 1 }; const holder = {}; for (holder.item of [shared]) holder.item.x = 2; return shared.x; }",
"export function memberPattern() { const shared = { x: 1 }; const holder = {}; for ({child: holder.item} of [{child: shared}]) holder.item.x = 2; return shared.x; }",
"export function destructured() { const shared = { x: 1 }; for (const {child: t} of [{child: shared}]) t.x = 2; return shared.x; }",
"export function arrayDestructured() { const shared = { x: 1 }; for (const [t] of [[shared]]) t.x = 2; return shared.x; }",
"export function spread() { const shared = { x: 1 }; const arr = [shared]; for (const t of [...arr]) t.x = 2; return shared.x; }",
"export function objectRestChild() { const shared = { x: 1 }; for (const {...t} of [{child: shared}]) t.child.x = 2; return shared.x; }",
"export function arrayRestChild() { const shared = { x: 1 }; for (const [...t] of [[shared]]) t[0].x = 2; return shared.x; }",
"export function defaultChild() { const shared = { x: 1 }; for (const {child: t = shared} of [{}]) t.x = 2; return shared.x; }",
"export function updated() { const shared = { x: 1 }; for (const t of [shared]) t.x++; return shared.x; }",
"export function deleted() { const shared = { x: 1 }; for (const t of [shared]) delete t.x; return shared.x; }",
"export function escaped() { const shared = { x: 1 }; for (const t of [shared]) consume(t); return shared.x; }",
"export async function awaited() { const shared = { x: 1 }; for await (const t of [shared]) t.x = 2; return shared.x; }",
"export function indexed() { const shared = { x: 1 }; const arr = [shared]; for (let i = 0; i < arr.length; i++) { const t = arr[i]; t.x = 2; } return shared.x; }",
"export function copyWrite() { const shared = { x: 1 }; for (const {...t} of [shared]) t.x = 2; return shared.x; }",
"export function noWrite() { const shared = { x: 1 }; for (const t of [shared]) { const read = t.x; } return shared.x; }",
"export function empty() { const shared = { x: 1 }; for (const t of []) t.x = 2; return shared.x; }",
"export function keys() { const shared = { x: 1 }; for (const key in [shared]) { const read = key; } return shared.x; }",
"export function shadowed() { const t = { x: 1 }; const shared = { x: 3 }; for (const t of [shared]) t.x = 2; return t.x; }",
].join("\n");
const assertReturns = (fields: JavaScriptReturnFields): void => {
expect(fields("inline")).toEqual(
expect.arrayContaining([
expect.objectContaining({ path: "/x", state: "unknown" }),
expect.objectContaining({ path: "/keep", state: "literal", value: 7 }),
]),
);
for (const name of [
"named",
"declaredVar",
"assigned",
"assignedDestructured",
"declaredVarDestructured",
"memberTarget",
"memberPattern",
"destructured",
"arrayDestructured",
"spread",
"objectRestChild",
"arrayRestChild",
"defaultChild",
"updated",
"deleted",
"escaped",
"awaited",
"indexed",
])
expect(fields(name), name).toContainEqual(
expect.objectContaining({ path: "", state: "unknown" }),
);
for (const name of ["copyWrite", "noWrite", "empty", "keys", "shadowed"])
expect(fields(name), name).toContainEqual(
expect.objectContaining({ path: "", state: "literal", value: 1 }),
);
};
cliTest(
"preserves yielded-object mutation uncertainty through CLI and stdio MCP",
({ cli }) => verifyJavaScriptReturnShapes(cli, source, assertReturns),
120_000,
);
@@ -0,0 +1,98 @@
import { expect } from "vitest";
import {
verifyJavaScriptReturnShapes,
type JavaScriptReturnFields,
} from "../../fixtures/javascriptReturnShapes.js";
import { cliTest } from "../../support/cli/cliFixture.js";
const stores = {
object: "const o = {a: {x: 0}}; o.a = shared; o.a.x = 2;",
array: "const arr = [{x: 0}]; arr[0] = shared; arr[0].x = 2;",
captured: "const o = {a: {x: 0}}; o.a = shared; const t = o.a; t.x = 2;",
nested: "const o = {a: {b: {x: 0}}}; o.a.b = shared; o.a.b.x = 2;",
quoted: 'const o = {}; o["a/b~c"] = shared; o["a/b~c"].x = 2;',
dynamic: 'const o = {}; const key = "entry"; o[key] = shared; o[key].x = 2;',
receiverAlias: "const o = {}; const t = o; t.a = shared; o.a.x = 2;",
transitive: "const p = {}; const o = {}; o.a = p; p.b = shared; o.a.b.x = 2;",
overwritten: "const o = {}; o.a = {x: 0}; o.a = shared; o.a.x = 2;",
replacedReference:
"const o = {}; const other = {x: 0}; o.a = other; o.a = shared; o.a.x = 2;",
copiedDestination:
"const o = {}; o.a = shared; const copy = {...o}; copy.a.x = 2;",
iteration: "const arr = []; arr[0] = shared; for (const t of arr) t.x = 2;",
nestedArray: "const o = {}; o.a = [shared]; o.a[0].x = 2;",
orAssignment: "const o = {a: null}; o.a ||= shared; o.a.x = 2;",
nullishAssignment: "const o = {a: null}; o.a ??= shared; o.a.x = 2;",
andAssignment: "const o = {a: {x: 0}}; o.a &&= shared; o.a.x = 2;",
objectPattern: "const o = {}; ({child: o.a} = {child: shared}); o.a.x = 2;",
arrayPattern: "const o = {}; [o.a] = [shared]; o.a.x = 2;",
defaultPattern: "const o = {}; ({child: o.a = shared} = {}); o.a.x = 2;",
objectRestMember:
"const o = {}; ({...o.a} = {child: shared}); o.a.child.x = 2;",
arrayRestMember: "const o = {}; [...o.a] = [shared]; o.a[0].x = 2;",
iteratedObjectRest:
"const o = {}; for ({...o.a} of [{child: shared}]) o.a.child.x = 2;",
iteratedArrayRest: "const o = {}; for ([...o.a] of [[shared]]) o.a[0].x = 2;",
classField:
"class Holder {} const o = new Holder(); o.a = shared; o.a.x = 2;",
};
const source = [
...Object.entries(stores).map(
([name, body]) =>
`export function ${name}() { const shared = {x: 1}; ${body} return shared.x; }`,
),
"export function primitive() { const n = 1; const o = {}; o.a = n; o.a = 2; return n; }",
"export function nestedChild() { const shared = {inner: {x: 1}}; const o = {}; o.a = shared; o.a.inner.x = 2; return shared.inner.x; }",
"export function readOnlyStore() { const shared = {x: 1}; const o = {}; o.a = shared; const captured = o.a.x; return shared.x; }",
"export function copiedScalar() { const shared = {x: 1}; const o = {}; o.a = {...shared}; o.a.x = 2; return shared.x; }",
"export function copiedArrayScalar() { const shared = {x: 1}; const o = {}; o.a = [shared.x]; o.a[0] = 2; return shared.x; }",
"export function unrelated() { const shared = {x: 1}; const other = {x: 9}; const o = {}; o.a = shared; o.a.x = 2; return other.x; }",
"export function copiedChild() { const child = {x: 1}; const parent = {child, keep: 7}; const o = {}; o.a = {...parent}; o.a.child.x = 2; return {child: child.x, keep: parent.keep}; }",
"export function objectRestExclusion() { const child = {x: 1}; const skip = {x: 3}; const parent = {child, skip, keep: 7}; const o = {}; let ignored; ({skip: ignored, ...o.a} = parent); o.a.child.x = 2; return {child: child.x, skip: skip.x, keep: parent.keep}; }",
"export function arrayRestOffset() { const child = {x: 1}; const skip = {x: 3}; const items = [skip, child]; const o = {}; let ignored; [ignored, ...o.a] = items; o.a[0].x = 2; return {child: child.x, skip: items[0].x}; }",
].join("\n");
const assertReturns = (fields: JavaScriptReturnFields): void => {
for (const name of [...Object.keys(stores), "nestedChild"]) {
const field = fields(name).find(({ path }) => path === "");
expect(field, name).toBeDefined();
expect(field?.state, name).toMatch(/^(unknown|literal)$/);
if (field?.state === "literal") expect(field.value, name).toBe(2);
}
const readOnly = fields("readOnlyStore").find(({ path }) => path === "");
expect(readOnly?.state).toMatch(/^(unknown|literal)$/);
if (readOnly?.state === "literal") expect(readOnly.value).toBe(1);
for (const [name, value] of Object.entries({
primitive: 1,
copiedScalar: 1,
copiedArrayScalar: 1,
unrelated: 9,
}))
expect(fields(name), name).toContainEqual(
expect.objectContaining({ path: "", state: "literal", value }),
);
const child = fields("copiedChild").find(({ path }) => path === "/child");
expect(child?.state).toMatch(/^(unknown|literal)$/);
if (child?.state === "literal") expect(child.value).toBe(2);
expect(fields("copiedChild")).toContainEqual(
expect.objectContaining({ path: "/keep", state: "literal", value: 7 }),
);
for (const name of ["objectRestExclusion", "arrayRestOffset"]) {
const child = fields(name).find(({ path }) => path === "/child");
expect(child?.state, name).toMatch(/^(unknown|literal)$/);
if (child?.state === "literal") expect(child.value, name).toBe(2);
expect(fields(name), name).toContainEqual(
expect.objectContaining({ path: "/skip", state: "literal", value: 3 }),
);
}
expect(fields("objectRestExclusion")).toContainEqual(
expect.objectContaining({ path: "/keep", state: "literal", value: 7 }),
);
};
cliTest(
"does not report stale literals after storing references in member slots",
({ cli }) => verifyJavaScriptReturnShapes(cli, source, assertReturns),
120_000,
);
@@ -0,0 +1,76 @@
import { execFile } from "node:child_process";
import { mkdir } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const execute = promisify(execFile);
const MARKER = "REA_TEST_RESOLVED ";
// Dependencies that only one command uses; startup must not resolve them.
const DEFERRED_PACKAGES = ["playwright-core", "isomorphic-git"] as const;
// Report each resolved deferred package on stderr without changing resolution.
const RESOLUTION_HOOK = `data:text/javascript,${encodeURIComponent(`
import { registerHooks } from "node:module";
const packages = ${JSON.stringify(DEFERRED_PACKAGES)};
registerHooks({
resolve(specifier, context, next) {
const resolved = next(specifier, context);
const name = packages.find((item) =>
resolved.url.includes("/node_modules/" + item + "/"),
);
if (name !== undefined)
process.stderr.write(${JSON.stringify(MARKER)} + name + "\\n");
return resolved;
},
});
`)}`;
const resolvedPackages = async (
arguments_: readonly string[],
): Promise<ReadonlySet<string>> => {
const { stderr } = await execute(
process.execPath,
[`--import=${RESOLUTION_HOOK}`, ...arguments_],
{ cwd: process.cwd(), maxBuffer: 16 * 1_024 * 1_024 },
);
return new Set(
stderr
.split("\n")
.filter((line) => line.startsWith(MARKER))
.map((line) => line.slice(MARKER.length)),
);
};
const evaluate = (source: string): readonly string[] => [
"--input-type=module",
"--eval",
source,
];
describe("CLI startup imports", () => {
it("detects each deferred package when its command code loads", async () => {
await expect(
resolvedPackages(
evaluate('await import("./dist/composition/browserScenario.js");'),
),
).resolves.toContain("playwright-core");
const source = await createTestTempDirectory("rea-startup-imports-");
await mkdir(join(source, ".git"));
await expect(
resolvedPackages(
evaluate(
`const { readReferenceSourceVcs } = await import("./dist/application/ReferenceSourceVcsAdapter.js"); await readReferenceSourceVcs(${JSON.stringify(source)});`,
),
),
).resolves.toContain("isomorphic-git");
});
it("does not load command-specific packages to register commands", async () => {
await expect(
resolvedPackages(["scripts/rea.mjs", "--help"]),
).resolves.toEqual(new Set());
});
});
@@ -169,7 +169,7 @@ const createBuildCacheFixture = async (): Promise<string> => {
"scripts/clean-build-output.mjs",
"scripts/generate-package-metadata.mjs",
"scripts/lib/generated-file.mjs",
"skill-src/reverse-engineer-anything/SKILL.md",
".agents/skills/reverse-engineer-anything/SKILL.md",
"src/generatedPackageMetadata.ts",
];
await Promise.all(
@@ -21,7 +21,7 @@ async function fixture(eol = "\n") {
await mkdir(dirname(join(root, path)), { recursive: true });
await copyFile(join(repositoryRoot, path), join(root, path));
}
const sourceRoot = join(root, "skill-src/reverse-engineer-anything");
const sourceRoot = join(root, ".agents/skills/reverse-engineer-anything");
const outputRoot = join(root, "skills/reverse-engineer-anything");
await mkdir(join(sourceRoot, "references"), { recursive: true });
await mkdir(join(root, "dist"));
@@ -0,0 +1,44 @@
import { execFile } from "node:child_process";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
it("analyzes direct returns after deep source without exhausting the default process stack", async () => {
const root = await createTestTempDirectory("rea-deep-direct-returns-");
await writeFile(
join(root, "app.js"),
`export function render() { object${".property".repeat(20_000)}; function nested() { return "nested"; } class Inner { method() { return "method"; } } return "ready"; }`,
);
const service = new URL(
"../../../dist/application/javascript/JavaScriptApplicationService.js",
import.meta.url,
).href;
const script = `
import { analyzeJavaScriptApplication } from ${JSON.stringify(service)};
const result = await analyzeJavaScriptApplication({ input_path: ${JSON.stringify(root)}, format: "directory" });
if (!result.ok) throw result.error;
const nodes = result.value.normalized_result.semantic_graph.nodes;
console.log(JSON.stringify(nodes.filter(node => node.kind === "return-site").map(node => node.function_node_id)));
`;
const { stdout, stderr } = await promisify(execFile)(
process.execPath,
["--input-type=module", "-e", script],
{
timeout: 10_000,
// Bound the child heap while retaining Node's default stack size.
env: {
HOME: root,
TMPDIR: root,
NODE_OPTIONS: "--max-old-space-size=768",
},
},
);
expect(stderr).toBe("");
const owners: unknown = JSON.parse(stdout);
expect(owners).toHaveLength(3);
expect(new Set(Array.isArray(owners) ? owners : []).size).toBe(3);
});
+76 -1
View File
@@ -1,4 +1,6 @@
import { readFile } from "node:fs/promises";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { readFile, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -43,6 +45,79 @@ describe("production MCP doctor", () => {
);
}, 30_000);
it("rejects a schema-invalid probe while retaining the discovered inventory", async () => {
const root = await createTestTempDirectory("rea-mcp-doctor-reply-");
const snapshotPath = join(root, "reply.json");
const environment = { PATH: process.env.PATH ?? "" };
const client = new Client({ name: "doctor-reply-capture", version: "1" });
const transport = new StdioClientTransport({
command: process.execPath,
args: [resolve("scripts/rea.mjs"), "mcp"],
cwd: process.cwd(),
env: environment,
stderr: "pipe",
});
transport.stderr?.on("data", () => undefined);
try {
await client.connect(transport);
const tools = await client.listTools();
const prompts = await client.listPrompts();
const toolDefinition = tools.tools.find(
({ name }) => name === "binary_session",
);
if (toolDefinition === undefined)
throw new Error("Production binary_session contract is missing");
const reply = await client.callTool(
{ name: "binary_session", arguments: {} },
{ toolDefinition },
);
await writeFile(
snapshotPath,
JSON.stringify({
serverInfo: client.getServerVersion(),
protocolVersion: client.getNegotiatedProtocolVersion(),
tools,
prompts,
reply,
}),
);
} finally {
await client.close();
await transport.close();
}
// Replay real production metadata through a synthetic stdio producer.
for (const mode of ["valid", "invalid"]) {
const result = await runProductionMcpDoctor({
command: process.execPath,
args: [
resolve("tests/fixtures/mcpDoctorReply.mjs"),
snapshotPath,
mode,
],
cwd: process.cwd(),
environment,
});
expect(result.healthy).toBe(mode === "valid");
expect(result.inventory?.tools.observed).toBe(
CATALOG_IDENTITY.counts.mcp_tools,
);
expect(result.inventory?.prompts.observed).toBe(
CATALOG_IDENTITY.counts.mcp_prompts,
);
expect(result.checks).toContainEqual({
name: "initialize",
ok: true,
detail: expect.any(String),
});
if (mode === "invalid")
expect(result.checks).toContainEqual({
name: "request-flow",
ok: false,
detail: expect.stringMatching(/output schema/iu),
});
}
}, 30_000);
it("reports exact missing, unexpected, and duplicate inventory names", () => {
expect(compareInventory(["a", "b"], ["b", "c", "c"])).toEqual({
expected: 2,
@@ -0,0 +1,108 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { McpServer } from "@modelcontextprotocol/server";
import { expect, it } from "vitest";
import { z } from "zod";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { toolOutputSchemaWithMetadata } from "../../../src/contracts/toolSchemaMetadata.js";
const advertised = <
Schema extends z.ZodType<Readonly<Record<string, unknown>>>,
>(
schema: Schema,
): Schema =>
toolOutputSchemaWithMetadata({
...toolContract("binary_session"),
outputSchema: schema,
});
const connect = async (server: McpServer, client: Client): Promise<void> => {
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
};
it("validates changed schemas after catalog refreshes and availability changes", async () => {
const client = new Client({ name: "output-reuse-test", version: "1" });
const server = new McpServer({ name: "output-reuse-fixture", version: "1" });
const schema = advertised(z.strictObject({ state: z.literal("ready") }));
let state = "ready";
const selected = server.registerTool(
"selected",
{ inputSchema: z.strictObject({}), outputSchema: schema },
() => ({ content: [], structuredContent: { state } }),
);
server.registerTool(
"equivalent",
{ inputSchema: z.strictObject({}), outputSchema: schema },
() => ({ content: [], structuredContent: { state: "ready" } }),
);
try {
await connect(server, client);
await client.listTools();
expect(
(await client.callTool({ name: "selected" })).structuredContent,
).toEqual({
state: "ready",
});
await client.listTools();
await client.callTool({ name: "equivalent" });
selected.update({
outputSchema: advertised(z.strictObject({ state: z.literal("updated") })),
});
state = "updated";
await client.listTools();
expect(
(await client.callTool({ name: "selected" })).structuredContent,
).toEqual({
state: "updated",
});
selected.disable();
const unavailable = await client.listTools();
expect(unavailable.tools.some((tool) => tool.name === "selected")).toBe(
false,
);
await expect(client.callTool({ name: "selected" })).rejects.toThrow(
/not found|disabled/iu,
);
await client.callTool({ name: "equivalent" });
selected.enable();
await client.listTools();
await client.callTool({ name: "selected" });
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
it("uses the new server's schema after reconnecting the client", async () => {
const client = new Client({ name: "output-reconnect-test", version: "1" });
const servers: McpServer[] = [];
try {
for (const state of ["first", "second"]) {
const server = new McpServer({ name: `fixture-${state}`, version: "1" });
servers.push(server);
server.registerTool(
"selected",
{
inputSchema: z.strictObject({}),
outputSchema: advertised(z.strictObject({ state: z.literal(state) })),
},
() => ({ content: [], structuredContent: { state } }),
);
await connect(server, client);
await client.listTools();
expect(
(await client.callTool({ name: "selected" })).structuredContent,
).toEqual({ state });
await client.close();
await server.close();
}
} finally {
await Promise.allSettled([
client.close(),
...servers.map((server) => server.close()),
]);
}
});
@@ -64,6 +64,7 @@ itWithCaptureCapability(
).toBe(true);
expect(capture.manifest.comparison_contract).toMatchObject({
port_normalization_version: "contextual-endpoints-v2",
rendered_line_format: "trailing-spaces-trimmed-v1",
});
expect(capture.exit).toMatchObject({ code: 0, reason: "exited" });
expect(capture.cleanup).toMatchObject({
@@ -1,4 +1,5 @@
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
@@ -7,6 +8,7 @@ import { expect, it, onTestFinished } from "vitest";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { compareProcessCaptures } from "../../../src/domain/process/processComparison.js";
import { parseProcessCapture } from "../../../src/domain/process/processCaptureParsing.js";
import { parseProcessScenario } from "../../../src/domain/process/processScenario.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
@@ -58,6 +60,108 @@ const captureViaMcp = async (scenario: Record<string, unknown>) => {
return evidence;
};
itWithCaptureCapability.each(["cli", "mcp"] as const)(
"hashes the documented complete report despite omitted terminal output through %s",
async (adapter) => {
const document = await readFile("docs/process-capture.md", "utf8");
const example = document
.split("## Hash a report independently of terminal output")[1]
?.match(/```json\n([\s\S]*?)\n```/u)?.[1];
if (example === undefined)
throw new Error("Missing report capture example");
const scenario = parseProcessScenario(JSON.parse(example));
const root = await createTestTempDirectory("rea-full-report-adapter-");
const evidence = await (adapter === "cli" ? captureViaCli : captureViaMcp)({
...scenario,
executable: process.execPath,
working_directory: root,
filesystem_observation_paths: [join(root, "reports")],
});
const capture = parseProcessCapture(evidence.normalized_result);
const bytes = await readFile(join(root, "reports", "final.json"));
expect(JSON.parse(bytes.toString())).toEqual({
status: "complete",
data: "X".repeat(131072),
});
expect(bytes.length).toBeGreaterThan(scenario.limits.output_bytes);
expect(capture.files_after).toContainEqual(
expect.objectContaining({
path: "root_0:final.json",
size: bytes.length,
sha256: createHash("sha256").update(bytes).digest("hex"),
}),
);
expect(capture.truncation_details.filesystem_after).toMatchObject({
enumeration_truncated: false,
hash_budget_bytes: scenario.limits.file_bytes,
hashed_bytes: bytes.length,
hash_omissions: [],
});
expect(capture.truncation_details.raw_terminal.retained_bytes).toBeLessThan(
capture.truncation_details.raw_terminal.observed_bytes,
);
},
20_000,
);
itWithCaptureCapability.each(["cli", "mcp"] as const)(
"accounts for exact cumulative hash budgets independently at each %s checkpoint",
async (adapter) => {
const runCapture = adapter === "cli" ? captureViaCli : captureViaMcp;
for (const shortfall of [0, 1]) {
const root = await createTestTempDirectory("rea-report-cumulative-");
const periodic = Buffer.from('{"status":"running"}');
const final = Buffer.from('{"status":"complete"}');
await writeFile(join(root, "periodic.json"), periodic);
const budget = periodic.length + final.length - shortfall;
const evidence = await runCapture({
executable: process.execPath,
arguments: [
"-e",
"require('node:fs').writeFileSync('final.json','{\"status\":\"complete\"}')",
],
working_directory: root,
filesystem_observation_paths: [root],
limits: { output_bytes: 1, file_bytes: budget },
});
const capture = parseProcessCapture(evidence.normalized_result);
expect(capture.truncation_details.filesystem_before).toMatchObject({
hashed_bytes: periodic.length,
hash_omissions: [],
});
expect(capture.files_after).toContainEqual(
expect.objectContaining({
path: "root_0:final.json",
sha256: createHash("sha256").update(final).digest("hex"),
}),
);
expect(capture.truncation_details.filesystem_after).toMatchObject({
enumeration_truncated: false,
hashed_bytes: final.length + (shortfall === 0 ? periodic.length : 0),
hash_omissions:
shortfall === 0
? []
: [
{
path: "root_0:periodic.json",
reason: "file_bytes_budget",
remaining_budget_bytes: periodic.length - 1,
},
],
});
expect(
capture.files_after.find(({ path }) => path === "root_0:periodic.json")
?.sha256,
).toBe(
shortfall === 0
? createHash("sha256").update(periodic).digest("hex")
: null,
);
}
},
20_000,
);
itWithCaptureCapability.each(["cli", "mcp"] as const)(
"reports unknown absence instead of deletion in truncated %s capture Evidence",
async (adapter) => {
@@ -552,6 +552,43 @@ describe("native macOS provider inspection", () => {
});
});
describe("native macOS provider raw results", () => {
it("records command provenance once, in the normalized result", async () => {
directory = await createTestTempDirectory("rea-native-");
const app = join(directory, "Fixture.app");
const executable = join(app, "Contents/MacOS/Fixture");
await mkdir(join(app, "Contents/MacOS"), { recursive: true });
await writeFile(executable, "fixture");
await writeFile(join(app, "Contents/Info.plist"), "fixture");
const client = new NativeMacOSProvider(
{},
new FixtureRunner(),
"darwin",
).createClient(await nativeMachoTargetForFile(executable, app));
const requests: readonly (readonly [
Parameters<typeof client.execute>[0],
Parameters<typeof client.execute>[1],
])[] = [
["inspect_macho", {}],
["list_architectures", {}],
["inspect_signature", {}],
["inspect_plist", {}],
["demangle_swift", { symbols: ["$s4Test3fooyyF", "plain_symbol"] }],
];
for (const [operation, parameters] of requests) {
const execution = await client.execute(operation, parameters);
if (!execution.ok) throw execution.error;
expect(execution.value.rawResult, operation).toBeNull();
expect(execution.value.result, operation).toMatchObject({
provenance: expect.arrayContaining([
expect.objectContaining({ tool: expect.any(String) }),
]),
});
}
});
});
describe("native plist defaults for iOS-style bundles", () => {
it("defaults to the Info.plist the bundle program was resolved from", async () => {
directory = await createTestTempDirectory("rea-native-flat-");
@@ -89,6 +89,45 @@ describe("static Electron application analysis", () => {
expect(requestedMembers).toEqual(["*"]);
});
it("maps Electron boundaries through bundler-renamed bindings", async () => {
const root = await renamedBindingFixtureDirectory();
const result = await reconstructJavaScriptArtifact({ input_path: root });
const graph = parseJavaScriptApplicationGraph(result.graph);
const handledChannels = graph.nodes.flatMap(({ kind, observations }) =>
kind === "ipc-handler"
? observations.flatMap(({ properties }) =>
properties.side === "main" ? [properties.channel] : [],
)
: [],
);
expect(result.electron_summary).toMatchObject({
browser_windows: 1,
context_bridge_apis: 1,
exposed_api_members: 2,
ipc: {
main_handlers: 2,
paired_renderer_transmissions: 2,
unpaired_literal_renderer_transmissions: 0,
},
utility_processes: 1,
});
expect(handledChannels.sort()).toEqual(["rea:read", "rea:write"]);
});
it("maps unchanged var and let require aliases while excluding reassigned bindings", async () => {
const root = await requireAliasFixtureDirectory();
const result = await reconstructJavaScriptArtifact({ input_path: root });
expect(result.electron_summary.ipc).toMatchObject({
main_handlers: 2,
paired_renderer_transmissions: 2,
unpaired_literal_renderer_transmissions: 0,
});
});
it("returns a tagged cancellation without executing application code", async () => {
const root = await fixtureDirectory();
const controller = new AbortController();
@@ -299,6 +338,89 @@ const fixtureDirectory = async (): Promise<string> => {
return root;
};
const requireAliasFixtureDirectory = async (): Promise<string> => {
const root = await createTestTempDirectory("rea-electron-require-aliases-");
await Promise.all([
writeFile(
join(root, "package.json"),
JSON.stringify({
name: "rea-electron-require-aliases",
main: "main.cjs",
}),
),
writeFile(
join(root, "main.cjs"),
String.raw`
var { ipcMain: main } = require("electron");
let listener = require("electron/main").ipcMain;
main.handle("rea:read", async () => "value");
listener.on("rea:write", () => undefined);
let replaced = require("electron").ipcMain;
replaced = { handle() {} };
replaced.handle("rea:reassigned", () => undefined);
var assignedLater;
assignedLater.handle("rea:before-assignment", () => undefined);
assignedLater = require("electron").ipcMain;
if (globalThis.registerIpc) {
var conditional = require("electron").ipcMain;
}
conditional.handle("rea:conditional", () => undefined);
`,
),
writeFile(
join(root, "preload.cjs"),
String.raw`
const { ipcRenderer } = require("electron");
ipcRenderer.invoke("rea:read");
ipcRenderer.send("rea:write", "value");
`,
),
]);
return root;
};
const renamedBindingFixtureDirectory = async (): Promise<string> => {
const root = await createTestTempDirectory("rea-electron-renamed-");
await Promise.all([
writeFile(
join(root, "package.json"),
JSON.stringify({ name: "rea-electron-renamed", main: "main.mjs" }),
),
// Bundlers rename colliding imports, e.g. esbuild's ipcMain2.
writeFile(
join(root, "main.mjs"),
String.raw`
import { BrowserWindow as BrowserWindow2, ipcMain as ipcMain2 } from "electron";
import { ipcMain as ipcMain3, utilityProcess as utility } from "electron/main";
new BrowserWindow2({ webPreferences: { preload: "./preload.cjs" } });
ipcMain2.handle("rea:read", async () => "value");
ipcMain3.on("rea:write", () => undefined);
utility.fork("./worker.js");
function register(ipcMain2) {
ipcMain2.handle("rea:shadowed", async () => "local");
}
export { register };
`,
),
writeFile(
join(root, "preload.cjs"),
String.raw`
const { contextBridge: bridge, ipcRenderer: ipc } = require("electron");
bridge.exposeInMainWorld("reaApi", {
read: () => ipc.invoke("rea:read"),
write: (value) => ipc.send("rea:write", value),
});
`,
),
writeFile(join(root, "worker.js"), "module.exports = {};"),
]);
return root;
};
const computedMemberFixtureDirectory = async (): Promise<string> => {
const root = await createTestTempDirectory("rea-electron-computed-members-");
await mkdir(join(root, "native"));
+8 -3
View File
@@ -8,10 +8,15 @@ __attribute__((noinline, used)) int rea_cross_leaf(int value) {
}
__attribute__((noinline, used)) int rea_cross_branch(int value) {
if (value > 10) {
return rea_cross_leaf(value);
/* A volatile-dependent loop keeps this callee multi-block at every
optimization level: newer clang folds a symmetric if/else of tail calls
into a conditional negate, and cross-format verification requires a
recovered multi-block callee. */
int adjusted = value > 10 ? value + 1 : -value;
while (adjusted > 100) {
adjusted -= rea_cross_global;
}
return rea_cross_leaf(-value);
return rea_cross_leaf(adjusted);
}
__attribute__((noinline, used)) int rea_cross_indirect(
+4 -1
View File
@@ -74,7 +74,10 @@ export const createJadxProtocolFixture = async (
ownsProcessLifetime: true,
cleanup: () => cleanupOwnedProcessGroup(spawned.ownership),
});
expect((await supervisor.stop()).status).not.toBe("incomplete");
const stopped = await supervisor.stop();
expect(stopped, JSON.stringify(stopped)).not.toMatchObject({
status: "incomplete",
});
if (options.cwd !== undefined)
await rm(options.cwd, { recursive: true, force: true });
});
+91
View File
@@ -0,0 +1,91 @@
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { expect } from "vitest";
import { toolContract } from "../../src/contracts/toolContracts.js";
import { javascriptApplicationAnalysisResultSchema } from "../../src/domain/javascript/javascriptApplicationAnalysis.js";
import { projectedExportReturnShapesSchema } from "../../src/domain/javascript/javascriptExportShapeComparisonSchemas.js";
import { createTestTempDirectory } from "./temporaryDirectory.js";
import type { TestCli } from "../support/cli/cliFixture.js";
const exportedReturnFields = (value: unknown) => {
const analysis = javascriptApplicationAnalysisResultSchema.parse(value);
const projections = analysis.graph.nodes
.flatMap(({ observations }) => observations)
.filter(
({ properties }) => properties.semantic_role === "export-return-shapes",
)
.map(({ properties }) =>
projectedExportReturnShapesSchema.parse(properties),
);
return (name: string) => {
const projection = projections.find(
({ exported_name }) => exported_name === name,
);
if (projection === undefined) throw new Error(`Missing export ${name}`);
expect(projection.return_shape_coverage).toMatchObject({
status: "complete",
projection_complete: true,
});
return projection.static_return_shapes.flatMap(({ fields }) => fields);
};
};
/** Select complete return fields from a real JavaScript application result. */
export type JavaScriptReturnFields = ReturnType<typeof exportedReturnFields>;
/** Exercise identical return assertions through the compiled CLI and stdio MCP. */
export const verifyJavaScriptReturnShapes = async (
cli: TestCli,
source: string,
check: (fields: JavaScriptReturnFields) => void,
): Promise<void> => {
const root = await createTestTempDirectory("rea-return-shapes-");
await writeFile(join(root, "app.js"), source);
const cliResponse = await cli.run({
arguments: [
"analyze-javascript-application",
root,
"--artifact-format",
"directory",
"--json",
],
});
expect(cliResponse.exitCode).toBe(0);
const contract = toolContract("analyze_javascript_application");
const cliEvidence = contract.outputSchema.parse(cliResponse.json);
check(exportedReturnFields(cliEvidence.normalized_result));
const client = new Client({ name: "return-shapes-e2e", version: "1" });
const transport = new StdioClientTransport({
command: process.execPath,
args: [resolve("scripts/rea.mjs"), "mcp"],
cwd: process.cwd(),
env: { PATH: process.env.PATH ?? "" },
stderr: "pipe",
});
transport.stderr?.on("data", () => undefined);
try {
await client.connect(transport);
const response = await client.callTool({
name: "analyze_javascript_application",
arguments: { input_path: root, format: "directory" },
});
expect(response.isError).not.toBe(true);
const evidence = contract.outputSchema.parse(response.structuredContent);
expect(evidence.evidence_id).toBe(cliEvidence.evidence_id);
check(exportedReturnFields(evidence.normalized_result));
const text = response.content.find((item) => item.type === "text");
if (text?.type !== "text") throw new Error("Missing MCP text result");
check(
exportedReturnFields(
contract.outputSchema.parse(JSON.parse(text.text)).normalized_result,
),
);
await client.ping();
} finally {
await client.close();
await transport.close();
}
};
+48
View File
@@ -0,0 +1,48 @@
import { readFile } from "node:fs/promises";
import { createInterface } from "node:readline";
const snapshot = JSON.parse(await readFile(process.argv[2], "utf8"));
const reply = structuredClone(snapshot.reply);
if (process.argv[3] === "invalid") {
reply.structuredContent.schema_violation_control = true;
reply.content = reply.content.map((item) =>
item.type === "text"
? { ...item, text: JSON.stringify(reply.structuredContent) }
: item,
);
}
const input = createInterface({ input: process.stdin });
input.on("line", (line) => {
const request = JSON.parse(line);
if (request.id === undefined) return;
let result;
switch (request.method) {
case "initialize":
result = {
protocolVersion: snapshot.protocolVersion,
capabilities: { tools: {}, prompts: {} },
serverInfo: snapshot.serverInfo,
};
break;
case "tools/list":
result = snapshot.tools;
break;
case "prompts/list":
result = snapshot.prompts;
break;
case "tools/call":
if (request.params.name === "binary_session") result = reply;
break;
case "ping":
result = {};
break;
}
const response =
result === undefined
? { error: { code: -32601, message: "Unknown fixture method or tool" } }
: { result };
process.stdout.write(
`${JSON.stringify({ jsonrpc: "2.0", id: request.id, ...response })}\n`,
);
});