chore: integrate main for process progress verification

This commit is contained in:
N0zoM1z0
2026-10-10 17:33:17 +08:00
252 changed files with 13258 additions and 1040 deletions
@@ -0,0 +1,263 @@
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { createHash } from "node:crypto";
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 { applicationVersionComparisonResultSchema } from "../../../src/domain/javascript/javascriptApplicationVersionComparisonSchemas.js";
import { applicationFeatureTraceResultSchema } from "../../../src/domain/javascript/javascriptFeatureTraceSchemas.js";
import { javaScriptSemanticTraceResultSchema } from "../../../src/domain/javascript/javascriptSemanticTraceSchemas.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
cliTest(
"keeps full endpoint evidence usable without copying large values into metadata",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-endpoint-payload-");
const endpoint = `https://example.invalid/${"part/ğ".repeat(160_000)}`;
const digestLookalike = `value-sha256:${createHash("sha256").update(JSON.stringify(endpoint)).digest("hex")}`;
// UTF-8 replacement would conflate these distinct JavaScript strings.
const surrogate = "\ud800".repeat(100);
const replacement = "\ufffd".repeat(100);
const values = [
endpoint,
digestLookalike,
"/ok",
"/ok",
surrogate,
replacement,
];
const source = values
.map((value) => `fetch(${JSON.stringify(value)});`)
.join("\n");
const sourcePath = join(root, "main.js");
await writeFile(sourcePath, source);
const cliResponse = await cli.run({
arguments: [
"analyze-javascript-application",
root,
"--artifact-format",
"directory",
"--json",
],
timeoutMs: 60_000,
});
expect(cliResponse.exitCode).toBe(0);
const cliEvidence = toolContract(
"analyze_javascript_application",
).outputSchema.parse(cliResponse.json);
const client = new Client({ name: "endpoint-payload-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 = toolContract(
"analyze_javascript_application",
).outputSchema.parse(response.structuredContent);
expect(evidence.evidence_id).toBe(cliEvidence.evidence_id);
const text = response.content.find((item) => item.type === "text");
if (text?.type !== "text") throw new Error("Missing MCP text result");
const textEvidence = toolContract(
"analyze_javascript_application",
).outputSchema.parse(JSON.parse(text.text));
expect(textEvidence.evidence_id).toBe(evidence.evidence_id);
const result = javascriptApplicationAnalysisResultSchema.parse(
evidence.normalized_result,
);
const endpoints = result.graph.nodes.filter(
(node) => node.kind === "endpoint",
);
const nodeFor = (value: string) => {
const node = endpoints.find((candidate) =>
candidate.observations.some(
({ properties }) => properties.value === value,
),
);
if (node === undefined) throw new Error("Complete endpoint was lost");
return node;
};
const endpointNode = nodeFor(endpoint);
expect(
new Set(
[endpoint, digestLookalike, surrogate, replacement].map(
(value) => nodeFor(value).node_id,
),
).size,
).toBe(4);
const repeatedNode = nodeFor("/ok");
expect(
endpoints.filter((node) =>
node.observations.some(
({ properties }) => properties.value === "/ok",
),
),
).toHaveLength(1);
expect(repeatedNode.observations).toHaveLength(2);
expect(repeatedNode.identity).toMatchObject({ key: "/ok" });
expect(
repeatedNode.observations.every(({ label }) => label === "/ok"),
).toBe(true);
expect(endpointNode.identity).toMatchObject({
artifact_sha256: createHash("sha256").update(source).digest("hex"),
});
expect(endpointNode.observations[0]?.evidence.location).toMatchObject({
available: true,
value: { kind: "source-range", source: "main.js" },
});
const requests = result.semantic_graph.nodes.filter(
(node) =>
node.kind === "request" && node.properties.endpoint === endpoint,
);
expect(requests).toHaveLength(1);
await verifyEndpointWorkflows({
client,
evidenceId: evidence.evidence_id,
endpoint,
endpointNodeId: endpointNode.node_id,
requestNodeIds: requests.map(({ node_id }) => node_id),
root,
source,
sourcePath,
});
await client.ping();
} finally {
await client.close();
await transport.close();
}
},
120_000,
);
interface EndpointWorkflowInput {
readonly client: Client;
readonly evidenceId: string;
readonly endpoint: string;
readonly endpointNodeId: string;
readonly requestNodeIds: readonly string[];
readonly root: string;
readonly source: string;
readonly sourcePath: string;
}
const verifyEndpointWorkflows = async ({
client,
evidenceId,
endpoint,
endpointNodeId,
requestNodeIds,
root,
source,
sourcePath,
}: EndpointWorkflowInput): Promise<void> => {
const application = {
kind: "retained-evidence",
evidence_id: evidenceId,
};
const featureResponse = await client.callTool({
name: "trace_application_feature",
arguments: {
application,
seed: {
kind: "string",
value: endpoint,
match: "exact",
case_sensitive: true,
},
},
});
expect(featureResponse.isError).not.toBe(true);
const featureEvidence = toolContract(
"trace_application_feature",
).outputSchema.parse(featureResponse.structuredContent);
const feature = applicationFeatureTraceResultSchema.parse(
featureEvidence.normalized_result,
);
expect(feature.seed_matches.map(({ node_id }) => node_id)).toContain(
endpointNodeId,
);
const traceResponse = await client.callTool({
name: "trace_javascript_semantics",
arguments: {
application,
query: {
seed: { kind: "endpoint", value: endpoint },
direction: "backward-provenance",
},
},
});
expect(traceResponse.isError).not.toBe(true);
const traceEvidence = toolContract(
"trace_javascript_semantics",
).outputSchema.parse(traceResponse.structuredContent);
const trace = javaScriptSemanticTraceResultSchema.parse(
traceEvidence.normalized_result,
);
expect(trace.seed_node_ids).toEqual(requestNodeIds);
expect(
trace.nodes.some((node) => node.properties.endpoint === endpoint),
).toBe(true);
await writeFile(sourcePath, `// next artifact version\n${source}`);
const nextResponse = await client.callTool({
name: "analyze_javascript_application",
arguments: { input_path: root, format: "directory" },
});
expect(nextResponse.isError).not.toBe(true);
const nextEvidence = toolContract(
"analyze_javascript_application",
).outputSchema.parse(nextResponse.structuredContent);
const next = javascriptApplicationAnalysisResultSchema.parse(
nextEvidence.normalized_result,
);
const nextEndpoint = next.graph.nodes.find(
(node) =>
node.kind === "endpoint" &&
node.observations.some(({ properties }) => properties.value === endpoint),
);
if (nextEndpoint === undefined) throw new Error("Next endpoint was lost");
const comparisonResponse = await client.callTool({
name: "compare_application_versions",
arguments: {
left: application,
right: {
kind: "retained-evidence",
evidence_id: nextEvidence.evidence_id,
},
},
});
expect(comparisonResponse.isError).not.toBe(true);
const comparisonEvidence = toolContract(
"compare_application_versions",
).outputSchema.parse(comparisonResponse.structuredContent);
const comparison = applicationVersionComparisonResultSchema.parse(
comparisonEvidence.normalized_result,
);
expect(comparison.items).toContainEqual(
expect.objectContaining({
node_kind: "endpoint",
left_node_id: endpointNodeId,
right_node_id: nextEndpoint.node_id,
match: expect.objectContaining({
status: "matched",
basis: "semantic-key",
}),
}),
);
};
@@ -0,0 +1,164 @@
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { createHash } from "node:crypto";
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 { javaScriptSemanticTraceResultSchema } from "../../../src/domain/javascript/javascriptSemanticTraceSchemas.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
cliTest(
"retains large event names and emitter-scoped listener ownership through CLI and stdio MCP",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-event-payload-");
const name = "payload/ğ".repeat(80_000);
const lookalike = `value-sha256:${createHash("sha256").update(JSON.stringify(name)).digest("hex")}`;
const source = [
'import {EventEmitter} from "node:events";',
"const bus = new EventEmitter(); const other = new EventEmitter(); const handler = () => {};",
`bus.on(${JSON.stringify(name)}, handler);`,
`bus.emit(${JSON.stringify(name)});`,
`bus.off(${JSON.stringify(name)}, handler);`,
`bus.on(${JSON.stringify(lookalike)}, handler); bus.emit(${JSON.stringify(lookalike)});`,
'bus.on("ok", handler); bus.emit("ok"); other.on("ok", handler); other.emit("ok");',
"bus.on(getEventName(), handler);",
].join("\n");
await writeFile(join(root, "main.js"), source);
const cliResponse = await cli.run({
arguments: [
"analyze-javascript-application",
root,
"--artifact-format",
"directory",
"--json",
],
timeoutMs: 60_000,
});
expect(cliResponse.exitCode).toBe(0);
const cliEvidence = toolContract(
"analyze_javascript_application",
).outputSchema.parse(cliResponse.json);
const client = new Client({ name: "event-payload-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 = toolContract(
"analyze_javascript_application",
).outputSchema.parse(response.structuredContent);
expect(evidence.evidence_id).toBe(cliEvidence.evidence_id);
const text = response.content.find((item) => item.type === "text");
if (text?.type !== "text") throw new Error("Missing MCP text result");
expect(
toolContract("analyze_javascript_application").outputSchema.parse(
JSON.parse(text.text),
).evidence_id,
).toBe(evidence.evidence_id);
const graph = javascriptApplicationAnalysisResultSchema.parse(
evidence.normalized_result,
).semantic_graph;
const events = graph.nodes.filter((node) => node.kind === "event");
const selected = events.filter(
(node) => node.properties.event_name === name,
);
expect(selected).toHaveLength(1);
const event = selected[0];
if (event === undefined) throw new Error("Complete event was lost");
const listeners = graph.nodes.filter(
(node) =>
node.kind === "listener" && node.properties.event_name === name,
);
expect(new Set(listeners.map((node) => node.properties.method))).toEqual(
new Set(["on", "off"]),
);
const listenerIds = new Set(listeners.map((node) => node.node_id));
expect(
graph.relations
.filter(
(relation) =>
relation.source_node_id === event.node_id &&
listenerIds.has(relation.target_node_id),
)
.map((relation) => relation.relation),
).toEqual(
expect.arrayContaining(["registers-listener", "removes-listener"]),
);
const lookalikeEvent = events.find(
(node) => node.properties.event_name === lookalike,
);
expect(lookalikeEvent).toBeDefined();
expect(lookalikeEvent?.node_id).not.toBe(event.node_id);
const shortEvents = events.filter(
(node) => node.properties.event_name === "ok",
);
expect(shortEvents).toHaveLength(2);
expect(
new Set(shortEvents.map((node) => node.properties.emitter_key)).size,
).toBe(2);
expect(
shortEvents.every(
(node) =>
node.label === "ok" && node.identity.role_key.endsWith("\0ok"),
),
).toBe(true);
const dynamic = events.find(
(node) => node.properties.event_name === null,
);
expect(dynamic?.label).toBeNull();
expect(
graph.unknowns.some(
(unknown) =>
unknown.node_id === dynamic?.node_id && unknown.family === "event",
),
).toBe(true);
const traceResponse = await client.callTool({
name: "trace_javascript_semantics",
arguments: {
application: {
kind: "retained-evidence",
evidence_id: evidence.evidence_id,
},
query: {
seed: { kind: "event", name },
direction: "forward-influence",
},
},
});
expect(traceResponse.isError).not.toBe(true);
const traceEvidence = toolContract(
"trace_javascript_semantics",
).outputSchema.parse(traceResponse.structuredContent);
const trace = javaScriptSemanticTraceResultSchema.parse(
traceEvidence.normalized_result,
);
expect(new Set(trace.seed_node_ids)).toEqual(
new Set([event.node_id, ...listenerIds]),
);
expect(
trace.nodes
.filter((node) => listenerIds.has(node.node_id))
.map((node) => node.properties.event_name),
).toEqual(listeners.map(() => name));
await client.ping();
} finally {
await client.close();
await transport.close();
}
},
120_000,
);
@@ -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,100 @@
import { expect } from "vitest";
import {
verifyJavaScriptReturnShapes,
type JavaScriptReturnFields,
} from "../../fixtures/javascriptReturnShapes.js";
import { cliTest } from "../../support/cli/cliFixture.js";
const writes = {
direct: "const get = () => shared; get().x = 2;",
captured: "const get = () => shared; const t = get(); t.x = 2;",
declaration:
"function get() { return shared; } const o = {}; o.a = get(); o.a.x = 2;",
immediate: "const o = {}; o.a = (() => shared)(); o.a.x = 2;",
method:
"const box = {get() { return shared; }}; const o = {}; o.a = box.get(); o.a.x = 2;",
methodDirect: "const box = {get() { return shared; }}; box.get().x = 2;",
quotedMethod:
"const box = {['get/ref']() { return shared; }}; box['get/ref']().x = 2;",
alias: "const get = () => shared; const another = get; another().x = 2;",
alternative: "const get = true ? () => shared : () => ({x: 0}); get().x = 2;",
nestedReturn: "const get = () => ({child: shared}); get().child.x = 2;",
arrayReturn: "const get = () => [shared]; get()[0].x = 2;",
returnedProperty:
"const holder = {inner: shared}; const get = () => holder.inner; get().x = 2;",
transitive:
"const first = () => shared; const second = () => first(); second().x = 2;",
updated: "const get = () => shared; get().x++;",
asyncAwait: "const get = async () => shared; const t = await get(); t.x = 2;",
generator:
"function* get() { yield shared; } for (const t of get()) t.x = 2;",
returnedYield:
"function* get() { return yield shared; } for (const t of get()) t.x = 2;",
delegatedYield:
"function* get() { yield* [shared]; } for (const t of get()) t.x = 2;",
recursiveWrapper:
"let count = 0; const get = () => count++ === 0 ? {child: get()} : shared; get().child.x = 2;",
destructuredMethod:
"const box = {get() { return shared; }}; const {get} = box; get().x = 2;",
arrayCallable: "const methods = [() => shared]; methods[0]().x = 2;",
spreadArrayCallable:
"const methods = [...[], () => shared]; methods[0]().x = 2;",
classMethod:
"class Box { get() { return shared; } } const box = new Box(); box.get().x = 2;",
staticMethod:
"class Box { static get() { return shared; } } Box.get().x = 2;",
constructor:
"function Box() { return shared; } const t = new Box(); t.x = 2;",
callback: "const get = () => shared; [0].forEach(() => { get().x = 2; });",
};
const source = [
...Object.entries(writes).map(
([name, body]) =>
`export ${name === "asyncAwait" ? "async " : ""}function ${name}(){ const shared = {x: 1}; ${body} return shared.x; }`,
),
"export function directSibling(){ const shared = {x: 1}; const parent = {shared, keep: 7}; const get = () => parent.shared; get().x = 2; return {x: shared.x, keep: parent.keep}; }",
"export function primitive(){ const n = 1; const get = () => n; const t = get(); return n; }",
"export function copy(){ const shared = {x: 1}; const get = () => ({...shared}); get().x = 2; return shared.x; }",
"export function methodCopy(){ const shared = {x: 1}; const box = {get(){ return {...shared}; }}; box.get().x = 2; return shared.x; }",
"export function arrayCopy(){ const shared = {x: 1}; const get = () => [shared.x]; get()[0] = 2; return shared.x; }",
"export function unused(){ const shared = {x: 1}; const get = () => shared; get(); return shared.x; }",
"export function nestedCallable(){ const shared = {x: 1}; const get = () => { const inner = () => shared; return {x: 0}; }; get().x = 2; return shared.x; }",
"export function unrelated(){ const shared = {x: 1}; const other = {x: 9}; const get = () => shared; get().x = 2; return other.x; }",
].join("\n");
const assertReturns = (fields: JavaScriptReturnFields): void => {
for (const name of Object.keys(writes)) {
const field = fields(name).find(({ path }) => path === "");
expect(field?.state, name).toMatch(/^(unknown|literal)$/);
if (field?.state === "literal") expect(field.value, name).toBe(2);
}
const changed = fields("directSibling").find(({ path }) => path === "/x");
expect(changed?.state).toMatch(/^(unknown|literal)$/);
if (changed?.state === "literal") expect(changed.value).toBe(2);
expect(fields("directSibling")).toContainEqual(
expect.objectContaining({ path: "/keep", state: "literal", value: 7 }),
);
for (const name of [
"primitive",
"copy",
"methodCopy",
"arrayCopy",
"nestedCallable",
])
expect(fields(name), name).toContainEqual(
expect.objectContaining({ path: "", state: "literal", value: 1 }),
);
const unused = fields("unused").find(({ path }) => path === "");
expect(unused?.state).toMatch(/^(unknown|literal)$/);
if (unused?.state === "literal") expect(unused.value).toBe(1);
expect(fields("unrelated")).toContainEqual(
expect.objectContaining({ path: "", state: "literal", value: 9 }),
);
};
cliTest(
"preserves mutation uncertainty for objects returned by local calls",
({ 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,
);
@@ -144,6 +144,8 @@ describe("production stdio runtime", () => {
expect(evidence.operation).toBe("current_document");
expect(evidence.provider.id).toBe("hopper");
expect(evidence.normalized_result).toBe(observation.normalized_result);
// Hopper's reply is the result; it is not repeated as raw_result.
expect(evidence.raw_result).toBeNull();
expect(records).toContainEqual(
expect.objectContaining({
application: "rea",
@@ -0,0 +1,98 @@
import { access, mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { parse } from "yaml";
import { expect } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
cliTest(
"Hermes setup, doctor and uninstall use the expanded profile and its personal skill",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-hermes-cli-");
const profile = join(home, "profile");
const config = join(profile, "config.yaml");
const skill = join(profile, "skills/reverse-engineer-anything/SKILL.md");
const original =
"# user settings\nmodel: custom\nmcp_servers:\n other:\n command: other-server\n";
await mkdir(profile);
await writeFile(config, original);
const run = (arguments_: readonly string[]) =>
cli.run({
arguments: arguments_,
cwd: home,
environment: {
HOME: home,
USERPROFILE: home,
HERMES_HOME: " ${HOME}/profile ",
},
timeoutMs: 20_000,
});
const planned = await run([
"setup",
"--client",
"hermes",
"--dry-run",
"--json",
]);
expect(planned.exitCode).toBe(0);
expect(planned.json).toMatchObject({
status: "planned",
plannedActions: expect.arrayContaining([
expect.objectContaining({ target: config }),
expect.objectContaining({
target: join(profile, "skills/reverse-engineer-anything"),
}),
]),
});
expect(await readFile(config, "utf8")).toBe(original);
await expect(access(skill)).rejects.toMatchObject({ code: "ENOENT" });
const applied = await run([
"setup",
"--client",
"hermes",
"--yes",
"--json",
]);
expect(applied.exitCode).toBe(0);
expect(applied.json).toMatchObject({ status: "ready" });
expect(parse(await readFile(config, "utf8"))).toMatchObject({
model: "custom",
mcp_servers: {
other: { command: "other-server" },
rea: { enabled: true },
},
});
expect(await readFile(config + ".rea.backup", "utf8")).toBe(original);
expect(await readFile(skill, "utf8")).toContain(
"reverse-engineer-anything",
);
await expect(
access(join(home, ".agents/skills/reverse-engineer-anything/SKILL.md")),
).rejects.toMatchObject({ code: "ENOENT" });
const doctor = await run([
"doctor",
"--client",
"hermes",
"--skill",
"--json",
]);
expect(doctor.exitCode).toBe(0);
expect(doctor.json).toMatchObject({
healthy: true,
identity: { skill: { state: "aligned" } },
});
const repeat = await run([
"setup",
"--client",
"hermes",
"--yes",
"--json",
]);
expect(repeat.json).toMatchObject({ status: "ready", appliedActions: [] });
const uninstall = await run(["uninstall", "--json"]);
expect(uninstall.exitCode).toBe(0);
expect(parse(await readFile(config, "utf8"))).toEqual(parse(original));
await expect(access(skill)).rejects.toMatchObject({ code: "ENOENT" });
},
);
@@ -0,0 +1,311 @@
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { expect } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
cliTest(
"Pi public CLI plans, requires approval, applies, diagnoses, repeats, and uninstalls only owned content",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-pi-cli-");
const agent = join(home, "custom-agent");
const config = join(agent, "mcp.json");
const skill = join(
home,
".agents/skills/reverse-engineer-anything/SKILL.md",
);
const original =
'{ "mcpServers": { "other": { "command": "other-server" } }, "autoEnableCodemode": false }\n';
await mkdir(agent);
await writeFile(config, original);
const cliPath = resolve("scripts/rea.mjs");
const run = (arguments_: readonly string[]) =>
cli.run({
arguments: arguments_,
cwd: home,
environment: {
HOME: home,
USERPROFILE: home,
PI_CODING_AGENT_DIR: "custom-agent",
OMP_PROFILE: "work",
PI_PROFILE: "legacy",
PI_CONFIG_DIR: ".omp-other",
},
timeoutMs: 20_000,
});
const planned = await run([
"setup",
"--client",
"pi",
"--dry-run",
"--json",
]);
expect(planned.exitCode).toBe(0);
expect(planned.json).toMatchObject({
status: "planned",
plannedActions: [
{
id: "configure_client:pi",
label: "Pi",
target: join("custom-agent", "mcp.json"),
operation: "update",
},
{ id: "install_skill" },
],
appliedActions: [],
});
expect(await readFile(config, "utf8")).toBe(original);
await expect(readFile(`${config}.rea.backup`)).rejects.toMatchObject({
code: "ENOENT",
});
await expect(readFile(skill)).rejects.toMatchObject({ code: "ENOENT" });
const unapproved = await run(["setup", "--client", "pi", "--json"]);
expect(unapproved.json).toMatchObject({
status: "needs_confirmation",
appliedActions: [],
});
expect(await readFile(config, "utf8")).toBe(original);
const applied = await run(["setup", "--client", "pi", "--yes", "--json"]);
expect(applied.exitCode).toBe(0);
expect(applied.json).toMatchObject({
status: "ready",
clients: { pi: { status: "configured" } },
appliedActions: ["configured_pi", "installed_skill"],
});
const configured = await readFile(config, "utf8");
expect(JSON.parse(configured)).toMatchObject({
mcpServers: {
other: { command: "other-server" },
rea: {
type: "stdio",
command: process.platform === "win32" ? process.execPath : cliPath,
args: process.platform === "win32" ? [cliPath, "mcp"] : ["mcp"],
},
},
autoEnableCodemode: false,
});
expect(await readFile(`${config}.rea.backup`, "utf8")).toBe(original);
expect(await readFile(skill, "utf8")).toContain(
"reverse-engineer-anything",
);
const doctor = await run(["doctor", "--client", "pi", "--json"]);
expect(doctor.exitCode).toBe(0);
expect(doctor.json).toMatchObject({
healthy: true,
identity: {
registrations: expect.arrayContaining([
expect.objectContaining({ client: "pi", state: "aligned" }),
]),
},
});
const repeat = await run(["setup", "--client", "pi", "--yes", "--json"]);
expect(repeat.exitCode).toBe(0);
expect(repeat.json).toMatchObject({
status: "ready",
plannedActions: [],
appliedActions: [],
});
expect(await readFile(config, "utf8")).toBe(configured);
expect(await readFile(`${config}.rea.backup`, "utf8")).toBe(original);
// Uninstall is global; there is no --client or --yes on this CLI surface.
const help = await run(["uninstall", "--help"]);
expect(help.exitCode).toBe(0);
expect(help.stdout).toContain("--purge-data");
const removed = await run(["uninstall", "--json"]);
expect(removed.exitCode).toBe(0);
expect(JSON.parse(await readFile(config, "utf8"))).toEqual(
JSON.parse(original),
);
expect(await readFile(`${config}.rea.backup`, "utf8")).toBe(original);
await expect(readFile(skill)).rejects.toMatchObject({ code: "ENOENT" });
},
);
cliTest(
"Pi public CLI creates missing strict-JSON configuration and never repairs a malformed file",
async ({ cli }) => {
const created = await createTestTempDirectory("rea-pi-cli-strict-");
const agent = join(created, "custom-agent");
const config = join(agent, "mcp.json");
await mkdir(agent);
const runIn = (home: string) => (arguments_: readonly string[]) =>
cli.run({
arguments: arguments_,
cwd: home,
environment: {
HOME: home,
USERPROFILE: home,
PI_CODING_AGENT_DIR: "custom-agent",
},
timeoutMs: 20_000,
});
const run = runIn(created);
const setup = await run(["setup", "--client", "pi", "--yes", "--json"]);
expect(setup.exitCode).toBe(0);
expect(setup.json).toMatchObject({
status: "ready",
clients: { pi: { status: "configured" } },
});
const text = await readFile(config, "utf8");
expect(() => JSON.parse(text)).not.toThrow();
expect(JSON.parse(text)).toMatchObject({
mcpServers: { rea: { type: "stdio" } },
});
const doctor = await run(["doctor", "--client", "pi", "--json"]);
expect(doctor.exitCode).toBe(0);
expect(doctor.json).toMatchObject({
healthy: true,
identity: {
registrations: expect.arrayContaining([
expect.objectContaining({ client: "pi", state: "aligned" }),
]),
},
});
await run(["uninstall", "--json"]);
expect(
JSON.parse(await readFile(config, "utf8")).mcpServers.rea,
).toBeUndefined();
const blocked = await createTestTempDirectory("rea-pi-cli-malformed-");
const malformedPath = join(blocked, "custom-agent", "mcp.json");
await mkdir(join(blocked, "custom-agent"));
const malformed = `{ // Pi loads strict JSON only\n"mcpServers": { "other": { "command": "other" } }\n}\n`;
await writeFile(malformedPath, malformed);
const runMalformed = runIn(blocked);
const plan = await runMalformed([
"setup",
"--client",
"pi",
"--dry-run",
"--json",
]);
expect(plan.exitCode).not.toBe(0);
expect(plan.json).toMatchObject({
status: "needs_human",
plannedActions: [],
appliedActions: [],
remediation: expect.stringContaining("malformed"),
});
const applied = await runMalformed([
"setup",
"--client",
"pi",
"--yes",
"--json",
]);
expect(applied.exitCode).not.toBe(0);
expect(applied.json).toMatchObject({
status: "needs_human",
plannedActions: [],
appliedActions: [],
});
expect(await readFile(malformedPath, "utf8")).toBe(malformed);
await expect(readFile(`${malformedPath}.rea.backup`)).rejects.toMatchObject(
{
code: "ENOENT",
},
);
const doctorMalformed = await runMalformed([
"doctor",
"--client",
"pi",
"--json",
]);
expect(doctorMalformed.exitCode).not.toBe(0);
expect(doctorMalformed.json).toMatchObject({
healthy: false,
identity: {
registrations: expect.arrayContaining([
expect.objectContaining({ client: "pi", state: "invalid" }),
]),
},
});
const removed = await runMalformed(["uninstall", "--json"]);
expect(removed.exitCode).not.toBe(0);
expect(removed.json).toMatchObject({
status: "failed",
items: expect.arrayContaining([
expect.objectContaining({ name: "pi", status: "failed" }),
]),
});
expect(await readFile(malformedPath, "utf8")).toBe(malformed);
},
);
cliTest(
"malformed Pi overrides do not block selected Codex setup or doctor and never fall back for Pi",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-pi-invalid-cli-");
const run = (arguments_: readonly string[]) =>
cli.run({
arguments: arguments_,
cwd: home,
environment: {
HOME: home,
USERPROFILE: home,
PI_CODING_AGENT_DIR: "file:///agent%2fdir",
},
timeoutMs: 20_000,
});
const plan = await run([
"setup",
"--client",
"codex",
"--dry-run",
"--json",
]);
expect(plan.exitCode).toBe(0);
expect(plan.json).toMatchObject({ status: "planned", appliedActions: [] });
expect(await readdir(home)).toEqual([]);
const rejected = await run(["setup", "--client", "pi", "--yes", "--json"]);
expect(rejected.exitCode).not.toBe(0);
expect(rejected.json).toMatchObject({
status: "needs_human",
plannedActions: [],
appliedActions: [],
remediation: expect.stringContaining("PI_CODING_AGENT_DIR"),
});
expect(await readdir(home)).toEqual([]);
const applied = await run([
"setup",
"--client",
"codex",
"--yes",
"--json",
]);
expect(applied.exitCode).toBe(0);
expect(applied.json).toMatchObject({
status: "ready",
clients: { codex: { status: "configured" } },
});
const doctor = await run(["doctor", "--client", "codex", "--json"]);
expect(doctor.exitCode).toBe(0);
expect(doctor.json).toMatchObject({
healthy: true,
identity: {
registrations: [
{ client: "codex", state: "aligned" },
{
client: "pi",
state: "invalid",
remediation: expect.stringContaining("PI_CODING_AGENT_DIR"),
},
],
},
});
const piDoctor = await run(["doctor", "--client", "pi", "--json"]);
expect(piDoctor.exitCode).not.toBe(0);
expect(piDoctor.json).toMatchObject({ healthy: false });
expect((await readdir(home)).sort()).toEqual([".agents", ".codex"]);
},
);
@@ -0,0 +1,96 @@
import { access, mkdir, readFile, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { parse } from "jsonc-parser";
import { expect } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
cliTest(
"keeps Qwen profile registration and shared skill consistent through setup, doctor and uninstall",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-qwen-profile-");
const home = join(root, "account");
const profile = join(root, "selected profile");
const settings = join(profile, "settings.json");
const skill = join(
home,
".agents",
"skills",
"reverse-engineer-anything",
"SKILL.md",
);
const environment = { USERPROFILE: home, QWEN_HOME: profile };
const original =
'{\n // Keep my configuration.\n "model": {"name": "existing"},\n "mcpServers": {"other": {"command": "other-server"}}\n}\n';
await mkdir(profile, { recursive: true });
await writeFile(settings, original);
const run = (arguments_: readonly string[]) =>
cli.run({ arguments: [...arguments_, "--json"], environment });
const plan = await run(["setup", "--client", "qwen_code", "--dry-run"]);
expect(plan.exitCode, plan.stderr).toBe(0);
expect(plan.json).toMatchObject({
status: "planned",
plannedActions: [
{ kind: "configure_client", target: settings },
{
kind: "install_skill",
target: join(home, ".agents", "skills", "reverse-engineer-anything"),
},
],
});
expect(await readFile(settings, "utf8")).toBe(original);
await expect(access(skill)).rejects.toMatchObject({ code: "ENOENT" });
const installed = await run(["setup", "--client", "qwen_code", "--yes"]);
expect(installed.exitCode, installed.stderr).toBe(0);
expect(installed.json).toMatchObject({ status: "ready" });
expect(await readFile(`${settings}.rea.backup`, "utf8")).toBe(original);
const configured = await readFile(settings, "utf8");
expect(configured).toContain("// Keep my configuration.");
expect(parse(configured)).toMatchObject({
model: { name: "existing" },
mcpServers: {
other: { command: "other-server" },
rea: {
command:
process.platform === "win32"
? process.execPath
: resolve("scripts/rea.mjs"),
args:
process.platform === "win32"
? [resolve("scripts/rea.mjs"), "mcp"]
: ["mcp"],
},
},
});
expect(await readFile(skill, "utf8")).toContain(
"name: reverse-engineer-anything",
);
const doctor = await run(["doctor", "--client", "qwen_code", "--skill"]);
expect(doctor.exitCode, doctor.stderr).toBe(0);
expect(doctor.json).toMatchObject({ healthy: true });
const repeated = await run(["setup", "--client", "qwen_code", "--yes"]);
expect(repeated.exitCode, repeated.stderr).toBe(0);
expect(repeated.json).toMatchObject({
status: "ready",
appliedActions: [],
});
expect(await readFile(settings, "utf8")).toBe(configured);
const removed = await run(["uninstall"]);
expect(removed.exitCode, removed.stderr).toBe(0);
expect(removed.json).toMatchObject({ status: "complete" });
expect(parse(await readFile(settings, "utf8"))).toEqual({
model: { name: "existing" },
mcpServers: { other: { command: "other-server" } },
});
await expect(access(skill)).rejects.toMatchObject({ code: "ENOENT" });
await expect(access(join(home, ".qwen"))).rejects.toMatchObject({
code: "ENOENT",
});
},
120_000,
);
@@ -83,18 +83,22 @@ it("reports real HAR heap exhaustion through CLI and MCP and preserves server us
});
expect(JSON.stringify(response)).not.toContain("caller-marked");
expect(JSON.stringify(response)).not.toContain("rea doctor");
await expect(
execute(process.execPath, [
cli,
"inspect-web-network-capture",
path,
"har",
"--json",
]),
).rejects.toMatchObject({
code: 1,
stdout: expect.stringContaining('"code": "resource_constraint"'),
});
const failed: unknown = await execute(process.execPath, [
cli,
"inspect-web-network-capture",
path,
"har",
"--json",
]).then(
() => undefined,
(cause: unknown) => cause,
);
expect(failed).toMatchObject({ code: 1 });
const stdout =
typeof failed === "object" && failed !== null && "stdout" in failed
? String(failed.stdout)
: "";
expect(JSON.parse(stdout)).toMatchObject({ code: "resource_constraint" });
const small = join(root, "small.har");
await writeFile(small, capture(2));
await client.ping();
@@ -7,6 +7,8 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
import { analysisViewLayoutEvidence } from "../../fixtures/analysisView.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { ghidraFunctionDossier } from "../../../src/domain/ghidraValues.fixture.js";
cliTest(
"projects one section from a JSON file of inline layout Evidence",
async ({ cli }) => {
@@ -43,6 +45,48 @@ cliTest(
},
);
cliTest(
"projects native function pseudocode without requiring Ghidra",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-native-view-cli-");
const parent = createEvidence(
{ path: "/fixtures/native.exe", format: "pe", sha256: "a".repeat(64) },
{ id: "ghidra", name: "Ghidra", version: "12.1.4" },
{
operation: "analyze_function",
parameters: { address: "0x401000" },
result: ghidraFunctionDossier(),
},
);
const input = join(root, "native-view.json");
await writeFile(
input,
JSON.stringify({
source: { kind: "inline", evidence: parent },
view: { kind: "native", facet: "pseudocode", offset: 0, limit: 12 },
}),
);
const result = await cli.run({
arguments: ["inspect-analysis-view", input, "--json"],
environment: { HOME: root, XDG_CONFIG_HOME: root, XDG_CACHE_HOME: root },
});
expect(result.exitCode).toBe(0);
expect(result.json).toMatchObject({
operation: "inspect_analysis_view",
normalized_result: {
kind: "native",
parent_evidence_id: parent.evidence_id,
procedure_address: "0x401000",
item: { text: "int fixture_", unit: "utf16-code-units" },
},
locations: [
{ kind: "artifact-path", path: "/fixtures/native.exe" },
{ kind: "address", address: "0x401000" },
],
});
},
);
cliTest("rejects malformed JSON before projection", async ({ cli }) => {
const root = await createTestTempDirectory("rea-analysis-view-cli-bad-");
const result = await cli.run({
@@ -80,3 +124,48 @@ cliTest("rejects a request that omits source", async ({ cli }) => {
details: { operation: "inspect-analysis-view" },
});
});
for (const [view, reason] of [
[{ kind: "unknown-view" }, "invalid_value"],
[{}, "missing_argument"],
] as const) {
cliTest(
`reports correction details for ${reason} view kind`,
async ({ cli }) => {
const root = await createTestTempDirectory("rea-view-variant-");
const input = join(root, "view.json");
await writeFile(
input,
JSON.stringify({
source: {
kind: "inline",
evidence: analysisViewLayoutEvidence(),
},
view,
}),
);
const result = await cli.run({
arguments: ["inspect-analysis-view", input, "--json"],
environment: {
HOME: root,
XDG_CONFIG_HOME: root,
XDG_CACHE_HOME: root,
},
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "invalid_request",
details: {
issues: [
{
path: ["view", "kind"],
reason,
expected: expect.arrayContaining(["summary", "page"]),
},
],
},
});
expect(JSON.stringify(result.json)).not.toContain("unknown-view");
},
);
}
@@ -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());
});
});
+786
View File
@@ -0,0 +1,786 @@
import { access, mkdir, readFile, writeFile, rm } from "node:fs/promises";
import { dirname, join } from "node:path";
import { expect } from "vitest";
import { parse } from "jsonc-parser";
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
const cases = [
{
client: "gemini_cli",
env: { GEMINI_CLI_HOME: "profile" },
config: "profile/.gemini/settings.json",
skill: "profile/.agents/skills",
},
{
client: "opencode",
env: { OPENCODE_CONFIG_DIR: "profile" },
config: "profile/opencode.json",
skill: ".agents/skills",
},
{
client: "opencode",
env: { OPENCODE_CONFIG_DIR: "" },
config: ".config/opencode/opencode.json",
skill: ".agents/skills",
},
{
client: "codex",
env: { CODEX_HOME: "" },
config: ".codex/config.toml",
skill: ".agents/skills",
},
{
client: "grok_build",
env: { GROK_HOME: "" },
config: ".grok/config.toml",
skill: ".agents/skills",
},
{
client: "omp",
env: { PI_CODING_AGENT_DIR: "profile" },
config: "profile/mcp.json",
skill: ".agents/skills",
},
{
client: "devin",
env: { XDG_CONFIG_HOME: "profile" },
config: "profile/devin/mcp_config.json",
skill: ".agents/skills",
},
{
client: "antigravity",
env: {},
config: ".gemini/config/mcp_config.json",
skill: ".gemini/config/skills",
},
];
for (const testCase of cases.filter(
({ client }) => process.platform !== "win32" || client !== "devin",
)) {
cliTest(
`${testCase.client} lifecycle follows the selected roots (${testCase.config})`,
async ({ cli }) => {
const home = await createTestTempDirectory("rea-client-profile-");
const environment: NodeJS.ProcessEnv = { HOME: home, USERPROFILE: home };
for (const [key, value] of Object.entries(testCase.env))
environment[key] = value === "profile" ? join(home, value) : value;
// OMP's relative override is relative to the caller, not silently ignored.
if (testCase.client === "omp")
environment.PI_CODING_AGENT_DIR = "profile";
const config = join(home, testCase.config);
const skillDirectory = join(
home,
testCase.skill,
"reverse-engineer-anything",
);
const run = (arguments_: readonly string[]) =>
cli.run({
arguments: arguments_,
cwd: home,
environment,
timeoutMs: 20_000,
});
const planned = await run([
"setup",
"--client",
testCase.client,
"--dry-run",
"--json",
]);
expect(planned.exitCode).toBe(0);
expect(planned.json).toMatchObject({
status: "planned",
plannedActions: expect.arrayContaining([
expect.objectContaining({ target: config }),
expect.objectContaining({ target: skillDirectory }),
]),
});
await expect(access(config)).rejects.toMatchObject({ code: "ENOENT" });
const setup = await run([
"setup",
"--client",
testCase.client,
"--yes",
"--json",
]);
expect(setup.exitCode).toBe(0);
expect(setup.json).toMatchObject({ status: "ready" });
await expect(access(config)).resolves.toBeUndefined();
expect(
await readFile(join(skillDirectory, "SKILL.md"), "utf8"),
).toContain("reverse-engineer-anything");
await expect(access(join(home, "config.toml"))).rejects.toMatchObject({
code: "ENOENT",
});
const doctor = await run([
"doctor",
"--client",
testCase.client,
"--skill",
"--json",
]);
expect(doctor.exitCode).toBe(0);
expect(doctor.json).toMatchObject({
healthy: true,
identity: { skill: { state: "aligned" } },
});
if (testCase.client === "grok_build") {
const original = await readFile(config, "utf8");
await writeFile(
config,
original.replace(
"[mcp_servers.rea]",
"[mcp_servers.rea]\ndisabled = true",
),
);
expect(
(await run(["doctor", "--client", "grok_build", "--json"])).exitCode,
).toBe(0);
await writeFile(config, original);
}
const repeat = await run([
"setup",
"--client",
testCase.client,
"--yes",
"--json",
]);
expect(repeat.json).toMatchObject({
status: "ready",
appliedActions: [],
});
const uninstall = await run(["uninstall", "--json"]);
expect(uninstall.exitCode).toBe(0);
expect(uninstall.json).toMatchObject({ status: "complete" });
await expect(
access(join(skillDirectory, "SKILL.md")),
).rejects.toMatchObject({ code: "ENOENT" });
},
);
}
for (const policy of [{ excluded: ["rea"] }, { allowed: ["other"] }]) {
cliTest(
`Gemini refuses a registration blocked by ${Object.keys(policy)[0]}`,
async ({ cli }) => {
const home = await createTestTempDirectory("rea-gemini-policy-");
const config = join(home, ".gemini/settings.json");
const original = JSON.stringify({
mcp: policy,
mcpServers: {
rea: {
command: "npx",
args: ["-y", PRODUCT_IDENTITY.registrationPackageSpecifier, "mcp"],
},
},
});
await mkdir(dirname(config), { recursive: true });
await writeFile(config, original);
const run = (arguments_: readonly string[]) =>
cli.run({
arguments: arguments_,
cwd: home,
environment: { HOME: home, USERPROFILE: home },
timeoutMs: 20_000,
});
const setup = await run([
"setup",
"--client",
"gemini_cli",
"--yes",
"--json",
]);
expect(setup.exitCode).toBe(1);
expect(setup.json).toMatchObject({
status: "needs_human",
plannedActions: [],
appliedActions: [],
remediation: expect.stringContaining("mcp." + Object.keys(policy)[0]),
});
expect(await readFile(config, "utf8")).toBe(original);
await expect(access(config + ".rea.backup")).rejects.toMatchObject({
code: "ENOENT",
});
const doctor = await run(["doctor", "--client", "gemini_cli", "--json"]);
expect(doctor.exitCode).toBe(1);
expect(doctor.json).toMatchObject({
healthy: false,
identity: {
registrations: expect.arrayContaining([
expect.objectContaining({
client: "gemini_cli",
state: "stale",
remediation: expect.stringContaining("mcp."),
}),
]),
},
});
},
);
}
cliTest(
"OpenCode diagnoses merged JSON/JSONC and removes owned entries from both files",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-opencode-layers-");
const directory = join(home, ".config/opencode");
await mkdir(directory, { recursive: true });
const lower = join(directory, "opencode.json");
const higher = join(directory, "opencode.jsonc");
const originalLower = JSON.stringify({
mcp: {
rea: {
type: "local",
command: [
"npx",
"-y",
PRODUCT_IDENTITY.registrationPackageSpecifier,
"mcp",
],
enabled: true,
},
other: { type: "local", command: ["other"] },
},
});
const originalHigher =
'// keep this comment\n{"mcp":{"rea":{"enabled":false}},"theme":"system"}\n';
await writeFile(lower, originalLower);
await writeFile(higher, originalHigher);
const run = (arguments_: readonly string[]) =>
cli.run({
arguments: arguments_,
cwd: home,
environment: { HOME: home, USERPROFILE: home },
timeoutMs: 20_000,
});
const before = await run(["doctor", "--client", "opencode", "--json"]);
expect(before.exitCode).toBe(1);
expect(before.json).toMatchObject({
identity: {
registrations: expect.arrayContaining([
expect.objectContaining({ client: "opencode", state: "stale" }),
]),
},
});
const setup = await run([
"setup",
"--client",
"opencode",
"--yes",
"--json",
]);
expect(setup.exitCode).toBe(0);
expect(setup.json).toMatchObject({ status: "ready" });
expect(await readFile(lower, "utf8")).toBe(originalLower);
expect(await readFile(higher + ".rea.backup", "utf8")).toBe(originalHigher);
expect(await readFile(higher, "utf8")).toContain("// keep this comment");
expect(
(await run(["doctor", "--client", "opencode", "--json"])).exitCode,
).toBe(0);
const uninstall = await run(["uninstall", "--json"]);
expect(uninstall.exitCode).toBe(0);
const report = uninstall.json as {
items?: readonly { name: string; status: string }[];
};
const opencodeItems = report.items?.filter(
({ name }) => name === "opencode",
);
expect(opencodeItems).toEqual([
expect.objectContaining({ status: "removed" }),
]);
expect(parse(await readFile(lower, "utf8"))).toEqual({
mcp: { other: { type: "local", command: ["other"] } },
});
expect(parse(await readFile(higher, "utf8"))).toEqual({
mcp: {},
theme: "system",
});
},
);
cliTest(
"malformed lower-priority OpenCode config blocks setup before any writes",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-opencode-invalid-layer-");
const directory = join(home, ".config/opencode");
await mkdir(directory, { recursive: true });
const lower = join(directory, "opencode.json");
const higher = join(directory, "opencode.jsonc");
await writeFile(lower, "malformed");
await writeFile(higher, "{}");
const result = await cli.run({
arguments: ["setup", "--client", "opencode", "--yes", "--json"],
cwd: home,
environment: { HOME: home, USERPROFILE: home },
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
status: "needs_human",
plannedActions: [],
appliedActions: [],
});
expect(await readFile(lower, "utf8")).toBe("malformed");
expect(await readFile(higher, "utf8")).toBe("{}");
await expect(access(higher + ".rea.backup")).rejects.toMatchObject({
code: "ENOENT",
});
},
);
cliTest(
"Gemini system policy blocks a new registration without modifying managed files",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-gemini-managed-");
const policy = join(home, "managed.json");
const original = JSON.stringify({
mcp: { excluded: ["rea"] },
unrelated: true,
});
await writeFile(policy, original);
const environment = {
HOME: home,
USERPROFILE: home,
GEMINI_CLI_SYSTEM_SETTINGS_PATH: policy,
GEMINI_CLI_SYSTEM_DEFAULTS_PATH: join(home, "defaults.json"),
};
const setup = await cli.run({
arguments: ["setup", "--client", "gemini_cli", "--yes", "--json"],
cwd: home,
environment,
});
expect(setup.exitCode).toBe(1);
expect(setup.json).toMatchObject({
status: "needs_human",
plannedActions: [],
appliedActions: [],
remediation: expect.stringContaining("mcp.excluded"),
});
expect(await readFile(policy, "utf8")).toBe(original);
await expect(
access(join(home, ".gemini/settings.json")),
).rejects.toMatchObject({ code: "ENOENT" });
await expect(access(policy + ".rea.backup")).rejects.toMatchObject({
code: "ENOENT",
});
},
);
cliTest(
"Gemini intersects system/default/user allowlists and accepts an empty effective allowlist",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-gemini-allowlists-");
const system = join(home, "system.json");
const defaults = join(home, "defaults.json");
const user = join(home, ".gemini/settings.json");
await mkdir(dirname(user), { recursive: true });
await writeFile(
system,
JSON.stringify({ mcp: { allowed: ["rea", "other"] } }),
);
await writeFile(defaults, JSON.stringify({ mcp: { allowed: ["other"] } }));
await writeFile(
user,
JSON.stringify({ mcp: { allowed: ["rea", "other"] } }),
);
const environment = {
HOME: home,
USERPROFILE: home,
GEMINI_CLI_SYSTEM_SETTINGS_PATH: system,
GEMINI_CLI_SYSTEM_DEFAULTS_PATH: defaults,
};
const run = () =>
cli.run({
arguments: ["setup", "--client", "gemini_cli", "--yes", "--json"],
cwd: home,
environment,
});
const blocked = await run();
expect(blocked.exitCode).toBe(1);
expect(blocked.json).toMatchObject({
status: "needs_human",
appliedActions: [],
});
await writeFile(defaults, JSON.stringify({ mcp: { allowed: ["rea"] } }));
const allowed = await run();
expect(allowed.exitCode).toBe(0);
expect(allowed.json).toMatchObject({ status: "ready" });
expect(JSON.parse(await readFile(defaults, "utf8"))).toEqual({
mcp: { allowed: ["rea"] },
});
// The consumer treats an empty consolidated allowlist as unrestricted.
await writeFile(defaults, JSON.stringify({ mcp: { allowed: [] } }));
const empty = await run();
expect(empty.exitCode).toBe(0);
expect(empty.json).toMatchObject({ status: "ready", appliedActions: [] });
},
);
cliTest(
"OpenCode doctor sees a global registration when the custom directory is absent",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-opencode-absent-custom-");
const global = join(home, ".config/opencode/opencode.json");
const custom = join(home, "missing-custom");
await mkdir(dirname(global), { recursive: true });
await writeFile(
global,
JSON.stringify({
mcp: {
rea: {
type: "local",
command: [
"npx",
"-y",
PRODUCT_IDENTITY.registrationPackageSpecifier,
"mcp",
],
enabled: true,
},
},
}),
);
const run = (args: readonly string[]) =>
cli.run({
arguments: args,
cwd: home,
environment: {
HOME: home,
USERPROFILE: home,
OPENCODE_CONFIG_DIR: custom,
},
});
const doctor = await run(["doctor", "--client", "opencode", "--json"]);
expect(doctor.exitCode).toBe(0);
expect(doctor.json).toMatchObject({
identity: {
registrations: expect.arrayContaining([
expect.objectContaining({ client: "opencode", state: "aligned" }),
]),
},
});
const planned = await run([
"setup",
"--client",
"opencode",
"--dry-run",
"--json",
]);
expect(planned.json).toMatchObject({
clientStates: expect.arrayContaining([
expect.objectContaining({
client: expect.objectContaining({ name: "opencode" }),
detected: true,
}),
]),
});
await expect(access(custom)).rejects.toMatchObject({ code: "ENOENT" });
},
);
cliTest(
"OpenCode retains the XDG global layer when a custom directory is selected",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-opencode-global-custom-");
const global = join(home, ".config/opencode/opencode.json");
const custom = join(home, "custom/opencode.jsonc");
await mkdir(dirname(global), { recursive: true });
await mkdir(dirname(custom), { recursive: true });
const owned = {
type: "local",
command: [
"npx",
"-y",
PRODUCT_IDENTITY.registrationPackageSpecifier,
"mcp",
],
enabled: true,
};
const original = JSON.stringify({
mcp: { rea: owned, other: { type: "local", command: ["other"] } },
});
await writeFile(global, original);
await writeFile(custom, "{}");
const run = (args: readonly string[]) =>
cli.run({
arguments: args,
cwd: home,
environment: {
HOME: home,
USERPROFILE: home,
OPENCODE_CONFIG_DIR: dirname(custom),
},
});
const doctor = await run(["doctor", "--client", "opencode", "--json"]);
expect(doctor.json).toMatchObject({
identity: {
registrations: expect.arrayContaining([
expect.objectContaining({ client: "opencode", state: "aligned" }),
]),
},
});
await writeFile(global, "malformed");
expect(
(await run(["setup", "--client", "opencode", "--yes", "--json"])).json,
).toMatchObject({
status: "needs_human",
plannedActions: [],
appliedActions: [],
remediation: expect.stringContaining(global),
});
expect(await readFile(custom, "utf8")).toBe("{}");
await writeFile(global, original);
expect(
(await run(["setup", "--client", "opencode", "--yes", "--json"]))
.exitCode,
).toBe(0);
expect((await run(["uninstall", "--json"])).exitCode).toBe(0);
expect(parse(await readFile(global, "utf8"))).toEqual({
mcp: { other: { type: "local", command: ["other"] } },
});
expect(parse(await readFile(custom, "utf8"))).toEqual({ mcp: {} });
},
);
cliTest(
"Gemini blocks a conflicting system definition and accepts an identical managed entry",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-gemini-managed-server-");
const user = join(home, ".gemini/settings.json");
const system = join(home, "system.json");
const defaults = join(home, "defaults.json");
const environment = {
HOME: home,
USERPROFILE: home,
GEMINI_CLI_SYSTEM_SETTINGS_PATH: system,
GEMINI_CLI_SYSTEM_DEFAULTS_PATH: defaults,
};
const run = (args: readonly string[]) =>
cli.run({ arguments: args, cwd: home, environment });
const command = ["setup", "--client", "gemini_cli", "--yes", "--json"];
// A user registration overrides a default definition, including its entire env object.
await writeFile(
defaults,
JSON.stringify({
mcpServers: {
rea: { command: "managed-default", env: { EXTRA: "default" } },
},
}),
);
expect((await run(command)).exitCode).toBe(0);
const original = await readFile(user, "utf8");
const managed = JSON.stringify({
mcpServers: { rea: { command: "managed-override", args: [] } },
unrelated: true,
});
await writeFile(system, managed);
expect((await run(command)).json).toMatchObject({
status: "needs_human",
plannedActions: [],
appliedActions: [],
remediation: expect.stringContaining(system),
});
expect(
(await run(["doctor", "--client", "gemini_cli", "--json"])).json,
).toMatchObject({
healthy: false,
identity: {
registrations: expect.arrayContaining([
expect.objectContaining({
client: "gemini_cli",
state: "stale",
remediation: expect.stringContaining("mcpServers.rea"),
}),
]),
},
});
expect(await readFile(user, "utf8")).toBe(original);
expect(await readFile(system, "utf8")).toBe(managed);
const aligned = JSON.stringify({
mcpServers: JSON.parse(original).mcpServers,
});
await writeFile(system, aligned);
expect((await run(command)).json).toMatchObject({
status: "ready",
appliedActions: [],
});
expect(
(await run(["doctor", "--client", "gemini_cli", "--json"])).exitCode,
).toBe(0);
expect(await readFile(system, "utf8")).toBe(aligned);
await expect(access(system + ".rea.backup")).rejects.toMatchObject({
code: "ENOENT",
});
},
);
cliTest(
"Gemini workspace policy follows persisted trust and explicit trust overrides",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-gemini-workspace-policy-");
const project = join(home, "project");
const workspace = join(project, ".gemini/settings.json");
const trust = join(home, "trust.json");
await mkdir(dirname(workspace), { recursive: true });
const environment: NodeJS.ProcessEnv = {
HOME: home,
USERPROFILE: home,
GEMINI_CLI_SYSTEM_SETTINGS_PATH: join(home, "system.json"),
GEMINI_CLI_SYSTEM_DEFAULTS_PATH: join(home, "defaults.json"),
GEMINI_CLI_TRUSTED_FOLDERS_PATH: trust,
};
const run = (args: readonly string[]) =>
cli.run({ arguments: args, cwd: project, environment });
const command = ["setup", "--client", "gemini_cli", "--yes", "--json"];
const original = JSON.stringify({
mcp: { excluded: ["rea"] },
unrelated: true,
});
await writeFile(workspace, original);
await writeFile(
trust,
JSON.stringify({ [home]: "TRUST_FOLDER", [project]: "DO_NOT_TRUST" }),
);
expect((await run(command)).exitCode).toBe(0);
await writeFile(
trust,
JSON.stringify({ [join(project, "child")]: "TRUST_PARENT" }),
);
expect((await run(command)).json).toMatchObject({
status: "needs_human",
appliedActions: [],
remediation: expect.stringContaining(workspace),
});
expect(
(await run(["doctor", "--client", "gemini_cli", "--json"])).json,
).toMatchObject({
healthy: false,
identity: {
registrations: expect.arrayContaining([
expect.objectContaining({
client: "gemini_cli",
state: "stale",
remediation: expect.stringContaining("mcp.excluded"),
}),
]),
},
});
environment.GEMINI_CLI_TRUST_WORKSPACE = "false";
expect((await run(command)).json).toMatchObject({
status: "ready",
appliedActions: [],
});
environment.GEMINI_CLI_TRUST_WORKSPACE = "true";
await writeFile(workspace, JSON.stringify({ mcp: { allowed: ["other"] } }));
expect((await run(command)).json).toMatchObject({
status: "needs_human",
remediation: expect.stringContaining("mcp.allowed"),
});
// Restricted mode takes precedence over an explicit trust opt-in.
environment.GEMINI_RESTRICTED_MODE = "true";
expect((await run(command)).json).toMatchObject({
status: "ready",
appliedActions: [],
});
expect(JSON.parse(await readFile(workspace, "utf8"))).toEqual({
mcp: { allowed: ["other"] },
});
await expect(access(workspace + ".rea.backup")).rejects.toMatchObject({
code: "ENOENT",
});
},
);
cliTest(
"Gemini workspace definitions use shallow precedence and remain read-only",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-gemini-workspace-server-");
const project = join(home, "project");
const workspace = join(project, ".gemini/settings.json");
const system = join(home, "system.json");
await mkdir(dirname(workspace), { recursive: true });
const environment: NodeJS.ProcessEnv = {
HOME: home,
USERPROFILE: home,
GEMINI_CLI_SYSTEM_SETTINGS_PATH: system,
GEMINI_CLI_SYSTEM_DEFAULTS_PATH: join(home, "defaults.json"),
GEMINI_CLI_TRUST_WORKSPACE: "true",
};
const run = (args: readonly string[]) =>
cli.run({ arguments: args, cwd: project, environment });
const command = ["setup", "--client", "gemini_cli", "--yes", "--json"];
const original = JSON.stringify({
mcpServers: { rea: { command: "project-server", args: [] } },
});
await writeFile(workspace, original);
expect((await run(command)).json).toMatchObject({
status: "needs_human",
plannedActions: [],
appliedActions: [],
remediation: expect.stringContaining(workspace),
});
await expect(
access(join(home, ".gemini/settings.json")),
).rejects.toMatchObject({ code: "ENOENT" });
// Obtain this setup invocation's actual command while workspace settings are untrusted.
environment.GEMINI_CLI_TRUST_WORKSPACE = "false";
expect((await run(command)).exitCode).toBe(0);
const user = JSON.parse(
await readFile(join(home, ".gemini/settings.json"), "utf8"),
);
environment.GEMINI_CLI_TRUST_WORKSPACE = "true";
// System's entire entry wins over the workspace entry.
await writeFile(system, JSON.stringify({ mcpServers: user.mcpServers }));
expect((await run(command)).exitCode).toBe(0);
expect(
(await run(["doctor", "--client", "gemini_cli", "--json"])).exitCode,
).toBe(0);
expect(await readFile(workspace, "utf8")).toBe(original);
await expect(access(workspace + ".rea.backup")).rejects.toMatchObject({
code: "ENOENT",
});
},
);
cliTest(
"Gemini validates trust configuration and honors a disabled folder trust feature",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-gemini-trust-invalid-");
const project = join(home, "project");
const workspace = join(project, ".gemini/settings.json");
const user = join(home, ".gemini/settings.json");
const trust = join(home, ".gemini/trustedFolders.json");
await mkdir(dirname(workspace), { recursive: true });
await mkdir(dirname(user), { recursive: true });
await writeFile(workspace, JSON.stringify({ mcp: { excluded: ["rea"] } }));
await writeFile(trust, JSON.stringify({ [project]: "INVALID" }));
const run = () =>
cli.run({
arguments: ["setup", "--client", "gemini_cli", "--yes", "--json"],
cwd: project,
environment: {
HOME: home,
USERPROFILE: home,
GEMINI_CLI_SYSTEM_SETTINGS_PATH: join(home, "system.json"),
GEMINI_CLI_SYSTEM_DEFAULTS_PATH: join(home, "defaults.json"),
},
});
expect((await run()).json).toMatchObject({
status: "needs_human",
plannedActions: [],
appliedActions: [],
remediation: expect.stringContaining(trust),
});
await expect(access(user)).rejects.toMatchObject({ code: "ENOENT" });
await rm(trust);
await writeFile(
user,
JSON.stringify({ security: { folderTrust: { enabled: false } } }),
);
expect((await run()).json).toMatchObject({
status: "needs_human",
remediation: expect.stringContaining("mcp.excluded"),
});
},
);
+15
View File
@@ -16,6 +16,7 @@ import { silentLogger } from "../../../src/logger.js";
const collect = async (
value: unknown,
format: "json" | "jsonl" = "json",
terminal = true,
): Promise<string> => {
const chunks: Buffer[] = [];
const destination = new Writable({
@@ -28,6 +29,7 @@ const collect = async (
callback();
},
});
if (terminal) Object.defineProperty(destination, "isTTY", { value: true });
await writeJsonOutput(value, destination, format);
return Buffer.concat(chunks).toString("utf8");
};
@@ -52,6 +54,16 @@ describe("incremental CLI JSON", () => {
expect(await collect(value)).toBe(`${JSON.stringify(value, null, 2)}\n`);
});
it("indents JSON only for a terminal and writes piped JSON compactly", async () => {
const value = { nested: [{ value: null }], text: "雪𝟠" };
expect(await collect(value, "json", true)).toBe(
`${JSON.stringify(value, null, 2)}\n`,
);
expect(await collect(value, "json", false)).toBe(
`${JSON.stringify(value)}\n`,
);
});
it("writes compact JSONL records and preserves an empty record set", async () => {
const value = [{ text: "first\nrecord" }, { text: "雪𝟠" }];
expect(await collect(value, "jsonl")).toBe(
@@ -78,6 +90,7 @@ describe("incremental CLI JSON", () => {
}, 1);
},
});
Object.defineProperty(destination, "isTTY", { value: true });
await writeJsonOutput({ leaf }, destination);
expect(largestChunk).toBeLessThan(Buffer.byteLength(leaf));
const actual = Buffer.concat(chunks).toString("utf8");
@@ -212,6 +225,8 @@ describe("streamed CLI result surface", () => {
expect(operation).toBe("inspect_managed_members");
return value;
});
// A terminal destination exercises the indented encoding past the limit.
Object.defineProperty(destination, "isTTY", { value: true });
const argv = ["inspect-managed-members", "fixture.dll", "--json"];
const output = createStreamedCliJsonOutput(argv, destination);
if (output === undefined) throw new Error("Missing JSON output surface");
@@ -50,10 +50,9 @@ describe("artifact inventory entry order", () => {
const parent = artifactOccurrenceAt(observed, parentPath);
expect(observed.edges).toContainEqual(
expect.objectContaining({
logical_path: path,
occurrence_id: occurrence.occurrence_id,
relation: "contains",
parent_artifact_id: parent.artifact_id,
child_artifact_id: occurrence.artifact_id,
}),
);
}
@@ -100,7 +99,6 @@ describe("entry-order validation and reader controls", () => {
it.each([
["pkg/data.txt", "pkg/data.txt/"],
["pkg/data.txt/", "pkg/data.txt"],
["pkg/data.txt", "PKG/other.txt"],
["pkg/data.txt", "pkg"],
["../escape.txt"],
])("keeps invalid/colliding paths rejected for %j", async (...entries) => {
@@ -112,6 +110,25 @@ describe("entry-order validation and reader controls", () => {
});
});
it("keeps case-distinct directory names separate in either entry order", async () => {
const root = await createTestTempDirectory("rea-entry-order-case-");
const archive = join(root, "case-distinct.zip");
const entries = ["pkg/", "pkg/data.txt", "PKG/", "PKG/other.txt"];
const parents = {
".": null,
pkg: ".",
"pkg/data.txt": "pkg",
PKG: ".",
"PKG/other.txt": "PKG",
};
for (const ordered of [entries, entries.toReversed()]) {
await writeOrderedZip(archive, ordered);
expect(artifactParentPaths(await inventoryArtifact(archive))).toEqual(
parents,
);
}
});
it("preserves ordinary directory and ASAR structure", async () => {
const root = await createTestTempDirectory("rea-entry-order-readers-");
const directory = join(root, "source");
@@ -75,10 +75,9 @@ describe("expanded ASAR inventory containment", () => {
const child = artifactOccurrenceAt(nested, path);
expect(nested.edges).toContainEqual(
expect.objectContaining({
logical_path: path,
occurrence_id: child.occurrence_id,
relation: "contains",
parent_artifact_id: artifactOccurrenceAt(nested, parent).artifact_id,
child_artifact_id: child.artifact_id,
}),
);
if (path.startsWith("resources/app.asar/"))
@@ -9,6 +9,7 @@ import { createCli } from "../../../src/cli.js";
import { parseCliJsonInput } from "../../../src/cliJsonInput.js";
import { readCliJsonFile } from "../../../src/cliJsonFile.js";
import { analysisCliErrorEnvelopeSchema } from "../../../src/contracts/errorSchemas.js";
import { JSON_BYTE_ORDER_MARK_MESSAGE } from "../../../src/application/Utf8JsonInput.js";
import { readWithoutFifoWriter } from "../../fixtures/fifoInput.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
@@ -160,6 +161,21 @@ describe("CLI JSON streamed input", () => {
}
});
it("names a leading byte-order mark in small and streamed files", async () => {
const root = await createTestTempDirectory("rea-json-input-bom-");
const path = join(root, "input.json");
for (const body of ["{}", `${" ".repeat(9 * 1024 * 1024)}{}`]) {
await writeFile(path, `\uFEFF${body}`);
expect(await parseCliJsonInput(path, "test-input")).toMatchObject({
ok: false,
error: {
input_reason: "invalid-json",
details: { issues: [{ message: JSON_BYTE_ORDER_MARK_MESSAGE }] },
},
});
}
});
it.each([Buffer.from([0xf0, 0x28, 0x8c, 0xbc]), Buffer.from([0xe2, 0x82])])(
"rejects malformed and incomplete UTF-8 at a read boundary (%j)",
async (invalid) => {
@@ -32,6 +32,7 @@ const getClients = (home: string) =>
"vscode",
"devin",
"omp",
"pi",
].includes(name),
);
@@ -44,6 +45,7 @@ describe("additional client configuration dialects", () => {
"vscode",
"devin",
"omp",
"pi",
] as const)("registers, reads back, and uninstalls %s", async (name) => {
const home = await createTestTempDirectory("rea-client-dialect-");
const client = getClients(home).find(
@@ -78,7 +80,7 @@ describe("additional client configuration dialects", () => {
command,
enabled: true,
});
if (name === "vscode" || name === "omp")
if (name === "vscode" || name === "omp" || name === "pi")
expect(registration).toMatchObject({
type: "stdio",
command: "npx",
@@ -59,9 +59,12 @@ describe("client configuration filesystem lifecycle", () => {
"antigravity",
"copilot_cli",
"commandcode",
"qwen_code",
"vscode",
"grok_build",
"omp",
"pi",
"hermes",
"grok_bot",
]);
expect(
@@ -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,165 @@
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { parse as parseYaml } from "yaml";
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
import { npxRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js";
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
import { supportedClients } from "../../../src/application/SupportedClients.js";
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { clearClientLocationEnvironment } from "../../fixtures/clientEnvironment.js";
/**
* The registration command setup writes on the host running the tests. Windows
* wraps it in `cmd.exe /d /c`, so the expected entry follows the host too.
*/
const command = npxRegistrationCommand(process.platform);
beforeEach(clearClientLocationEnvironment);
afterEach(() => vi.unstubAllEnvs());
const hermesPath = (
env: Parameters<typeof supportedClients>[2],
platform: NodeJS.Platform = "linux",
) =>
supportedClients(join("/home/a"), platform, env).find(
({ name }) => name === "hermes",
);
describe("Hermes configuration paths", () => {
it("resolves config.yaml under the platform Hermes home", () => {
expect(hermesPath({})).toEqual({
name: "hermes",
displayName: "Hermes",
configPath: join("/home/a", ".hermes", "config.yaml"),
markerPath: join("/home/a", ".hermes"),
format: "hermes",
});
// Windows uses the native data directory, matching Hermes's own resolver.
expect(
hermesPath({ LOCALAPPDATA: "C:\\Users\\a\\AppData\\Local" }, "win32")
?.configPath,
).toBe(join("C:\\Users\\a\\AppData\\Local", "hermes", "config.yaml"));
});
it("expands and trims Hermes overrides without changing the suffix", () => {
expect(hermesPath({ HERMES_HOME: " ~/profile " })?.markerPath).toBe(
join("/home/a", "profile"),
);
expect(
hermesPath({
HERMES_HOME: "${PROFILE_ROOT}/agent",
PROFILE_ROOT: "/custom",
})?.markerPath,
).toBe(join("/custom", "agent"));
expect(
hermesPath({
HERMES_HOME: "$PROFILE_ROOT/agent",
PROFILE_ROOT: "/custom",
})?.markerPath,
).toBe(join("/custom", "agent"));
expect(hermesPath({ LOCALAPPDATA: " " }, "win32")?.markerPath).toBe(
join("/home/a", "AppData", "Local", "hermes"),
);
});
it("honours HERMES_HOME and Hermes's data-directory suffix", () => {
expect(
hermesPath({ HERMES_HOME: join("/srv", "hermes") })?.configPath,
).toBe(join("/srv", "hermes", "config.yaml"));
// A blank override falls through to the platform default.
expect(hermesPath({ HERMES_HOME: " " })?.configPath).toBe(
join("/home/a", ".hermes", "config.yaml"),
);
// Hermes appends the suffix to the literal directory name.
expect(hermesPath({ HERMES_DATA_DIR_SUFFIX: "-dev" })?.configPath).toBe(
join("/home/a", ".hermes-dev", "config.yaml"),
);
expect(
hermesPath(
{
HERMES_DATA_DIR_SUFFIX: "-dev",
LOCALAPPDATA: "C:\\Users\\a\\AppData\\Local",
},
"win32",
)?.configPath,
).toBe(join("C:\\Users\\a\\AppData\\Local", "hermes-dev", "config.yaml"));
});
});
describe("Hermes YAML registration", () => {
const hermesClient = async () => {
const home = await createTestTempDirectory("rea-hermes-");
const client = supportedClients(home, process.platform, {}).find(
({ name }) => name === "hermes",
);
if (client?.markerPath === undefined)
throw new Error("missing Hermes client");
await mkdir(client.markerPath, { recursive: true });
return { home, client };
};
it("writes mcp_servers, preserves comments, reads back, and uninstalls", async () => {
const { home, client } = await hermesClient();
await writeFile(
client.configPath,
`# Hermes configuration
display:
language: en
mcp_servers:
# An independently managed server.
other:
command: other-server
`,
);
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
const text = await readFile(client.configPath, "utf8");
expect(text).toContain("# Hermes configuration");
expect(text).toContain("# An independently managed server.");
expect(parseYaml(text)).toEqual({
display: { language: "en" },
mcp_servers: {
other: { command: "other-server" },
rea: { command: command[0], args: command.slice(1), enabled: true },
},
});
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "unchanged",
});
expect(
(
await readClientRegistrationStatuses(home, undefined, {
platform: process.platform,
environment: {},
})
).find(({ client: name }) => name === "hermes"),
).toMatchObject({ state: "aligned", command });
expect((await systemUninstallHost(home).removeClient(client)).status).toBe(
"removed",
);
expect(parseYaml(await readFile(client.configPath, "utf8"))).toEqual({
display: { language: "en" },
mcp_servers: { other: { command: "other-server" } },
});
});
it("creates config.yaml when Hermes has no configuration yet", async () => {
const { client } = await hermesClient();
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
expect(parseYaml(await readFile(client.configPath, "utf8"))).toEqual({
mcp_servers: {
rea: { command: command[0], args: command.slice(1), enabled: true },
},
});
});
});
@@ -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);
});
@@ -38,9 +38,9 @@ describe("OMP configuration paths", () => {
expect(ompPath({ PI_CODING_AGENT_DIR: "/custom/agent" })?.configPath).toBe(
"/custom/agent/mcp.json",
);
// A relative override names a different file in every working directory.
// Match OMP by resolving the override against the caller working directory.
expect(ompPath({ PI_CODING_AGENT_DIR: "agent" })?.configPath).toBe(
"/home/a/.omp/agent/mcp.json",
resolve("agent", "mcp.json"),
);
});
@@ -0,0 +1,333 @@
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
import { parseClientConfiguration } from "../../../src/application/ClientConfigurationDocument.js";
import {
configureClientConfiguration,
inspectClientConfiguration,
} from "../../../src/application/SetupClientConfiguration.js";
import { detectClients } from "../../../src/application/SetupHost.js";
import { supportedClients } from "../../../src/application/SupportedClients.js";
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
clearClientLocationEnvironment,
NPX_REGISTRATION_COMMAND,
} from "../../fixtures/clientEnvironment.js";
beforeEach(clearClientLocationEnvironment);
afterEach(() => vi.unstubAllEnvs());
const piPath = (
home: string,
platform: NodeJS.Platform,
env: Parameters<typeof supportedClients>[2],
) => supportedClients(home, platform, env).find(({ name }) => name === "pi");
// Catch fallback to OMP paths, loss of relative overrides, and normalization
// that differs from Pi's public getAgentDir()/normalizePath boundary.
describe("Pi user configuration paths", () => {
it.each([
[undefined, "/home/a/.pi/agent"],
["", "/home/a/.pi/agent"],
["/custom/agent", "/custom/agent"],
["~", "/home/a"],
["~/custom/agent", "/home/a/custom/agent"],
["agent", "agent"],
["./agent", "./agent"],
[" agent ", " agent "],
["~other/agent", "~other/agent"],
["file:///custom/agent%20dir", "/custom/agent dir"],
["/mnt/c/agent", "/mnt/c/agent"],
])(
"uses Pi's agent directory for %s, independently of OMP",
(override, expected) => {
const client = piPath("/home/a", "linux", {
PI_CODING_AGENT_DIR: override,
OMP_PROFILE: "work",
PI_PROFILE: "legacy",
PI_CONFIG_DIR: ".omp-other",
});
expect(client?.markerPath).toBe(expected);
expect(client?.configPath).toBe(join(expected, "mcp.json"));
},
);
it.each([
[undefined, "C:\\Users\\a\\.pi\\agent"],
["", "C:\\Users\\a\\.pi\\agent"],
["~", "C:\\Users\\a"],
["~/agent", "C:\\Users\\a\\agent"],
["~\\agent", "C:\\Users\\a\\agent"],
["C:\\custom\\agent", "C:\\custom\\agent"],
["/c/custom/agent", "C:\\custom\\agent"],
["/mnt/c/custom/agent", "C:\\custom\\agent"],
["/cygdrive/c/custom/agent", "C:\\custom\\agent"],
["/c", "C:\\"],
["//server/share/agent", "//server/share/agent"],
["\\\\server\\share\\agent", "\\\\server\\share\\agent"],
["agent", "agent"],
["file:///C:/custom/agent%20dir", "C:\\custom\\agent dir"],
["file://server/share/agent", "\\\\server\\share\\agent"],
])("normalizes Windows Pi override %s", (override, expected) => {
const client = piPath("C:\\Users\\a", "win32", {
PI_CODING_AGENT_DIR: override,
});
expect(client?.markerPath).toBe(expected);
expect(client?.configPath).toBe(
`${expected.replace(/[\\/]+$/u, "").replaceAll("/", "\\")}\\mcp.json`,
);
});
it("reports malformed file URLs instead of silently choosing the default", async () => {
const home = await createTestTempDirectory("rea-pi-invalid-path-");
const client = piPath(home, "linux", {
PI_CODING_AGENT_DIR: "file:///agent%2fdir",
});
expect(client).toMatchObject({
configPath: "file:///agent%2fdir",
configPathError: expect.stringContaining("PI_CODING_AGENT_DIR"),
});
if (client === undefined) throw new Error("missing Pi client");
expect(await configureClientConfiguration(client)).toEqual({
status: "failed",
reason: "path",
});
expect(await systemUninstallHost(home).removeClient(client)).toMatchObject({
status: "failed",
detail: expect.stringContaining("PI_CODING_AGENT_DIR"),
});
expect(
await detectClients(home, "linux", {
PI_CODING_AGENT_DIR: "file:///agent%2fdir",
}),
).toEqual([]);
});
it("detects the normalized override marker without needing mcp.json", async () => {
const home = await createTestTempDirectory("rea-pi-detection-");
await mkdir(join(home, "custom-agent"));
const detected = await detectClients(home, process.platform, {
PI_CODING_AGENT_DIR: "~/custom-agent",
});
expect(detected.find(({ name }) => name === "pi")?.configPath).toBe(
join(home, "custom-agent", "mcp.json"),
);
});
});
const piClient = async () => {
const home = await createTestTempDirectory("rea-pi-config-");
const client = piPath(home, process.platform, {});
if (client?.markerPath === undefined) throw new Error("missing Pi client");
await mkdir(client.markerPath, { recursive: true });
return { home, client };
};
describe("Pi registration semantics", () => {
it("preserves unrelated content and OMP-only lists during setup, repeat, and uninstall", async () => {
const { home, client } = await piClient();
// Pi loads mcp.json with strict JSON, so the retained unrelated settings
// are valid strict JSON rather than the commented JSONC fixture.
const original = `{"autoEnableCodemode": false,
"mcpServers": { "other": { "command": "other-server" } },
"enabledServers": ["other"],
"disabledServers": ["rea", "other"]
}\n`;
await writeFile(client.configPath, original);
expect(
await configureClientConfiguration(client, {}, NPX_REGISTRATION_COMMAND),
).toMatchObject({ status: "configured" });
expect(await readFile(`${client.configPath}.rea.backup`, "utf8")).toBe(
original,
);
const configured = await readFile(client.configPath, "utf8");
expect(JSON.parse(configured)).toEqual({
autoEnableCodemode: false,
mcpServers: {
other: { command: "other-server" },
rea: {
type: "stdio",
command: "npx",
args: NPX_REGISTRATION_COMMAND.slice(1),
},
},
enabledServers: ["other"],
disabledServers: ["rea", "other"],
});
expect(
await configureClientConfiguration(client, {}, NPX_REGISTRATION_COMMAND),
).toEqual({ status: "unchanged" });
expect(await readFile(client.configPath, "utf8")).toBe(configured);
expect(
(
await readClientRegistrationStatuses(home, undefined, {
environment: {},
})
).find(({ client: name }) => name === "pi"),
).toMatchObject({ state: "aligned" });
expect((await systemUninstallHost(home).removeClient(client)).status).toBe(
"removed",
);
expect(JSON.parse(await readFile(client.configPath, "utf8"))).toEqual(
JSON.parse(original),
);
expect(await readFile(`${client.configPath}.rea.backup`, "utf8")).toBe(
original,
);
});
it.each([
[undefined, true, "aligned"],
["stdio", true, "aligned"],
["http", true, "invalid"],
["streamable-http", true, "invalid"],
["sse", true, "invalid"],
[undefined, false, "stale"],
["stdio", false, "stale"],
])(
"doctor handles type %s and enabled %s without OMP allowlist overrides",
async (type, enabled, state) => {
const { home, client } = await piClient();
await writeFile(
client.configPath,
JSON.stringify({
mcpServers: {
rea: {
command: "npx",
args: NPX_REGISTRATION_COMMAND.slice(1),
type,
enabled,
},
},
enabledServers: ["rea"],
}),
);
const statuses = await readClientRegistrationStatuses(home, undefined, {
environment: {},
});
expect(statuses.find(({ client: name }) => name === "pi")).toMatchObject({
state,
});
},
);
});
describe("Pi strict JSON parsing", () => {
it.each([
[
"a comment",
`{ // Pi loads strict JSON only\n"mcpServers": { "other": { "command": "other" } }\n}\n`,
],
[
"a trailing comma",
`{"mcpServers": { "other": { "command": "other" }, },}\n`,
],
[
"a BOM before valid JSON",
`\uFEFF{"mcpServers": { "other": { "command": "other" } }}\n`,
],
["empty text", ""],
["whitespace only", "\n \t\r\n"],
["a BOM only", "\uFEFF"],
])(
"rejects an existing Pi configuration with %s before any mutation",
async (_description, original) => {
const { home, client } = await piClient();
await writeFile(client.configPath, original);
expect(() => parseClientConfiguration(original, "pi")).toThrow();
expect(
await inspectClientConfiguration(client, {}, NPX_REGISTRATION_COMMAND),
).toMatchObject({ status: "invalid" });
expect(
await configureClientConfiguration(
client,
{},
NPX_REGISTRATION_COMMAND,
),
).toEqual({ status: "failed", reason: "readback" });
expect(await readFile(client.configPath, "utf8")).toBe(original);
await expect(
readFile(`${client.configPath}.rea.backup`),
).rejects.toMatchObject({ code: "ENOENT" });
expect(
(
await readClientRegistrationStatuses(home, undefined, {
environment: {},
})
).find(({ client: name }) => name === "pi"),
).toMatchObject({ state: "invalid" });
expect(
await systemUninstallHost(home).removeClient(client),
).toMatchObject({
name: "pi",
status: "failed",
detail: expect.stringContaining("not valid JSON"),
});
expect(await readFile(client.configPath, "utf8")).toBe(original);
await expect(
readFile(`${client.configPath}.rea.backup`),
).rejects.toMatchObject({ code: "ENOENT" });
},
);
it("initializes a missing Pi configuration as valid strict JSON without a backup", async () => {
const { home, client } = await piClient();
await expect(readFile(client.configPath)).rejects.toMatchObject({
code: "ENOENT",
});
expect(
await inspectClientConfiguration(client, {}, NPX_REGISTRATION_COMMAND),
).toEqual({ status: "create" });
expect(
await configureClientConfiguration(client, {}, NPX_REGISTRATION_COMMAND),
).toMatchObject({ status: "configured" });
const created = await readFile(client.configPath, "utf8");
expect(() => JSON.parse(created)).not.toThrow();
expect(JSON.parse(created)).toEqual({
mcpServers: {
rea: {
type: "stdio",
command: "npx",
args: NPX_REGISTRATION_COMMAND.slice(1),
},
},
});
await expect(
readFile(`${client.configPath}.rea.backup`),
).rejects.toMatchObject({ code: "ENOENT" });
expect(
await configureClientConfiguration(client, {}, NPX_REGISTRATION_COMMAND),
).toEqual({ status: "unchanged" });
expect(await readFile(client.configPath, "utf8")).toBe(created);
expect(
(
await readClientRegistrationStatuses(home, undefined, {
environment: {},
})
).find(({ client: name }) => name === "pi"),
).toMatchObject({ state: "aligned" });
expect(await systemUninstallHost(home).removeClient(client)).toMatchObject({
name: "pi",
status: "removed",
});
expect(JSON.parse(await readFile(client.configPath, "utf8"))).toEqual({
mcpServers: {},
});
});
it("keeps JSONC tolerance for other dialects while Pi rejects the same text", () => {
const jsonc = `\uFEFF{\n // A comment Pi rejects but OpenCode keeps.\n "mcp": { "other": { "type": "local" }, },\n}\n`;
expect(parseClientConfiguration(jsonc, "opencode").servers).toEqual({
other: { type: "local" },
});
expect(parseClientConfiguration("", "opencode").document).toEqual({});
expect(parseClientConfiguration("\uFEFF", "opencode").document).toEqual({});
expect(() => parseClientConfiguration(jsonc, "pi")).toThrow();
expect(() => parseClientConfiguration("", "pi")).toThrow();
expect(() => parseClientConfiguration("\uFEFF", "pi")).toThrow();
});
});
@@ -0,0 +1,183 @@
import { access, mkdir, readFile, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { parse as parseJsonc } from "jsonc-parser";
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
import { systemSetupHost } from "../../../src/application/SetupHost.js";
import { supportedClients } from "../../../src/application/SupportedClients.js";
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
clearClientLocationEnvironment,
NPX_REGISTRATION_COMMAND,
} from "../../fixtures/clientEnvironment.js";
const command = NPX_REGISTRATION_COMMAND;
beforeEach(clearClientLocationEnvironment);
afterEach(() => vi.unstubAllEnvs());
const qwenPath = (
home: string,
platform: NodeJS.Platform,
env: Parameters<typeof supportedClients>[2] = {},
) =>
supportedClients(home, platform, env).find(
({ name }) => name === "qwen_code",
);
describe("Qwen Code configuration paths", () => {
it("resolves the user settings file and marker directory", () => {
expect(qwenPath("/home/a", "linux")).toEqual({
name: "qwen_code",
displayName: "Qwen Code",
configPath: join("/home/a", ".qwen", "settings.json"),
markerPath: join("/home/a", ".qwen"),
format: "json",
});
expect(qwenPath("/Users/a", "darwin")?.configPath).toBe(
join("/Users/a", ".qwen", "settings.json"),
);
});
it.each([
["", join("/home/a", ".qwen")],
["~", "/home/a"],
["~/profiles/work", join("/home/a", "profiles", "work")],
["~\\profiles\\work", join("/home/a", "profiles", "work")],
["profiles/work", resolve("profiles/work")],
[" profile ", resolve(" profile ")],
["$PROFILE", resolve("$PROFILE")],
])("matches Qwen's QWEN_HOME resolution for %j", (override, directory) => {
vi.stubEnv("QWEN_HOME", override);
const client = qwenPath("/home/a", process.platform, {
QWEN_HOME: override,
});
expect(
supportedClients("/home/a").find(({ name }) => name === "qwen_code"),
).toEqual(client);
expect(client).toMatchObject({
configPath: join(directory, "settings.json"),
markerPath: directory,
});
});
});
describe("Qwen Code client lifecycle", () => {
const qwenClient = async () => {
const home = await createTestTempDirectory("rea-qwen-");
const client = qwenPath(home, process.platform, {});
if (client?.markerPath === undefined)
throw new Error("missing Qwen Code client");
await mkdir(client.markerPath, { recursive: true });
return { home, client };
};
it("registers rea in mcpServers while preserving unrelated settings and comments", async () => {
const { home, client } = await qwenClient();
await writeFile(
client.configPath,
`{
// Keep this note.
"model": { "name": "qwen3-coder-plus" },
"mcpServers": { "other": { "command": "other-server" } }
}
`,
);
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
const text = await readFile(client.configPath, "utf8");
expect(text).toContain("// Keep this note.");
expect(parseJsonc(text)).toEqual({
model: { name: "qwen3-coder-plus" },
mcpServers: {
other: { command: "other-server" },
rea: { command: "npx", args: command.slice(1) },
},
});
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "unchanged",
});
expect((await systemUninstallHost(home).removeClient(client)).status).toBe(
"removed",
);
const removedText = await readFile(client.configPath, "utf8");
const removed = parseJsonc(removedText);
expect(removed).toEqual({
model: { name: "qwen3-coder-plus" },
mcpServers: { other: { command: "other-server" } },
});
expect(removedText).toContain("// Keep this note.");
});
it("reports a package-runner registration as aligned", async () => {
const { home, client } = await qwenClient();
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
const entry = resolve("scripts/rea.mjs");
const status = (
await readClientRegistrationStatuses(home, entry, { environment: {} })
).find(({ client: name }) => name === "qwen_code");
expect(status).toMatchObject({ state: "aligned" });
});
});
describe("Qwen Code profile setup", () => {
it.each([false, true])(
"installs and removes the shared skill with a custom home: %s",
async (customHome) => {
const home = await createTestTempDirectory("rea-qwen-profile-");
const profile = join(home, customHome ? "qwen-profile" : ".qwen");
const environment = {
HOME: home,
USERPROFILE: home,
...(customHome ? { QWEN_HOME: profile } : {}),
};
await mkdir(profile);
const setup = systemSetupHost(undefined, environment);
const client = (await setup.detectedClients()).find(
({ name }) => name === "qwen_code",
);
if (client === undefined) throw new Error("missing Qwen Code client");
expect(client.configPath).toBe(join(profile, "settings.json"));
expect(await setup.configureClient(client, {}, command)).toEqual({
status: "configured",
});
expect(await setup.installSkill([client.name])).toBe("installed");
const skill = join(home, ".agents", "skills", PRODUCT_IDENTITY.skillName);
expect(await readFile(join(skill, "SKILL.md"), "utf8")).toContain(
"reverse-engineer-anything",
);
expect(await setup.clientNeedsConfigure(client, {}, command)).toBe(false);
expect(await setup.skillNeedsInstall([client.name])).toBe(false);
expect(await setup.installSkill([client.name])).toBe("unchanged");
expect(
(
await readClientRegistrationStatuses(
home,
resolve("scripts/rea.mjs"),
{ environment },
)
).find(({ client: name }) => name === "qwen_code"),
).toMatchObject({ state: "aligned" });
const uninstall = systemUninstallHost(home, undefined, environment);
const registered = (await uninstall.clients()).find(
({ name }) => name === "qwen_code",
);
expect(registered).toEqual(client);
expect((await uninstall.removeClient(client)).status).toBe("removed");
expect((await uninstall.removeSkill()).status).toBe("removed");
await expect(access(skill)).rejects.toMatchObject({ code: "ENOENT" });
if (customHome)
await expect(access(join(home, ".qwen"))).rejects.toMatchObject({
code: "ENOENT",
});
},
);
});
+11 -8
View File
@@ -13,7 +13,6 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
canonicalSkillNeedsInstall,
claudeCodeSkillsDirectory,
installCanonicalSkill,
} from "../../../src/application/SetupSkill.js";
import {
@@ -56,9 +55,7 @@ describe("canonical skill transaction", () => {
it("installs only the selected Claude Code personal skill", async () => {
const home = await createTestTempDirectory("rea-claude-skill-");
const configDirectory = join(home, "claude-config");
const skillsDirectory = claudeCodeSkillsDirectory(home, {
CLAUDE_CONFIG_DIR: configDirectory,
});
const skillsDirectory = join(configDirectory, "skills");
const claudeSkill = join(
skillsDirectory,
"reverse-engineer-anything/SKILL.md",
@@ -84,13 +81,19 @@ describe("canonical skill transaction", () => {
});
expect(
await canonicalSkillNeedsInstall(home, ["claude_code"], skillsDirectory),
await canonicalSkillNeedsInstall(home, ["claude_code"], {
CLAUDE_CONFIG_DIR: dirname(skillsDirectory),
}),
).toBe(true);
expect(
await installCanonicalSkill(home, ["claude_code"], skillsDirectory),
await installCanonicalSkill(home, ["claude_code"], {
CLAUDE_CONFIG_DIR: dirname(skillsDirectory),
}),
).toBe("installed");
expect(
await canonicalSkillNeedsInstall(home, ["claude_code"], skillsDirectory),
await canonicalSkillNeedsInstall(home, ["claude_code"], {
CLAUDE_CONFIG_DIR: dirname(skillsDirectory),
}),
).toBe(false);
await expect(access(claudeSkill)).resolves.toBeUndefined();
await expect(
@@ -112,7 +115,7 @@ describe("canonical skill transaction", () => {
home,
".agents/skills/reverse-engineer-anything/SKILL.md",
);
const claudeSkills = claudeCodeSkillsDirectory(home);
const claudeSkills = join(home, ".claude", "skills");
const claudeSkill = join(
claudeSkills,
"reverse-engineer-anything/SKILL.md",
+130 -1
View File
@@ -6,7 +6,9 @@ import { z } from "zod";
import { BinaryLayoutService } from "../../../src/application/binaryDiagnostics/BinaryLayoutService.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import { functionDossierSchema } from "../../../src/domain/hopperValues.js";
import { ghidraFunctionDossier } from "../../../src/domain/ghidraValues.fixture.js";
import { ok } from "../../../src/domain/result.js";
import {
createJavaScriptApplicationGraph,
@@ -109,6 +111,68 @@ it("advertises exact schemas and projects one layout section from retained Evide
);
});
it("delivers a bounded native dossier view over MCP without a Ghidra provider or lost connection", async () => {
const { client, session } = await connect();
const original = functionDossierSchema.parse(ghidraFunctionDossier());
const parent = createEvidence(
{
path: "/fixtures/oversized-native.exe",
format: "pe",
sha256: "b".repeat(64),
},
{ id: "ghidra", name: "Ghidra", version: "12.1.4" },
{
operation: "analyze_function",
parameters: { address: "0x401000" },
result: { ...original, pseudocode: "X".repeat(11 * 1024 * 1024) },
},
);
expect(session.recordEvidence(parent).ok).toBe(true);
const advertised = (await client.listTools()).tools.find(
(tool) => tool.name === "inspect_analysis_view",
);
if (advertised?.outputSchema === undefined)
throw new Error("missing 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 arguments_ = {
source: { kind: "retained-evidence", evidence_id: parent.evidence_id },
view: { kind: "native", facet: "pseudocode", offset: 0, limit: 500 },
};
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
expect(
ajv.validate(inputSchema, arguments_),
JSON.stringify(ajv.errors),
).toBe(true);
const response = await client.callTool({
name: "inspect_analysis_view",
arguments: arguments_,
});
expect(response.isError).not.toBe(true);
expect(
ajv.validate(outputSchema, response.structuredContent),
JSON.stringify(ajv.errors),
).toBe(true);
const parsed = toolContract("inspect_analysis_view").outputSchema.parse(
response.structuredContent,
);
expect(parsed.normalized_result).toMatchObject({
kind: "native",
parent_evidence_id: parent.evidence_id,
procedure_address: "0x401000",
coverage: { examined: 500, next_offset: 500, total: 11 * 1024 * 1024 },
});
expect(parsed.evidence_links).toEqual([parent.evidence_id]);
expect(parsed.locations).toEqual([
{ kind: "artifact-path", path: "/fixtures/oversized-native.exe" },
{ kind: "address", address: "0x401000" },
]);
expect(JSON.stringify(response.structuredContent).length).toBeLessThan(12000);
await client.ping();
});
it("retains an oversized selected observation and keeps subsequent views usable", async () => {
const { client, session } = await connect();
const analysis = analysisViewJavaScriptAnalysisWithSource();
@@ -185,6 +249,71 @@ it("retains an oversized selected observation and keeps subsequent views usable"
expect(summary.isError).not.toBe(true);
});
it("retains an oversized native assembly row and permits a subsequent smaller view", async () => {
const { client, session } = await connect();
const row = "\0".repeat(1_000_000);
const parent = createEvidence(
{ path: "/fixtures/large-row.exe", format: "pe", sha256: "c".repeat(64) },
{ id: "ghidra", name: "Ghidra", version: "12.1.4" },
{
operation: "analyze_function",
parameters: {},
result: {
...functionDossierSchema.parse(ghidraFunctionDossier()),
assembly: [row],
},
},
);
expect(session.recordEvidence(parent).ok).toBe(true);
const source = { kind: "retained-evidence", evidence_id: parent.evidence_id };
const response = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source,
view: { kind: "native", facet: "assembly", offset: 0, limit: 1 },
},
});
expect(response.isError).toBe(true);
const error = z
.object({
error: z.object({
details: z.object({
reported_limits: z.object({
evidence_reference: z.object({
kind: z.literal("retained-evidence"),
evidence_id: z.string(),
}),
}),
}),
}),
})
.parse(parseMcpToolError(response));
const retained = session.evidenceById(
error.error.details.reported_limits.evidence_reference.evidence_id,
);
expect(retained?.normalized_result).toMatchObject({
item: [row],
parent_evidence_id: parent.evidence_id,
});
const next = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source,
view: { kind: "native", facet: "pseudocode", offset: 0, limit: 12 },
},
});
expect(next.isError).not.toBe(true);
expect(
toolContract("inspect_analysis_view").outputSchema.parse(
next.structuredContent,
).normalized_result,
).toMatchObject({
item: { text: "int fixture_" },
parent_evidence_id: parent.evidence_id,
});
await client.ping();
});
it("returns a JavaScript summary without graph payloads from a retained reference", async () => {
const { client, session } = await connect();
const parent = analysisViewJavaScriptEvidence();
@@ -0,0 +1,281 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { STDIO_DEFAULT_MAX_BUFFER_SIZE } from "@modelcontextprotocol/server";
import { Ajv2020 } from "ajv/dist/2020.js";
import { describe, expect, it } from "vitest";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import { compactAdvertisedInputSchema } from "../../../src/contracts/compactInputSchema.js";
import {
COMPACT_INPUT_SCHEMA_BUDGET_BYTES,
parseMcpInputSchemaProfile,
} from "../../../src/config/mcpInputSchemaProfile.js";
import { processScenarioSchema } from "../../../src/domain/process/processScenario.js";
import { EvidenceMcpServer } from "../../../src/server/EvidenceMcpServer.js";
import { ToolResultDelivery } from "../../../src/server/toolResult.js";
import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js";
interface AdvertisedTool {
readonly name: string;
readonly inputSchema: Record<string, unknown>;
readonly outputSchema?: Record<string, unknown> | undefined;
readonly description?: string | undefined;
}
const serializedBytes = (value: unknown): number =>
Buffer.byteLength(JSON.stringify(value), "utf8");
const listToolsThroughTransport = async (
server: EvidenceMcpServer,
): Promise<readonly AdvertisedTool[]> => {
const client = new Client({ name: "compact-profile", version: "0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
return (await client.listTools()).tools;
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
};
const registerCatalog = (server: EvidenceMcpServer): void => {
for (const contract of TOOL_CONTRACTS)
server.registerTool(
contract.name,
toolRegistrationOptions(contract),
async () => ({ content: [] }),
);
};
const compactServer = (): EvidenceMcpServer =>
new EvidenceMcpServer(
{ name: "compact-profile", version: "0" },
{ capabilities: {} },
undefined,
new ToolResultDelivery(STDIO_DEFAULT_MAX_BUFFER_SIZE),
{ budgetBytes: COMPACT_INPUT_SCHEMA_BUDGET_BYTES },
);
const fullServer = (): EvidenceMcpServer =>
new EvidenceMcpServer(
{ name: "full-profile", version: "0" },
{ capabilities: {} },
undefined,
new ToolResultDelivery(STDIO_DEFAULT_MAX_BUFFER_SIZE),
);
describe("MCP compact input schema profile", () => {
it("advertises every tool input schema within the provider budget", async () => {
const server = compactServer();
registerCatalog(server);
const tools = await listToolsThroughTransport(server);
expect(tools.map(({ name }) => name).sort()).toEqual(
TOOL_CONTRACTS.map(({ name }) => name).sort(),
);
const oversized = tools.filter(
({ inputSchema }) =>
serializedBytes(inputSchema) > COMPACT_INPUT_SCHEMA_BUDGET_BYTES,
);
expect(oversized.map(({ name }) => name)).toEqual([]);
});
it("keeps output schemas and tool descriptions identical to the default profile", async () => {
const compact = compactServer();
const full = fullServer();
registerCatalog(compact);
registerCatalog(full);
const [compactTools, fullTools] = await Promise.all([
listToolsThroughTransport(compact),
listToolsThroughTransport(full),
]);
const fullByName = new Map(fullTools.map((tool) => [tool.name, tool]));
expect(compactTools.length).toBe(fullTools.length);
for (const tool of compactTools) {
const reference = fullByName.get(tool.name);
if (reference === undefined) throw new Error(`Missing ${tool.name}`);
expect(tool.outputSchema, tool.name).toEqual(reference.outputSchema);
expect(tool.description, tool.name).toBe(reference.description);
}
});
it("keeps compact schemas valid and accepting canonical examples", async () => {
const server = compactServer();
registerCatalog(server);
const tools = await listToolsThroughTransport(server);
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const contractsByName = new Map<string, (typeof TOOL_CONTRACTS)[number]>(
TOOL_CONTRACTS.map((contract) => [contract.name, contract]),
);
for (const tool of tools) {
expect(
ajv.validateSchema(tool.inputSchema),
`${tool.name}: ${ajv.errorsText(ajv.errors)}`,
).toBe(true);
const contract = contractsByName.get(tool.name);
const validate = ajv.compile(tool.inputSchema);
for (const example of contract?.examples ?? [])
expect(validate(example.input), `${tool.name}: ${example.title}`).toBe(
true,
);
}
});
it("reduces at most the structurally oversized tools", async () => {
const full = fullServer();
registerCatalog(full);
const tools = await listToolsThroughTransport(full);
const reduced: string[] = [];
for (const tool of tools) {
const { presentation } = compactAdvertisedInputSchema(
tool.inputSchema,
COMPACT_INPUT_SCHEMA_BUDGET_BYTES,
);
if (presentation === "reduced") reduced.push(tool.name);
}
expect(reduced.sort()).toEqual([
"build_reconstruction_obligation_ledger",
"capture_browser_scenario",
"compare_application_versions",
"compare_web_captures",
"evaluate_reconstruction_coverage",
"project_managed_application_graph",
]);
expect(tools.length).toBe(TOOL_CONTRACTS.length);
});
it("retains parameter types and avoids client-side reference expansion", async () => {
const server = compactServer();
registerCatalog(server);
const tools = await listToolsThroughTransport(server);
for (const tool of tools) {
// Kimi Code 2.1.1 expands references and defaults description-only
// properties to string. Inline schemas with explicit shallow types
// avoid both conversions for the structurally oversized tools.
expect(JSON.stringify(tool.inputSchema), tool.name).not.toContain(
'"$ref":',
);
}
const comparison = tools.find(
({ name }) => name === "compare_managed_members",
);
expect(comparison?.inputSchema.properties).toMatchObject({
left: {
properties: {
normalized_result: {
type: ["null", "boolean", "object", "array", "number", "string"],
},
},
},
});
const ledger = tools.find(
({ name }) => name === "build_reconstruction_obligation_ledger",
);
expect(ledger?.inputSchema.properties).toMatchObject({
evidence_bundle: { type: "object" },
reviewed_obligations: { type: "array" },
manifest: { type: "object" },
});
const coverage = tools.find(
({ name }) => name === "evaluate_reconstruction_coverage",
);
expect(coverage?.inputSchema.properties).toMatchObject({
coverage: { type: "object" },
boundary_id: { type: "string" },
});
});
it("parses the profile selection the server startup reads", () => {
expect(parseMcpInputSchemaProfile("compact")).toEqual({
ok: true,
value: "compact",
});
expect(parseMcpInputSchemaProfile("surprise")).not.toHaveProperty("value");
});
});
describe("MCP compact input schema canonical enforcement", () => {
it("still rejects canonical-invalid arguments the compact advertisement accepts", async () => {
const server = compactServer();
const contract = TOOL_CONTRACTS.find(
({ name }) => name === "capture_process_scenario",
);
if (contract === undefined)
throw new Error("Process capture contract was not registered");
let handlerCalled = false;
server.registerTool(
contract.name,
toolRegistrationOptions(contract),
async () => {
handlerCalled = true;
return {
content: [{ type: "text" as const, text: "handler ran" }],
isError: true,
};
},
);
const client = new Client({ name: "compact-validation", version: "0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const advertised = (await client.listTools()).tools.find(
({ name }) => name === contract.name,
);
if (advertised === undefined)
throw new Error("Process capture tool was not advertised");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const validate = ajv.compile(advertised.inputSchema);
const valid = { executable: "node", environment: { APP_MODE: "test" } };
const reserved = {
executable: "node",
environment: { REA_PROCESS_RUN_ID: "caller-value" },
};
expect(validate(valid)).toBe(true);
expect(processScenarioSchema.safeParse(valid).success).toBe(true);
expect(processScenarioSchema.safeParse(reserved).success).toBe(false);
const result = await client.callTool({
name: contract.name,
arguments: reserved,
});
expect(result.isError).toBe(true);
expect(handlerCalled).toBe(false);
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
it("compacts plain standard schemas that are not Zod instances", async () => {
// Mirrors registerWebNetworkCaptureTool: a plain standard schema reusing
// the advertised projection while owning its own permissive validator.
const server = compactServer();
const contract = TOOL_CONTRACTS.find(
({ name }) => name === "inspect_web_network_capture",
);
if (contract === undefined)
throw new Error("Network capture contract was not registered");
const registration = toolRegistrationOptions(contract);
const inputSchema = {
"~standard": {
...registration.inputSchema["~standard"],
vendor: "rea-application",
validate: (value: unknown) => ({ value }),
},
};
server.registerTool(
contract.name,
{ ...registration, inputSchema },
async () => ({ content: [] }),
);
const tools = await listToolsThroughTransport(server);
const advertised = tools.find(({ name }) => name === contract.name);
if (advertised === undefined)
throw new Error("Network capture tool was not advertised");
expect(serializedBytes(advertised.inputSchema)).toBeLessThanOrEqual(
COMPACT_INPUT_SCHEMA_BUDGET_BYTES,
);
const ajv = new Ajv2020({ strict: false, validateFormats: false });
expect(ajv.validateSchema(advertised.inputSchema)).toBe(true);
});
});
@@ -0,0 +1,154 @@
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { createHash } from "node:crypto";
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 { javaScriptSemanticTraceResultSchema } from "../../../src/domain/javascript/javascriptSemanticTraceSchemas.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
cliTest(
"delivers complete large literals through CLI and default stdio MCP without metadata copies",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-literal-payload-");
const value = 'rea_literal_payload_ğ\\"\0'.padEnd(24, "x").repeat(65_536);
const source = [
`export const payload = ${JSON.stringify(value)};`,
'export const choice = flag ? 1 : "1";',
'export const empty = "";',
].join("\n");
await writeFile(join(root, "main.js"), source);
const cliResponse = await cli.run({
arguments: [
"analyze-javascript-application",
root,
"--artifact-format",
"directory",
"--json",
],
timeoutMs: 60_000,
});
expect(cliResponse.exitCode).toBe(0);
const cliEvidence = toolContract(
"analyze_javascript_application",
).outputSchema.parse(cliResponse.json);
const client = new Client({ name: "literal-payload-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" },
});
// The old payload-bearing role key/label exceed the default wire budget.
expect(response.isError).not.toBe(true);
const evidence = toolContract(
"analyze_javascript_application",
).outputSchema.parse(response.structuredContent);
expect(evidence.evidence_id).toBe(cliEvidence.evidence_id);
const text = response.content.find((item) => item.type === "text");
if (text?.type !== "text") throw new Error("Missing MCP text result");
const textEvidence = toolContract(
"analyze_javascript_application",
).outputSchema.parse(JSON.parse(text.text));
expect(textEvidence.evidence_id).toBe(evidence.evidence_id);
const graph = javascriptApplicationAnalysisResultSchema.parse(
evidence.normalized_result,
).semantic_graph;
const literal = graph.nodes.find(
(node) => node.kind === "literal" && node.properties.value === value,
);
if (literal === undefined) throw new Error("Complete literal was lost");
const sourceSha256 = createHash("sha256").update(source).digest("hex");
expect(literal.identity).toMatchObject({
module_path: "main.js",
artifact_sha256: sourceSha256,
});
expect(literal.evidence.location).toMatchObject({
available: true,
value: { kind: "source-range", source: "main.js" },
});
const choices = graph.nodes.filter(
(node) =>
node.kind === "literal" &&
(node.properties.value === 1 || node.properties.value === "1"),
);
expect(choices.length).toBe(2);
expect(new Set(choices.map((node) => node.node_id)).size).toBe(2);
expect(
graph.nodes.some(
(node) => node.kind === "literal" && node.properties.value === "",
),
).toBe(true);
const traceResponse = await client.callTool({
name: "trace_javascript_semantics",
arguments: {
application: {
kind: "retained-evidence",
evidence_id: evidence.evidence_id,
},
query: {
seed: { kind: "semantic-node", node_id: literal.node_id },
direction: "backward-provenance",
},
},
});
expect(traceResponse.isError).not.toBe(true);
const traceEvidence = toolContract(
"trace_javascript_semantics",
).outputSchema.parse(traceResponse.structuredContent);
const trace = javaScriptSemanticTraceResultSchema.parse(
traceEvidence.normalized_result,
);
expect(
trace.nodes.some(
(node) =>
node.node_id === literal.node_id && node.properties.value === value,
),
).toBe(true);
const valueTraceResponse = await client.callTool({
name: "trace_javascript_semantics",
arguments: {
application: {
kind: "retained-evidence",
evidence_id: evidence.evidence_id,
},
query: {
seed: { kind: "literal", value: "1" },
direction: "backward-provenance",
},
},
});
expect(valueTraceResponse.isError).not.toBe(true);
const valueTraceEvidence = toolContract(
"trace_javascript_semantics",
).outputSchema.parse(valueTraceResponse.structuredContent);
const valueTrace = javaScriptSemanticTraceResultSchema.parse(
valueTraceEvidence.normalized_result,
);
expect(valueTrace.seed_node_ids).toEqual(
choices
.filter((node) => node.properties.value === "1")
.map((node) => node.node_id),
);
await client.ping();
} finally {
await client.close();
await transport.close();
}
},
60_000,
);
+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()),
]);
}
});
@@ -43,12 +43,14 @@ const exerciseDeliveryFailure = async (
recordEvidence,
delivery,
);
server.registerTool("large_failure", { inputSchema: {} }, async () =>
oversizedFailure(),
server.registerTool(
"large_failure",
{ inputSchema: z.object({}) },
async () => oversizedFailure(),
);
server.registerTool(
"healthy",
{ inputSchema: {} },
{ inputSchema: z.object({}) },
async (): Promise<CallToolResult> => ({
content: [{ type: "text", text: "still connected" }],
}),
@@ -161,7 +163,7 @@ it("delivers an error whose text fits although structured and text copies would
},
delivery,
);
server.registerTool("mid_failure", { inputSchema: {} }, async () =>
server.registerTool("mid_failure", { inputSchema: z.object({}) }, async () =>
failureWithName(nameBytes),
);
const client = new Client({ name: "mid-sized-error-client", version: "1" });
+12 -9
View File
@@ -117,7 +117,7 @@ function expectKnownAuthorityHints(tools: readonly ToolSchemas[]): void {
expect(advertised.get(name), name).toMatchObject({ annotations });
}
function expectRecursivePropertyDescriptions(
function expectMeaningfulPropertyDescriptions(
schema: unknown,
path: string,
root: unknown = schema,
@@ -125,7 +125,7 @@ function expectRecursivePropertyDescriptions(
): void {
if (!isRecord(schema)) return;
if (typeof schema.$ref === "string" && !active.has(schema.$ref))
expectRecursivePropertyDescriptions(
expectMeaningfulPropertyDescriptions(
resolveReference(root, schema.$ref),
`${path}.${schema.$ref}`,
root,
@@ -133,10 +133,13 @@ function expectRecursivePropertyDescriptions(
);
if (isRecord(schema.properties)) {
for (const [property, child] of Object.entries(schema.properties)) {
expect(child, `${path}.${property}`).toMatchObject({
description: expect.any(String),
});
expectRecursivePropertyDescriptions(
// Omit a description rather than restate the property name.
const description = isRecord(child) ? child.description : undefined;
if (description !== undefined)
expect(description, `${path}.${property}`).toEqual(
expect.not.stringMatching(/^(?:Value for .*)?$/u),
);
expectMeaningfulPropertyDescriptions(
child,
`${path}.${property}`,
root,
@@ -147,12 +150,12 @@ function expectRecursivePropertyDescriptions(
for (const key of ["items", "additionalProperties"])
if (schema[key] !== undefined)
expectRecursivePropertyDescriptions(schema[key], path, root, active);
expectMeaningfulPropertyDescriptions(schema[key], path, root, active);
for (const key of ["allOf", "anyOf", "oneOf", "prefixItems"]) {
const children = schema[key];
if (Array.isArray(children))
children.forEach((child: unknown, index: number) =>
expectRecursivePropertyDescriptions(
expectMeaningfulPropertyDescriptions(
child,
`${path}.${key}[${index}]`,
root,
@@ -358,7 +361,7 @@ describe("MCP JSON Schema validity", () => {
contract.inputSchema.safeParse(example.input).success,
`${contract.name}: ${example.title}`,
).toBe(true);
expectRecursivePropertyDescriptions(tool?.inputSchema, contract.name);
expectMeaningfulPropertyDescriptions(tool?.inputSchema, contract.name);
}
} finally {
await Promise.allSettled([client.close(), server.close()]);
@@ -11,6 +11,7 @@ import {
parseProcessScenario,
} from "../../../src/domain/process/processScenario.js";
import { parseProcessCapture } from "../../../src/domain/process/processCaptureParsing.js";
import { compareProcessCaptures } from "../../../src/domain/process/processComparison.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { itWithCaptureCapability } from "./processCaptureCapability.js";
@@ -64,7 +65,11 @@ itWithCaptureCapability(
).toBe(true);
expect(capture.manifest.comparison_contract).toMatchObject({
port_normalization_version: "contextual-endpoints-v2",
rendered_line_format: "trailing-spaces-trimmed-v1",
});
expect(capture.manifest.comparison_contract).not.toHaveProperty(
"pattern_normalization_version",
);
expect(capture.exit).toMatchObject({ code: 0, reason: "exited" });
expect(capture.cleanup).toMatchObject({
owned_process_group: "verified",
@@ -73,6 +78,67 @@ itWithCaptureCapability(
},
);
itWithCaptureCapability.each([
{ pattern: "AB", replacement: "$&$&", expected: "$&$&" },
{
pattern: "AB",
replacement: "$$ $` $' $1",
expected: "$$ $` $' $1",
},
{ pattern: "", replacement: "-", expected: "-A-B-" },
])(
"preserves literal replacement $replacement and rejects legacy comparison semantics",
async ({ pattern, replacement, expected }) => {
const root = await createTestTempDirectory("rea-process-literal-");
const scenario = parseProcessScenario({
executable: process.execPath,
arguments: ["-e", 'process.stdout.write("AB")'],
working_directory: root,
normalization: {
paths: false,
pids: false,
ports: false,
patterns: [{ pattern, replacement }],
},
settle_ms: 100,
});
const result = await captureProcessScenario(scenario);
if (!result.ok) throw result.error;
const capture = parseProcessCapture(
createProcessCaptureEvidence(scenario, result.value).normalized_result,
);
expect(capture.frames.map(({ data }) => data).join("")).toBe(expected);
expect(
capture.frames.map(({ raw_data, data }) => raw_data ?? data).join(""),
).toBe("AB");
expect(capture.cleanup).toMatchObject({
owned_process_group: "verified",
temporary_root: "removed",
});
expect(compareProcessCaptures(capture, capture).terminal).toBe("unchanged");
const legacyContract = { ...capture.manifest.comparison_contract };
delete legacyContract.pattern_normalization_version;
const legacy = parseProcessCapture({
...capture,
manifest: {
...capture.manifest,
comparison_contract: legacyContract,
comparison_contract_sha256: digestProcessCommitment(legacyContract),
},
});
expect(() => compareProcessCaptures(legacy, capture)).toThrow(
expect.objectContaining({
issues: [
expect.objectContaining({
expected: ["pattern_normalization_version"],
}),
],
}),
);
},
20_000,
);
itWithLinuxCaptureCapability.each([false, true])(
"honors pids=%s in owned Linux capture samples and committed Evidence",
async (pids) => {
@@ -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) => {
@@ -60,6 +60,18 @@ describe("artifact archive inventory", () => {
expect(inspectionEvidence.evidence_links).toEqual(
inspection.evidence_links,
);
// The graph is delivered once, in the nested inventory Evidence.
expect(
artifactInventoryResultSchema.parse(
inspection.substeps[0]?.evidence.normalized_result,
).occurrences,
).toHaveLength(3);
// Occurrences name every logical path; neither Evidence repeats them.
expect(inspectionEvidence.locations).toEqual([]);
expect(inspection.substeps[0]?.evidence.locations).toEqual([]);
expect(inspection.observations.map(({ kind }) => kind)).toEqual([
"root-manifest",
]);
const cancellation = new AbortController();
cancellation.abort();
await expect(
@@ -1,4 +1,4 @@
import { readFile, writeFile } from "node:fs/promises";
import { lstat, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
@@ -9,6 +9,8 @@ import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js
import { createDirectAnalysis } from "../../../../src/composition/directAnalysis.js";
import {
ArtifactPathRegistry,
destinationCaseCollisionMessage,
ENGLISH_UNICODE_CASE_INVENTORY_LIMITATION,
normalizeArtifactPath,
} from "../../../../src/artifacts/ArtifactPaths.js";
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
@@ -18,6 +20,7 @@ import { artifactInventoryResultSchema } from "../../../../src/domain/artifactGr
import type { BinaryTarget } from "../../../../src/domain/binaryTargetTypes.js";
import { parseBinaryTarget } from "../../../../src/application/BinaryTargetResolver.js";
import { parseEvidence } from "../../../../src/domain/evidence.js";
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
const { runProviderAnalysis } = createDirectAnalysis({});
@@ -95,17 +98,8 @@ describe("artifact archive safety", () => {
});
const registry = new ArtifactPathRegistry();
registry.add("A.js", "file");
let collisionError: unknown;
try {
registry.add("a.js", "file");
} catch (error: unknown) {
collisionError = error;
}
expect(collisionError).toBeInstanceOf(ArtifactReaderFailure);
expect(collisionError).toMatchObject({
reason: "path",
message: "Artifact path collision: a.js differs only in case from A.js",
});
expect(() => registry.add("a.js", "file")).not.toThrow();
expect(() => registry.add("A.js", "file")).toThrow(ArtifactReaderFailure);
for (const [filePath, childPath] of [
["Foo", "foo/bar"],
@@ -113,11 +107,15 @@ describe("artifact archive safety", () => {
] as const) {
const casePrefixRegistry = new ArtifactPathRegistry();
casePrefixRegistry.add(filePath, "file");
expect(() => casePrefixRegistry.add(childPath, "file")).toThrow(
ArtifactReaderFailure,
);
expect(() => casePrefixRegistry.add(childPath, "file")).not.toThrow();
}
const exactPrefixRegistry = new ArtifactPathRegistry();
exactPrefixRegistry.add("Foo", "file");
expect(() => exactPrefixRegistry.add("Foo/bar", "file")).toThrow(
ArtifactReaderFailure,
);
const sameDirectoryRegistry = new ArtifactPathRegistry();
sameDirectoryRegistry.add("Foo/one.js", "file");
expect(() => sameDirectoryRegistry.add("Foo/two.js", "file")).not.toThrow();
@@ -126,8 +124,64 @@ describe("artifact archive safety", () => {
caseVariantDirectoryRegistry.add("Foo/one.js", "file");
expect(() =>
caseVariantDirectoryRegistry.add("foo/two.js", "file"),
).toThrow(ArtifactReaderFailure);
).not.toThrow();
});
it("names a destination case collision from the directory listing", () => {
expect(
destinationCaseCollisionMessage("res/2f.xml", ["2F.xml", "other.xml"]),
).toBe(
"Destination filesystem cannot store both res/2f.xml and res/2F.xml; inventory retains both logical names.",
);
expect(
destinationCaseCollisionMessage("res/2f.xml", ["2f.xml", "2F.xml"]),
).toBeUndefined();
});
});
it("extracts case-distinct names only when the destination can preserve them", async () => {
const root = await createTestTempDirectory("rea-case-distinct-zip-");
await writeFile(join(root, "case-probe"), "lower");
await writeFile(join(root, "CASE-PROBE"), "upper");
const caseSensitive =
(await readFile(join(root, "case-probe"), "utf8")) === "lower";
const path = join(root, "fixture.zip");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("Main.js", new TextReader("upper"));
await writer.add("main.js", new TextReader("lower"));
await writeFile(path, await writer.close());
const parsed = await parseBinaryTarget(path);
if (!parsed.ok) throw parsed.error;
const result = await inventory(parsed.value);
expect(result.limitations).toContain(
ENGLISH_UNICODE_CASE_INVENTORY_LIMITATION,
);
expect(
result.occurrences
.filter(({ logical_path }) => logical_path !== ".")
.map(({ logical_path }) => logical_path)
.sort(),
).toEqual(["Main.js", "main.js"]);
const output = join(root, "output");
const extracted = await new ArtifactProvider(process.env)
.createClient(parsed.value)
.execute(
"extract_artifact",
artifactExtractionExecutionSchema.parse({ output_root: output }),
);
if (!caseSensitive) {
if (extracted.ok) throw new Error("expected a destination case collision");
expect(projectAnalysisError(extracted.error)).toMatchObject({
message:
"Destination filesystem cannot store both main.js and Main.js; inventory retains both logical names.",
details: { operation: "extract_artifact", reason: "path" },
});
await expect(lstat(output)).rejects.toMatchObject({ code: "ENOENT" });
return;
}
if (!extracted.ok) throw extracted.error;
expect(await readFile(join(output, "Main.js"), "utf8")).toBe("upper");
expect(await readFile(join(output, "main.js"), "utf8")).toBe("lower");
});
const inventory = async (targetValue: BinaryTarget) => {
const result = await new ArtifactProvider(process.env)
@@ -65,7 +65,7 @@ describe("artifact directory inventory", () => {
expect.objectContaining({
relation: "maps-source",
parent_artifact_id: script?.artifact_id,
child_artifact_id: sourceMap?.artifact_id,
occurrence_id: sourceMap?.occurrence_id,
}),
]),
);
@@ -65,6 +65,8 @@ describe("artifact extraction", () => {
]),
extraction_manifest: { output_root_alias: "$OUTPUT_ROOT" },
});
// artifacts names every extracted path; the Evidence does not repeat them.
expect(result.value.locations).toEqual([]);
expect(await readFile(join(output, "assets", "selected.js"), "utf8")).toBe(
"selected();\n",
);
@@ -6,30 +6,73 @@ import { writeOrderedZip } from "../../../fixtures/artifactEntryOrder.js";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { parseBinaryTarget } from "../../../../src/application/BinaryTargetResolver.js";
import {
destinationCaseCollisionMessage,
ENGLISH_UNICODE_CASE_INVENTORY_LIMITATION,
} from "../../../../src/artifacts/ArtifactPaths.js";
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
import { artifactInventoryResultSchema } from "../../../../src/domain/artifactGraph.js";
import { ArtifactOperationError } from "../../../../src/domain/artifactOperationError.js";
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
it.each([
[
["Main.js", "main.js"],
"Artifact path collision: main.js differs only in case from Main.js",
],
[["a\\b.js"], 'Artifact path is absolute or unsafe: "a\\\\b.js"'],
] as const)(
"reports the failed path constraint for %j",
async (entries, detail) => {
const root = await createTestTempDirectory("rea-artifact-detail-");
const path = join(root, "fixture.zip");
await writeOrderedZip(path, entries);
const target = await parseBinaryTarget(path);
if (!target.ok) throw new Error("expected a ZIP target");
const result = await new ArtifactProvider(process.env)
.createClient(target.value)
.execute("inventory_artifact", {});
if (result.ok) throw new Error("expected the path constraint to fail");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "artifact_operation_failed",
details: { operation: "inventory_artifact", reason: "path", detail },
});
},
);
it("keeps logical names that differ only in case and records the limitation", async () => {
const root = await createTestTempDirectory("rea-artifact-detail-");
const path = join(root, "fixture.zip");
await writeOrderedZip(path, ["Main.js", "main.js"]);
const target = await parseBinaryTarget(path);
if (!target.ok) throw new Error("expected a ZIP target");
const result = await new ArtifactProvider(process.env)
.createClient(target.value)
.execute("inventory_artifact", {});
if (!result.ok) throw result.error;
const inventory = artifactInventoryResultSchema.parse(result.value.result);
expect(inventory.occurrences.map(({ logical_path }) => logical_path)).toEqual(
expect.arrayContaining(["Main.js", "main.js"]),
);
expect(inventory.limitations).toContain(
ENGLISH_UNICODE_CASE_INVENTORY_LIMITATION,
);
for (const logicalPath of ["Main.js", "main.js"]) {
expect(
inventory.occurrences
.find((occurrence) => occurrence.logical_path === logicalPath)
?.limitations.join("\n"),
).toContain("English (en-US) Unicode case folding");
}
});
it("reports an unsafe path as a hostile artifact path", async () => {
const root = await createTestTempDirectory("rea-artifact-detail-");
const path = join(root, "fixture.zip");
await writeOrderedZip(path, ["a\\b.js"]);
const target = await parseBinaryTarget(path);
if (!target.ok) throw new Error("expected a ZIP target");
const result = await new ArtifactProvider(process.env)
.createClient(target.value)
.execute("inventory_artifact", {});
if (result.ok) throw new Error("expected the path constraint to fail");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "artifact_operation_failed",
message:
"Artifact contains an unsafe internal path. Inspect the reported path and correct the artifact before retrying.",
details: {
operation: "inventory_artifact",
reason: "path",
detail: 'Artifact path is absolute or unsafe: "a\\\\b.js"',
},
});
});
it("returns a destination case collision as the user-facing path message", () => {
const detail = destinationCaseCollisionMessage("res/2f.xml", ["2F.xml"]);
expect(detail).toEqual(expect.any(String));
if (detail === undefined) return;
expect(
projectAnalysisError(
new ArtifactOperationError("extract_artifact", "path", undefined, detail),
),
).toMatchObject({
message: detail,
details: { reason: "path", detail },
});
});
@@ -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-");
@@ -86,6 +86,12 @@ describe("Android application projection", () => {
expect(left.bridge_candidates).toEqual([
expect.objectContaining({ basis: "react-native-convention" }),
]);
expect(left.limitations).toEqual(
expect.arrayContaining([
"A bridge basis is inferred from the native path and is repeated for every managed component.",
"ZIP inventory cannot see the APK Signing Block, so an empty signing array does not mean the APK is unsigned.",
]),
);
expect(JSON.stringify(left)).not.toContain("opaque signing");
});
@@ -146,6 +152,45 @@ describe("Android application projection", () => {
});
});
describe("case-distinct APK resource names", () => {
it("inventories and projects an APK whose resource names differ only in case", async () => {
const root = await createTestTempDirectory("rea-android-case-");
const path = join(root, "Shrunk.apk");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add(
"AndroidManifest.xml",
new Uint8ArrayReader(Uint8Array.from([3, 0, 8, 0])),
);
await writer.add(
"classes.dex",
new Uint8ArrayReader(
Uint8Array.from([0x64, 0x65, 0x78, 0x0a, 0x30, 0x33, 0x35, 0]),
),
);
await writer.add("res/2F.xml", new TextReader("upper"));
await writer.add("res/2f.xml", new TextReader("lower"));
await writeFile(path, await writer.close());
const inventory = parseEvidence(
await runProviderAnalysis(path, "inventory_artifact", {}),
);
const result = projectAndroidApplicationEvidence({
inventory_evidence: [inventory],
});
const projection = androidApplicationProjectionResultSchema.parse(
requireSuccessfulProjection(result).normalized_result,
);
expect(projection.root_format).toBe("apk");
expect(projection.components.manifests).toHaveLength(1);
expect(projection.components.dex).toHaveLength(1);
expect(JSON.stringify(inventory)).toContain("res/2F.xml");
expect(JSON.stringify(inventory)).toContain("res/2f.xml");
expect(JSON.stringify(inventory)).toContain(
"English (en-US) Unicode case folding",
);
});
});
describe("Android bridge candidate coverage", () => {
it("returns every component and bridge candidate from the inventory", async () => {
const root = await createTestTempDirectory("rea-android-complete-");
@@ -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"));
@@ -0,0 +1,29 @@
import { describe, expect, it } from "vitest";
import { parseMcpInputSchemaProfile } from "../../../src/config/mcpInputSchemaProfile.js";
describe("MCP input schema profile configuration", () => {
it("accepts the full and compact presentations", () => {
expect(parseMcpInputSchemaProfile(undefined)).toEqual({
ok: true,
value: undefined,
});
expect(parseMcpInputSchemaProfile("full")).toEqual({
ok: true,
value: "full",
});
expect(parseMcpInputSchemaProfile("compact")).toEqual({
ok: true,
value: "compact",
});
});
it.each(["", "FULL", "compact ", "minimal", "0"])(
"rejects unknown profiles: %j",
(value) => {
const parsed = parseMcpInputSchemaProfile(value);
if (parsed.ok) throw new Error("Expected invalid profile");
expect(parsed.error.message).toContain("REA_MCP_INPUT_SCHEMA_PROFILE");
},
);
});
+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(
@@ -21,6 +21,7 @@ const translatedReadmes = [
"README_pt-BR.md",
"README_ar.md",
"README_fa.md",
"README_id.md",
] as const;
const jsonExamples = (content: string): unknown[] =>
+1 -1
View File
@@ -99,7 +99,7 @@ export const analysisViewLayoutEvidence = (
operation: "inspect_binary_layout",
parameters: { path: layout.artifact.path },
result: layout,
rawResult: layout,
rawResult: null,
confidence: "observed",
limitations: layout.limitations,
locations: [{ kind: "artifact-path", path: layout.artifact.path }],
+5 -1
View File
@@ -74,7 +74,11 @@ export const createJadxProtocolFixture = async (
ownsProcessLifetime: true,
cleanup: () => cleanupOwnedProcessGroup(spawned.ownership),
});
expect((await supervisor.stop()).status).not.toBe("incomplete");
// The SDK can close the child transport before process exit settles.
// Retry retained ownership without bypassing the supervisor's proof.
await expect
.poll(() => supervisor.stop(), { timeout: 5_000 })
.not.toMatchObject({ status: "incomplete" });
if (options.cwd !== undefined)
await rm(options.cwd, { recursive: true, force: true });
});
+11
View File
@@ -17,11 +17,22 @@ export const CLIENT_LOCATION_ENVIRONMENT = [
"CODEX_HOME",
"COPILOT_HOME",
"GROK_HOME",
"GEMINI_CLI_HOME",
"GEMINI_CLI_TRUST_WORKSPACE",
"GEMINI_RESTRICTED_MODE",
"GEMINI_CLI_TRUSTED_FOLDERS_PATH",
"GEMINI_CLI_SYSTEM_SETTINGS_PATH",
"GEMINI_CLI_SYSTEM_DEFAULTS_PATH",
"HERMES_DATA_DIR_SUFFIX",
"HERMES_HOME",
"LOCALAPPDATA",
"OMP_PROFILE",
"OPENCODE_CONFIG",
"OPENCODE_CONFIG_DIR",
"PI_CODING_AGENT_DIR",
"PI_CONFIG_DIR",
"PI_PROFILE",
"QWEN_HOME",
"SAND_DATA_ROOT",
"XDG_CONFIG_HOME",
] as const;
+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`,
);
});
@@ -1,6 +1,7 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { STDIO_DEFAULT_MAX_BUFFER_SIZE } from "@modelcontextprotocol/server";
import { afterEach, expect, it, vi } from "vitest";
import { z } from "zod";
import { createAnalysisExecution } from "../../src/application/AnalysisProvider.js";
import { AnalysisInputError } from "../../src/domain/analysisErrorCore.js";
@@ -73,16 +74,19 @@ it("keeps independent server budgets for successful results and oversized errors
Math.ceil((smallBudget + 65536) / 17),
);
for (const server of [small, large])
server.registerTool("selected_failure", { inputSchema: {} }, async () =>
server.delivery.toErrorToolResult(
new AnalysisInputError("fixture", undefined, [
{
path: ["procedure"],
reason: "invalid_value",
message: diagnostic,
},
]),
),
server.registerTool(
"selected_failure",
{ inputSchema: z.object({}) },
async () =>
server.delivery.toErrorToolResult(
new AnalysisInputError("fixture", undefined, [
{
path: ["procedure"],
reason: "invalid_value",
message: diagnostic,
},
]),
),
);
const [smallClient, largeClient] = await Promise.all([