Merge remote-tracking branch 'origin/main' into feat/claude-code-plugin

This commit is contained in:
GamerDubz
2026-10-12 05:18:13 +02:00
389 changed files with 22916 additions and 2950 deletions
@@ -0,0 +1,168 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { expect } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js";
import { writeFixtureFiles } from "../../support/javascriptApplicationFixture.js";
const execute = promisify(execFile);
const createModuleLookupFixture = async () => {
const root = await createTestTempDirectory("rea-module-lookup-");
await writeFixtureFiles(root, {
"package.json": JSON.stringify({ name: "module-lookup-fixture" }),
"esm/entry.mjs": [
'import "./extensionless";',
'import "./directory";',
'import "./explicit.js";',
'import "./exact.js";',
'import fallback from "empty-main";',
'import "nested-main";',
"void fallback;",
].join("\n"),
"esm/extensionless.js": "module.exports = 1;",
"esm/directory/index.js": "module.exports = 2;",
"esm/explicit.js.js": "module.exports = 3;",
"esm/exact.js": "module.exports = 4;",
"cjs/entry.cjs": [
'require("./extensionless");',
'require("./feature");',
'require("./feature.cjs");',
'require("./default-js");',
'require("./default-json");',
'require("./default-node");',
'require("empty-main");',
'require("nested-main");',
].join("\n"),
"cjs/extensionless.cjs": "module.exports = 1;",
"cjs/feature.cjs": "module.exports = 2;",
"cjs/default-js.js": "module.exports = 3;",
"cjs/default-json.json": JSON.stringify({ value: 4 }),
// Inventory-only placeholder: never pass this path to Node's runtime.
"cjs/default-node.node": "source-owned opaque native-module placeholder",
"node_modules/empty-main/package.json": JSON.stringify({ main: "" }),
"node_modules/empty-main/index.js": "module.exports = 42;",
"node_modules/nested-main/package.json": JSON.stringify({ main: "sub" }),
"node_modules/nested-main/sub/package.json": JSON.stringify({
main: "other",
}),
"node_modules/nested-main/sub/other.js": "module.exports = 99;",
"runtime-control.mjs": [
'const specifiers = ["./esm/extensionless", "./esm/directory", "./esm/explicit.js", "./esm/exact.js", "empty-main", "nested-main"];',
"const results = [];",
"for (const specifier of specifiers) {",
" try { await import(specifier); results.push({ specifier, ok: true }); }",
" catch (error) { results.push({ specifier, ok: false, code: error.code }); }",
"}",
"console.log(JSON.stringify(results));",
].join("\n"),
"runtime-control.cjs": [
'const specifiers = ["./cjs/extensionless", "./cjs/feature", "./cjs/feature.cjs", "./cjs/default-js", "./cjs/default-json", "empty-main", "nested-main"];',
"const results = [];",
"for (const specifier of specifiers) {",
" try { require(specifier); results.push({ specifier, ok: true }); }",
" catch (error) { results.push({ specifier, ok: false, code: error.code }); }",
"}",
"console.log(JSON.stringify(results));",
].join("\n"),
});
return root;
};
cliTest.for(["CLI", "stdio MCP"] as const)(
"matches Node module lookup for ESM and CommonJS through %s",
async (surface, { cli }) => {
const root = await createModuleLookupFixture();
const [esmControl, cjsControl] = await Promise.all([
execute(process.execPath, ["runtime-control.mjs"], {
cwd: root,
timeout: 5_000,
}),
execute(process.execPath, ["runtime-control.cjs"], {
cwd: root,
timeout: 5_000,
}),
]);
const esmResults = JSON.parse(esmControl.stdout) as Array<{
readonly specifier: string;
readonly ok: boolean;
readonly code?: string;
}>;
const cjsResults = JSON.parse(cjsControl.stdout) as Array<{
readonly specifier: string;
readonly ok: boolean;
readonly code?: string;
}>;
expect(esmResults).toEqual([
{
specifier: "./esm/extensionless",
ok: false,
code: "ERR_MODULE_NOT_FOUND",
},
{
specifier: "./esm/directory",
ok: false,
code: "ERR_UNSUPPORTED_DIR_IMPORT",
},
{
specifier: "./esm/explicit.js",
ok: false,
code: "ERR_MODULE_NOT_FOUND",
},
{ specifier: "./esm/exact.js", ok: true },
{ specifier: "empty-main", ok: true },
{ specifier: "nested-main", ok: false, code: "ERR_MODULE_NOT_FOUND" },
]);
expect(cjsResults).toEqual([
{
specifier: "./cjs/extensionless",
ok: false,
code: "MODULE_NOT_FOUND",
},
{
specifier: "./cjs/feature",
ok: false,
code: "MODULE_NOT_FOUND",
},
{ specifier: "./cjs/feature.cjs", ok: true },
{ specifier: "./cjs/default-js", ok: true },
{ specifier: "./cjs/default-json", ok: true },
{ specifier: "empty-main", ok: true },
{ specifier: "nested-main", ok: false, code: "MODULE_NOT_FOUND" },
]);
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
const expectations = [
["import", "./extensionless", null, "not-found"],
["import", "./directory", null, "not-found"],
["import", "./explicit.js", null, "not-found"],
["import", "./exact.js", "esm/exact.js", "resolved"],
["import", "empty-main", "node_modules/empty-main/index.js", "resolved"],
["import", "nested-main", null, "not-found"],
["require", "./extensionless", null, "not-found"],
["require", "./feature", null, "not-found"],
["require", "./feature.cjs", "cjs/feature.cjs", "resolved"],
["require", "./default-js", "cjs/default-js.js", "resolved"],
["require", "./default-json", "cjs/default-json.json", "resolved"],
["require", "./default-node", "cjs/default-node.node", "resolved"],
["require", "empty-main", "node_modules/empty-main/index.js", "resolved"],
["require", "nested-main", null, "not-found"],
] as const;
for (const [kind, specifier, resolvedPath, status] of expectations)
expect(graph.edges).toContainEqual(
expect.objectContaining({
relation: "imports",
properties: expect.objectContaining({
module_link_kind: kind,
specifier,
resolved_path: resolvedPath,
resolution_status: status,
}),
}),
);
},
);
@@ -7,7 +7,11 @@ import { z } from "zod";
import { CATALOG_IDENTITY } from "../../../src/catalogIdentity.js";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import { evidenceResultOf } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
import {
evidenceResultOf,
expandToolAvailability,
toolAvailabilityInventory,
} from "../../../src/contracts/toolOutputSchemaPrimitives.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
const mainPath = fileURLToPath(
@@ -24,15 +28,14 @@ const expectAvailableToolInventory = async (client: Client) => {
arguments: {},
});
expect(status.isError).not.toBe(true);
const availability = z
const inventory = z
.object({
result: z.object({
tool_availability: z.array(
z.object({ name: z.string(), available: z.boolean() }),
),
tool_availability: toolAvailabilityInventory,
}),
})
.parse(status.structuredContent).result.tool_availability;
const availability = expandToolAvailability(inventory);
// This asserts the compiled entrypoint matches the source catalog. When it
// fails, check that `dist/` is current (`npm run build:cached`) before
// suspecting a registration bug -- a stale build is by far the likeliest
@@ -3,12 +3,10 @@ import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { z } from "zod";
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js";
import { writeFixtureFiles } from "../../support/javascriptApplicationFixture.js";
cliTest.for(["CLI", "stdio MCP"] as const)(
"recovers retained prefixed source-map originals and byte identity through %s",
@@ -29,27 +27,9 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
);
await writeFile(mapPath, mapText);
let document: unknown;
if (surface === "CLI") {
const response = await cli.run({
arguments: ["analyze-javascript-application", root, "--format", "json"],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(response.exitCode, response.stderr).toBe(0);
document = response.json;
} else {
const { call } = await connectLocalToolsMcp();
const response = await call("analyze_javascript_application", {
input_path: root,
format: "directory",
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
document = response.structuredContent;
}
const { graph } = z
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
.parse(document).normalized_result;
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
const mapDigest = createHash("sha256").update(mapText).digest("hex");
const originalDigest = createHash("sha256").update(original).digest("hex");
expect(graph.nodes).toContainEqual(
expect.objectContaining({
kind: "source-module",
@@ -57,7 +37,7 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
strategy: "source-map-original",
source_map_sha256: mapDigest,
original_source: "original.ts",
source_sha256: createHash("sha256").update(original).digest("hex"),
source_sha256: originalDigest,
}),
observations: expect.arrayContaining([
expect.objectContaining({
@@ -65,7 +45,13 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
source_name: "original.ts",
map_path: "bundle.js.map",
}),
properties: { content_available: true },
properties: {
source_index: 0,
declaration_index: 0,
source_name_available: true,
content_available: true,
content_sha256: originalDigest,
},
evidence: expect.objectContaining({
artifact: expect.objectContaining({ sha256: mapDigest }),
}),
@@ -77,3 +63,91 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
expect(await readFile(mapPath, "utf8")).toBe(mapText);
},
);
cliTest.for(["CLI", "stdio MCP"] as const)(
"retains nullable source-map declarations and aligned content through %s",
async (surface, { cli }) => {
const root = await createTestTempDirectory("rea-nullable-map-");
const original = "export const answer: number = 42;";
const unnamed = "retained source text without a declared name";
const maps = {
"absent.js.map": JSON.stringify({
version: 3,
sources: ["unembedded.ts"],
sourcesContent: null,
names: [],
mappings: "AAAA",
}),
"mixed.js.map": JSON.stringify({
version: 3,
sources: [null, "original.ts"],
sourcesContent: [unnamed, original],
names: [],
mappings: "ACAA",
}),
};
await writeFixtureFiles(root, {
...maps,
"absent.js":
"export const absent = 1;\n//# sourceMappingURL=absent.js.map\n",
"mixed.js":
"export const answer = 42;\n//# sourceMappingURL=mixed.js.map\n",
});
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
const digest = (text: string) =>
createHash("sha256").update(text).digest("hex");
for (const [name, mapPath, content] of [
["unembedded.ts", "absent.js.map", null],
["original.ts", "mixed.js.map", original],
] as const) {
const mapDigest = digest(maps[mapPath]);
expect(graph.nodes).toContainEqual(
expect.objectContaining({
kind: "source-module",
identity: expect.objectContaining({
strategy: "source-map-original",
source_map_sha256: mapDigest,
original_source: name,
source_sha256: content === null ? null : digest(content),
}),
observations: expect.arrayContaining([
expect.objectContaining({
source_map_reference: expect.objectContaining({
source_name: name,
map_path: mapPath,
}),
properties: expect.objectContaining({
content_available: content !== null,
}),
evidence: expect.objectContaining({
artifact: expect.objectContaining({ sha256: mapDigest }),
}),
}),
]),
}),
);
}
expect(graph.nodes).toContainEqual(
expect.objectContaining({
kind: "unknown",
observations: expect.arrayContaining([
expect.objectContaining({
properties: expect.objectContaining({
source_name_available: false,
content_available: true,
content_sha256: digest(unnamed),
}),
evidence: expect.objectContaining({
artifact: expect.objectContaining({
sha256: digest(maps["mixed.js.map"]),
}),
}),
}),
]),
}),
);
expect(graph.coverage.status).toBe("complete");
for (const [path, text] of Object.entries(maps))
expect(await readFile(join(root, path), "utf8")).toBe(text);
},
);
@@ -0,0 +1,232 @@
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { expect } from "vitest";
import { parse } from "yaml";
import { z } from "zod";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
cliTest(
"DSH CLI previews, approves, repairs, launches MCP, repeats and uninstalls while preserving caller YAML",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-dsh-lifecycle-");
const profile = join(home, "selected harness");
const config = join(profile, "cordis.patch.yml");
const skill = join(
home,
".agents/skills/reverse-engineer-anything/SKILL.md",
);
await mkdir(profile);
const original = `# caller home patch
- insert:
- id: rea-mcp
name: '@deepseek-ai/dsh-mcp-client'
config: {serverName: rea, transport: stdio, command: stale, args: [mcp]}
- holder: &op
insert:
- id: unrelated
name: caller-plugin
disabled: true
config: {cwd: !!js process.cwd()}
- id: rea-mcp
name: '@deepseek-ai/dsh-mcp-client'
config:
serverName: rea
transport: stdio
command: stale
args: [mcp]
cwd: !!js process.cwd()
env:
REA_LOG_LEVEL: !!js process.env.REA_LOG_LEVEL
- *op
`;
await writeFile(config, original);
const environment = { HOME: home, USERPROFILE: home, DSH_HOME: profile };
const run = (args: readonly string[]) =>
cli.run({
arguments: [...args, "--json"],
cwd: home,
environment,
timeoutMs: 20_000,
});
const plan = await run(["setup", "--client", "dsh", "--dry-run"]);
expect(plan.exitCode).toBe(0);
expect(plan.json).toMatchObject({
status: "planned",
appliedActions: [],
plannedActions: expect.arrayContaining([
expect.objectContaining({ id: "configure_client:dsh", target: config }),
expect.objectContaining({ id: "install_skill" }),
]),
});
expect(await readFile(config, "utf8")).toBe(original);
await expect(readFile(`${config}.rea.backup`)).rejects.toMatchObject({
code: "ENOENT",
});
const unapproved = await run(["setup", "--client", "dsh"]);
expect(unapproved.json).toMatchObject({
status: "needs_confirmation",
appliedActions: [],
});
expect(await readFile(config, "utf8")).toBe(original);
const configured = await run(["setup", "--client", "dsh", "--yes"]);
expect(configured.exitCode).toBe(0);
expect(configured.json).toMatchObject({
status: "ready",
clients: { dsh: { status: "configured" } },
});
const text = await readFile(config, "utf8");
expect(text).toContain("# caller home patch");
const patches = parse(text, {
customTags: [
{
tag: "tag:yaml.org,2002:js",
resolve: (source: string) => ({ __jsExpr: source }),
},
],
}) as { insert?: { id: string; config: unknown }[] }[];
const rows = patches.flatMap((patch) => patch.insert ?? []);
expect(rows.filter(({ id }) => id === "unrelated")).toEqual([
{
id: "unrelated",
name: "caller-plugin",
disabled: true,
config: { cwd: { __jsExpr: "process.cwd()" } },
},
]);
expect(rows.filter(({ id }) => id === "rea-mcp")).toHaveLength(1);
const registration = z
.object({
command: z.string(),
args: z.array(z.string()),
cwd: z.unknown(),
env: z.unknown(),
})
.parse(rows.find(({ id }) => id === "rea-mcp")?.config);
expect(registration.cwd).toEqual({ __jsExpr: "process.cwd()" });
expect(registration.env).toMatchObject({
REA_LOG_LEVEL: { __jsExpr: "process.env.REA_LOG_LEVEL" },
});
const doctor = await run(["doctor", "--client", "dsh", "--skill"]);
expect(doctor.exitCode).toBe(0);
expect(doctor.json).toMatchObject({
healthy: true,
identity: {
registrations: expect.arrayContaining([
expect.objectContaining({ client: "dsh", state: "aligned" }),
]),
},
});
await verifyGeneratedLauncher(registration, home, environment);
const repeated = await run(["setup", "--client", "dsh", "--yes"]);
expect(repeated.json).toMatchObject({
status: "ready",
appliedActions: [],
plannedActions: [],
});
expect(await readFile(config, "utf8")).toBe(text);
expect(await readFile(`${config}.rea.backup`, "utf8")).toBe(original);
const removed = await run(["uninstall"]);
expect(removed.exitCode).toBe(0);
expect(removed.json).toMatchObject({
status: "complete",
items: expect.arrayContaining([
expect.objectContaining({ name: "dsh", status: "removed" }),
]),
});
const remaining = parse(await readFile(config, "utf8"), {
logLevel: "silent",
}) as { insert?: { id: string }[] }[];
expect(
remaining.flatMap((patch) => patch.insert ?? []).map(({ id }) => id),
).toEqual(["unrelated"]);
expect(await readFile(`${config}.rea.backup`, "utf8")).toBe(original);
await expect(readFile(skill)).rejects.toMatchObject({ code: "ENOENT" });
},
);
async function verifyGeneratedLauncher(
registration: { command: string; args: string[] },
home: string,
environment: Record<string, string>,
): Promise<void> {
// Exercise the generated launcher. Native Cordis expression evaluation belongs
// to verify:deepseek-client, not this SDK transport journey.
const transport = new StdioClientTransport({
command: registration.command,
args: registration.args,
cwd: home,
env: { PATH: process.env.PATH ?? "", ...environment },
stderr: "pipe",
});
const client = new Client({ name: "dsh-setup-lifecycle", version: "1" });
try {
await client.connect(transport);
expect((await client.listTools()).tools.map(({ name }) => name)).toContain(
"binary_session",
);
const session = await client.callTool({
name: "binary_session",
arguments: {},
});
expect(session.isError).not.toBe(true);
expect(session.structuredContent).toMatchObject({
result: { open: false },
});
} finally {
await client.close();
await transport.close();
}
}
cliTest.for(["null", "caller-value", "[caller-value]"])(
"DSH CLI refuses to edit config %s and plain uninstall removes its owned row",
async (configValue, { cli }) => {
const home = await createTestTempDirectory("rea-dsh-malformed-config-");
const profile = join(home, ".dsh");
const config = join(profile, "cordis.patch.yml");
await mkdir(profile);
const initial = `# caller patch
- insert:
- id: other
name: caller-plugin
- id: rea-mcp
name: '@deepseek-ai/dsh-mcp-client'
config: ${configValue}
`;
await writeFile(config, initial);
const run = (args: readonly string[]) =>
cli.run({
arguments: [...args, "--json"],
cwd: home,
environment: { HOME: home, USERPROFILE: home, DSH_HOME: profile },
});
const configured = await run(["setup", "--client", "dsh", "--yes"]);
expect(configured.exitCode).not.toBe(0);
expect(configured.json).toMatchObject({
status: "needs_human",
appliedActions: [],
remediation: expect.stringContaining("config: Use a literal mapping"),
});
expect(await readFile(config, "utf8")).toBe(initial);
await expect(readFile(`${config}.rea.backup`)).rejects.toMatchObject({
code: "ENOENT",
});
const removed = await run(["uninstall"]);
expect(removed.exitCode).toBe(0);
expect(removed.json).toMatchObject({
status: "complete",
items: expect.arrayContaining([
expect.objectContaining({ name: "dsh", status: "removed" }),
]),
});
const remaining = await readFile(config, "utf8");
expect(remaining).toContain("# caller patch");
expect(parse(remaining)).toEqual([
{ insert: [{ id: "other", name: "caller-plugin" }] },
]);
expect(await readFile(`${config}.rea.backup`, "utf8")).toBe(initial);
},
);
@@ -96,6 +96,16 @@ const pathRequests: readonly [string, Record<string, unknown>][] = [
"export_web_scripts",
{ capture_path: nul, output_directory: "/tmp/exported-scripts" },
],
["inspect_pe_resources", { path: nul }],
["inspect_binary_layout", { path: nul }],
["inspect_recorded_crash", { path: nul }],
["inspect_wasm_artifact", { path: nul }],
["inspect_wasm_artifact", { path: "/tmp/sample.wasm", glue_paths: [nul] }],
[
"inspect_wasm_artifact",
{ path: "/tmp/sample.wasm", candidate_paths: [nul] },
],
["inspect_evm_interface", { path: nul, encoding: "raw" }],
[
"export_web_scripts",
{ capture_path: "/tmp/capture.json", output_directory: nul },
@@ -131,6 +131,178 @@ it("preserves unavailable response observations and captures completed peers", a
).toEqual(["missing-body", "available"]);
});
it("marks malformed JSON body shapes unavailable while preserving partial request shapes", async () => {
const browser = await startFakeCdpBrowser({
commandEvents(command, origin) {
if (command.method !== "Network.enable") return undefined;
const session =
command.sessionId === undefined ? {} : { sessionId: command.sessionId };
return ["unavailable", "partial"].flatMap((requestId) => {
const url = `${origin}/${requestId}`;
return [
{
...session,
method: "Network.requestWillBeSent",
params: {
requestId,
request: {
url,
method: requestId === "partial" ? "POST" : "GET",
...(requestId === "partial"
? {
headers: { "Content-Type": "application/json" },
postData: '{"request":true}',
}
: {}),
},
initiator: { type: "other" },
},
},
{
...session,
method: "Network.responseReceived",
params: {
requestId,
response: { url, status: 200, mimeType: "application/json" },
},
},
{
...session,
method: "Network.loadingFinished",
params: { requestId, encodedDataLength: 0 },
},
];
});
},
commandResult(command) {
return command.method === "Network.getResponseBody"
? { body: "{", base64Encoded: false }
: undefined;
},
});
trackBrowser(browser);
const result = await new CdpBrowserProvider().inspectPage(
inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
observation_ms: 20,
include_json_body_shapes: true,
}),
);
if (!result.ok) throw result.error;
expect(result.value.network.requests).toEqual([
expect.objectContaining({
request_id: "unavailable",
body_shapes: { status: "unavailable", request: null, response: null },
}),
expect.objectContaining({
request_id: "partial",
body_shapes: {
status: "partial",
request: expect.any(Object),
response: null,
},
}),
]);
expect(result.value.completeness.unavailable_sections).toContain(
"json_body_shapes",
);
expect(result.value.completeness.excluded).not.toContainEqual(
expect.objectContaining({
section: "json_body_shapes",
reason: "invalid_protocol_value",
}),
);
});
it("rejects malformed response-body envelopes and preserves request shapes", async () => {
const browser = await startFakeCdpBrowser({
commandEvents(command, origin) {
if (command.method !== "Network.enable") return undefined;
const session =
command.sessionId === undefined ? {} : { sessionId: command.sessionId };
return ["missing-encoding-flag", "invalid-encoding-flag"].flatMap(
(requestId) => {
const url = `${origin}/${requestId}`;
return [
{
...session,
method: "Network.requestWillBeSent",
params: {
requestId,
request: {
url,
method:
requestId === "invalid-encoding-flag" ? "POST" : "GET",
...(requestId === "invalid-encoding-flag"
? {
headers: { "Content-Type": "application/json" },
postData: '{"request":true}',
}
: {}),
},
initiator: { type: "other" },
},
},
{
...session,
method: "Network.responseReceived",
params: {
requestId,
response: { url, status: 200, mimeType: "application/json" },
},
},
{
...session,
method: "Network.loadingFinished",
params: { requestId, encodedDataLength: 0 },
},
];
},
);
},
commandResult(command) {
if (command.method !== "Network.getResponseBody") return undefined;
return command.params.requestId === "missing-encoding-flag"
? { body: '{"response":true}' }
: { body: '{"response":true}', base64Encoded: "false" };
},
});
trackBrowser(browser);
const result = await new CdpBrowserProvider().inspectPage(
inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
observation_ms: 20,
include_json_body_shapes: true,
}),
);
if (!result.ok) throw result.error;
expect(result.value.network.requests).toEqual([
expect.objectContaining({
request_id: "missing-encoding-flag",
body_shapes: { status: "unavailable", request: null, response: null },
}),
expect.objectContaining({
request_id: "invalid-encoding-flag",
body_shapes: {
status: "partial",
request: expect.any(Object),
response: null,
},
}),
]);
expect(result.value.completeness.excluded).toContainEqual({
section: "json_body_shapes",
reason: "invalid_protocol_value",
count: 2,
});
});
it.each([
{
options: {
@@ -751,7 +751,7 @@ describe("web source-map sourcesContent validation", () => {
JSON.stringify({
version: 3,
sources: ["source.ts"],
sourcesContent: [null],
sourcesContent: null,
names: [],
mappings: "",
}),
@@ -763,10 +763,61 @@ describe("web source-map sourcesContent validation", () => {
expect(result.items[0]).toMatchObject({
status: "included",
original_sources: [
{ source: `${origin}/assets/source.ts`, artifact: null },
{
source_index: 0,
declaration_index: 0,
source: `${origin}/assets/source.ts`,
artifact: null,
},
],
});
});
it("keeps unnamed source slots and mapping indices", async () => {
const result = await fetchWebSourceMaps([request], input(), undefined, {
fetch: () =>
Promise.resolve(
new Response(
JSON.stringify({
version: 3,
sources: [null, "source.ts"],
sourcesContent: ["unknown source text", "named source text"],
names: [],
mappings: "ACAA",
}),
{ status: 200 },
),
),
});
expect(result.items[0]).toMatchObject({
status: "partial",
original_sources: [
{
source_index: 0,
declaration_index: 0,
source: null,
artifact: { text: "unknown source text" },
},
{
source_index: 1,
declaration_index: 1,
source: `${origin}/assets/source.ts`,
artifact: { text: "named source text" },
},
],
mappings: [
{
source_index: 1,
declaration_index: 1,
source: `${origin}/assets/source.ts`,
},
],
});
expect(result.items[0]?.limitation).toContain(
"unnamed source at declaration 0",
);
});
});
describe("source-map original dependency syntax", () => {
@@ -345,7 +345,7 @@ it.each(cases)(
item.mappings.map((entry) => [
entry.generated_line,
entry.generated_column,
entry.source.replace(origin + "/", ""),
entry.source?.replace(origin + "/", "") ?? null,
]),
).toEqual(expected);
expect(item.artifact.sha256).toBe(
+43 -1
View File
@@ -1,9 +1,14 @@
import { expect, it } from "vitest";
import { chmod, lstat, readFile } from "node:fs/promises";
import { expect, it, onTestFinished } from "vitest";
import {
expectConfigurationRefusal,
serveCli as serve,
} from "./cliServeHarness.js";
import {
createTestWorkspace,
removeTestWorkspace,
} from "../../support/workspace/workspaceFixture.js";
it.each([
[
@@ -46,3 +51,40 @@ it("requires the output directory option on pull", async () => {
]);
expect(result.exitCode).not.toBe(0);
});
it.skipIf(process.platform === "win32")(
"refuses a trailing device separator through the CLI before adb or output effects",
async () => {
const workspace = await createTestWorkspace("rea-adb-cli-pull-");
onTestFinished(() => removeTestWorkspace(workspace.root));
const adb = await workspace.write(
"adb",
`#!/bin/sh
if [ "$1" = "version" ]; then
printf 'Android Debug Bridge version 1.0.41\\nVersion 34.0.5-cli\\nInstalled as %s\\n' "$0"
exit 0
fi
: > '${workspace.path("invoked")}'
exit 0
`,
);
await chmod(adb, 0o755);
const output = workspace.path("pulls");
const result = await serve(
[
"pull-adb-file",
"emulator-5554",
"/data/local/tmp/",
"--output-directory",
output,
"--json",
],
{ REA_ADB_PATH: adb },
);
expect(JSON.parse(result.stdout)).toMatchObject({
code: "invalid_request",
});
await expect(readFile(workspace.path("invoked"))).rejects.toThrow();
await expect(lstat(output)).rejects.toMatchObject({ code: "ENOENT" });
},
);
+158 -1
View File
@@ -1,3 +1,6 @@
import { apiSurfaceHar } from "../../fixtures/historicalHar.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { createHash } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -6,12 +9,89 @@ import { expect } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
import { analysisViewLayoutEvidence } from "../../fixtures/analysisView.js";
import {
analysisViewLayoutEvidence,
analysisViewCaptureFixture,
analysisViewCaptureEvidence,
analysisViewObjectDenseCapture,
} from "../../fixtures/analysisView.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { ghidraFunctionDossier } from "../../../src/domain/ghidraValues.fixture.js";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import { inspectEvidenceBundle } from "../../../src/application/investigation/InspectEvidenceBundle.js";
cliTest(
"admits portable captures before parsing and preserves capture caveats",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-inline-capture-cli-");
const path = join(root, "view.json");
const environment = {
HOME: root,
XDG_CONFIG_HOME: root,
XDG_CACHE_HOME: root,
};
await writeFile(
path,
JSON.stringify({
source: {
kind: "inline",
evidence: analysisViewCaptureEvidence(
analysisViewObjectDenseCapture(),
),
},
view: { kind: "api-surface" },
}),
);
const refused = await cli.run({
arguments: ["inspect-analysis-view", path, "--json"],
environment,
});
expect(refused.exitCode).toBe(1);
expect(refused.json).toMatchObject({
code: "resource_constraint",
details: { resource: "memory" },
});
const capture = analysisViewCaptureFixture();
capture.records = capture.records.slice(0, 1);
capture.total_records = 1;
const caveat = "Producer omitted exchanges before capture startup.";
capture.limitations = [caveat, caveat];
capture.records[0]!.reported = {
request: { method: "GET", url: "https://api.test/a" },
response: {
status: 200,
content: { mimeType: "\u000btext/plain\u000b" },
},
};
const parent = analysisViewCaptureEvidence(capture);
expect(parent.limitations).not.toContain(caveat);
await writeFile(
path,
JSON.stringify({
source: { kind: "inline", evidence: parent },
view: { kind: "api-surface" },
}),
);
const response = await cli.run({
arguments: ["inspect-analysis-view", path, "--json"],
environment,
});
expect(response.exitCode, response.stdout).toBe(0);
const result = parseEvidence(response.json);
expect(result.limitations.filter((value) => value === caveat)).toEqual([
caveat,
]);
expect(result.normalized_result).toMatchObject({
groups: [{ content_types: [], flags: ["single-sample"] }],
limitations: expect.arrayContaining([caveat]),
unknowns: [
"Some retained records have unavailable status or content type values.",
],
});
},
);
cliTest(
"discovers native records from a complete portable bundle using the shared workflow",
async ({ cli }) => {
@@ -216,3 +296,80 @@ for (const [view, reason] of [
},
);
}
cliTest(
"decodes HAR credentials and projects recorded API paths through the compiled workflows",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-surface-cli-");
const fixture = apiSurfaceHar();
const entry = fixture.log.entries[0]!;
const urls = [
"https://user:password@api.example.test/a/%2e%2e/admin?token=ordinary#fragment",
"https://api.example.test/admin",
"https:user:password@api.example.test/path",
"https:///user:password@api.example.test/path",
];
fixture.log.entries.push(
...urls.map((url) => ({
...entry,
request: { ...entry.request, url },
})),
);
const bytes = JSON.stringify(fixture);
const capturePath = join(root, "capture.har");
const input = join(root, "view.json");
const environment = {
HOME: root,
XDG_CONFIG_HOME: root,
XDG_CACHE_HOME: root,
};
await writeFile(capturePath, bytes);
const capture = await cli.run({
arguments: ["inspect-web-network-capture", capturePath, "har", "--json"],
environment,
});
expect(capture.exitCode, capture.stdout).toBe(0);
const parent = parseEvidence(capture.json);
expect(parent.subject?.digest.sha256).toBe(
createHash("sha256").update(bytes).digest("hex"),
);
expect(JSON.stringify(parent)).not.toContain("password");
await writeFile(
input,
JSON.stringify({
source: { kind: "inline", evidence: parent },
view: { kind: "api-surface" },
}),
);
const result = await cli.run({
arguments: ["inspect-analysis-view", input, "--json"],
environment,
});
expect(result.exitCode, result.stdout).toBe(0);
expect(result.json).toMatchObject({
confidence: "inferred",
evidence_links: [parent.evidence_id],
normalized_result: {
kind: "api-surface",
records: { examined: 17, total: 17, excluded: 2 },
coverage: { total: 14, exhausted: true },
groups: expect.arrayContaining([
expect.objectContaining({
path_template: "/a/%2e%2e/admin",
record_ordinals: [13],
}),
expect.objectContaining({
path_template: "/admin",
record_ordinals: [14],
}),
]),
excluded_records: [
{ ordinal: 15, reason: "url-redacted" },
{ ordinal: 16, reason: "url-redacted" },
],
},
});
expect(JSON.stringify(result.json)).not.toContain("password");
expect(JSON.stringify(result.json)).not.toContain("ordinary");
},
);
+3 -1
View File
@@ -123,7 +123,9 @@ registerHooks({
resolve(specifier, context, next) {
const resolved = next(specifier, context);
const name = imports.find((item) =>
resolved.url.includes(item.path),
resolved.url.includes(item.path) ||
(item.path.startsWith("/dist/") && item.path.endsWith(".js") &&
resolved.url.includes("/dist/cli-runtime/" + item.path.slice(6, -3).split("/").join("__") + "-")),
);
if (name !== undefined)
process.stderr.write(${JSON.stringify(MARKER)} + name.name + "\\n");
+5 -5
View File
@@ -11,7 +11,7 @@ describe("executable dispatcher", () => {
async ({ processes, workspace }) => {
const scripts = await workspace.mkdir("scripts");
await workspace.mkdir("dist");
await workspace.mkdir("dist/cli");
await workspace.mkdir("dist/cli-runtime");
await workspace.mkdir("dist/mcp");
await Promise.all([
copyFile("scripts/rea.mjs", join(scripts, "rea.mjs")),
@@ -24,19 +24,19 @@ describe("executable dispatcher", () => {
'export const runEntrypoint = () => process.stdout.write(JSON.stringify({ adapter: "mcp" }));\n',
),
workspace.write(
"dist/cli.js",
"dist/cli-runtime/cli.js",
'export const createCli = () => ({ serve: (args) => process.stdout.write(JSON.stringify({ adapter: "cli", args })) });\n',
),
workspace.write(
"dist/cliOutput.js",
"dist/cli-runtime/cliOutput.js",
"export const validateCliOutputArguments = () => ({ ok: true }); export const renderCliOutputArgumentError = () => ''; export const renderEmptyFilteredCliOutput = () => undefined;\n",
),
workspace.write(
"dist/cli/streamedJsonOutput.js",
"dist/cli-runtime/streamedJsonOutput.js",
"export const createStreamedCliJsonOutput = () => undefined;\n",
),
workspace.write(
"dist/mcpDoctor.js",
"dist/cli-runtime/mcpDoctor.js",
'export const runProductionMcpDoctorCli = (args) => Promise.resolve({ output: JSON.stringify({ adapter: "mcp-doctor", args }), exitCode: 0 });\n',
),
]);
@@ -0,0 +1,227 @@
import { expect } from "vitest";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { z } from "zod";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { writeFixtureFiles } from "../../support/javascriptApplicationFixture.js";
import { cliTest, type TestCli } from "../../support/cli/cliFixture.js";
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import { applicationFeatureTraceResultSchema } from "../../../src/domain/javascript/javascriptFeatureTraceSchemas.js";
import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js";
const analyze = async (cli: TestCli, extra = "") => {
const root = await createTestTempDirectory("rea-electron-wrapped-paths-");
await writeFixtureFiles(root, {
"preload.js": `const e=require("electron");
const sender=channel=>(...args)=>e.ipcRenderer.send(channel,...args);
e.contextBridge.exposeInMainWorld("desktop",{copy:sender("test:copy"),cut:sender("test:cut")});`,
"main.js": `const e=require("electron");
function register(channel,handler){e.ipcMain.addListener(channel,event=>allowed(event)&&handler(event))}
register("test:copy",event=>event.sender.copy());
register("test:cut",event=>event.sender.cut());${extra}`,
});
const output = await cli.run({
arguments: ["analyze-javascript-application", root, "--json"],
});
expect(output.exitCode).toBe(0);
const { normalized_result: result } = z
.object({
normalized_result: javascriptApplicationAnalysisResultSchema,
})
.parse(output.json);
return { root, application: output.json, ...result };
};
cliTest(
"traces a wrapped bridge member through a unique IPC channel using the public CLI",
async ({ cli }) => {
const { root, application, graph } = await analyze(cli);
const byId = new Map(graph.nodes.map((n) => [n.node_id, n]));
const joins = graph.edges.filter(
(e) => e.evidence.extractor.operation === "join-electron-wrapper-paths",
);
expect(joins).toHaveLength(2);
for (const edge of joins) {
expect(edge.evidence).toMatchObject({
state: "inferred",
authority: "static-relationship-inference",
});
expect(edge.properties.pairing_basis).toBe(
"unique-exact-literal-channel",
);
expect(
byId.get(edge.source_node_id)?.observations[0]?.properties.channel,
).toBe(edge.properties.channel);
expect(
byId.get(edge.target_node_id)?.observations[0]?.properties.channel,
).toBe(edge.properties.channel);
expect(edge.properties.conditions).toEqual([
expect.objectContaining({ expression: "allowed(event)" }),
]);
}
const start = graph.nodes.find((n) =>
n.observations.some(
(o) =>
o.properties.entry === "desktop.copy" &&
o.properties.step_kind === "exposure",
),
);
expect(start).toBeDefined();
const visited = new Set<string>(),
pending = start ? [start.node_id] : [];
while (pending.length) {
const id = pending.pop();
if (!id || visited.has(id)) continue;
visited.add(id);
for (const edge of graph.edges)
if (edge.source_node_id === id) pending.push(edge.target_node_id);
}
expect(
[...visited].some((id) =>
byId
.get(id)
?.observations.some((o) => o.label === "ipc-event.sender.copy"),
),
).toBe(true);
expect(
[...visited].some((id) =>
byId
.get(id)
?.observations.some((o) => o.label === "ipc-event.sender.cut"),
),
).toBe(false);
const input = join(root, "trace-input.json");
await writeFile(
input,
JSON.stringify({
application,
seed: { kind: "api", value: "desktop.copy", match: "exact" },
direction: "outgoing",
}),
);
const traced = await cli.run({
arguments: ["trace-application-feature", input, "--json"],
});
expect(traced.exitCode).toBe(0);
const { normalized_result: trace } = z
.object({
normalized_result: applicationFeatureTraceResultSchema,
})
.parse(traced.json);
expect(trace.seed_matches).toHaveLength(1);
expect(
trace.paths.some(
(path) =>
path.contains_inference &&
path.node_ids.length > 8 &&
byId
.get(path.end_node_id)
?.observations.some((o) => o.label === "ipc-event.sender.copy"),
),
).toBe(true);
},
);
for (const surface of ["CLI", "stdio MCP"] as const) {
cliTest(
`preserves handler ambiguity and short-circuit factory paths through ${surface}`,
async ({ cli }) => {
const root = await createTestTempDirectory("rea-electron-branch-paths-");
await writeFixtureFiles(root, {
"preload.js": `const e=require("electron");
e.contextBridge.exposeInMainWorld("empty", {});
function choose(){
if(flag)return ()=>e.ipcRenderer.send("test:copy");
else return ()=>e.ipcRenderer.send("test:cut");
return ()=>e.ipcRenderer.send("test:dead");
}
e.contextBridge.exposeInMainWorld("desktop", {
choose:choose(),
ambiguous:()=>e.ipcRenderer.send("test:ambiguous"),
competing:()=>e.ipcRenderer.send("test:competing"),
conditional:()=>e.ipcRenderer.send("test:conditional"),
fallback:()=>e.ipcRenderer.send("test:fallback"),
});`,
"main.js": `const e=require("electron");
const copy=event=>event.sender.copy(), cut=event=>event.sender.cut();
function register(channel,handler){e.ipcMain.on(channel,handler)}
register("test:copy",copy);register("test:cut",cut);
register("test:ambiguous",flag?copy:cut);
register("test:competing",copy);
register("test:competing",flag?copy:unknownHandler);
if(flag) register("test:conditional",copy);
register("test:fallback",event=>{false ?? event.sender.copy()});`,
});
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
const empty = graph.nodes
.filter((node) => node.kind === "context-bridge-api")
.flatMap((node) => node.observations)
.find((observation) => observation.properties.api_key === "empty");
expect(empty).toMatchObject({
properties: {
api_status: "object-literal",
members: [],
unknown_members: 0,
resolution_basis: "direct-syntax",
},
evidence: { state: "observed" },
});
const joins = graph.edges.filter(
(edge) =>
edge.evidence.extractor.operation === "join-electron-wrapper-paths",
);
expect(joins.map((edge) => edge.properties.channel).sort()).toEqual([
"test:copy",
"test:cut",
]);
const steps = graph.nodes
.flatMap((node) => node.observations)
.filter(
(observation) => observation.properties.step_kind === "terminal",
);
expect(
[
...new Set(
steps
.filter((step) => step.properties.entry === "desktop.choose")
.map((step) => step.properties.channel),
),
].sort(),
).toEqual(["test:copy", "test:cut"]);
for (const [channel, expression] of [
["test:copy", "flag"],
["test:cut", "!(flag)"],
])
expect(
steps.find(
(step) =>
step.properties.entry === "desktop.choose" &&
step.properties.channel === channel,
)?.properties.conditions,
).toEqual([expect.objectContaining({ expression })]);
expect(
steps.some(
(step) =>
step.properties.entry_kind === "ipc-handler" &&
["test:ambiguous", "test:fallback"].includes(
String(step.properties.channel),
),
),
).toBe(false);
},
);
}
cliTest(
"does not join a channel with another untraced compatible handler",
async ({ cli }) => {
const { graph } = await analyze(
cli,
'e.ipcMain.on("test:copy",event=>unresolved(event));',
);
const joins = graph.edges.filter(
(e) => e.evidence.extractor.operation === "join-electron-wrapper-paths",
);
expect(joins.map((e) => e.properties.channel)).toEqual(["test:cut"]);
},
);
@@ -1,15 +1,15 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Filter } from "incur";
import { expect } from "vitest";
import { z } from "zod";
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import { analyzeJavaScriptApplication } from "../../support/javascriptApplicationScope.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
const filter = "evidence_id,normalized_result.graph.nodes[0:1].node_id";
const filter = "evidence_id,normalized_result.graph.nodes[0,1].node_id";
for (const scenario of [
{
@@ -34,6 +34,9 @@ for (const scenario of [
await writeFile(join(root, "main.js"), "fetch('');\n");
const direct = await analyzeJavaScriptApplication({ input_path: root });
if (!direct.ok) throw direct.error;
const normalized = javascriptApplicationAnalysisResultSchema.parse(
direct.value.normalized_result,
);
const output = await cli.run({
arguments: [
scenario.command,
@@ -61,9 +64,20 @@ for (const scenario of [
}
expect(data).toEqual(
scenario.filtered
? Filter.apply(direct.value, Filter.parse(filter))
? {
evidence_id: direct.value.evidence_id,
normalized_result: {
graph: {
nodes: normalized.graph.nodes
.slice(0, 1)
.map(({ node_id }) => ({ node_id })),
},
},
}
: direct.value,
);
if (scenario.filtered)
expect(normalized.graph.nodes.length).toBeGreaterThan(0);
},
);
}
@@ -123,3 +137,67 @@ cliTest(
expect(output.json).toEqual({});
},
);
cliTest(
"honors caller-selected semantic node limits across files and records them in Evidence",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-js-node-budgets-");
await writeFile(join(root, "first.js"), "external;\n".repeat(40));
await writeFile(join(root, "second.js"), "another;\n".repeat(40));
const output = await cli.run({
arguments: [
"analyze-javascript-application",
root,
"--format",
"json",
"--max-semantic-nodes",
"50",
"--max-semantic-nodes-per-file",
"30",
],
});
expect(output.exitCode).toBe(0);
const result = z
.object({
parameters: z.object({
max_semantic_nodes: z.number(),
max_semantic_nodes_per_file: z.number(),
}),
normalized_result: z.object({
semantic_graph: z.object({
nodes: z.array(
z.object({ identity: z.object({ module_path: z.string() }) }),
),
coverage: z.object({
truncated: z.boolean(),
omitted_nodes: z.number().nullable(),
limits: z.array(
z.object({ name: z.string(), value: z.number() }),
),
}),
}),
}),
})
.parse(output.json);
expect(result.parameters).toEqual({
max_semantic_nodes: 50,
max_semantic_nodes_per_file: 30,
});
const graph = result.normalized_result.semantic_graph;
expect(graph.nodes).toHaveLength(50);
expect(
graph.nodes.filter((node) => node.identity.module_path === "first.js"),
).toHaveLength(30);
expect(
graph.nodes.filter((node) => node.identity.module_path === "second.js"),
).toHaveLength(20);
expect(graph.coverage.truncated).toBe(true);
expect(graph.coverage.omitted_nodes).toBeNull();
expect(graph.coverage.limits).toEqual(
expect.arrayContaining([
{ name: "semantic_graph_node_ceiling", value: 50 },
{ name: "semantic_graph_file_node_ceiling", value: 30 },
]),
);
},
);
@@ -0,0 +1,24 @@
import { expect } from "vitest";
import { parseEvidence } from "../../../src/domain/evidence.js";
import {
expectKeyedArchivePrototypeKeys,
keyedArchivePrototypeKeyFixture,
} from "../../fixtures/keyedArchivePrototypeKeys.js";
import { cliTest } from "../../support/cli/cliFixture.js";
cliTest(
"compiled CLI decodes formatted XML prototype keys",
async ({ cli }) => {
const fixture = await keyedArchivePrototypeKeyFixture();
const output = await cli.run({
arguments: ["inspect-keyed-archive", fixture.path, "--json"],
environment: { REA_LOG_LEVEL: "silent", REA_ANALYSIS_PROVIDER: "auto" },
});
expect(output.exitCode, output.stderr).toBe(0);
expectKeyedArchivePrototypeKeys(
parseEvidence(output.json).normalized_result,
fixture.digest,
);
},
);
+2 -2
View File
@@ -32,7 +32,7 @@ cliTest(
});
expect(missing.exitCode).toBe(1);
expect(missing.json).toMatchObject({
code: "target_unavailable",
code: "invalid_request",
details: { reason: expect.stringContaining("architecture") },
});
},
@@ -62,7 +62,7 @@ cliTest(
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "target_unavailable",
code: "invalid_request",
details: { reason: expect.stringContaining("must be 4-byte aligned") },
});
},
@@ -3,6 +3,7 @@ import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { withArtifactResourceScope } from "../../fixtures/artifactInventory.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
@@ -76,11 +77,14 @@ describe("analysis snapshots: persistence", () => {
const directory = await createTestTempDirectory("rea-snapshot-");
const path = join(directory, "analysis.json");
const snapshot = snapshotFixture();
const written = await writeAnalysisSnapshot(snapshot, path, false);
expect(written.ok).toBe(true);
const written = await withArtifactResourceScope((resources) =>
writeAnalysisSnapshot(snapshot, path, false, resources),
);
if (!written.ok) throw written.error;
expect((await readFile(path, "utf8")).endsWith("\n")).toBe(true);
expect((await stat(path)).mode & 0o777).toBe(0o600);
expect((await readAnalysisSnapshot(path)).ok).toBe(true);
const roundTrip = await readAnalysisSnapshot(path);
if (!roundTrip.ok) throw roundTrip.error;
const altered: unknown = JSON.parse(await readFile(path, "utf8"));
if (
@@ -102,8 +106,9 @@ describe("analysis snapshots: persistence", () => {
Reflect.set(first.parameters, "address", "0x2000");
await writeFile(path, JSON.stringify(altered));
const loaded = await readAnalysisSnapshot(path);
expect(loaded.ok).toBe(false);
if (!loaded.ok) expect(loaded.error._tag).toBe("EvidenceIntegrityError");
if (loaded.ok)
throw new Error("Expected changed snapshot identity rejection");
expect(loaded.error._tag).toBe("EvidenceIntegrityError");
expect(() => parseAnalysisSnapshot(altered)).toThrow(/identifier/u);
});
});
@@ -5,6 +5,7 @@ import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { expect, it } from "vitest";
import { writeOrderedZip } from "../../fixtures/artifactEntryOrder.js";
import { inventoryArtifact } from "../../fixtures/artifactInventory.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
@@ -12,6 +13,108 @@ import { ZipArtifactReader } from "../../../src/artifacts/ZipArtifactReader.js";
import { withArtifactClient } from "../../support/artifactClientScope.js";
import { artifactInventoryResultSchema } from "../../../src/domain/artifactGraph.js";
it.each([
["legacy CP437", Buffer.from([0x82, 0x2e, 0x74, 0x78, 0x74]), false, "é.txt"],
[
"EFS with leading U+FEFF",
Buffer.from([0xef, 0xbb, 0xbf, 0x61, 0x62]),
true,
"\uFEFFab",
],
] as const)(
"preserves %s ZIP member names",
async (_label, rawName, utf8Flag, logicalPath) => {
const root = await createTestTempDirectory("rea-zip-decoded-name-");
const path = join(root, "names.zip");
await writeSingleEntryZip(path, "x.txt");
const archive = await readFile(path);
await writeFile(
path,
rewriteSingleEntryName(archive, "x.txt", rawName, utf8Flag),
);
const inventory = await inventoryArtifact(path);
expect(inventory.occurrences).toContainEqual(
expect.objectContaining({
logical_path: logicalPath,
hash_status: "verified",
}),
);
},
);
it("preserves valid Info-ZIP Unicode Path overrides", async () => {
const root = await createTestTempDirectory("rea-zip-unicode-path-");
const path = join(root, "unicode-path.zip");
const rawName = Buffer.from("legacy.txt");
const unicodeName = Buffer.from("café.txt", "utf8");
const field = Buffer.alloc(5 + unicodeName.length);
field[0] = 1;
field.writeUInt32LE(zipCrc32(rawName), 1);
unicodeName.copy(field, 5);
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("legacy.txt", new TextReader("unicode path"), {
extraField: new Map([[0x7075, field]]),
});
const archive = Buffer.from(await writer.close());
await writeFile(
path,
rewriteSingleEntryName(archive, "legacy.txt", rawName, false),
);
const inventory = await inventoryArtifact(path);
expect(inventory.occurrences).toContainEqual(
expect.objectContaining({
logical_path: "café.txt",
hash_status: "verified",
}),
);
});
it("rejects malformed UTF-8 in flagged ZIP member names", async () => {
const root = await createTestTempDirectory("rea-zip-invalid-utf8-name-");
const path = join(root, "invalid-utf8.zip");
await writeSingleEntryZip(path, "x.txt");
const archive = await readFile(path);
const malformedName = Buffer.from([0xc3, 0x28, 0x2e, 0x74, 0x78]);
await writeFile(
path,
rewriteSingleEntryName(archive, "x.txt", malformedName, true),
);
await expect(inventoryArtifact(path)).rejects.toMatchObject({
name: "ArtifactReaderFailure",
reason: "format",
message: "ZIP filename is not valid UTF-8",
});
});
it("rejects malformed UTF-8 in a CRC-valid Unicode Path extra field", async () => {
const root = await createTestTempDirectory("rea-zip-invalid-unicode-extra-");
const path = join(root, "invalid-unicode-extra.zip");
const rawName = Buffer.from("legacy.txt");
const malformedName = Buffer.from([0xc3, 0x28, 0x2e, 0x74, 0x78]);
const field = Buffer.alloc(5 + malformedName.length);
field[0] = 1;
field.writeUInt32LE(zipCrc32(rawName), 1);
malformedName.copy(field, 5);
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("legacy.txt", new TextReader("malformed extra"), {
extraField: new Map([[0x7075, field]]),
});
const archive = Buffer.from(await writer.close());
await writeFile(
path,
rewriteSingleEntryName(archive, "legacy.txt", rawName, false),
);
await expect(inventoryArtifact(path)).rejects.toMatchObject({
name: "ArtifactReaderFailure",
reason: "format",
message: "ZIP Unicode Path extra field is not valid UTF-8",
});
});
it("bounds a requested metadata read without rejecting the underlying valid ZIP", async () => {
const root = await createTestTempDirectory("rea-zip-metadata-budget-");
const path = join(root, "large-directory.zip");
@@ -295,3 +398,66 @@ it("rejects a truncated ZIP through artifact inventory", async () => {
error: { _tag: "ArtifactOperationError", reason: "io" },
});
});
const writeSingleEntryZip = async (
path: string,
name: string,
): Promise<void> => {
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add(name, new TextReader("member bytes"));
await writeFile(path, await writer.close());
};
const rewriteSingleEntryName = (
archive: Buffer,
originalName: string,
rawName: Buffer,
utf8Flag: boolean,
): Buffer => {
const rewritten = Buffer.from(archive);
const expectedName = Buffer.from(originalName, "utf8");
for (const { signature, nameOffset, flagsOffset, lengthOffset } of [
{
signature: Buffer.from([0x50, 0x4b, 0x03, 0x04]),
nameOffset: 30,
flagsOffset: 6,
lengthOffset: 26,
},
{
signature: Buffer.from([0x50, 0x4b, 0x01, 0x02]),
nameOffset: 46,
flagsOffset: 8,
lengthOffset: 28,
},
]) {
const header = rewritten.indexOf(signature);
if (header < 0) throw new Error("Expected ZIP member header");
const nameLength = rewritten.readUInt16LE(header + lengthOffset);
if (
nameLength !== expectedName.length ||
nameLength !== rawName.length ||
!rewritten
.subarray(header + nameOffset, header + nameOffset + nameLength)
.equals(expectedName)
)
throw new Error("Expected the original ZIP member name");
rawName.copy(rewritten, header + nameOffset);
const flags = rewritten.readUInt16LE(header + flagsOffset);
rewritten.writeUInt16LE(
utf8Flag ? flags | 0x0800 : flags & ~0x0800,
header + flagsOffset,
);
}
return rewritten;
};
const zipCrc32 = (bytes: Uint8Array): number => {
let checksum = 0xffffffff;
for (const byte of bytes) {
checksum ^= byte;
for (let bit = 0; bit < 8; bit += 1)
checksum =
(checksum & 1) === 1 ? (checksum >>> 1) ^ 0xedb88320 : checksum >>> 1;
}
return (checksum ^ 0xffffffff) >>> 0;
};
@@ -20,12 +20,47 @@ import {
} from "../../../src/application/AppBundleExecutable.js";
import {
dosMz,
fat,
pe,
thinMach,
} from "../../../src/domain/binaryTarget.fixture.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
it.each([{ cpus: [0x0100000c] }, { cpus: [0x01000007, 0x0100000c] }])(
"preserves a FAT container's format in the resolved target and Evidence ($cpus)",
async ({ cpus }) => {
const directory = await createTestTempDirectory("rea-universal-target-");
const path = join(directory, "image");
await writeFile(path, fat(cpus));
const resolved = await parseBinaryTarget(path, {
hostArchitecture: "arm64",
});
if (!resolved.ok) throw resolved.error;
expect(resolved.value).toMatchObject({
kind: "executable",
format: "mach-o-universal",
architecture: "arm64",
});
const evidence = createEvidence(
resolved.value,
{ id: "fixture", name: "Fixture", version: "1" },
{
operation: "inspect_macho",
parameters: {},
result: null,
},
);
expect(
parseEvidence(JSON.parse(JSON.stringify(evidence))).subject,
).toMatchObject({
format: "mach-o-universal",
architecture: "arm64",
});
},
);
describe("binary target I/O: app plist permissions and decoding", () => {
it.each([
["EACCES", "permission denied reading app Info.plist"],
@@ -67,6 +67,7 @@ describe("client configuration filesystem lifecycle", () => {
"omp",
"pi",
"hermes",
"dsh",
"grok_bot",
]);
expect(
@@ -3,6 +3,7 @@ import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { withArtifactResourceScope } from "../../fixtures/artifactInventory.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { writeAnalysisSnapshot } from "../../../src/application/binary/AnalysisSnapshotFiles.js";
@@ -84,9 +85,10 @@ describe("direct analysis snapshot files", () => {
workflow_entries: [],
evidence_bundle: createEvidenceBundle([evidence]),
};
expect(
(await writeAnalysisSnapshot(snapshot, snapshotPath, false)).ok,
).toBe(true);
const written = await withArtifactResourceScope((resources) =>
writeAnalysisSnapshot(snapshot, snapshotPath, false, resources),
);
if (!written.ok) throw written.error;
vi.stubEnv("HOPPER_LAUNCHER_PATH", launcherPath);
await expect(
@@ -2,7 +2,7 @@ import { parseConfig } from "../../../src/config/parseConfig.js";
import { writeFile } from "node:fs/promises";
import { basename, dirname, join } from "node:path";
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import { z } from "zod";
import { runDirectAnalysis } from "../../../src/application/DirectAnalysis.js";
@@ -33,11 +33,13 @@ import {
createAnalysisSnapshotWorkflowEntry,
type AnalysisSnapshot,
} from "../../../src/domain/analysisSnapshot.js";
import { withArtifactResourceScope } from "../../fixtures/artifactInventory.js";
import {
createTestBinarySession,
createTestProviderRouter,
} from "../../fixtures/binarySession.js";
import { BinarySession } from "../../../src/application/binary/BinarySession.js";
import { OwnedStagedOutput } from "../../../src/filesystem/OwnedStagedOutput.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
CAPABILITIES as GHIDRA_CAPABILITIES,
@@ -342,6 +344,58 @@ const withEarlierHistoricalEvidence = (
};
};
describe("snapshot output cleanup lifecycle", () => {
it("returns completed analysis after retrying cleanup of a published snapshot", async () => {
const fixture = await createSnapshotReplayFixture(
"rea-snapshot-cleanup-retry-",
);
const cleanup = vi
.spyOn(OwnedStagedOutput.prototype, "close")
.mockRejectedValueOnce(new Error("transient staging cleanup failure"));
try {
const output = await runDirectAnalysis(
fixture.dependencies(fixture.createProvider()),
fixture.path,
"binary_overview",
{},
{ snapshotPath: fixture.snapshotPath },
);
expect(parseEvidence(output).operation).toBe("binary_overview");
const saved = await readAnalysisSnapshot(fixture.snapshotPath);
if (!saved.ok) throw saved.error;
expect(saved.value.workflow_entries).toHaveLength(1);
expect(cleanup).toHaveBeenCalledTimes(2);
} finally {
cleanup.mockRestore();
}
});
it("saves snapshots after closing and reopening the same session", async () => {
const fixture = await createSnapshotReplayFixture("rea-snapshot-reopen-");
const session = createTestBinarySession(fixture.createProvider());
try {
for (const index of [1, 2]) {
const opened = await session.open(fixture.path);
if (!opened.ok) throw opened.error;
const analyzed = await session.execute("list_segments", {});
if (!analyzed.ok) throw analyzed.error;
const path = join(
dirname(fixture.snapshotPath),
`snapshot-${index}.json`,
);
const saved = await session.closeWithSnapshot(path, false);
if (!saved.ok) throw saved.error;
const loaded = await readAnalysisSnapshot(path);
if (!loaded.ok) throw loaded.error;
expect(loaded.value.target.sha256).toBe(opened.value.sha256);
}
} finally {
const closed = await session.close();
if (!closed.ok) throw closed.error;
}
});
});
describe("direct analysis composed snapshot replay", () => {
it.each([
{
@@ -530,15 +584,15 @@ describe("binary overview snapshot replay", () => {
);
if (current === undefined)
throw new Error("composed Evidence was not saved");
expect(
(
await writeAnalysisSnapshot(
withEarlierHistoricalEvidence(loaded.value, fixture.path, current),
fixture.snapshotPath,
true,
)
).ok,
).toBe(true);
const written = await withArtifactResourceScope((resources) =>
writeAnalysisSnapshot(
withEarlierHistoricalEvidence(loaded.value, fixture.path, current),
fixture.snapshotPath,
true,
resources,
),
);
if (!written.ok) throw written.error;
const second = await runDirectAnalysis(
dependencies,
@@ -735,15 +789,15 @@ describe("workflow snapshot profile and cancellation binding", () => {
);
if (current === undefined)
throw new Error("composed Evidence was not saved");
expect(
(
await writeAnalysisSnapshot(
withAlternateWorkflowProfile(loaded.value, fixture.path, current),
fixture.snapshotPath,
true,
)
).ok,
).toBe(true);
const written = await withArtifactResourceScope((resources) =>
writeAnalysisSnapshot(
withAlternateWorkflowProfile(loaded.value, fixture.path, current),
fixture.snapshotPath,
true,
resources,
),
);
if (!written.ok) throw written.error;
const refreshed = await runDirectAnalysis(
dependencies,
File diff suppressed because it is too large Load Diff
@@ -11,6 +11,7 @@ import { join } from "node:path";
import { describe, expect, it, vi } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { withArtifactResourceScope } from "../../fixtures/artifactInventory.js";
import {
readEvidenceBundle,
@@ -99,15 +100,10 @@ describe("evidence bundle export cancellation", () => {
yield "unused";
}
expect(
await writeTextParts(
parts(),
join(root, "missing", "bundle.json"),
false,
{
signal: controller.signal,
operation: "export_evidence_bundle",
},
),
await writeParts(parts(), join(root, "missing", "bundle.json"), false, {
signal: controller.signal,
operation: "export_evidence_bundle",
}),
).toMatchObject({
ok: false,
error: {
@@ -118,7 +114,7 @@ describe("evidence bundle export cancellation", () => {
expect(advanced).toBe(false);
expect(await readdir(root)).toEqual([]);
expect(
await writeEvidenceBundle(
await writeBundle(
bundle(),
join(root, "bundle.json"),
false,
@@ -149,7 +145,7 @@ describe("evidence bundle export cancellation", () => {
}
}
expect(
await writeTextParts(parts(), path, overwrite, {
await writeParts(parts(), path, overwrite, {
signal: controller.signal,
operation: "export_evidence_bundle",
}),
@@ -164,9 +160,9 @@ describe("evidence bundle export cancellation", () => {
expect(continued).toBe(false);
expect(await readdir(root)).toEqual(overwrite ? ["bundle.json"] : []);
if (overwrite) expect(await readFile(path, "utf8")).toBe("original");
expect(
await writeEvidenceBundle(bundle(), path, overwrite),
).toMatchObject({ ok: true });
expect(await writeBundle(bundle(), path, overwrite)).toMatchObject({
ok: true,
});
expect(await readEvidenceBundle(path)).toEqual({
ok: true,
value: bundle(),
@@ -184,7 +180,7 @@ describe("evidence bundle export cancellation", () => {
controller.abort();
}
expect(
await writeTextParts(parts(), path, true, {
await writeParts(parts(), path, true, {
signal: controller.signal,
operation: "export_evidence_bundle",
}),
@@ -194,6 +190,29 @@ describe("evidence bundle export cancellation", () => {
});
});
const writeBundle = (
value: ReturnType<typeof bundle>,
path: string,
overwrite: boolean,
signal?: AbortSignal,
) =>
withArtifactResourceScope((resources) =>
writeEvidenceBundle(value, path, overwrite, resources, signal),
);
const writeParts = (
parts: Iterable<string>,
path: string,
overwrite: boolean,
cancellation?: {
readonly signal: AbortSignal;
readonly operation: string;
},
) =>
withArtifactResourceScope((resources) =>
writeTextParts(parts, path, overwrite, resources, cancellation),
);
describe("evidence bundle publication", () => {
it.each([false, true])(
"never publishes a partial streamed file (overwrite: %s)",
@@ -205,9 +224,7 @@ describe("evidence bundle publication", () => {
yield "partial";
throw new Error("Source stream failed");
}
expect(
await writeTextParts(brokenParts(), path, overwrite),
).toMatchObject({
expect(await writeParts(brokenParts(), path, overwrite)).toMatchObject({
ok: false,
error: { _tag: "EvidenceFileError", reason: "io" },
});
@@ -220,7 +237,7 @@ describe("evidence bundle publication", () => {
const root = await createTestTempDirectory("rea-stream-bytes-");
const path = join(root, "bundle.json");
const parts = ["雪", "😀", "\n"];
expect(await writeTextParts(parts, path, false)).toEqual({
expect(await writeParts(parts, path, false)).toEqual({
ok: true,
value: { path, bytes: Buffer.byteLength(parts.join("")) },
});
@@ -233,7 +250,7 @@ describe("evidence bundle publication", () => {
const path = join(root, "bundle.json");
const candidates = [bundle(), bundle(false)];
const results = await Promise.all(
candidates.map((value) => writeEvidenceBundle(value, path, false)),
candidates.map((value) => writeBundle(value, path, false)),
);
expect(results.filter(({ ok }) => ok)).toHaveLength(1);
expect(results.filter(({ ok }) => !ok)).toMatchObject([
@@ -253,7 +270,7 @@ describe("evidence bundle publication", () => {
await mkdir(directory);
const path = join(directory, "bundle.json");
const value = bundle();
expect(await writeEvidenceBundle(value, path, false)).toMatchObject({
expect(await writeBundle(value, path, false)).toMatchObject({
ok: true,
});
expect(await readEvidenceBundle(path)).toEqual({
@@ -308,7 +325,7 @@ describe("evidence bundle filesystem adapter", () => {
const directory = await createTestTempDirectory("rea-evidence-");
const path = join(directory, "bundle.json");
const evidenceBundle = bundle();
const first = await writeEvidenceBundle(evidenceBundle, path, false);
const first = await writeBundle(evidenceBundle, path, false);
expect(first).toMatchObject({ ok: true, value: { path } });
expect(await readFile(path, "utf8")).toBe(
serializeEvidenceBundle(evidenceBundle),
@@ -329,15 +346,13 @@ describe("evidence bundle filesystem adapter", () => {
summary: { records_unchanged: 1 },
},
});
expect(
await writeEvidenceBundle(evidenceBundle, path, false),
).toMatchObject({
expect(await writeBundle(evidenceBundle, path, false)).toMatchObject({
ok: false,
error: { _tag: "EvidenceFileError", reason: "exists" },
});
expect(await writeEvidenceBundle(evidenceBundle, path, true)).toMatchObject(
{ ok: true },
);
expect(await writeBundle(evidenceBundle, path, true)).toMatchObject({
ok: true,
});
});
it("reads the caller-selected symlink target and refuses to replace a symlink", async () => {
@@ -352,7 +367,7 @@ describe("evidence bundle filesystem adapter", () => {
ok: true,
value: bundle(),
});
expect(await writeEvidenceBundle(bundle(), link, true)).toMatchObject({
expect(await writeBundle(bundle(), link, true)).toMatchObject({
ok: false,
error: { _tag: "EvidenceFileError", reason: "not-file" },
});
@@ -373,7 +388,7 @@ describe("evidence bundle filesystem adapter", () => {
});
const orphan = join(directory, "absent", "bundle.json");
const written = await writeEvidenceBundle(bundle(), orphan, false);
const written = await writeBundle(bundle(), orphan, false);
expect(written).toMatchObject({
ok: false,
error: { _tag: "EvidenceFileError", reason: "missing", path: orphan },
@@ -185,4 +185,28 @@ mcp_servers:
},
});
});
it.each(["", "\n"])(
"configures an empty config.yaml %j as a new document",
async (original) => {
const { home, client } = await hermesClient();
await writeFile(client.configPath, original);
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 },
},
});
expect(
(
await readClientRegistrationStatuses(home, undefined, {
platform: process.platform,
environment: {},
})
).find(({ client: name }) => name === "hermes"),
).toMatchObject({ state: "aligned", command });
},
);
});
@@ -11,7 +11,78 @@ import { ArtifactReaderFailure } from "../../../../src/artifacts/ArtifactReader.
import { scanCanonicalArtifactInventory } from "../../../fixtures/artifactInventory.js";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
import { analyzeJavaScriptApplication } from "../../../support/javascriptApplicationScope.js";
import { AnalysisCancelledError } from "../../../../src/domain/analysisErrorCore.js";
import {
analyzeJavaScriptApplication,
readJavaScriptArtifactFiles,
} from "../../../support/javascriptApplicationScope.js";
import { createJavaScriptArtifactReader } from "../../../../src/artifacts/javascript/JavaScriptArtifactReader.js";
import { createJavaScriptSourceAnalysis } from "../../../../src/artifacts/javascript/JavaScriptSourceAnalysis.js";
import { analyzeAndAdoptJavaScriptArtifactFiles } from "../../../../src/application/javascript/JavaScriptArtifactAnalysis.js";
import { createJavaScriptSemanticGraphProjection } from "../../../../src/application/javascript/JavaScriptSemanticGraphBuilder.js";
describe("JavaScript source selection cancellation boundary", () => {
it("keeps unselected files outside scope when the real worker cancels after the last selected file", async () => {
const root = await createTestTempDirectory(
"rea-js-selected-last-cancellation-",
);
await writeJavaScriptSourceSelectionFixture(root);
const snapshot = await scanCanonicalArtifactInventory(root, {});
const reader = createJavaScriptArtifactReader(root, "directory");
const controller = new AbortController();
const sourcePaths = ["main.mjs"];
try {
const files = await readJavaScriptArtifactFiles(
reader,
snapshot,
controller.signal,
sourcePaths,
);
const worker = createJavaScriptSourceAnalysis(
{ heapMb: 512, timeoutMs: 30_000 },
1,
);
let outcome: Awaited<
ReturnType<typeof analyzeAndAdoptJavaScriptArtifactFiles>
>;
try {
const realWorker = worker.analyze.bind(worker);
outcome = await analyzeAndAdoptJavaScriptArtifactFiles(
files,
{
analyze: async (...args) => {
const result = await realWorker(...args);
controller.abort();
return result;
},
},
createJavaScriptSemanticGraphProjection(),
async () => {},
controller.signal,
);
} finally {
await worker.close();
}
expect(outcome.interruption).toBeInstanceOf(AnalysisCancelledError);
const unselected = outcome.analysis.files.filter(
({ file }) =>
!file.text.included && file.text.reason === "outside-analysis-scope",
);
expect(unselected).toHaveLength(5);
expect(
unselected.every(
({ analysis_failure }) => analysis_failure === undefined,
),
).toBe(true);
expect(
outcome.analysis.files.find(({ file }) => file.path === "main.mjs")
?.javascript,
).toMatchObject({ parse_status: "complete" });
} finally {
await reader.close();
}
});
});
describe("Selected JavaScript source failure diagnostics", () => {
it("analyzes selected files in first-request order and reports only selected progress", async () => {
@@ -1,6 +1,7 @@
import { Readable } from "node:stream";
import { createHash } from "node:crypto";
import { symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Readable } from "node:stream";
import { expect, it } from "vitest";
@@ -135,6 +136,7 @@ it.each([
["a non-array sourcesContent value", { sourcesContent: "source" }],
["a non-string, non-null source entry", { sourcesContent: [42] }],
["a source-content array with the wrong length", { sourcesContent: [] }],
["a non-string source name", { sources: [42] }],
])(
"reports %s as an invalid local source map",
async (_description, content) => {
@@ -187,7 +189,7 @@ it("accepts omitted and explicitly null source-map source contents", async () =>
JSON.stringify({
version: 3,
sources: ["null.ts"],
sourcesContent: [null],
sourcesContent: null,
names: [],
mappings: "",
}),
@@ -209,6 +211,77 @@ it("accepts omitted and explicitly null source-map source contents", async () =>
expect(result.graph.coverage.status).toBe("complete");
});
it("retains unnamed source declarations without shifting later source evidence", async () => {
const root = await createTestTempDirectory("rea-javascript-unnamed-source-");
const text = JSON.stringify({
version: 3,
sections: [
{
offset: { line: 0, column: 0 },
map: {
version: 3,
sources: ["prior.ts"],
sourcesContent: ["export const prior = 1;"],
names: [],
mappings: "",
},
},
{
offset: { line: 1, column: 0 },
map: {
version: 3,
sources: [null, "original.ts"],
sourcesContent: [null, "export const answer: number = 42;"],
names: [],
mappings: "ACAA",
},
},
],
});
await writeFile(join(root, "bundle.js.map"), text);
const result = await reconstructJavaScriptArtifact({ input_path: root });
const nodes = result.graph.nodes;
const original = nodes.find(
({ kind, identity }) =>
kind === "source-module" &&
identity.strategy === "source-map-original" &&
identity.original_source === "original.ts",
);
const unnamed = nodes.find(
({ kind, observations }) =>
kind === "unknown" &&
observations.some(
({ properties }) => properties.source_name_available === false,
),
);
expect(original?.identity).toMatchObject({
strategy: "source-map-original",
source_sha256: createHash("sha256")
.update("export const answer: number = 42;")
.digest("hex"),
});
expect(original?.observations[0]?.properties).toMatchObject({
source_index: 1,
declaration_index: 2,
content_available: true,
});
expect(unnamed?.observations[0]?.properties).toMatchObject({
source_index: 0,
declaration_index: 1,
source_name_available: false,
content_available: false,
content_sha256: null,
});
expect(unnamed?.identity).toMatchObject({
strategy: "artifact-local-key",
namespace: "source-map-unnamed-declaration",
key: "1",
});
expect(result.graph.coverage.status).toBe("complete");
});
it("retains every repeated content observation and containment path", async () => {
const root = await createTestTempDirectory("rea-javascript-observations-");
await Promise.all(
@@ -0,0 +1,273 @@
import { readdirSync, renameSync, writeFileSync } from "node:fs";
import { mkdir, open, rm } from "node:fs/promises";
import * as fs from "node:fs/promises";
import { join } from "node:path";
import { expect, it, vi } from "vitest";
import { ArtifactResourceScope } from "../../../src/artifacts/ArtifactResourceScope.js";
import { AnalysisCancelledError } from "../../../src/domain/analysisErrorCore.js";
import { EvidenceFileError } from "../../../src/domain/evidenceErrors.js";
import { OwnedFileHandle } from "../../../src/filesystem/OwnedFileHandle.js";
import { OwnedStagedOutput } from "../../../src/filesystem/OwnedStagedOutput.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { writeTextParts } from "../../../src/application/JsonFiles.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
it("reports committed output when post-publication staging cleanup remains owned", async () => {
const root = await createTestTempDirectory("rea-json-write-");
const resources = new ArtifactResourceScope();
try {
const result = await writeTextParts(
stagingPollutingParts(root),
join(root, "bundle.json"),
false,
resources,
);
if (result.ok) throw new Error("Expected staged cleanup failure");
const cleanupResource = result.error.cleanup?.resources[0];
if (cleanupResource === undefined)
throw new Error("Expected retained staging resource");
expect(result.error).toBeInstanceOf(EvidenceFileError);
expect(result.error.published).toMatchObject({
path: join(root, "bundle.json"),
bytes: 16,
});
expect(cleanupResource).toContain(".rea-write-");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "cleanup_incomplete",
details: { published: true, published_path: join(root, "bundle.json") },
});
expect(await fs.readFile(join(root, "bundle.json"), "utf8")).toBe(
"canonical output",
);
await fs.rm(join(cleanupResource, "unexpected"));
} finally {
await resources.close();
await rm(root, { recursive: true, force: true });
}
});
it("preserves cancellation when staging cleanup also fails", async () => {
const root = await createTestTempDirectory("rea-json-cancel-");
const resources = new ArtifactResourceScope();
const controller = new AbortController();
try {
function* cancelledParts(): Generator<string> {
const directories = requireStages(root);
if (directories.length !== 1)
throw new Error("Expected one staging directory");
writeFileSync(join(root, directories[0]!, "unexpected"), "retain this");
controller.abort();
yield "must not publish";
}
const result = await writeTextParts(
cancelledParts(),
join(root, "cancelled.json"),
false,
resources,
{ signal: controller.signal, operation: "export_evidence_bundle" },
);
if (result.ok) throw new Error("Expected cancellation");
expect(result.error).toBeInstanceOf(AnalysisCancelledError);
expect(result.error.cleanupIncomplete).toBe(true);
expect(result.error.cause).toMatchObject({
cause: expect.any(AnalysisCancelledError),
owner: { directory: expect.stringContaining(".rea-write-") },
});
await expect(fs.access(join(root, "cancelled.json"))).rejects.toThrow();
const stage = requireStages(root)[0];
if (stage !== undefined) await fs.rm(join(root, stage, "unexpected"));
} finally {
await resources.close();
await rm(root, { recursive: true, force: true });
}
});
it("refuses to publish a staged path replaced after its descriptor opened", async () => {
const root = await createTestTempDirectory("rea-staged-swap-");
const resources = new ArtifactResourceScope();
const destination = join(root, "swapped.json");
try {
const result = await writeTextParts(
replacingStagedParts(root),
destination,
false,
resources,
);
if (result.ok) throw new Error("Expected staged identity rejection");
expect(
await fs.readFile(join(root, requireStages(root)[0]!, "content"), "utf8"),
).toBe("foreign bytes");
await expect(fs.access(destination)).rejects.toThrow();
const stage = requireStages(root)[0];
if (stage !== undefined) {
const directory = join(root, stage);
await fs.rm(join(directory, "content"));
await fs.rename(join(directory, "original"), join(directory, "content"));
}
} finally {
await resources.close();
await rm(root, { recursive: true, force: true });
}
});
it("does not invent a staged owner when the supplied scope is closed", async () => {
const root = await createTestTempDirectory("rea-closed-output-scope-");
const resources = new ArtifactResourceScope();
await resources.close();
const destination = join(root, "closed.json");
const result = await writeTextParts(
["unused"],
destination,
false,
resources,
);
if (result.ok) throw new Error("Expected closed-scope admission failure");
expect(result.error).toBeInstanceOf(EvidenceFileError);
expect(result.error.cleanupIncomplete).toBe(false);
expect(result.error.cleanupResources).toEqual([]);
expect(await fs.readdir(root)).toEqual([]);
});
function stagingPollutingParts(root: string): Iterable<string> {
return {
*[Symbol.iterator](): Generator<string> {
const directories = readdirSync(root);
const stage = directories.find((entry) =>
entry.startsWith(".rea-write-"),
);
if (stage === undefined) throw new Error("Expected staging directory");
writeFileSync(join(root, stage, "unexpected"), "retain this");
yield "canonical output";
},
};
}
function replacingStagedParts(root: string): Iterable<string> {
return {
*[Symbol.iterator](): Generator<string> {
const stage = requireStages(root)[0];
if (stage === undefined) throw new Error("Expected staging directory");
const content = join(root, stage, "content");
renameSync(content, join(root, stage, "original"));
writeFileSync(content, "foreign bytes");
yield "owned bytes";
},
};
}
const requireStages = (root: string): string[] =>
readdirSync(root).filter((entry) => entry.startsWith(".rea-write-"));
it("retains a failed file close owner and retries before removing its stage", async () => {
const root = await createTestTempDirectory("rea-staged-close-");
const directory = join(root, ".rea-write-owned");
await mkdir(directory);
const path = join(directory, "content");
const handle = await open(path, "wx", 0o600);
const owner = await OwnedStagedOutput.create(directory);
let closeAttempts = 0;
const actualClose = handle.close.bind(handle);
vi.spyOn(handle, "close").mockImplementation(async () => {
closeAttempts += 1;
if (closeAttempts === 1) throw new Error("injected close failure");
await actualClose();
});
await owner.setFile(new OwnedFileHandle(handle));
const resources = new ArtifactResourceScope();
const stagedOwner = {
kind: "staged-output" as const,
resource: directory,
output: owner,
};
try {
expect(await resources.release(stagedOwner)).toMatchObject({
kind: "failed",
});
await resources.close();
expect(closeAttempts).toBe(2);
await expect(fs.access(directory)).rejects.toThrow();
} finally {
await resources.close();
await rm(root, { recursive: true, force: true });
}
});
it("refuses to remove unexpected files from an owned staging directory", async () => {
const root = await createTestTempDirectory("rea-staged-replaced-");
const directory = join(root, ".rea-write-owned");
await mkdir(directory);
const owner = await OwnedStagedOutput.create(directory);
const unexpected = join(directory, "unexpected");
writeFileSync(unexpected, "unowned");
try {
await expect(owner.close()).rejects.toThrow(/Unexpected staging entries/u);
expect(await fs.readFile(unexpected, "utf8")).toBe("unowned");
} finally {
await fs.rm(unexpected, { force: true });
await owner.close();
await rm(root, { recursive: true, force: true });
}
});
it("retains cleanup when its staging directory was renamed", async () => {
const root = await createTestTempDirectory("rea-staged-renamed-dir-");
const directory = join(root, ".rea-write-owned");
const moved = join(root, ".rea-write-moved");
await mkdir(directory);
const path = join(directory, "content");
const handle = await open(path, "wx", 0o600);
const owner = await OwnedStagedOutput.create(directory);
await owner.setFile(new OwnedFileHandle(handle));
const resources = new ArtifactResourceScope();
const stagedOwner = {
kind: "staged-output" as const,
resource: directory,
output: owner,
};
try {
writeFileSync(join(directory, "unexpected"), "retain this");
expect(await resources.release(stagedOwner)).toMatchObject({
kind: "failed",
});
await fs.rename(directory, moved);
await expect(resources.close()).rejects.toThrow();
await fs.rename(moved, directory);
await rm(join(directory, "unexpected"));
await expect(resources.close()).resolves.toBeUndefined();
} finally {
await resources.close();
await rm(root, { recursive: true, force: true });
}
});
it("retains cleanup when owned staged content was renamed", async () => {
const root = await createTestTempDirectory("rea-staged-renamed-file-");
const directory = join(root, ".rea-write-owned");
const content = join(directory, "content");
const moved = join(directory, "moved-content");
await mkdir(directory);
const handle = await open(content, "wx", 0o600);
const owner = await OwnedStagedOutput.create(directory);
await owner.setFile(new OwnedFileHandle(handle));
const resources = new ArtifactResourceScope();
const stagedOwner = {
kind: "staged-output" as const,
resource: directory,
output: owner,
};
try {
await fs.rename(content, moved);
expect(await resources.release(stagedOwner)).toMatchObject({
kind: "failed",
});
await expect(resources.close()).rejects.toThrow(
/cleanup remains incomplete/u,
);
await fs.rename(moved, content);
await expect(resources.close()).resolves.toBeUndefined();
} finally {
await resources.close();
await rm(root, { recursive: true, force: true });
}
});
+27 -15
View File
@@ -7,7 +7,7 @@ import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver
import { AnalysisCancelledError } from "../../../src/domain/analysisErrorCore.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import type { MipsElfMetadata } from "../../../src/domain/binaryTargetTypes.js";
import { readMipsElfAbiFlags } from "../../../src/application/MipsElfAbiFlags.js";
import { readMipsElfMetadata } from "../../../src/application/MipsElfMetadata.js";
import { ok } from "../../../src/domain/result.js";
import {
ghidraMipsProfileParameters,
@@ -85,7 +85,7 @@ const inspect = async (
const path = await writeFixture(bytes);
const handle = await open(path, "r");
try {
const result = await readMipsElfAbiFlags(
const result = await readMipsElfMetadata(
handle,
metadata(little),
checkCancelled,
@@ -131,6 +131,8 @@ for (const little of [true, false]) {
const fp64 = await inspect(bytes, little);
assert.ok(fp64.ok);
const changed = target({ ...metadata(little), abiFlags: fp64.value });
assert.equal(fp64.value?.cpr1Size, 2);
assert.equal(fp64.value?.fpAbi, 6);
assert.match(ghidraMipsUnsupportedReason(changed) ?? "", /FP64/u);
assert.notDeepEqual(ghidraMipsProfileParameters(changed), before);
});
@@ -271,6 +273,13 @@ const unsupported: [string, (bytes: Buffer) => void, RegExp][] = [
},
/MIPS32r2/u,
],
[
"soft-float with declared CPR1",
(b) => {
b[abiOffset + 7] = 3;
},
/soft-float without CPR1/u,
],
[
"unspecified FP ABI",
(b) => {
@@ -301,19 +310,22 @@ for (const [name, change, reason] of unsupported) {
);
});
}
it("resolves soft-float ABI metadata and commits its integer-register storage policy", async () => {
const bytes = fixture();
bytes[abiOffset + 5] = 0;
bytes[abiOffset + 7] = 3;
const resolved = await resolveFixture(bytes);
assert.equal(resolved.mips.abiFlags?.cpr1Size, 0);
assert.equal(resolved.mips.abiFlags?.fpAbi, 3);
assert.equal(ghidraMipsUnsupportedReason(resolved), null);
assert.equal(
ghidraMipsProfileParameters(resolved).mips_soft_float_storage,
"o32-soft-float-prototype-v1",
);
});
it.each([true, false])(
"resolves soft-float ABI metadata and commits its integer-register storage policy (little endian: %s)",
async (little) => {
const bytes = fixture(little);
bytes[abiOffset + 5] = 0;
bytes[abiOffset + 7] = 3;
const resolved = await resolveFixture(bytes);
assert.equal(resolved.mips.abiFlags?.cpr1Size, 0);
assert.equal(resolved.mips.abiFlags?.fpAbi, 3);
assert.equal(ghidraMipsUnsupportedReason(resolved), null);
assert.equal(
ghidraMipsProfileParameters(resolved).mips_soft_float_storage,
"o32-soft-float-prototype-v1",
);
},
);
it("preserves the caller's cancellation error during table inspection", async () => {
const cancelled = new Error("caller cancellation sentinel");
let checks = 0;
@@ -0,0 +1,260 @@
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { open, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { it } from "vitest";
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
import { readMipsElfMetadata } from "../../../src/application/MipsElfMetadata.js";
import { AnalysisCancelledError } from "../../../src/domain/analysisErrorCore.js";
import {
ghidraMipsProfileParameters,
ghidraMipsUnsupportedReason,
} from "../../../src/ghidra/GhidraMipsProfile.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const relOffset = 4096;
const fixture = (little: boolean, count = 2): Buffer => {
const bytes = Buffer.alloc(relOffset + count * 8 + 16);
bytes.set([0x7f, 0x45, 0x4c, 0x46, 1, little ? 1 : 2, 1]);
const u16 = (value: number, offset: number) =>
little
? bytes.writeUInt16LE(value, offset)
: bytes.writeUInt16BE(value, offset);
const u32 = (value: number, offset: number) =>
little
? bytes.writeUInt32LE(value, offset)
: bytes.writeUInt32BE(value, offset);
u16(3, 16);
u16(8, 18);
u32(1, 20);
u32(52, 28);
u32(0x74001005, 36);
u16(52, 40);
u16(32, 42);
u16(2, 44);
u32(1, 52);
u32(bytes.length, 68);
u32(bytes.length, 72);
u32(2, 84);
u32(256, 88);
u32(256, 92);
u32(32, 100);
u32(32, 104);
u32(17, 256);
u32(relOffset, 260);
u32(18, 264);
u32(count * 8, 268);
u32(19, 272);
u32(8, 276);
for (let i = 1; i < count; i += 1) {
u32(512, relOffset + 8 * i);
u32(3, relOffset + 8 * i + 4);
}
return bytes;
};
const resolve = async (bytes: Buffer) => {
const directory = await createTestTempDirectory("rea-mips-shared-test-");
const path = join(directory, "shared.elf");
await writeFile(path, bytes);
const result = await parseBinaryTarget(path);
assert.ok(result.ok);
assert.equal(result.value.kind, "executable");
assert.equal(result.value.architecture, "mips");
if (
result.value.kind !== "executable" ||
result.value.architecture !== "mips"
)
throw new Error("expected MIPS ELF");
assert.equal(
result.value.sha256,
createHash("sha256").update(bytes).digest("hex"),
);
assert.deepEqual(await readFile(path), bytes);
return result.value;
};
for (const little of [true, false]) {
it(`retains complete dynamic declarations beyond the initial probe (${little ? "LE" : "BE"})`, async () => {
const target = await resolve(fixture(little));
assert.equal(target.mips.abiFlags, null);
assert.deepEqual(target.mips.sharedLoad, {
status: "complete",
relocationCount: 2,
relocationTypes: [0, 3],
symbolRelativeCount: 0,
});
assert.equal(ghidraMipsUnsupportedReason(target), null);
assert.deepEqual(ghidraMipsProfileParameters(target).mips_elf, {
elf_class: 32,
byte_order: little ? "little" : "big",
type: 3,
flags: 0x74001005,
abi_flags: null,
shared_load: {
status: "complete",
relocation_count: 2,
relocation_types: [0, 3],
symbol_relative_count: 0,
},
});
});
it(`retains and refuses symbol-bearing REL32 without repairing the mode tag (${little ? "LE" : "BE"})`, async () => {
const bytes = fixture(little);
if (little) bytes.writeUInt32LE(0x103, relOffset + 12);
else bytes.writeUInt32BE(0x103, relOffset + 12);
const target = await resolve(bytes);
assert.equal(target.mips.sharedLoad?.status, "complete");
assert.match(
ghidraMipsUnsupportedReason(target) ?? "",
/Symbol-bearing R_MIPS_REL32/u,
);
});
}
it("examines relocation records beyond a read chunk before deciding completeness", async () => {
const count = 8194;
const bytes = fixture(true, count);
bytes.writeUInt32LE(0x103, relOffset + (count - 1) * 8 + 4);
const target = await resolve(bytes);
assert.deepEqual(target.mips.sharedLoad, {
status: "complete",
relocationCount: count,
relocationTypes: [0, 3],
symbolRelativeCount: 1,
});
assert.match(ghidraMipsUnsupportedReason(target) ?? "", /mode tag/u);
});
it("does not treat uncaptured ABI declaration headers as an inspected absence", async () => {
const bytes = fixture(true);
bytes.writeUInt32LE(bytes.length + 1, 32);
bytes.writeUInt16LE(40, 46);
bytes.writeUInt16LE(1, 48);
const target = await resolve(bytes);
assert.equal(target.mips.abiFlags, null);
assert.equal(target.mips.sharedLoad?.status, "unavailable");
assert.match(
ghidraMipsUnsupportedReason(target) ?? "",
/unavailable headers remain unknown/u,
);
});
const malformed: [string, (bytes: Buffer) => void, RegExp][] = [
[
"overlapping load ranges",
(b) => {
b.writeUInt16LE(3, 44);
b.writeUInt32LE(1, 116);
b.writeUInt32LE(256, 124);
b.writeUInt32LE(16, 132);
b.writeUInt32LE(16, 136);
},
/overlapping MIPS PT_LOAD/u,
],
[
"inconsistent dynamic address",
(b) => b.writeUInt32LE(0x10000, 92),
/matching file-backed PT_LOAD/u,
],
["missing dynamic table", (b) => b.writeUInt32LE(0, 84), /no PT_DYNAMIC/u],
["repeated dynamic tables", (b) => b.writeUInt32LE(2, 52), /duplicate/u],
[
"declared dynamic tail outside file",
(b) => b.writeUInt32LE(b.length, 100),
/beyond the file/u,
],
[
"unavailable load bytes",
(b) => b.writeUInt32LE(b.length + 1, 68),
/PT_LOAD range/u,
],
["missing terminator", (b) => b.writeUInt32LE(1, 280), /DT_NULL/u],
[
"repeated scalar tags",
(b) => b.writeUInt32LE(17, 272),
/duplicate MIPS dynamic tag/u,
],
["invalid REL entry size", (b) => b.writeUInt32LE(16, 276), /DT_RELENT/u],
["truncated REL record", (b) => b.writeUInt32LE(17, 268), /DT_RELENT/u],
[
"unmapped REL table",
(b) => b.writeUInt32LE(0x10000, 260),
/PT_LOAD mapping/u,
],
[
"unmapped REL destination",
(b) => b.writeUInt32LE(0x10000, relOffset + 8),
/PT_LOAD memory range/u,
],
[
"RELA declaration",
(b) => {
b.writeUInt32LE(7, 272);
b.writeUInt32LE(4096, 276);
},
/RELA or PLT/u,
],
];
it.each(malformed)(
"preserves useful partial header facts for %s",
async (_name, mutate, reason) => {
const bytes = fixture(true);
mutate(bytes);
const target = await resolve(bytes);
assert.equal(target.mips.flags, 0x74001005);
assert.equal(target.mips.abiFlags, null);
assert.equal(target.mips.sharedLoad?.status, "unavailable");
assert.match(ghidraMipsUnsupportedReason(target) ?? "", reason);
},
);
it("retains unverified relocation type instead of claiming every examined record is supported", async () => {
const bytes = fixture(true);
bytes.writeUInt32LE(5, relOffset + 12);
const target = await resolve(bytes);
assert.deepEqual(target.mips.sharedLoad, {
status: "complete",
relocationCount: 2,
relocationTypes: [0, 5],
symbolRelativeCount: 0,
});
assert.match(
ghidraMipsUnsupportedReason(target) ?? "",
/other dynamic relocation types/u,
);
});
it("does not equate complete dynamic REL coverage with coverage of another section relocation table", async () => {
const bytes = fixture(true);
bytes.writeUInt32LE(1024, 32);
bytes.writeUInt16LE(40, 46);
bytes.writeUInt16LE(1, 48);
bytes.writeUInt32LE(9, 1028);
bytes.writeUInt32LE(2048, 1040);
bytes.writeUInt32LE(8, 1044);
bytes.writeUInt32LE(8, 1060);
const target = await resolve(bytes);
assert.equal(target.mips.sharedLoad?.status, "unavailable");
assert.match(
ghidraMipsUnsupportedReason(target) ?? "",
/section relocation declarations/u,
);
});
it("preserves the caller cancellation error during a bounded relocation scan", async () => {
const target = await resolve(fixture(true, 8194));
const handle = await open(target.path, "r");
const cancellation = new AnalysisCancelledError("open_binary");
let checks = 0;
try {
await assert.rejects(
readMipsElfMetadata(handle, target.mips, () => {
checks += 1;
if (checks === 100) throw cancellation;
}),
(error) => error === cancellation,
);
} finally {
await handle.close();
}
});
@@ -150,7 +150,10 @@ describe("Qwen Code profile setup", () => {
expect(await setup.configureClient(client, {}, command)).toEqual({
status: "configured",
});
expect(await setup.installSkill([client.name])).toBe("installed");
expect(await setup.installSkill([client.name])).toEqual({
ok: true,
value: "installed",
});
const skill = join(home, ".agents", "skills", PRODUCT_IDENTITY.skillName);
await writeFile(join(skill, "user-notes.txt"), "user-authored");
expect(await readFile(join(skill, "SKILL.md"), "utf8")).toContain(
@@ -158,7 +161,10 @@ describe("Qwen Code profile setup", () => {
);
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 setup.installSkill([client.name])).toEqual({
ok: true,
value: "unchanged",
});
expect(
(
await readClientRegistrationStatuses(
@@ -0,0 +1,237 @@
import {
mkdir,
open as fsOpen,
writeFile,
type FileHandle,
} from "node:fs/promises";
import { dirname, join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ArtifactResourceScope } from "../../../src/artifacts/ArtifactResourceScope.js";
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
import { createDoctorHostFixture } from "../../../src/application/Doctor.fixture.js";
import {
runDoctorOwned,
type DoctorHost,
} from "../../../src/application/Doctor.js";
import {
readSkillFile,
skillDestinations,
} from "../../../src/application/SetupSkill.js";
import { systemSetupHost } from "../../../src/application/SetupHost.js";
import {
runUninstall,
systemUninstallHost,
} from "../../../src/application/Uninstall.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
vi.mock("node:fs/promises", async (importOriginal) => {
const actual = await importOriginal<typeof import("node:fs/promises")>();
return { ...actual, open: vi.fn(actual.open) };
});
const openMock = vi.mocked(fsOpen);
let actualFs: typeof import("node:fs/promises");
beforeEach(async () => {
actualFs =
await vi.importActual<typeof import("node:fs/promises")>(
"node:fs/promises",
);
openMock.mockImplementation((...args) => actualFs.open(...args));
});
afterEach(() => openMock.mockReset());
const failFirstCloses = (path: string) => {
const attempts: FileHandle[] = [];
let allowClose = false;
openMock.mockImplementation(async (...args) => {
const handle = await actualFs.open(...args);
if (String(args[0]) !== path) return handle;
const nativeClose = handle.close.bind(handle);
vi.spyOn(handle, "close").mockImplementation(async () => {
attempts.push(handle);
if (!allowClose) throw new Error("test holds the skill handle open");
await nativeClose();
});
return handle;
});
return {
attempts,
release: () => {
allowClose = true;
},
};
};
describe("skill regular-file cleanup ownership", () => {
it("keeps setup skill reads owned until setup host disposal", async () => {
const home = await createTestTempDirectory("rea-setup-skill-close-");
const [destination] = skillDestinations(home, []);
if (destination === undefined) throw new Error("Shared skill root missing");
const manifest = join(destination.path, "SKILL.md");
await mkdir(dirname(manifest), { recursive: true });
await writeFile(manifest, "stale managed skill\n");
const close = failFirstCloses(manifest);
const host = systemSetupHost(
{ platform: "linux", homeDirectory: home } as DoctorHost,
{ HOME: home },
);
try {
expect(await host.skillNeedsInstall([])).toBe(true);
expect(close.attempts.length).toBeGreaterThan(0);
expect(new Set(close.attempts).size).toBe(1);
const attemptsBeforeClose = close.attempts.length;
close.release();
expect(await host.close?.()).toBeUndefined();
expect(close.attempts.length).toBeGreaterThan(attemptsBeforeClose);
expect(new Set(close.attempts).size).toBe(1);
expect(close.attempts[0]?.fd).toBe(-1);
} finally {
close.release();
await host.close?.();
}
});
it("waits for an admitted skill read before its resource scope closes", async () => {
const home = await createTestTempDirectory("rea-setup-skill-inflight-");
const [destination] = skillDestinations(home, []);
if (destination === undefined) throw new Error("Shared skill root missing");
const manifest = join(destination.path, "SKILL.md");
await mkdir(dirname(manifest), { recursive: true });
await writeFile(manifest, "stale managed skill\n");
const resources = new ArtifactResourceScope();
let beginRead!: () => void;
const readStarted = new Promise<void>((resolve) => {
beginRead = resolve;
});
let unblockRead!: () => void;
const readGate = new Promise<void>((resolve) => {
unblockRead = resolve;
});
let heldRead = false;
openMock.mockImplementation(async (...args) => {
const handle = await actualFs.open(...args);
if (String(args[0]) !== manifest || heldRead) return handle;
heldRead = true;
const nativeRead = handle.read.bind(handle);
vi.spyOn(handle, "read").mockImplementation(async (...readArgs) => {
beginRead();
await readGate;
return nativeRead(...readArgs);
});
return handle;
});
try {
const reading = readSkillFile(manifest, resources);
await readStarted;
let closed = false;
const closing = resources.close().then(() => {
closed = true;
});
await Promise.resolve();
expect(closed).toBe(false);
unblockRead();
expect(await reading).toBe("stale managed skill\n");
await closing;
expect(closed).toBe(true);
} finally {
unblockRead();
await resources.close();
}
});
});
describe("skill cleanup diagnostics", () => {
it("preserves a doctor report and cleanup diagnostic when host close still fails", async () => {
const home = await createTestTempDirectory("rea-doctor-skill-close-");
const [destination] = skillDestinations(home, []);
if (destination === undefined) throw new Error("Shared skill root missing");
const manifest = join(destination.path, "SKILL.md");
await mkdir(dirname(manifest), { recursive: true });
await writeFile(manifest, "managed skill fixture\n");
const close = failFirstCloses(manifest);
const resources = new ArtifactResourceScope();
const host = createDoctorHostFixture({
installedSkillIdentity: async () => {
await readSkillFile(manifest, resources);
return { version: null, toolCount: null, canonical: true };
},
close: async () => {
try {
await resources.close();
return undefined;
} catch (cause: unknown) {
return cause instanceof Error ? cause.message : String(cause);
}
},
});
try {
const report = await runDoctorOwned(undefined, host, { skill: true });
expect(report.healthy).toBe(false);
expect(report.identity?.skill.installed_version).toBeNull();
expect(report.checks).toContainEqual(
expect.objectContaining({
name: "doctor-resource-cleanup",
ok: false,
detail: expect.stringContaining(manifest),
}),
);
expect(close.attempts.length).toBeGreaterThan(0);
expect(new Set(close.attempts).size).toBe(1);
const attemptsBeforeClose = close.attempts.length;
close.release();
expect(await host.close?.()).toBeUndefined();
expect(close.attempts.length).toBeGreaterThan(attemptsBeforeClose);
expect(new Set(close.attempts).size).toBe(1);
expect(close.attempts[0]?.fd).toBe(-1);
} finally {
close.release();
await host.close?.();
}
});
it("returns uninstall changes with a failed cleanup item for a retained handle", async () => {
const home = await createTestTempDirectory("rea-uninstall-skill-close-");
const [destination] = skillDestinations(home, []);
if (destination === undefined) throw new Error("Shared skill root missing");
const manifest = join(destination.path, "SKILL.md");
await mkdir(dirname(manifest), { recursive: true });
await writeFile(
manifest,
`---\nname: ${PRODUCT_IDENTITY.skillName}\n---\nmanaged fixture\n`,
);
const close = failFirstCloses(manifest);
const host = systemUninstallHost(home, undefined, { HOME: home });
try {
const result = await runUninstall(false, host);
expect(result.status).toBe("failed");
expect(result.items).toContainEqual(
expect.objectContaining({
name: "uninstall_cleanup",
status: "failed",
detail: expect.stringContaining(manifest),
}),
);
expect(close.attempts.length).toBeGreaterThan(0);
expect(new Set(close.attempts).size).toBe(1);
const attemptsBeforeClose = close.attempts.length;
close.release();
expect(await host.close?.()).toBeUndefined();
expect(close.attempts.length).toBeGreaterThan(attemptsBeforeClose);
expect(new Set(close.attempts).size).toBe(1);
expect(close.attempts[0]?.fd).toBe(-1);
} finally {
close.release();
await host.close?.();
}
});
});
@@ -6,7 +6,130 @@ import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("executable format refusal diagnostics", () => {
it.each(["NE", "LE", "LX"] as const)(
"reports unsupported %s executables without path advice",
async (signature) => {
const directory = await createTestTempDirectory(
`rea-target-${signature.toLowerCase()}-`,
);
const path = join(directory, "unsupported.exe");
const bytes = Buffer.alloc(0x80 + 24);
bytes.write("MZ", 0, "ascii");
bytes.writeUInt32LE(0x80, 0x3c);
bytes.write(signature, 0x80, "ascii");
await writeFile(path, bytes);
const result = await parseBinaryTarget(path);
if (result.ok)
throw new Error(`unsupported ${signature} target was admitted`);
const reason = `unsupported ${signature} executable in MZ image`;
const projected = projectAnalysisError(result.error);
expect(projected).toMatchObject({
code: "target_unavailable",
category: "unsupported_target",
retryable: false,
message: `Cannot open artifact: ${reason}.`,
details: {
reason,
constraint: "file_format_rejected",
},
remediation: {
action:
"Review the reported file-format reason and select a supported, well-formed target.",
},
});
expect(projected.message).not.toContain("Check that the path");
expect(await systemDoctorHost().inspectTarget?.(path)).toMatchObject({
classification: "unsupported_target",
details: { constraint: "file_format_rejected" },
remediation:
"Review the reported file-format reason and select a supported, well-formed target.",
});
},
);
});
describe("target route diagnostics", () => {
it.each(["module.wasm", "module.bin", "misleading.js"])(
"identifies a WASM v1 header in %s without suggesting native provider installation",
async (name) => {
const directory = await createTestTempDirectory("rea-wasm-target-");
const path = join(directory, name);
const bytes = Buffer.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]);
await writeFile(path, bytes);
const result = await parseBinaryTarget(path);
if (result.ok) throw new Error("WASM was admitted to native opening");
const projected = projectAnalysisError(result.error);
expect(projected).toMatchObject({
code: "target_unavailable",
category: "unsupported_target",
retryable: false,
details: {
path: await realpath(path),
constraint: "wasm_requires_static_inspection",
},
});
expect(projected.message).toContain("WebAssembly");
expect(projected.remediation.action).toContain("inspect_wasm_artifact");
expect(projected.remediation.action).toContain("REA_WABT_BIN_DIRECTORY");
expect(projected.remediation.action).toContain("WABT 1.0.42");
expect(projected.remediation.action).toContain("does not execute");
expect(await systemDoctorHost().inspectTarget?.(path)).toMatchObject({
ok: false,
classification: "unsupported_target",
details: { constraint: "wasm_requires_static_inspection" },
remediation: projected.remediation.action,
});
},
);
it.each([
[0, 0x61, 0x73, 0x6d],
[0, 0x61, 0x73, 0x6d, 2, 0, 0, 0],
[1, 2, 3, 4, 5, 6, 7, 8],
])(
"does not infer supported WASM encoding from a suffix or incomplete header",
async (...bytes) => {
const directory = await createTestTempDirectory("rea-wasm-unknown-");
const path = join(directory, "module.wasm");
await writeFile(path, Buffer.from(bytes));
const result = await parseBinaryTarget(path);
if (result.ok) throw new Error("unknown header was admitted");
const projected = projectAnalysisError(result.error);
expect(projected).toMatchObject({
category: "unsupported_target",
retryable: false,
details: { constraint: "file_format_rejected" },
});
expect(projected.remediation.action).not.toContain(
"inspect_wasm_artifact",
);
},
);
it("preserves an explicit raw-binary selection even when the bytes have a WASM header", async () => {
const directory = await createTestTempDirectory("rea-wasm-explicit-raw-");
const path = join(directory, "module.wasm");
await writeFile(path, Buffer.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]));
expect(
await parseBinaryTarget(path, {
formatHint: "raw-binary",
architecture: "x86",
entryPoint: "0x001000",
}),
).toMatchObject({
ok: true,
value: {
path: await realpath(path),
format: "raw-binary",
architecture: "x86",
entryPoint: "0x1000",
entryPointSource: "0x001000",
},
});
});
it("identifies the directory opening constraint and gives the direct analysis route", async () => {
const directory = await createTestTempDirectory("rea-js-target-");
await writeFile(join(directory, "index.js"), "export const answer = 42;\n");
@@ -32,10 +155,14 @@ describe("target route diagnostics", () => {
});
const missing = await parseBinaryTarget(join(directory, "missing"));
if (missing.ok) throw new Error("missing target was admitted");
expect(projectAnalysisError(missing.error)).toMatchObject({
const missingProjection = projectAnalysisError(missing.error);
expect(missingProjection).toMatchObject({
details: { reason: expect.stringContaining("does not exist") },
message: expect.stringContaining("does not exist"),
});
expect(missingProjection.message).toContain(
"Check that the path exists, is readable, and points to a supported file.",
);
expect(
await doctor.inspectTarget?.(join(directory, "missing")),
).toMatchObject({
@@ -54,10 +181,14 @@ describe("target route diagnostics", () => {
try {
const result = await parseBinaryTarget(path);
if (result.ok) throw new Error("unreadable target was admitted");
expect(projectAnalysisError(result.error)).toMatchObject({
const projected = projectAnalysisError(result.error);
expect(projected).toMatchObject({
details: { reason: expect.stringContaining("permission denied") },
message: expect.stringContaining("permission denied"),
});
expect(projected.message).toContain(
"Check that the path exists, is readable, and points to a supported file.",
);
expect(await systemDoctorHost().inspectTarget?.(path)).toMatchObject({
ok: false,
classification: "config_drift",
@@ -69,3 +200,123 @@ describe("target route diagnostics", () => {
},
);
});
describe("raw-binary load rejection diagnostics", () => {
const rawBinaryRejection = async (
options: Parameters<typeof parseBinaryTarget>[1],
bytes = Buffer.alloc(64),
) => {
const directory = await createTestTempDirectory("rea-raw-load-");
const path = join(directory, "image.bin");
await writeFile(path, bytes);
const result = await parseBinaryTarget(path, options);
if (result.ok) throw new Error("invalid raw-binary load was admitted");
return projectAnalysisError(result.error);
};
it("projects a misaligned arm entry as caller input without path advice", async () => {
const projected = await rawBinaryRejection({
formatHint: "raw-binary",
architecture: "arm",
entryPoint: "0x1",
});
expect(projected).toMatchObject({
code: "invalid_request",
category: "invalid_input",
// invalid_request is retryable: correcting the load argument succeeds.
retryable: true,
message:
"Cannot open artifact: raw-binary arm entry_point 0x1 must be 4-byte aligned.",
details: {
reason: "raw-binary arm entry_point 0x1 must be 4-byte aligned",
constraint: "load_selection_rejected",
},
remediation: {
action:
"Correct the reported load argument (--target-format, --architecture, or --entry-point on the CLI; format, architecture, or entry_point through MCP) and retry.",
},
});
expect(projected.message).not.toContain("Check that the path");
});
it("projects an x86 entry beyond the address width as caller input", async () => {
const projected = await rawBinaryRejection({
formatHint: "raw-binary",
architecture: "x86",
entryPoint: "0xffffffffff",
});
expect(projected).toMatchObject({
code: "invalid_request",
category: "invalid_input",
details: { constraint: "load_selection_rejected" },
});
expect(projected.message).toContain("x86 address width");
expect(projected.message).not.toContain("Check that the path");
});
it("projects architecture and entry without raw-binary format as caller input", async () => {
const projected = await rawBinaryRejection({
architecture: "arm",
entryPoint: "0x0",
});
expect(projected).toMatchObject({
code: "invalid_request",
category: "invalid_input",
message:
"Cannot open artifact: architecture and entry_point apply only with format=raw-binary.",
details: { constraint: "load_selection_rejected" },
});
expect(projected.message).not.toContain("Check that the path");
});
it("keeps an empty raw-binary file a target refusal", async () => {
const projected = await rawBinaryRejection(
{
formatHint: "raw-binary",
architecture: "arm",
entryPoint: "0x8000000",
},
Buffer.alloc(0),
);
expect(projected).toMatchObject({
code: "target_unavailable",
category: "unsupported_target",
details: {
reason: "raw-binary requires at least one file byte",
constraint: "file_format_rejected",
},
});
});
it("projects the raw-binary target-kind pairing as caller input", async () => {
const projected = await rawBinaryRejection({
formatHint: "raw-binary",
targetKind: "database",
architecture: "x86",
entryPoint: "0x1000",
});
expect(projected).toMatchObject({
code: "invalid_request",
category: "invalid_input",
details: {
reason: "raw-binary format requires an executable target kind",
constraint: "load_selection_rejected",
},
});
});
it("projects the DOS COM target-kind pairing as caller input too", async () => {
const projected = await rawBinaryRejection({
formatHint: "dos-com",
targetKind: "database",
});
expect(projected).toMatchObject({
code: "invalid_request",
category: "invalid_input",
details: {
reason: "DOS COM format requires an executable target kind",
constraint: "load_selection_rejected",
},
});
});
});
@@ -0,0 +1,100 @@
import { createHash } from "node:crypto";
import { join } from "node:path";
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { analyzeJavaScriptSemantics } from "../../../src/domain/javascript/javascriptSemanticAnalysis.js";
import { projectJavaScriptModuleSemantics } from "../../../src/domain/javascript/javascriptModuleSemanticIr.js";
import type { JavaScriptArtifactFile } from "../../../src/domain/javascript/javascriptArtifactFiles.js";
import { completeJavaScriptAnalysisSteps } from "../../../src/application/javascript/JavaScriptAnalysisControl.js";
import { projectJavaScriptSemanticFileSteps } from "../../../src/application/javascript/JavaScriptSemanticGraphBuilder.js";
import {
javaScriptTransferByteBudget,
measureJavaScriptModuleTransfer,
writeJavaScriptAnalysisTransfer,
readJavaScriptAnalysisTransfer,
} from "../../../src/javascript/analysis/JavaScriptAnalysisTransfer.js";
it("allows larger streamed transfers only with corresponding parent capacity", () => {
const mib = 1024 * 1024;
expect(javaScriptTransferByteBudget(0)).toBe(512 * mib);
expect(javaScriptTransferByteBudget(4096 * mib)).toBe(512 * mib);
expect(javaScriptTransferByteBudget(12288 * mib)).toBe(1536 * mib);
expect(javaScriptTransferByteBudget(32768 * mib)).toBe(2048 * mib);
});
it("enforces the offered complete-file byte budget while preserving authenticated round trips", async () => {
const root = await createTestTempDirectory("rea-js-transfer-budget-");
const text = "export function add(value) { return value + 1; }";
const file: JavaScriptArtifactFile = {
path: "app.mjs",
sha256: createHash("sha256").update(text).digest("hex"),
container_sha256: "a".repeat(64),
bytes: Buffer.byteLength(text),
inventory_artifact_id: "fixture-source",
kind: "javascript",
unpacked: false,
text: { included: true, value: text },
};
const ir = analyzeJavaScriptSemantics(text);
const module = projectJavaScriptModuleSemantics(ir);
const projection = await completeJavaScriptAnalysisSteps(
projectJavaScriptSemanticFileSteps(file, ir, 100),
);
const observed = await writeJavaScriptAnalysisTransfer(
join(root, "observed"),
module,
projection,
);
const measured = measureJavaScriptModuleTransfer(module);
expect(measured).toMatchObject({
bytes: observed.module_bytes,
records: observed.module_records,
});
expect(measureJavaScriptModuleTransfer(module, measured.bytes)).toEqual(
measured,
);
expect(() =>
measureJavaScriptModuleTransfer(module, measured.bytes - 1),
).toThrowError(
expect.objectContaining({
resource: "transport",
reportedLimits: expect.objectContaining({
transfer_file_bytes: measured.bytes - 1,
}),
}),
);
expect(() =>
measureJavaScriptModuleTransfer(module, 2 ** 31 + 1),
).toThrowError(RangeError);
const exactPath = join(root, "exact");
const exact = await writeJavaScriptAnalysisTransfer(
exactPath,
module,
projection,
observed.bytes,
);
expect(exact).toEqual(observed);
expect(await readJavaScriptAnalysisTransfer(exactPath, exact, file)).toEqual({
module,
projection,
});
await expect(
writeJavaScriptAnalysisTransfer(
join(root, "short"),
module,
projection,
observed.bytes - 1,
),
).rejects.toMatchObject({
resource: "transport",
reportedLimits: { transfer_file_bytes: observed.bytes - 1 },
});
await expect(
writeJavaScriptAnalysisTransfer(
join(root, "oversized"),
module,
projection,
2 ** 31 + 1,
),
).rejects.toBeInstanceOf(RangeError);
});
+209 -2
View File
@@ -1,3 +1,11 @@
import { API_SURFACE_EXAMPLE } from "../../../src/contracts/analysisViewApiSurfaceExample.js";
import { createHash } from "node:crypto";
import { readFile, writeFile } from "node:fs/promises";
import { WebNetworkCaptureService } from "../../../src/application/WebNetworkCaptureService.js";
import { decodeHarCapture } from "../../../src/browser/history/HarCapture.js";
import { join } from "node:path";
import { apiSurfaceHar } from "../../fixtures/historicalHar.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { STDIO_DEFAULT_MAX_BUFFER_SIZE } from "@modelcontextprotocol/server";
@@ -25,17 +33,26 @@ import {
analysisViewBindJavaScriptGraphs,
analysisViewLayoutEvidence,
analysisViewLayoutFixture,
analysisViewCaptureFixture,
analysisViewCaptureEvidence,
analysisViewObjectDenseCapture,
} from "../../fixtures/analysisView.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { BINARY_LAYOUT_TEST_PROVIDER } from "../../fixtures/binaryDiagnostics/layout.js";
const connect = async (binaryLayout?: BinaryLayoutService) => {
const connect = async (
binaryLayout?: BinaryLayoutService,
webNetworkCapture?: WebNetworkCaptureService,
) => {
const session = createTestBinarySession(() => {
throw new Error("selected views must not start a deep provider");
});
const server = createServer(
{ kind: "session", session },
binaryLayout === undefined ? {} : { binaryLayout },
{
...(binaryLayout === undefined ? {} : { binaryLayout }),
...(webNetworkCapture === undefined ? {} : { webNetworkCapture }),
},
);
const client = new Client({ name: "analysis-view-mcp", version: "1" });
onTestFinished(async () => {
@@ -176,6 +193,18 @@ it("advertises exact schemas and projects one layout section from retained Evide
const outputSchema: Record<string, unknown> = advertised.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
expect(
ajv.validate(inputSchema, {
source: { kind: "inline", evidence: analysisViewLayoutEvidence() },
view: { kind: "summary" },
}),
).toBe(true);
expect(
ajv.validate(inputSchema, {
source: { kind: "inline", evidence: {} },
view: { kind: "summary" },
}),
).toBe(false);
expect(
ajv.validate(inputSchema, {
source: {
@@ -254,6 +283,100 @@ it("reports a tampered inline Evidence ID at its full MCP source path", async ()
});
});
it("admits portable captures before SDK Evidence parsing and preserves capture caveats", async () => {
const { client } = await connect();
const dense = analysisViewCaptureEvidence(analysisViewObjectDenseCapture());
const refused = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: { kind: "inline", evidence: dense },
view: { kind: "api-surface" },
},
});
expect(parseMcpToolError(refused).error).toMatchObject({
code: "resource_constraint",
details: { resource: "memory" },
});
await client.ping();
const capture = analysisViewCaptureFixture();
capture.records = capture.records.slice(0, 1);
capture.total_records = 1;
const caveat = "Producer omitted exchanges before capture startup.";
capture.limitations = [caveat, caveat];
capture.records[0]!.reported = {
request: { method: "GET", url: "https://api.test/a" },
response: { status: 200, content: { mimeType: "\u00a0text/plain\u00a0" } },
};
const parent = analysisViewCaptureEvidence(capture);
expect(parent.limitations).not.toContain(caveat);
const response = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: { kind: "inline", evidence: parent },
view: { kind: "api-surface" },
},
});
const result = parseEvidence(response.structuredContent);
expect(result.limitations.filter((value) => value === caveat)).toEqual([
caveat,
]);
expect(result.normalized_result).toMatchObject({
groups: [{ content_types: [], flags: ["single-sample"] }],
limitations: expect.arrayContaining([caveat]),
unknowns: [
"Some retained records have unavailable status or content type values.",
],
});
});
it("rejects inconsistent portable coverage and accepts caller-ordered ordinal subsets", async () => {
const { client } = await connect();
for (const [total, ordinals] of [
[0, [0]],
[2, [0, 0]],
[2, [2]],
] as const) {
const capture = analysisViewCaptureFixture();
capture.total_records = total;
capture.records = ordinals.map((ordinal) => ({
...capture.records[0]!,
ordinal,
}));
const response = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: {
kind: "inline",
evidence: analysisViewCaptureEvidence(capture),
},
view: { kind: "api-surface" },
},
});
expect(parseMcpToolError(response).error.code).toBe("invalid_request");
}
const capture = analysisViewCaptureFixture();
capture.records = [capture.records[8]!, capture.records[1]!];
const response = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: {
kind: "inline",
evidence: analysisViewCaptureEvidence(capture),
},
view: { kind: "api-surface" },
},
});
expect(
parseEvidence(response.structuredContent).normalized_result,
).toMatchObject({
records: { examined: 2, total: 15 },
limitations: expect.arrayContaining([
"Parent contains an ordinal subset; the surface covers only retained records.",
]),
});
});
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());
@@ -624,3 +747,87 @@ it("accepts a transport-constraint retained reference as the view source", async
},
]);
});
it("projects an actual HAR capture retained by the public MCP workflow", async () => {
const root = await createTestTempDirectory("rea-surface-mcp-");
const path = join(root, "surface.har");
await writeFile(path, JSON.stringify(apiSurfaceHar()));
const service = new WebNetworkCaptureService({
inspect: async (input) => {
const bytes = await readFile(input.capture_path);
return ok({
...decodeHarCapture(bytes.toString("utf8"), input.sensitive_values),
artifact: {
path: input.capture_path,
sha256: createHash("sha256").update(bytes).digest("hex"),
bytes: bytes.length,
},
format: "har",
runtime_attribution: "unknown",
limitations: [],
});
},
});
const { client } = await connect(undefined, service);
const captureResponse = await client.callTool({
name: "inspect_web_network_capture",
arguments: { capture_path: path, format: "har" },
});
expect(captureResponse.isError).not.toBe(true);
const parent = parseEvidence(captureResponse.structuredContent);
const response = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: { kind: "retained-evidence", evidence_id: parent.evidence_id },
view: { kind: "api-surface" },
},
});
expect(response.isError).not.toBe(true);
const evidence = parseEvidence(response.structuredContent);
expect(evidence.confidence).toBe("inferred");
expect(evidence.normalized_result).toMatchObject({
records: { examined: 13, total: 13, excluded: 0 },
coverage: { total: 12, exhausted: true },
groups: expect.arrayContaining([
expect.objectContaining({
path_template: "/users/{numeric}",
record_ordinals: [0, 1],
}),
]),
});
});
it("reproduces the published API surface example from decoded fixture bytes", async () => {
const fixture = apiSurfaceHar();
fixture.log.entries = fixture.log.entries.slice(0, 2);
const bytes = Buffer.from(JSON.stringify(fixture));
const service = new WebNetworkCaptureService({
inspect: async () =>
ok({
...decodeHarCapture(bytes.toString("utf8"), []),
artifact: {
path: "/fixtures/api-surface.har",
sha256: createHash("sha256").update(bytes).digest("hex"),
bytes: bytes.length,
},
format: "har",
runtime_attribution: "unknown",
limitations: [],
}),
});
const { client } = await connect(undefined, service);
const capture = await client.callTool({
name: "inspect_web_network_capture",
arguments: { capture_path: "/fixtures/api-surface.har", format: "har" },
});
expect(parseEvidence(capture.structuredContent).evidence_id).toBe(
API_SURFACE_EXAMPLE.input.source.evidence_id,
);
const response = await client.callTool({
name: "inspect_analysis_view",
arguments: API_SURFACE_EXAMPLE.input,
});
expect(parseEvidence(response.structuredContent).normalized_result).toEqual(
API_SURFACE_EXAMPLE.output,
);
});
+17 -11
View File
@@ -10,7 +10,11 @@ import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
import { webPageInspectionSchema } from "../../../src/domain/browserObservationSchemas.js";
import { createWebScreenshotArtifact } from "../../../src/domain/webScreenshot.js";
import { JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE } from "../../../src/contracts/javascript/javascriptRuntimeReconciliationExample.js";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import {
TOOL_CONTRACTS,
toolContract,
} from "../../../src/contracts/toolContracts.js";
import { expandToolAvailability } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
import { runCliJson } from "../../fixtures/cliJsonProcess.js";
@@ -59,16 +63,18 @@ it(
name: "binary_session",
arguments: {},
});
expect(status.structuredContent).toMatchObject({
result: {
tool_availability: expect.arrayContaining([
expect.objectContaining({
name: "inspect_web_page",
reason: expect.any(String),
}),
]),
},
});
const sessionStatus = toolContract("binary_session").outputSchema.parse(
status.structuredContent,
);
const availability = expandToolAvailability(
sessionStatus.result.tool_availability,
);
expect(availability).toContainEqual(
expect.objectContaining({
name: "inspect_web_page",
reason: expect.any(String),
}),
);
const listed = await connected.client.callTool({
name: "list_browser_targets",
arguments: {
+18 -1
View File
@@ -7,11 +7,25 @@ import {
import { describe, expect, it } from "vitest";
import { createServer } from "../../../src/server/createServer.js";
import {
TOOL_CONTRACTS,
toolContract,
} from "../../../src/contracts/toolContracts.js";
import { expandToolAvailability } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
import {
createCacheProvider,
createTestBinarySession,
} from "../../fixtures/binarySession.js";
const assertCompleteToolAvailability = (structuredContent: unknown): void => {
const status =
toolContract("binary_session").outputSchema.parse(structuredContent);
const availability = expandToolAvailability(status.result.tool_availability);
expect(availability.map(({ name }) => name).sort()).toEqual(
TOOL_CONTRACTS.map(({ name }) => name).sort(),
);
};
describe("per-request client capability reporting", () => {
it.each([
[{ elicitation: {} }, true, false],
@@ -39,6 +53,7 @@ describe("per-request client capability reporting", () => {
[CLIENT_CAPABILITIES_META_KEY]: capabilities,
},
});
assertCompleteToolAvailability(status.structuredContent);
expect(status.structuredContent).toMatchObject({
result: {
client_features: { elicitation_form: form, elicitation_url: url },
@@ -71,13 +86,15 @@ describe("initialize-scoped client metadata", () => {
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
return (
const result = (
await client.callTool({
name: "binary_session",
arguments: {},
...(meta === undefined ? {} : { _meta: meta }),
})
).structuredContent;
assertCompleteToolAvailability(result);
return result;
} finally {
await Promise.allSettled([
client.close(),
@@ -4,7 +4,6 @@ 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,
@@ -121,29 +120,6 @@ describe("MCP compact input schema profile", () => {
}
});
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);
@@ -8,11 +8,13 @@ import { z } from "zod";
import { ArtifactProvider } from "../../../src/artifacts/ArtifactProvider.js";
import {
CPU,
FILE_TYPE,
LC,
buildVersionCommand,
dylibCommand,
dyldEnvironmentCommand,
fatImage,
machoImage,
rpathCommand,
} from "../../../src/artifacts/apple/MachoImage.fixture.js";
@@ -112,6 +114,44 @@ it("traces dylib resolution for an opened app bundle and rejects a changed targe
});
});
it("traces architecture slices from a universal Mach-O target", async () => {
const root = await createTestTempDirectory("rea-dylib-universal-");
const executable = join(root, "Universal");
const cpu = process.arch === "arm64" ? CPU.arm64 : CPU.x86_64;
const architecture = process.arch === "arm64" ? "arm64" : "x86_64";
await writeFile(
executable,
fatImage([
{
cpu,
bytes: machoImage({
cpu,
commands: [buildVersionCommand(1)],
}),
},
]),
);
await withClient(async (client) => {
const opened = await client.callTool({
name: "open_binary",
arguments: { path: executable },
});
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
const called = await client.callTool({
name: "trace_dylib_resolution",
arguments: { architecture },
});
expect(called.isError, JSON.stringify(called.structuredContent)).not.toBe(
true,
);
const trace = dylibResolutionResultSchema.parse(
structuredResult(called.structuredContent),
);
expect(trace.roots).toEqual([{ image: "Universal", architecture }]);
});
});
it("rejects targets that are not Mach-O", async () => {
const directory = await createTestTempDirectory("rea-dylib-mcp-plist-");
const path = join(directory, "Info.plist");
@@ -189,7 +189,7 @@ const fixturePort = (): AnalysisOperationPort => ({
case "analyze_function":
return Promise.resolve(targetObservation(functionDossier));
default:
return Promise.resolve(ok(null));
throw new Error(`Unexpected analysis operation: ${name}`);
}
},
});
@@ -288,11 +288,43 @@ describe("enhanced MCP tools", () => {
failed: 0,
});
expect(results[3]).toEqual({
"0": [{ address: "0x1", status: "ok", calls: ["0x2", "0x3"] }],
"1": [
{ address: "0x2", status: "ok", calls: ["0x1"] },
{ address: "0x3", status: "ok", calls: [] },
],
graph: {
"0": [
{
address: "0x1",
status: "ok",
calls: ["0x2", "0x3"],
limitations: ["Provider did not report relationship coverage."],
relationship_coverage: {
status: "unknown",
reason: "Provider did not report relationship coverage.",
},
},
],
"1": [
{
address: "0x2",
status: "ok",
calls: ["0x1"],
limitations: ["Provider did not report relationship coverage."],
relationship_coverage: {
status: "unknown",
reason: "Provider did not report relationship coverage.",
},
},
{
address: "0x3",
status: "ok",
calls: [],
limitations: ["Provider did not report relationship coverage."],
relationship_coverage: {
status: "unknown",
reason: "Provider did not report relationship coverage.",
},
},
],
},
limitations: [],
});
expect(results[4]).toMatchObject({
total: 1,
@@ -354,7 +386,7 @@ describe("enhanced MCP tools", () => {
{ address: "0x1", depth: 0 },
{ address: "0x2", depth: 1 },
],
truncated: false,
truncated: true,
});
expect(results[11]).toMatchObject({
start: "missing-selector",
@@ -37,17 +37,20 @@ describe("enhanced MCP tools", () => {
expect(graph).toMatchObject({
ok: true,
value: {
"0": [
{
address: "0x1",
status: "error",
error: {
category: "execution_failure",
message:
"Analysis returned an unreadable result. Run `rea doctor` and review the reported details; repeating the unchanged request is not expected to succeed.",
graph: {
"0": [
{
address: "0x1",
status: "error",
error: {
category: "execution_failure",
message:
"Analysis returned an unreadable result. Run `rea doctor` and review the reported details; repeating the unchanged request is not expected to succeed.",
},
},
},
],
],
},
limitations: [],
},
});
expect(unresolved).toEqual({
@@ -130,7 +130,7 @@ describe("enhanced MCP tools", () => {
);
}
default:
return Promise.resolve(ok(null));
throw new Error(`Unexpected analysis operation: ${name}`);
}
},
});
@@ -174,26 +174,29 @@ describe("enhanced MCP tools", () => {
it("rejects a segment with omitted coordinates instead of reporting zero length", async () => {
const client = await connect({
execute: (name) =>
Promise.resolve(
name === "list_segments"
? ok([
{
name: "__TEXT",
end: "0x2000",
readable: null,
writable: null,
executable: null,
},
])
: ok(name === "current_document" ? "fixture" : []),
),
execute: (name) => {
if (name === "list_segments")
return Promise.resolve(
ok([
{
name: "__TEXT",
end: "0x2000",
readable: null,
writable: null,
executable: null,
},
]),
);
if (name === "current_document") return Promise.resolve(ok("fixture"));
if (name === "list_procedures" || name === "list_strings")
return Promise.resolve(ok([]));
throw new Error(`Unexpected analysis operation: ${name}`);
},
});
const result = await client.callTool({
name: "binary_overview",
arguments: {},
});
expect(result.isError).toBe(true);
expect(result.content).toContainEqual({
type: "text",
@@ -225,8 +228,11 @@ const overviewPort = (
},
]),
);
default:
case "list_procedures":
case "list_strings":
return Promise.resolve(ok([]));
default:
throw new Error(`Unexpected analysis operation: ${name}`);
}
},
});
@@ -7,6 +7,7 @@ import {
AnalysisCapabilityUnavailableError,
AnalysisOutputError,
} from "../../../src/domain/analysisErrorCore.js";
import type { RelationshipCoverage } from "../../../src/domain/relationshipCoverage.js";
import { err, ok as resultOk } from "../../../src/domain/result.js";
import { closeEnhancedToolResources, connect } from "./enhancedToolsHarness.js";
@@ -17,12 +18,16 @@ afterEach(closeEnhancedToolResources);
const relationshipExecution = (
result: unknown,
limitations: readonly string[] = [],
relationshipCoverage?: RelationshipCoverage,
) =>
resultOk(
createAnalysisExecution(
result,
{ id: "fixture", name: "Fixture analysis provider", version: "1" },
{ limitations },
{
limitations,
...(relationshipCoverage === undefined ? {} : { relationshipCoverage }),
},
),
);
@@ -38,6 +43,9 @@ describe("enhanced MCP tools", () => {
return relationshipExecution(
arguments_.procedure === "0x1" ? ["0x2"] : [],
arguments_.procedure === "0x1" ? [limitation] : [],
arguments_.procedure === "0x1"
? { status: "partial", limitations: [limitation] }
: { status: "complete" },
);
},
});
@@ -48,17 +56,23 @@ describe("enhanced MCP tools", () => {
expect(graph.isError).not.toBe(true);
expect(graph.structuredContent).toMatchObject({
normalized_result: {
"0": [
{
address: "0x1",
status: "ok",
calls: ["0x2"],
limitations: [limitation],
},
],
graph: {
"0": [
{
address: "0x1",
status: "ok",
calls: ["0x2"],
limitations: [limitation],
relationship_coverage: {
status: "partial",
limitations: [limitation],
},
},
],
},
limitations: [limitation],
},
});
const trace = await client.callTool({
name: "trace_call_path",
arguments: { start: "0x1", goal: "0x2" },
@@ -77,6 +91,94 @@ describe("enhanced MCP tools", () => {
});
});
it("keeps generic provider caveats visible without truncating complete relationships", async () => {
const caveat = "Decompiler output may omit indirect calls.";
const client = await connect({
execute: async (name, arguments_) => {
if (name === "procedure_address")
return relationshipExecution(String(arguments_.procedure));
if (name !== "procedure_callees")
throw new Error(`Unexpected operation: ${name}`);
return relationshipExecution(
arguments_.procedure === "0x1" ? ["0x2"] : [],
[caveat],
{ status: "complete" },
);
},
});
const graph = await client.callTool({
name: "get_call_graph",
arguments: { address: "0x1", direction: "forward" },
});
expect(graph.structuredContent).toMatchObject({
normalized_result: {
graph: {
"0": [
{ status: "ok", relationship_coverage: { status: "complete" } },
],
"1": [
{ status: "ok", relationship_coverage: { status: "complete" } },
],
},
limitations: [caveat],
},
});
expect(JSON.stringify(graph.structuredContent)?.split(caveat)).toHaveLength(
2,
);
const trace = await client.callTool({
name: "trace_call_path",
arguments: { start: "0x1", goal: "0x2" },
});
expect(trace.structuredContent).toMatchObject({
normalized_result: {
truncated: false,
residual_unknowns: [],
limitations: expect.arrayContaining([expect.stringContaining(caveat)]),
relationship_coverage: { "0x1": { status: "complete" } },
},
});
});
it("keeps unclassified legacy caveats on nodes with unknown coverage", async () => {
const caveat = "This legacy provider does not classify call limitations.";
const client = await connect({
execute: async (name, arguments_) => {
if (name === "procedure_address")
return relationshipExecution(String(arguments_.procedure));
if (name !== "procedure_callees")
throw new Error(`Unexpected operation: ${name}`);
return relationshipExecution([], [caveat]);
},
});
const graph = await client.callTool({
name: "get_call_graph",
arguments: { address: "0x1", direction: "forward" },
});
expect(graph.structuredContent).toMatchObject({
normalized_result: {
graph: {
"0": [
{
status: "ok",
relationship_coverage: { status: "unknown" },
limitations: [
"Provider did not report relationship coverage.",
caveat,
],
},
],
},
limitations: [caveat],
},
});
});
});
describe("enhanced MCP batches", () => {
it("returns every batch item in caller order with its own result", async () => {
const addresses = Array.from(
{ length: 37 },
+29 -36
View File
@@ -1,6 +1,8 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { describe, expect, it } from "vitest";
import { connectGhidraMcp } from "./ghidraMcpHarness.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { expandToolAvailability } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
describe("Ghidra MCP capability routing", () => {
it("routes composed and capability tools", async () => {
@@ -41,44 +43,35 @@ describe("Ghidra MCP capability routing", () => {
name: "binary_session",
arguments: {},
});
expect(status.structuredContent).toMatchObject({
result: {
open: true,
analysis_provider_binding: {
provider: { id: "ghidra", version: "12.1.4" },
},
tool_availability: expect.arrayContaining([
expect.objectContaining({
name: "binary_overview",
available: true,
}),
expect.objectContaining({
name: "get_objc_classes",
available: true,
}),
expect.objectContaining({
name: "batch_decompile",
available: true,
}),
expect.objectContaining({
name: "trace_feature",
available: true,
}),
expect.objectContaining({
name: "get_call_graph",
available: true,
}),
expect.objectContaining({
name: "find_xrefs_to_name",
available: true,
}),
expect.objectContaining({
name: "set_comment",
available: false,
}),
]),
const sessionStatus = toolContract("binary_session").outputSchema.parse(
status.structuredContent,
);
expect(sessionStatus.result).toMatchObject({
open: true,
analysis_provider_binding: {
provider: { id: "ghidra", version: "12.1.4" },
},
});
const availability = expandToolAvailability(
sessionStatus.result.tool_availability,
);
expect(availability).toEqual(
expect.arrayContaining([
expect.objectContaining({ name: "binary_overview", available: true }),
expect.objectContaining({
name: "get_objc_classes",
available: true,
}),
expect.objectContaining({ name: "batch_decompile", available: true }),
expect.objectContaining({ name: "trace_feature", available: true }),
expect.objectContaining({ name: "get_call_graph", available: true }),
expect.objectContaining({
name: "find_xrefs_to_name",
available: true,
}),
expect.objectContaining({ name: "set_comment", available: false }),
]),
);
} finally {
await harness.close();
}
@@ -3,7 +3,14 @@ import { ok as resultOk } from "../../../src/domain/result.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it } from "vitest";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import {
createBinarySessionTargets,
createTestBinarySession,
} from "../../fixtures/binarySession.js";
import {
createAnalysisExecution,
type AnalysisOperationPort,
} from "../../../src/application/AnalysisProvider.js";
import type { BinarySession } from "../../../src/application/binary/BinarySession.js";
import { FUNCTION_COMPARISON_EXAMPLE } from "../../../src/contracts/functionComparisonExample.js";
import { INVESTIGATION_EXAMPLES } from "../../../src/contracts/investigationExamples.js";
@@ -20,6 +27,7 @@ import {
} from "../../../src/domain/jsonValue.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
import type { RelationshipCoverage } from "../../../src/domain/relationshipCoverage.js";
it("aggregates comparison Evidence and records an approved runtime gap", async () => {
const { session, server, client } = await connected();
@@ -149,6 +157,183 @@ const dossierWithCallees = (addresses: readonly string[]) => {
);
};
it.each([
{
label: "complete",
coverage: { status: "complete" } as RelationshipCoverage,
providerLimitations: ["The provider version identity is unavailable."],
dossierLimitations: ["The dossier has no native value-flow observation."],
status: "not_found",
exhaustive: true,
},
{
label: "partial",
coverage: {
status: "partial",
limitations: ["Callee output was capped."],
} as RelationshipCoverage,
providerLimitations: [],
dossierLimitations: [],
status: "unknown",
exhaustive: false,
},
{
label: "unknown",
coverage: {
status: "unknown",
reason: "Callee coverage was not established.",
} as RelationshipCoverage,
providerLimitations: [],
dossierLimitations: [],
status: "unknown",
exhaustive: false,
},
{
label: "legacy limited",
coverage: undefined,
providerLimitations: [
"Legacy relationship completeness was not established.",
],
dossierLimitations: [],
status: "unknown",
exhaustive: false,
},
{
label: "legacy unlimited",
coverage: undefined,
providerLimitations: [],
dossierLimitations: [],
status: "not_found",
exhaustive: true,
},
])(
"preserves $label coverage through public analyze_function then build_call_path",
async (scenario) => {
const base = FUNCTION_COMPARISON_EXAMPLE.left;
if (base.subject === null) throw new Error("missing fixture subject");
const provider = {
id: "fixture",
name: "Fixture analysis provider",
version: "1",
};
const rawResult = { fixture_reply: scenario.label };
const execution = createAnalysisExecution(
{
...jsonObjectSchema.parse(base.normalized_result),
callees: [],
limitations: scenario.dossierLimitations,
},
provider,
{
rawResult,
limitations: scenario.providerLimitations,
locations: base.locations,
...(scenario.coverage === undefined
? {}
: { relationshipCoverage: scenario.coverage }),
},
);
const { session, server, client } = await connected({
execute: async (operation, parameters) => {
if (operation === "health") return observed(null);
if (operation !== "analyze_function")
throw new Error(`Unexpected operation: ${operation}`);
expect(parameters.procedure).toBe("0x1000");
return resultOk(execution);
},
});
try {
const [path] = await createBinarySessionTargets();
const opened = await client.callTool({
name: "open_binary",
arguments: { path },
});
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
const analyzed = await client.callTool({
name: "analyze_function",
arguments: { procedure: "0x1000" },
});
expect(analyzed.isError, JSON.stringify(analyzed)).not.toBe(true);
const dossier = inlineEvidence(analyzed.structuredContent);
expect(dossier).toMatchObject({
operation: "analyze_function",
parameters: { procedure: "0x1000" },
provider,
subject: {
local_path: path,
digest: { sha256: session.activeTarget()?.sha256 },
format: session.activeTarget()?.format,
},
raw_result: rawResult,
limitations: scenario.providerLimitations,
locations: base.locations,
normalized_result: {
callees: [],
limitations: scenario.dossierLimitations,
},
});
const response = await client.callTool({
name: "build_call_path",
arguments: {
functions: [dossier],
start: { address: "0x1000" },
goal: { address: "0x4000" },
},
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
const evidence = inlineEvidence(response.structuredContent);
const coverage = scenario.coverage;
const reasons =
coverage?.status === "partial"
? coverage.limitations
: coverage?.status === "unknown"
? [coverage.reason]
: [];
expect(evidence.normalized_result).toMatchObject({
status: scenario.status,
shortest_hops: null,
paths: [],
search_scope: { exhaustive: scenario.exhaustive },
limitations: expect.arrayContaining([
...scenario.providerLimitations,
...scenario.dossierLimitations,
...reasons,
]),
});
expect(evidence.evidence_links).toEqual([dossier.evidence_id]);
expect(dossier.relationship_coverage).toEqual(coverage ?? null);
if (coverage?.status === "partial") {
const tampered = {
...dossier,
relationship_coverage: { status: "complete" },
};
expect(() => parseEvidence(tampered)).toThrow();
const rejected = await client.callTool({
name: "build_call_path",
arguments: {
functions: [tampered],
start: { address: "0x1000" },
goal: { address: "0x4000" },
},
});
expect(rejected.isError, JSON.stringify(rejected)).toBe(true);
}
if (scenario.exhaustive)
expect(session.listUnknowns({ domain: "call-path" })).toEqual([]);
else
expect(session.listUnknowns({ domain: "call-path" })).toMatchObject([
{
question:
"Can the requested call path be established from complete analysis?",
supporting_evidence_ids: [evidence.evidence_id],
},
]);
} finally {
await close(session, server, client);
}
},
);
it("records a safe unresolved call-path question", async () => {
const { session, server, client } = await connected();
const dossier = dossierWithCallees(["0x2000"]);
@@ -326,10 +511,12 @@ it("cannot omit a session-owned active unknown from reconstruction input", async
}
});
const connected = async () => {
const connected = async (analysis?: AnalysisOperationPort) => {
const session = createTestBinarySession(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
execute:
analysis?.execute.bind(analysis) ??
(() => Promise.resolve(observed(null))),
close: () => Promise.resolve(resultOk(null)),
}));
const server = createServer({ kind: "session", session });
@@ -0,0 +1,49 @@
import { expect } from "vitest";
import { z } from "zod";
import { createBinarySession } from "../../../src/composition/binary.js";
import { parseConfig } from "../../../src/config/parseConfig.js";
import { keyedArchiveResultSchema } from "../../../src/domain/apple/keyedArchive.js";
import { silentLogger } from "../../../src/logger.js";
import { createServer } from "../../../src/server/createServer.js";
import {
expectKeyedArchivePrototypeKeys,
keyedArchivePrototypeKeyFixture,
} from "../../fixtures/keyedArchivePrototypeKeys.js";
import { mcpTest } from "../../support/mcp/mcpFixture.js";
mcpTest(
"MCP retains ordinary evidence with formatted XML prototype keys",
async ({ mcp, onTestFinished }) => {
const fixture = await keyedArchivePrototypeKeyFixture();
const configured = parseConfig({ REA_ANALYSIS_PROVIDER: "auto" });
if (!configured.ok) throw configured.error;
const session = createBinarySession(
configured.value,
silentLogger,
process.env,
);
onTestFinished(async () => {
await session.close();
});
const client = await mcp.connect(
createServer({ kind: "session", session }),
);
const opened = await client.callTool({
name: "open_binary",
arguments: { path: fixture.path },
});
expect(opened.isError, JSON.stringify(opened.content)).not.toBe(true);
const result = await client.callTool({
name: "inspect_keyed_archive",
arguments: {},
});
expect(result.isError, JSON.stringify(result.content)).not.toBe(true);
expectKeyedArchivePrototypeKeys(
z
.object({ normalized_result: keyedArchiveResultSchema })
.parse(result.structuredContent).normalized_result,
fixture.digest,
);
},
);
+53
View File
@@ -113,6 +113,7 @@ it("runs every managed static inspection independently of an active native targe
operation: "inspect_managed_members",
subject: { local_path: otherPath, format: "pe" },
});
await verifyManagedTypeSelection(client, path, otherPath);
const boundaries = structured(
await client.callTool({
name: "inspect_managed_native_boundaries",
@@ -445,6 +446,58 @@ const verifyImport = async (
});
};
/** Selected type names reach the provider and unmatched names stay visible. */
const verifyManagedTypeSelection = async (
client: Client,
path: string,
otherPath: string,
): Promise<void> => {
const advertised = (await client.listTools()).tools.find(
(tool) => tool.name === "inspect_managed_members",
);
if (advertised === undefined) throw new Error("missing managed member tool");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
expect(ajv.validateSchema(advertised.inputSchema)).toBe(true);
const validate = ajv.compile(advertised.inputSchema);
expect(
validate({ path, type_names: ["Fixture.Program", "Missing.Type"] }),
).toBe(true);
expect(
validate({ path, type_names: ["Fixture.Program", "Fixture.Program"] }),
).toBe(false);
const selected = structured(
await client.callTool({
name: "inspect_managed_members",
arguments: { path, type_names: ["Fixture.Program", "Missing.Type"] },
}),
);
expect(selected).toMatchObject({
parameters: { path, type_names: ["Fixture.Program", "Missing.Type"] },
normalized_result: {
types: [expect.objectContaining({ full_name: "Fixture.Program" })],
methods: [expect.objectContaining({ declaring_type: "Fixture.Program" })],
selection: {
type_names: ["Fixture.Program", "Missing.Type"],
unmatched_type_names: ["Missing.Type"],
},
},
});
const repeatedSelection = await client.callTool({
name: "inspect_managed_members",
arguments: { path, type_names: ["Fixture.Program", "Fixture.Program"] },
});
expect(repeatedSelection.isError).toBe(true);
const reselectedOtherTarget = structured(
await client.callTool({
name: "inspect_managed_artifact",
arguments: { path: otherPath },
}),
);
expect(reselectedOtherTarget).toMatchObject({
subject: { local_path: otherPath, format: "pe" },
});
};
const structured = (result: CallToolResult): Record<string, unknown> => {
if (result.isError === true) return parseMcpToolError(result);
if (
@@ -7,57 +7,75 @@ import { NativeMacOSProvider } from "../../../src/native/NativeMacOSProvider.js"
import {
machoImage,
rpathCommand,
CPU,
fatImage,
} from "../../../src/artifacts/apple/MachoImage.fixture.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { NativeFixtureRunner } from "../../fixtures/nativeCommands.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
it("rejects changed signature targets through MCP and accepts reopening the new version", async () => {
const path = join(
await createTestTempDirectory("rea-signature-binding-mcp-"),
"program",
);
await writeFile(path, machoImage({}));
const session = createTestBinarySession(
new NativeMacOSProvider({}, new NativeFixtureRunner(), "darwin"),
);
const server = createServer({ kind: "session", session });
const client = new Client({ name: "signature-binding-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const open = () =>
client.callTool({ name: "open_binary", arguments: { path } });
expect((await open()).isError).not.toBe(true);
await writeFile(
path,
machoImage({ commands: [rpathCommand("new-version")] }),
it.each(["mach-o", "mach-o-universal"] as const)(
"rejects changed %s signature targets through MCP and accepts reopening the new version",
async (format) => {
const path = join(
await createTestTempDirectory("rea-signature-binding-mcp-"),
"program",
);
const changed = await client.callTool({
name: "inspect_signature",
arguments: {},
});
expect(changed.isError).toBe(true);
expect(parseMcpToolError(changed)).toMatchObject({
error: { code: "artifact_changed", details: { path } },
});
expect((await open()).isError).not.toBe(true);
const inspected = await client.callTool({
name: "inspect_signature",
arguments: {},
});
expect(
inspected.isError,
JSON.stringify(inspected.structuredContent),
).not.toBe(true);
expect(inspected.structuredContent).toMatchObject({
normalized_result: { signed: true, identifier: "com.example.fixture" },
});
} finally {
await client.close();
await server.close();
}
});
const image = (commands: readonly Uint8Array[] = []) =>
format === "mach-o"
? machoImage({ commands })
: fatImage(
[CPU.arm64, CPU.x86_64].map((cpu) => ({
cpu,
bytes: machoImage({ cpu, commands }),
})),
);
await writeFile(path, image());
const session = createTestBinarySession(
new NativeMacOSProvider({}, new NativeFixtureRunner(), "darwin"),
);
const server = createServer({ kind: "session", session });
const client = new Client({ name: "signature-binding-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const open = () =>
client.callTool({ name: "open_binary", arguments: { path } });
const opened = await open();
expect(opened.isError).not.toBe(true);
expect(
toolContract("open_binary").outputSchema.parse(opened.structuredContent)
.result,
).toMatchObject({ format });
await writeFile(path, image([rpathCommand("new-version")]));
const changed = await client.callTool({
name: "inspect_signature",
arguments: {},
});
expect(changed.isError).toBe(true);
expect(parseMcpToolError(changed)).toMatchObject({
error: { code: "artifact_changed", details: { path } },
});
expect((await open()).isError).not.toBe(true);
const inspected = await client.callTool({
name: "inspect_signature",
arguments: {},
});
expect(
inspected.isError,
JSON.stringify(inspected.structuredContent),
).not.toBe(true);
expect(inspected.structuredContent).toMatchObject({
subject: { format },
normalized_result: { signed: true, identifier: "com.example.fixture" },
});
} finally {
await client.close();
await server.close();
}
},
);
@@ -14,6 +14,7 @@ import {
TOOL_CONTRACTS,
toolContract,
} from "../../../src/contracts/toolContracts.js";
import { expandToolAvailability } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
import { run } from "../../../src/main.js";
import { createServer } from "../../../src/server/createServer.js";
import { optionalObservationFactories } from "../../fixtures/optionalObservationProviders.js";
@@ -154,33 +155,37 @@ mcpTest.for(failedAdapters)(
name: "binary_session",
arguments: {},
});
expect(status.structuredContent).toMatchObject({
result: {
tool_availability: expect.arrayContaining([
expect.objectContaining({
name: operation,
available: false,
reason: "provider_unavailable",
remediation: expect.stringContaining(failure),
}),
expect.objectContaining({
name: "analyze_javascript_application",
available: true,
}),
expect.objectContaining({
name: "reconcile_javascript_runtime",
available: true,
}),
expect.objectContaining({
name:
port === "electronActiveObservation"
? "list_electron_targets"
: "capture_electron_scenario",
available: true,
}),
]),
},
});
const sessionStatus = toolContract("binary_session").outputSchema.parse(
status.structuredContent,
);
const availability = expandToolAvailability(
sessionStatus.result.tool_availability,
);
expect(availability).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: operation,
available: false,
reason: "provider_unavailable",
remediation: expect.stringContaining(failure),
}),
expect.objectContaining({
name: "analyze_javascript_application",
available: true,
}),
expect.objectContaining({
name: "reconcile_javascript_runtime",
available: true,
}),
expect.objectContaining({
name:
port === "electronActiveObservation"
? "list_electron_targets"
: "capture_electron_scenario",
available: true,
}),
]),
);
const healthy =
port === "javascriptRuntimeObservation"
? "list_browser_targets"
+19 -9
View File
@@ -54,9 +54,11 @@ describe("guided prompts over MCP", () => {
completions: {},
prompts: { listChanged: true },
});
for (const [index, contract] of PROMPT_CONTRACTS.entries()) {
const advertised = prompts.prompts[index];
expect(advertised?.arguments).toEqual(
const advertisedByName = new Map(
prompts.prompts.map((prompt) => [prompt.name, prompt]),
);
for (const contract of PROMPT_CONTRACTS) {
expect(advertisedByName.get(contract.name)?.arguments).toEqual(
Object.entries(contract.arguments).map(
([name, { description, required }]) => ({
name,
@@ -271,15 +273,21 @@ describe("guided prompt completion registry", () => {
});
await connectPair(server, client);
resources.push(session);
expect((await client.listPrompts()).prompts[0]?.title).toBe(
"Investigate a feature",
const contract = PROMPT_CONTRACTS.find(
({ name }) => name === "investigate_feature",
);
if (contract === undefined)
throw new Error("Missing investigate_feature prompt contract");
const initialPrompt = (await client.listPrompts()).prompts.find(
({ name }) => name === contract.name,
);
expect(initialPrompt?.title).toBe(contract.title);
registry.update({
...PROMPT_CONTRACTS[0],
title: "Investigate a feature (updated)",
...contract,
title: `${contract.title} (updated)`,
arguments: {
...PROMPT_CONTRACTS[0].arguments,
...contract.arguments,
document: {
description: "Updated provider-backed selector",
required: false,
@@ -289,7 +297,9 @@ describe("guided prompt completion registry", () => {
});
await changed;
const prompts = await client.listPrompts();
expect(prompts.prompts[0]?.title).toBe("Investigate a feature (updated)");
expect(
prompts.prompts.find(({ name }) => name === contract.name)?.title,
).toBe(`${contract.title} (updated)`);
expect(await complete(client, "document", "fixture")).toEqual(["fixture"]);
});
});
@@ -40,10 +40,6 @@ describe("reconstruction obligation ledger MCP parity", () => {
summary: { total: 0 },
},
});
expect(result.structuredContent).toHaveProperty(
"normalized_result.schema",
"ReconstructionObligationLedger",
);
} finally {
await client.close();
await server.close();
+57 -24
View File
@@ -15,6 +15,10 @@ import { CLI_COMMAND_NAMES } from "../../../src/cliCommandNames.js";
import { PACKAGE_METADATA } from "../../../src/generatedPackageMetadata.js";
import { PRODUCT_IDENTITY, SDK_IDENTITY } from "../../../src/identity.js";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import {
expandToolAvailability,
sessionProvider,
} from "../../../src/contracts/toolOutputSchemaPrimitives.js";
import { PROMPT_CONTRACTS } from "../../../src/contracts/promptContracts.js";
import { createServer } from "../../../src/server/createServer.js";
import { createServerIdentity } from "../../../src/serverIdentity.js";
@@ -70,20 +74,18 @@ const statusCapability = (
readonly reason: string;
} = { available: true },
) => ({
operation,
effects: {
mutates_artifact: false,
launches_process: false,
may_show_ui: false,
may_access_network: false,
may_write_filesystem: false,
changes_permissions: false,
requires_root: false,
},
limitations: [],
...(availability.available
? { available: true as const, reason: null, availability_code: null }
: availability),
provider: { id: "status-fixture", name: "Status fixture", version: null },
shared_limitations: [],
groups: [
{
operations: [operation],
effects: [],
limitations: [],
...(availability.available
? { available: true as const, reason: null, availability_code: null }
: availability),
},
],
});
describe("server and catalog identity", () => {
@@ -326,15 +328,10 @@ const activeTargetReasons = async (
name: "binary_session",
arguments: {},
});
const availability = z
.object({
result: z.object({
tool_availability: z.array(
z.object({ name: z.string(), reason: z.string() }).loose(),
),
}),
})
.parse(status.structuredContent).result.tool_availability;
const availability = expandToolAvailability(
z.object({ result: sessionProvider }).parse(status.structuredContent).result
.tool_availability,
);
return Object.fromEntries(
["inspect_macho", "inspect_artifact", "inspect_managed_artifact"].map(
(name) => [name, availability.find((tool) => tool.name === name)?.reason],
@@ -347,6 +344,32 @@ const assertLiveIdentity = async (client: Client): Promise<void> => {
name: "binary_session",
arguments: {},
});
const status = z
.object({ result: sessionProvider })
.parse(identity.structuredContent).result;
expect(Object.keys(status.server_identity.catalog).sort()).toEqual([
"counts",
"digests",
]);
const availability = expandToolAvailability(status.tool_availability);
expect(availability.map(({ name }) => name).sort()).toEqual(
TOOL_CONTRACTS.map(({ name }) => name).sort(),
);
for (const contract of TOOL_CONTRACTS) {
expect(availability).toContainEqual(
expect.objectContaining({
name: contract.name,
surface: contract.kind,
effects: contract.effects,
annotations: {
read_only: contract.annotations.readOnlyHint ?? false,
destructive: contract.annotations.destructiveHint ?? false,
idempotent: contract.annotations.idempotentHint ?? false,
open_world: contract.annotations.openWorldHint ?? true,
},
}),
);
}
expect(identity.structuredContent).toMatchObject({
result: {
server_identity: {
@@ -370,7 +393,17 @@ const assertSessionIdentity = async (client: Client): Promise<void> => {
name: "binary_session",
arguments: { expected_package_version: "1.2.0" },
});
expect(status.structuredContent).toMatchObject({
const parsed = z
.object({ result: sessionProvider })
.parse(status.structuredContent);
expect({
result: {
...parsed.result,
tool_availability: expandToolAvailability(
parsed.result.tool_availability,
),
},
}).toMatchObject({
result: {
server_identity: {
catalog: {
+10 -9
View File
@@ -3,7 +3,6 @@ import { ok as resultOk } from "../../../src/domain/result.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { CallToolResult } from "@modelcontextprotocol/server";
import { afterEach, expect, it } from "vitest";
import { z } from "zod";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import type {
@@ -12,8 +11,11 @@ import type {
} from "../../../src/application/AnalysisProvider.js";
import { observed as ok } from "../../fixtures/analysisExecution.js";
import { createServer } from "../../../src/server/createServer.js";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import { toolAvailability } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
import {
TOOL_CONTRACTS,
toolContract,
} from "../../../src/contracts/toolContracts.js";
import { expandToolAvailability } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
const resources: Array<{ close(): Promise<void> }> = [];
@@ -65,7 +67,7 @@ it("executes a realistic workflow: list methods, decompile selected, get xrefs",
case "xrefs":
return Promise.resolve(ok(["0x1000"]));
default:
return Promise.resolve(ok(null));
throw new Error(`Unexpected analysis operation: ${name}`);
}
},
});
@@ -126,11 +128,10 @@ it("advertises the complete currently available inventory with a session", async
arguments: {},
}),
);
const inventory = z
.object({
result: z.object({ tool_availability: z.array(toolAvailability) }),
})
.parse(status).result.tool_availability;
const inventory = expandToolAvailability(
toolContract("binary_session").outputSchema.parse(status).result
.tool_availability,
);
for (const availability of inventory) {
if (availability.available) continue;
expect(availability.reason).not.toBe("available");
+7 -8
View File
@@ -26,6 +26,8 @@ import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
import { MAX_JSON_DEPTH } from "../../../src/domain/jsonValue.js";
import { parseAnalysisSnapshot } from "../../../src/domain/analysisSnapshot.js";
import { INVESTIGATION_EXAMPLES } from "../../../src/contracts/investigationExamples.js";
import { expandProviderCapabilities } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { ok as resultOk } from "../../../src/domain/result.js";
import {
createSessionMcpHarness,
@@ -294,15 +296,12 @@ describe("target-free MCP workflow", () => {
expect(openedStatus).toMatchObject({
result: { path: await realpath(first) },
});
const sessionStatus =
toolContract("binary_session").outputSchema.parse(openedStatus);
expect(
z
.object({
result: z.object({
capabilities: z.array(z.object({ operation: z.string() })),
}),
})
.parse(openedStatus)
.result.capabilities.map(({ operation }) => operation),
expandProviderCapabilities(sessionStatus.result.capabilities).map(
({ operation }) => operation,
),
).not.toContain("inventory_artifact");
expect(
text(await mcp.callTool({ name: "current_document", arguments: {} })),
+85 -26
View File
@@ -1,17 +1,93 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { Client } from "@modelcontextprotocol/client";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it, onTestFinished, vi } from "vitest";
import { readFile, realpath, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { WasmArtifactService } from "../../../src/application/wasm/WasmArtifactService.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { ok } from "../../../src/domain/result.js";
import { createServer } from "../../../src/server/createServer.js";
import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import {
wasmArtifactFixture,
wasmArtifactExecution,
} from "../../fixtures/wasm/artifact.js";
const wasmToolSchemas = async (client: Client) => {
const advertised = (await client.listTools()).tools.find(
(tool) => tool.name === "inspect_wasm_artifact",
);
if (advertised?.outputSchema === undefined)
throw new Error("WASM recovery must name an advertised static tool");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = advertised.inputSchema;
const outputSchema: Record<string, unknown> = advertised.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
return { name: advertised.name, ajv, inputSchema, outputSchema };
};
it("directs rejected native WASM opening to the advertised static tool while preserving missing-WABT diagnostics", async () => {
const directory = await createTestTempDirectory("rea-wasm-recovery-");
const path = join(
await realpath(directory),
process.platform === "win32" ? "module space.bin" : 'module "quoted".bin',
);
await writeFile(path, Buffer.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]));
const createClient = vi.fn(() => {
throw new Error("native provider must not start for WASM");
});
const session = createTestBinarySession(createClient);
const harness = await createApplicationMcpHarness({
session,
serverOptions: { environment: {} },
});
onTestFinished(harness.close);
const { client } = harness;
const { name, ajv, inputSchema } = await wasmToolSchemas(client);
const input = { path };
expect(
toolContract("inspect_wasm_artifact").inputSchema.safeParse(input).success,
).toBe(true);
const opening = await client.callTool({
name: "open_binary",
arguments: input,
});
expect(opening.isError).toBe(true);
const failure = parseMcpToolError(opening);
expect(failure).toMatchObject({
error: {
code: "target_unavailable",
category: "unsupported_target",
details: { constraint: "wasm_requires_static_inspection" },
},
});
expect(failure.error.remediation.action).toContain(JSON.stringify({ path }));
expect(ajv.validate(inputSchema, input)).toBe(true);
const inspection = await client.callTool({
name,
arguments: input,
});
expect(inspection.isError).toBe(true);
expect(parseMcpToolError(inspection)).toMatchObject({
error: {
code: "capability_unavailable",
details: {
operation: "inspect_wasm_artifact",
reason: expect.stringContaining("REA_WABT_BIN_DIRECTORY"),
},
},
});
await client.ping();
expect(createClient).not.toHaveBeenCalled();
expect(await readFile(path)).toEqual(
Buffer.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0]),
);
});
it("advertises exact valid schemas and records inline WASM interface evidence without a binary target", async () => {
const value = wasmArtifactFixture();
const close = vi.fn(() => Promise.resolve());
@@ -22,30 +98,13 @@ it("advertises exact valid schemas and records inline WASM interface evidence wi
const session = createTestBinarySession(() => {
throw new Error("deep provider must not start");
});
const server = createServer(
{ kind: "session", session },
{ wasmArtifact: service },
);
const client = new Client({ name: "wasm-artifact-contract", version: "1" });
onTestFinished(async () => {
await client.close();
await server.close();
await session.close();
const harness = await createApplicationMcpHarness({
session,
serverOptions: { wasmArtifact: service },
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const advertised = (await client.listTools()).tools.find(
(tool) => tool.name === "inspect_wasm_artifact",
);
if (advertised?.outputSchema === undefined)
throw new Error("WASM interface inspection must publish both schemas");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = advertised.inputSchema;
const outputSchema: Record<string, unknown> = advertised.outputSchema;
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
onTestFinished(harness.close);
const { client } = harness;
const { ajv, inputSchema, outputSchema } = await wasmToolSchemas(client);
expect(ajv.validate(inputSchema, { path: value.artifact.path })).toBe(true);
expect(
ajv.validate(inputSchema, {
@@ -79,6 +138,6 @@ it("advertises exact valid schemas and records inline WASM interface evidence wi
})
).isError,
).toBe(true);
await server.close();
await harness.close();
expect(close).toHaveBeenCalled();
});
@@ -22,9 +22,16 @@ import {
createSystemProcessOwnershipHost,
systemProcessOwnershipHost,
} from "../../../src/process/ProcessOwnershipObservation.js";
import { createDarwinProcessRunTokenReader } from "../../../src/process/DarwinProcessRunTokenReader.js";
import {
createDarwinProcessRunTokenReader,
DarwinProcessOwnershipInspectionError,
} from "../../../src/process/DarwinProcessRunTokenReader.js";
import { execFileOutput } from "../../../src/process/ExecFileOutput.js";
import { normalizeCaptureFailure } from "../../../src/process/capture/ProcessCaptureError.js";
import {
normalizeCaptureFailure,
ProcessCaptureError,
} from "../../../src/process/capture/ProcessCaptureError.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { PlaywrightElectronActiveProvider } from "../../../src/browser/PlaywrightElectronActiveProvider.js";
import { electronActiveObservationInputSchema } from "../../../src/domain/javascript/electronActiveObservation.js";
@@ -168,8 +175,19 @@ it("reports an actionable missing Swift compiler without installing it", async (
}
});
const preparationFailure = async (
reader: ReturnType<typeof createDarwinProcessRunTokenReader>,
): Promise<DarwinProcessOwnershipInspectionError> => {
const cause = await reader.prepare().then(
() => undefined,
(failure: unknown) => failure,
);
expect(cause).toBeInstanceOf(DarwinProcessOwnershipInspectionError);
return cause as DarwinProcessOwnershipInspectionError;
};
it.skipIf(process.platform === "win32")(
"preserves compiler diagnostics when Swift preparation fails",
"reports the compiler exit code with its diagnostics when preparation fails",
async () => {
const directory = await createTestTempDirectory(
"rea-process-token-compiler-failure-test-",
@@ -177,13 +195,136 @@ it.skipIf(process.platform === "win32")(
const executable = join(directory, "failing-xcrun");
await writeFile(
executable,
'#!/usr/bin/env node\nprocess.stderr.write("module cache is not writable\\n"); process.exitCode = 1;\n',
'#!/usr/bin/env node\nprocess.stderr.write("module cache is not writable\\n" + "x".repeat(12000)); process.exitCode = 1;\n',
);
await chmod(executable, 0o755);
const reader = createDarwinProcessRunTokenReader({ xcrun: executable });
try {
await expect(reader.prepare()).rejects.toThrow(
/compilation failed.*module cache is not writable/su,
const failure = await preparationFailure(reader);
expect(failure.compilerOutcome).toMatchObject({
outcome: "exited",
code: 1,
signal: null,
stderr: expect.stringMatching(/^module cache is not writable\n/u),
stderrTruncated: true,
killed: false,
});
expect(failure.message).toContain(
"(compiler result: exit code 1): module cache is not writable",
);
expect(failure.message).toContain("[diagnostics truncated]");
const normalized = normalizeCaptureFailure(failure, undefined);
if (!(normalized instanceof ProcessCaptureError))
throw new Error("Expected a normalized process capture error");
expect(projectAnalysisError(normalized)).toMatchObject({
code: "process_capture_failed",
details: {
execution_failure: expect.stringContaining(
"compiler result: exit code 1",
),
captured_output: {
stderr: expect.stringContaining("module cache is not writable"),
exit_code: 1,
truncated: true,
},
},
});
} finally {
await reader.close();
}
},
);
it.skipIf(process.platform === "win32")(
"reports compiler diagnostics captured before the compilation deadline",
async () => {
const directory = await createTestTempDirectory(
"rea-process-token-compiler-timeout-test-",
);
const executable = join(directory, "hanging-xcrun");
await writeFile(
executable,
'#!/usr/bin/env node\nprocess.stderr.write("error: PCH was compiled with module cache path that differs\\n", () => { setInterval(() => {}, 1000); });\n',
);
await chmod(executable, 0o755);
const reader = createDarwinProcessRunTokenReader({
xcrun: executable,
// Headroom for the child interpreter's cold start under suite load.
compileTimeoutMs: 3_000,
});
try {
await expect(preparationFailure(reader)).resolves.toMatchObject({
message:
"macOS process ownership helper compilation failed via xcrun (compiler result: timed out after 3000 ms): error: PCH was compiled with module cache path that differs",
compilerOutcome: {
outcome: "timed_out",
code: "ETIMEDOUT",
timeoutMs: 3_000,
},
});
} finally {
await reader.close();
}
},
);
it.skipIf(process.platform === "win32")(
"reports the stop signal when the compiler dies without an exit code",
async () => {
const directory = await createTestTempDirectory(
"rea-process-token-compiler-signal-test-",
);
const executable = join(directory, "segv-xcrun");
await writeFile(
executable,
'#!/usr/bin/env node\nprocess.stderr.write("fatal: segmentation fault during type checking\\n");\nprocess.kill(process.pid, "SIGSEGV");\n',
);
await chmod(executable, 0o755);
const reader = createDarwinProcessRunTokenReader({ xcrun: executable });
try {
await expect(preparationFailure(reader)).resolves.toMatchObject({
message:
"macOS process ownership helper compilation failed via xcrun (compiler result: stopped by signal SIGSEGV): fatal: segmentation fault during type checking",
compilerOutcome: {
outcome: "signaled",
code: null,
signal: "SIGSEGV",
},
});
} finally {
await reader.close();
}
},
);
it.skipIf(process.platform === "win32")(
"bounds embedded compiler diagnostics and marks the truncation",
async () => {
const directory = await createTestTempDirectory(
"rea-process-token-compiler-verbose-test-",
);
const executable = join(directory, "verbose-xcrun");
const diagnostic = "x".repeat(600);
await writeFile(
executable,
`#!/usr/bin/env node\nprocess.stderr.write(${JSON.stringify(`${diagnostic}\n`)}); process.exitCode = 1;\n`,
);
await chmod(executable, 0o755);
const reader = createDarwinProcessRunTokenReader({ xcrun: executable });
try {
const failure = await preparationFailure(reader);
const outcome = failure.compilerOutcome;
if (outcome === undefined) throw new Error("Expected compiler outcome");
expect(outcome.stderrBytes).toBe(601);
expect(outcome.stderrTruncated).toBe(false);
expect(failure.message).toContain(
`: ${"x".repeat(512)}… [diagnostics truncated]`,
);
const excerpt = failure.message.split("): ")[1]?.split("…")[0];
expect(excerpt).toBe("x".repeat(512));
expect(Buffer.byteLength(excerpt ?? "", "utf8")).toBeLessThanOrEqual(512);
expect(Buffer.byteLength(outcome.stderr, "utf8")).toBeLessThanOrEqual(
8 * 1024,
);
} finally {
await reader.close();
@@ -1,6 +1,5 @@
import { randomUUID } from "node:crypto";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { expect, it } from "vitest";
+35 -1
View File
@@ -277,6 +277,40 @@ it("fetches all class pages rather than silently retaining the first upstream pa
await verifyCleanup(launches);
});
it("preserves duplicate class-name rows and occurrence counts", async () => {
const { service, apk, launches, provider } = await setup(
"duplicate-class-name",
);
const outcome = await service.execute("search_android_classes", {
path: apk,
query: "fixture.Target",
});
if (!outcome.ok) throw outcome.error;
const result = androidResultSchemas.search_android_classes.parse(
outcome.value.normalized_result,
);
expect(result.total_classes).toBe(402);
expect(result.matches).toEqual(["fixture.Target", "fixture.Target"]);
expect(result.duplicate_names).toEqual([
{ name: "fixture.Target", occurrences: 2 },
]);
const full = await service.execute("search_android_classes", {
path: apk,
query: "",
});
if (!full.ok) throw full.error;
const fullResult = androidResultSchemas.search_android_classes.parse(
full.value.normalized_result,
);
expect(fullResult.total_classes).toBe(402);
expect(fullResult.matches).toHaveLength(402);
expect(fullResult.duplicate_names).toEqual([
{ name: "fixture.Target", occurrences: 2 },
]);
await provider.close();
await verifyCleanup(launches);
});
it("exposes overload candidates and executes only an explicitly selected ambiguous method", async () => {
const { service, apk, launches, provider } = await setup();
const input = {
@@ -504,7 +538,7 @@ it("rejects bytes changed after target admission without launching an engine", a
});
it("retains an uncertain workspace and blocks later launches after cleanup cannot be verified", async () => {
const { service, apk, launches, provider } = await setup("cleanup-failure");
const { service, apk, launches } = await setup("cleanup-failure");
const outcome = await service.execute("inspect_android_package", {
path: apk,
});
@@ -1,12 +1,5 @@
import { execFile } from "node:child_process";
import {
access,
mkdir,
readFile,
readdir,
rm,
writeFile,
} from "node:fs/promises";
import { access, mkdir, readFile, readdir, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { promisify } from "node:util";
import { pathToFileURL } from "node:url";
@@ -4,15 +4,16 @@ import { pathToFileURL } from "node:url";
import { describe, expect } from "vitest";
import { bundleMcpRuntime } from "../../../scripts/bundle-mcp-runtime.mjs";
import { bundleRuntime } from "../../../scripts/bundle-runtime.mjs";
import { workspaceCliTest } from "../../support/cli/workspaceCliFixture.js";
describe("MCP runtime bundle", () => {
describe("CLI and MCP runtime bundles", () => {
workspaceCliTest(
"preserves module locations, lazy side effects, package resolution and worker entrypoints",
async ({ processes, workspace }) => {
await workspace.mkdir("dist/provider");
await workspace.mkdir("dist/composition");
await workspace.mkdir("dist/cli");
await workspace.mkdir("bridge");
await workspace.mkdir("node_modules/external-probe");
const files = {
@@ -45,8 +46,17 @@ globalThis.effects.push('lazy');
export const lazyUrl = import.meta.url;`,
"dist/composition/javascriptAnalysisWorkerProcess.js":
'process.stdout.write("worker-entry");',
"dist/generatedPackageMetadata.js":
'export const generatedPackageMetadata = { version: "1.0.0" };',
"dist/cli.js": 'export { facts, run } from "./main.js";',
"dist/cliOutput.js": 'export { facts } from "./provider/probe λ.js";',
"dist/cli/streamedJsonOutput.js":
'export { facts } from "../provider/probe λ.js";',
"dist/mcpDoctor.js": 'export { run } from "./main.js";',
"dist/main.js": `
import { facts } from './provider/probe λ.js';
import { generatedPackageMetadata } from './generatedPackageMetadata.js';
export { facts };
import { execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
globalThis.effects.push('main');
@@ -54,7 +64,7 @@ export const run = async () => {
const beforeLazy = [...globalThis.effects];
const { lazyUrl } = await import('./lazy.js');
return {
...facts, beforeLazy, afterLazy: globalThis.effects, lazyUrl,
...facts, version: generatedPackageMetadata.version, beforeLazy, afterLazy: globalThis.effects, lazyUrl,
workerOutput: execFileSync(process.execPath, [fileURLToPath(facts.worker)], { encoding: 'utf8' })
};
};`,
@@ -76,9 +86,23 @@ export const run = async () => {
return JSON.parse(result.stdout) as unknown;
};
const original = await invoke("dist/main.js");
await bundleMcpRuntime(workspace.root);
await bundleRuntime(workspace.root);
const bundled = await invoke("dist/mcp/main.js");
expect(bundled).toEqual(original);
expect(await invoke("dist/cli-runtime/cli.js")).toEqual(
await invoke("dist/cli.js"),
);
const cliDirectory = join(workspace.root, "dist/cli-runtime");
const identity = await processes.run(
process.execPath,
[
"--input-type=module",
"--eval",
`const { facts } = await import(${JSON.stringify(pathToFileURL(join(cliDirectory, "cli.js")).href)}); const output = await import(${JSON.stringify(pathToFileURL(join(cliDirectory, "cliOutput.js")).href)}); const streamed = await import(${JSON.stringify(pathToFileURL(join(cliDirectory, "streamedJsonOutput.js")).href)}); process.stdout.write(JSON.stringify(facts === output.facts && facts === streamed.facts));`,
],
{ cwd: workspace.root },
);
expect(identity).toMatchObject({ exitCode: 0, stdout: "true" });
expect(bundled).toMatchObject({
resource: "bridge resource\n",
external: "external",
@@ -93,6 +117,14 @@ export const run = async () => {
expect(
(await readdir(join(workspace.root, "dist/mcp"))).length,
).toBeGreaterThan(1);
await workspace.write(
"dist/generatedPackageMetadata.js",
'export const generatedPackageMetadata = { version: "0.0.0" };',
);
const previousRelease = await invoke("dist/main.js");
expect(previousRelease).toMatchObject({ version: "0.0.0" });
expect(await invoke("dist/mcp/main.js")).toEqual(previousRelease);
expect(await invoke("dist/cli-runtime/cli.js")).toEqual(previousRelease);
},
);
@@ -100,18 +132,26 @@ export const run = async () => {
"rejects module-relative resolution and unknown import metadata during the build",
async ({ workspace }) => {
await workspace.mkdir("dist");
await workspace.mkdir("dist/cli");
await workspace.write("package.json", '{"type":"module"}');
for (const expression of [
"import.meta.resolve('./worker.js')",
"import.meta.env",
]) {
await workspace.write(
"dist/main.js",
`export const value = ${expression};`,
);
await expect(bundleMcpRuntime(workspace.root)).rejects.toThrow(
"Unsupported import.meta use in MCP bundle",
);
for (const path of [
"dist/cliOutput.js",
"dist/cli/streamedJsonOutput.js",
"dist/mcpDoctor.js",
])
await workspace.write(path, "export {};\n");
for (const entry of ["dist/main.js", "dist/cli.js"]) {
for (const expression of [
"import.meta.resolve('./worker.js')",
"import.meta.env",
]) {
await workspace.write("dist/main.js", "export {};\n");
await workspace.write("dist/cli.js", "export {};\n");
await workspace.write(entry, `export const value = ${expression};`);
await expect(bundleRuntime(workspace.root)).rejects.toThrow(
"Unsupported import.meta use in runtime bundle",
);
}
}
},
);
@@ -40,34 +40,41 @@ it("shows the callee edges of an ARM64 procedure in the call graph", async () =>
result.value,
"the root lists both observed callees instead of an empty observed list",
).toMatchObject({
"0": [
{
address: "0x1000",
status: "ok",
calls: ["0x2000", "0x3000"],
limitations: expect.arrayContaining([
"This relationship read does not establish calls to targets IDA does not recognize as functions; imports and other non-function call targets remain unknown.",
]),
},
],
"1": [
{
address: "0x2000",
status: "ok",
calls: [],
limitations: expect.arrayContaining([
"This relationship read does not establish calls to targets IDA does not recognize as functions; imports and other non-function call targets remain unknown.",
]),
},
{
address: "0x3000",
status: "ok",
calls: [],
limitations: expect.arrayContaining([
"This relationship read does not establish calls to targets IDA does not recognize as functions; imports and other non-function call targets remain unknown.",
]),
},
],
graph: {
"0": [
{
address: "0x1000",
status: "ok",
calls: ["0x2000", "0x3000"],
limitations: expect.arrayContaining([
"This relationship read does not establish calls to targets IDA does not recognize as functions; imports and other non-function call targets remain unknown.",
]),
},
],
"1": [
{
address: "0x2000",
status: "ok",
calls: [],
limitations: expect.arrayContaining([
"This relationship read does not establish calls to targets IDA does not recognize as functions; imports and other non-function call targets remain unknown.",
]),
},
{
address: "0x3000",
status: "ok",
calls: [],
limitations: expect.arrayContaining([
"This relationship read does not establish calls to targets IDA does not recognize as functions; imports and other non-function call targets remain unknown.",
]),
},
],
},
limitations: expect.arrayContaining([
expect.stringContaining(
"Provider version identifies the REA IDA adapter.",
),
]),
});
expect(
requestedRoots(producer),
@@ -122,13 +129,16 @@ it("traverses every ARM64 callee in a call path without a goal and records no fa
{ source_address: "0x1000", target_address: "0x3000" },
],
failures: [],
truncated: true,
truncated: false,
limitations: expect.arrayContaining([
"This relationship read does not establish calls to targets IDA does not recognize as functions; imports and other non-function call targets remain unknown.",
]),
residual_unknowns: expect.arrayContaining([
expect.stringContaining("Call relationships for 0x1000 are limited:"),
]),
residual_unknowns: [],
relationship_coverage: {
"0x1000": { status: "complete" },
"0x2000": { status: "complete" },
"0x3000": { status: "complete" },
},
});
expect(
requestedRoots(producer),
@@ -180,15 +190,17 @@ it("preserves missing callgraph coverage through direct, graph, and trace workfl
});
if (!graph.ok) throw graph.error;
expect(graph.value).toMatchObject({
"0": [
{
status: "ok",
calls: [],
limitations: expect.arrayContaining([
expect.stringContaining("callgraph was unavailable"),
]),
},
],
graph: {
"0": [
{
status: "ok",
calls: [],
limitations: expect.arrayContaining([
expect.stringContaining("callgraph was unavailable"),
]),
},
],
},
});
const trace = await application.execute("trace_call_path", {
@@ -203,7 +215,9 @@ it("preserves missing callgraph coverage through direct, graph, and trace workfl
expect.stringContaining("callgraph was unavailable"),
]),
residual_unknowns: expect.arrayContaining([
expect.stringContaining("Call relationships for 0x1000 are limited:"),
expect.stringContaining(
"Call relationship coverage is unknown for 0x1000:",
),
]),
});
expect(
@@ -234,13 +248,18 @@ it("records a failed ARM64 call graph read as the node's error, not as a complet
result.value,
"the transport-truncated graph is a recorded failure and no callee list is invented",
).toEqual({
"0": [
{
address: "0x1000",
status: "error",
error: expect.objectContaining({ code: "unreadable_output" }),
},
],
graph: {
"0": [
{
address: "0x1000",
status: "error",
error: expect.objectContaining({ code: "unreadable_output" }),
},
],
},
limitations: expect.arrayContaining([
expect.stringContaining("Live results are never replayed"),
]),
});
} finally {
expect((await client.close()).ok).toBe(true);
@@ -268,12 +287,15 @@ it("preserves an explicit root cap below the edge limit through every relationsh
});
if (!graph.ok) throw graph.error;
expect(graph.value).toMatchObject({
"0": [
{
calls: ["0x2000"],
limitations: expect.arrayContaining([limitation]),
},
],
graph: {
"0": [
{
calls: ["0x2000"],
limitations: expect.arrayContaining([limitation]),
},
],
},
limitations: expect.arrayContaining([limitation]),
});
const trace = await application.execute("trace_call_path", {
start: "main",
@@ -58,14 +58,17 @@ describe("provider-derived selectors in IDA composed workflows", () => {
result.value,
"the resolved root stays ok and only the derived node carries the producer fault",
).toMatchObject({
"0": [{ address: "0x1000", status: "ok" }],
"1": [
{
address: "0x2000",
status: "error",
error: { code: "unreadable_output" },
},
],
graph: {
"0": [{ address: "0x1000", status: "ok" }],
"1": [
{
address: "0x2000",
status: "error",
error: { code: "unreadable_output" },
},
],
},
limitations: expect.any(Array),
});
} finally {
expect((await client.close()).ok).toBe(true);
@@ -459,9 +459,83 @@ describe("managed member comparison of ambiguous undecoded signatures", () => {
});
});
const inspect = (bytes: Buffer, path: string) => {
describe("managed member comparison of selected types", () => {
it("keeps members outside the other side's selection unknown", () => {
const left = inspect(buildManagedPeFixture(), "/tmp/left-all.dll");
const right = inspect(buildManagedPeFixture(), "/tmp/right-selected.dll", [
"Missing.Type",
]);
const result = compareManagedMembers(
{ evidenceId: left.evidenceId, result: left.result },
{ evidenceId: right.evidenceId, result: right.result },
);
expect(result.summary).toMatchObject({ added: 0, removed: 0, unknown: 2 });
expect(result.methods[0]).toMatchObject({
status: "unknown",
left: { token: "0x06000001" },
right: null,
});
expect(result.coverage.status).toBe("partial");
expect(result.limitations).toContain(
"The observations select different declaring types; a member outside the other side's selection is unknown, not added or removed.",
);
});
it("does not remap members across types neither side observed", () => {
const left = inspect(buildManagedPeFixture(), "/tmp/left-a.dll", [
"Fixture.Program",
]);
const right = inspect(
buildManagedPeFixture({
mvid: Buffer.from("00112233445566778899aabbccddeefe", "hex"),
typeName: "A",
typeNamespace: "X",
}),
"/tmp/right-b.dll",
["X.A"],
);
const result = compareManagedMembers(
{ evidenceId: left.evidenceId, result: left.result },
{ evidenceId: right.evidenceId, result: right.result },
);
expect(result.matching.exact_il_signature).toBe(0);
expect(result.summary).toMatchObject({
unchanged: 0,
added: 0,
removed: 0,
unknown: 4,
});
});
it("compares two identical selections within those types", () => {
const left = inspect(buildManagedPeFixture(), "/tmp/left-sel.dll", [
"Fixture.Program",
]);
const right = inspect(buildManagedPeFixture(), "/tmp/right-sel.dll", [
"Fixture.Program",
]);
const result = compareManagedMembers(
{ evidenceId: left.evidenceId, result: left.result },
{ evidenceId: right.evidenceId, result: right.result },
);
expect(result.methods[0]).toMatchObject({ status: "unchanged" });
expect(result.coverage.status).toBe("complete-within-inputs");
expect(result.limitations).toContain(
"Both observations cover only the selected declaring types (Fixture.Program); member totals and statuses describe those types, not the whole assembly.",
);
});
});
const inspect = (bytes: Buffer, path: string, typeNames?: string[]) => {
const target = managedPeFixtureTarget(bytes, path);
const result = inspectManagedMembersBytes(bytes, target);
const result = inspectManagedMembersBytes(
bytes,
target,
typeNames === undefined ? {} : { typeNames },
);
return {
result,
evidenceId: `ev_${hash(Buffer.from(path))}`,
@@ -0,0 +1,55 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { parseBinaryTarget } from "../../../../src/application/BinaryTargetResolver.js";
import { buildManagedPeFixture } from "../../../../src/dotnet/ManagedPe.fixture.js";
import { ManagedStaticProvider } from "../../../../src/dotnet/ManagedStaticProvider.js";
// ReadyToRun images compiled for a non-Windows OS store the machine XORed with
// IMAGE_FILE_MACHINE_NATIVE_OS_OVERRIDE (dotnet/runtime src/coreclr/inc/pedecoder.h).
it.each([
["Linux x86", 0x014c ^ 0x7b79, 0, "x86"],
["Linux ARM", 0x01c4 ^ 0x7b79, 0, "arm"],
["Apple ARM", 0x01c4 ^ 0x4644, 0, "arm"],
["FreeBSD x86", 0x014c ^ 0xadc4, 0, "x86"],
] as const)(
"opens and inspects the %s ReadyToRun machine through the public path",
async (_label, machine, cliFlags, architecture) => {
const bytes = buildManagedPeFixture({ cliFlags, readyToRun: true });
bytes.writeUInt16LE(machine, bytes.readUInt32LE(0x3c) + 4);
const directory = await createTestTempDirectory("rea-managed-os-machine-");
const path = join(directory, "fixture.dll");
await writeFile(path, bytes);
const parsed = await parseBinaryTarget(path);
if (!parsed.ok) throw parsed.error;
expect(parsed.value).toMatchObject({
kind: "executable",
format: "pe",
architecture,
managed: true,
});
const client = new ManagedStaticProvider().createClient(parsed.value);
try {
for (const operation of [
"inspect_managed_artifact",
"inspect_managed_members",
"inspect_managed_native_boundaries",
] as const) {
const observed = await client.execute(operation, {});
if (!observed.ok) throw observed.error;
expect(observed.value.result).toMatchObject({
module: { name: "Fixture.dll" },
});
}
const artifact = await client.execute("inspect_managed_artifact", {});
if (!artifact.ok) throw artifact.error;
expect(artifact.value.result).toMatchObject({
pe: { machine, architecture },
classification: { managed_architecture: architecture },
});
} finally {
await client.close();
}
},
);
@@ -1,3 +1,4 @@
import { createHash } from "node:crypto";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -142,6 +143,57 @@ const asManagedMemberResult = (execution: AnalysisExecution) =>
const asManagedNativeBoundaryResult = (execution: AnalysisExecution) =>
managedNativeBoundaryInspectionSchema.parse(execution.result);
it("preserves custom attribute value evidence through the filesystem provider when its constructor is invalid", async () => {
const directory = await createTestTempDirectory("rea-managed-attribute-");
const path = join(directory, "fixture.exe");
await writeFile(path, buildManagedPeFixture({ customAttributeTypeRaw: 19 }));
const parsed = await parseBinaryTarget(path);
if (!parsed.ok) throw parsed.error;
const frameworkText = Buffer.from(".NETCoreApp,Version=v8.0", "utf8");
const attributeValue = Buffer.concat([
Buffer.from([1, 0, frameworkText.length]),
frameworkText,
Buffer.alloc(2),
]);
const client = new ManagedStaticProvider().createClient(parsed.value);
try {
const execution = await client.execute("inspect_managed_artifact", {});
if (!execution.ok) throw execution.error;
const result = asManagedResult(execution.value);
expect(result).toMatchObject({
attributes: [
{
parent_token: "0x20000001",
constructor_token: null,
type_name: null,
value_length: attributeValue.length,
value_sha256: createHash("sha256")
.update(attributeValue)
.digest("hex"),
token: "0x0c000001",
},
],
coverage: {
state: "partial",
},
});
const attribute = result.attributes[0];
if (attribute === undefined) throw new Error("Fixture omitted attribute");
expect(result.coverage.issues).toEqual([
expect.objectContaining({
code: "invalid-row",
scope: "metadata.CustomAttribute:0x0c000001",
offset: attribute.row_offset + 2,
detail:
"CustomAttribute constructor coded index 0x13 is invalid: coded index selects row 2 in table 10, which has 1 rows",
}),
]);
} finally {
await client.close();
}
});
it("retains U+FEFF metadata through the filesystem target and provider", async () => {
const directory = await createTestTempDirectory("rea-managed-bom-");
const path = join(directory, "fixture.exe");
@@ -291,3 +291,61 @@ describe("artifact Mach-O arm64e variant slices", () => {
},
);
});
// macOS 26 lipo leaves capabilities blank, even for a LIB64 x86_64 slice.
describe("artifact Mach-O LIB64 slices", () => {
const LIB64 = { type: 0x01000007, subtype: 0x80000003 } as const;
const lib64Slices = async (x86Subtype: string) => {
const root = await createTestTempDirectory("rea-slices-lib64-");
const binary = join(root, "fat");
const x86 = machoImage({ cpu: LIB64 });
const arm = machoImage({ cpu: CPU.arm64 });
await writeFile(
binary,
fatImage([
{ cpu: LIB64, bytes: x86 },
{ cpu: CPU.arm64, bytes: arm },
]),
);
const reader = new MachOSliceArtifactReader(
binary,
{},
lipoRunner(
[
"architecture x86_64",
" cputype CPU_TYPE_X86_64",
` cpusubtype ${x86Subtype}`,
" capabilities ",
" offset 4096",
` size ${String(x86.length)}`,
" align 2^12 (4096)",
"architecture arm64",
" cputype CPU_TYPE_ARM64",
" cpusubtype CPU_SUBTYPE_ARM64_ALL",
" capabilities ",
" offset 8192",
` size ${String(arm.length)}`,
" align 2^12 (4096)",
"",
].join("\n"),
),
);
onTestFinished(() => reader.close());
const entries = [];
for await (const entry of reader.entries()) entries.push(entry);
return entries.map(({ path, byteOffset }) => [path, byteOffset]);
};
it("matches an x86_64 LIB64 slice whose lipo capabilities are blank", async () => {
expect(await lib64Slices("CPU_SUBTYPE_X86_ALL")).toEqual([
["slices/x86_64", 4096],
["slices/arm64", 8192],
]);
});
it("still rejects a blank-capability subtype that names other bits", async () => {
await expect(lib64Slices("CPU_SUBTYPE_X86_64_H")).rejects.toMatchObject({
reason: "integrity",
});
});
});
@@ -0,0 +1,73 @@
import { access, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it, vi } from "vitest";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
import { ArtifactReaderFailure } from "../../../../src/artifacts/ArtifactReader.js";
import { artifactExtractionExecutionSchema } from "../../../../src/contracts/artifactToolContracts.js";
import type { BinaryTarget } from "../../../../src/domain/binaryTargetTypes.js";
const sliceReader = vi.hoisted(() => ({
reached: vi.fn(),
failure: null as unknown,
}));
vi.mock("../../../../src/artifacts/MachOSliceArtifactReader.js", () => ({
MachOSliceArtifactReader: class {
async *entries() {
sliceReader.reached();
yield* [];
throw sliceReader.failure;
}
close() {
return Promise.resolve();
}
provenance() {
return [];
}
},
}));
it("routes universal Mach-O extraction through slice inventory", async () => {
sliceReader.reached.mockClear();
sliceReader.failure = new ArtifactReaderFailure(
"unavailable",
"fixture reached universal slice inventory",
);
const root = await createTestTempDirectory("rea-extract-universal-");
const image = join(root, "Universal");
await writeFile(image, Buffer.from([0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 0]));
const output = join(root, "output");
const result = await new ArtifactProvider(process.env)
.createClient(universalTarget(image))
.execute(
"extract_artifact",
artifactExtractionExecutionSchema.parse({ output_root: output }),
);
expect(result).toMatchObject({
ok: false,
error: {
_tag: "ArtifactOperationError",
reason: "unavailable",
detail: "fixture reached universal slice inventory",
},
});
expect(sliceReader.reached).toHaveBeenCalledOnce();
await expect(access(output)).rejects.toThrow();
});
const universalTarget = (path: string): BinaryTarget => ({
path,
sourcePath: path,
sha256: "0".repeat(64),
kind: "executable",
format: "mach-o-universal",
architecture: "arm64",
availableArchitectures: ["arm64"],
});
@@ -95,6 +95,74 @@ it("retains empty dylib-use options and rejects missing or ambiguous encoding fi
}
});
it.each(["vmaddr", "vmsize", "uuid", "entryoff"])(
"rejects a required %s label truncated before its value",
async (key) => {
const raw = await nativeFixture("otool-load.txt");
const truncated = raw.replace(
new RegExp(`^(\\s*${key})\\s+\\S.*$`, "mu"),
"$1",
);
expect(truncated).not.toBe(raw);
expect(() => parseOtoolLoadCommands(raw)).not.toThrow();
// Only the empty dylib-use options row may omit its value.
expect(() => parseOtoolLoadCommands(truncated)).toThrow(
`otool field ${key} has no value`,
);
},
);
it("retains the unnamed segment of a Mach-O object file", () => {
// Captured from `otool -l` on a clang `-c` object: MH_OBJECT sections live
// in one segment whose segname is empty, printed as a bare label.
const objectSegment = [
"Load command 0",
" cmd LC_SEGMENT_64",
" cmdsize 152",
" segname ",
" vmaddr 0x0000000000000000",
" vmsize 0x0000000000000018",
" fileoff 392",
" filesize 24",
" maxprot 0x00000007",
" initprot 0x00000007",
" nsects 1",
" flags 0x0",
"Section",
" sectname __text",
" segname __TEXT",
" addr 0x0000000000000000",
" size 0x0000000000000018",
" offset 392",
" align 2^2 (4)",
" reloff 0",
" nreloc 0",
" flags 0x80000400",
" reserved1 0",
" reserved2 0",
"",
].join("\n");
const load = parseOtoolLoadCommands(withOtoolMachHeader(objectSegment));
expect(load.segments).toMatchObject([
{ name: "unknown", sections: [{ segment: "__TEXT", name: "__text" }] },
]);
// An all-NUL section name is printed the same way and stays "unknown".
expect(
parseOtoolLoadCommands(
withOtoolMachHeader(
objectSegment.replace(" sectname __text", " sectname "),
),
).segments,
).toMatchObject([{ sections: [{ segment: "__TEXT", name: "unknown" }] }]);
expect(() =>
parseOtoolLoadCommands(
withOtoolMachHeader(
objectSegment.replace(" vmaddr 0x0000000000000000", " vmaddr"),
),
),
).toThrow("otool field vmaddr has no value");
});
it("preserves dependency install names that begin with the word stamp", () => {
const load = parseOtoolLoadCommands(
withOtoolMachHeader(
@@ -9,6 +9,78 @@ import {
withOtoolMachHeader,
} from "../../../fixtures/nativeCommands.js";
it("retains the delayed dependency in the complete real framed otool output", async () => {
const output = await nativeFixture("otool-dylib-use.txt");
const runner = new NativeFixtureRunner({ "otool:-h": output });
const client = new NativeMacOSProvider({}, runner, "darwin").createClient(
nativeMachoTarget("/owned/fixture"),
);
const result = await client.execute("inspect_macho", {});
if (!result.ok) throw result.error;
expect(result.value.result).toMatchObject({
load_commands: {
items: expect.arrayContaining([
expect.objectContaining({
index: 16,
kind: "LC_LOAD_DYLIB",
fields: expect.objectContaining({ options: "delay-init" }),
}),
]),
},
dependencies: {
items: expect.arrayContaining([
expect.objectContaining({
path: "@rpath/libdelay.dylib",
current_version: "0.0.0",
compatibility_version: "1.0.0",
}),
]),
},
});
expect(parseOtoolLoadCommands(output).commands).toHaveLength(23);
});
it("rejects a repeated options field even when the duplicate has no value", async () => {
const output = (await nativeFixture("otool-dylib-use.txt")).replace(
" options delay-init ",
" options delay-init\n options",
);
expect(() => parseOtoolLoadCommands(output)).toThrow(/otool/u);
});
it.each([
"vmaddr",
"vmsize",
"uuid",
"entryoff",
"addr",
"current version",
"time stamp",
])(
"rejects a required %s label with no value and retains its producer output",
async (field) => {
const original = await nativeFixture("otool-load.txt");
const output = original.replace(
new RegExp(`^([ \\t]*${field})[ \\t]+\\S[^\\n]*$`, "mu"),
"$1",
);
if (output === original) throw new Error(`Fixture has no ${field} value`);
const runner = new NativeFixtureRunner({ "otool:-h": output });
const client = new NativeMacOSProvider({}, runner, "darwin").createClient(
nativeMachoTarget("/owned/fixture"),
);
const result = await client.execute("inspect_macho", {});
if (result.ok) throw new Error(`Expected missing ${field} value rejection`);
expect(result.error).toMatchObject({
_tag: "AnalysisOutputError",
capturedOutput: { stdout: output, stderr: "", truncated: false },
});
expect(result.error.cause).toMatchObject({
message: expect.stringContaining(field),
});
},
);
it("collects the actual Mach header alongside the native load commands", async () => {
// The provider always invokes `otool -h -l`, which the runner resolves
// via the "otool:-h" key; no bare `otool` override is needed.
@@ -32,6 +32,10 @@ it("does not attribute the first universal slice's UUID and segments to the sele
if (!result.ok) throw result.error;
expect(result.value.result).toMatchObject({
uuid: "01234567-89AB-CDEF-0123-456789ABCDEF",
selected_architecture: {
name: "arm64",
container_file_offset: 32768,
},
architectures: { total: 2 },
});
const normalized = inspectMachoSchema.parse(result.value.result);
@@ -125,16 +129,19 @@ it("projects universal segment evidence into the selected slice's container offs
start: 32768,
end: 40960,
});
expect(result.value.locations).toContainEqual({
kind: "file-offset",
offset: 36864,
});
expect(result.value.locations).not.toContainEqual({
kind: "file-offset-range",
start: 0,
end: 8192,
});
// The normalized tool field remains slice-relative; only evidence is projected.
expect(
inspectMachoSchema.parse(result.value.result).segments.items[0]
?.file_offset,
).toBe(0);
// Normalized tool fields keep their slice-relative meaning.
const normalized = inspectMachoSchema.parse(result.value.result);
expect(normalized.segments.items[0]?.file_offset).toBe(0);
expect(normalized.entrypoints.items[0]?.file_offset).toBe(4096);
});
it.each([
@@ -168,6 +175,12 @@ it.each([
start: offset,
end: offset + 8192,
});
expect(result.value.result).toMatchObject({
selected_architecture: {
name: "arm64",
container_file_offset: offset,
},
});
if (offset > 0)
expect(result.value.locations).not.toContainEqual({
kind: "file-offset-range",
@@ -206,7 +219,10 @@ it.each([
end: 8192,
});
expect(result.value.limitations).toContain(
"Segment evidence file offsets are unavailable because the selected Mach-O slice's container offset was not observed.",
"The selected Mach-O slice's container file offset was not observed; slice-based evidence locations are unavailable.",
);
expect(result.value.result).toMatchObject({
selected_architecture: { container_file_offset: null },
});
},
);
@@ -597,10 +597,19 @@ describe("provider health and availability", () => {
expect(session.status()).toMatchObject({
capabilities: expect.arrayContaining([
expect.objectContaining({
operation: "address_name",
available: false,
reason:
"ProviderAdapterError: Provider fixture adapter failed during address_name",
provider: {
id: "fixture",
name: "Fixture analysis provider",
version: "1",
},
groups: expect.arrayContaining([
expect.objectContaining({
operations: expect.arrayContaining(["address_name"]),
available: false,
reason:
"ProviderAdapterError: Provider fixture adapter failed during address_name",
}),
]),
}),
]),
});
@@ -609,9 +618,18 @@ describe("provider health and availability", () => {
expect(session.status()).toMatchObject({
capabilities: expect.arrayContaining([
expect.objectContaining({
operation: "address_name",
available: true,
reason: null,
provider: {
id: "fixture",
name: "Fixture analysis provider",
version: "1",
},
groups: expect.arrayContaining([
expect.objectContaining({
operations: expect.arrayContaining(["address_name"]),
available: true,
reason: null,
}),
]),
}),
]),
});
@@ -657,9 +675,18 @@ describe("provider health and availability", () => {
expect(session.status()).toMatchObject({
capabilities: expect.arrayContaining([
expect.objectContaining({
operation: "address_name",
available: true,
reason: null,
provider: {
id: "fixture",
name: "Fixture analysis provider",
version: "1",
},
groups: expect.arrayContaining([
expect.objectContaining({
operations: expect.arrayContaining(["address_name"]),
available: true,
reason: null,
}),
]),
}),
]),
});
@@ -629,3 +629,55 @@ describe("managed application graph coverage", () => {
});
});
});
describe("managed application graph type selection", () => {
const project = (result: Parameters<typeof createEvidence>[2]["result"]) => {
const bytes = buildManagedPeFixture();
const binary = managedPeFixtureTarget(bytes, "/fixture/ManagedInterop.exe");
const projection = projectManagedApplicationGraphEvidence({
managed_members: createEvidence(binary, MANAGED_STATIC_PROVIDER, {
operation: "inspect_managed_members",
parameters: {},
result,
rawResult: null,
limitations: [],
}),
});
if (!projection.ok) throw new Error("projection failed");
return managedApplicationGraphResultSchema.parse(
parseEvidence(projection.value).normalized_result,
);
};
it("marks a graph from selected member inspection partial", () => {
const bytes = buildManagedPeFixture();
const binary = managedPeFixtureTarget(bytes, "/fixture/ManagedInterop.exe");
const selected = inspectManagedMembersBytes(bytes, binary, {
typeNames: ["Fixture.Program"],
});
expect(selected.coverage.state).toBe("complete");
const result = project(selected);
expect(result.coverage).toMatchObject({ status: "partial" });
expect(result.limitations).toContain(
"Managed member Evidence selected only these declaring types: Fixture.Program; type, method, and field nodes of other types are omitted, not absent.",
);
expect(result.limitations).not.toContain(
"At least one supplied managed Evidence record has partial coverage.",
);
});
it("accepts member Evidence recorded before type selection existed", () => {
const bytes = buildManagedPeFixture();
const binary = managedPeFixtureTarget(bytes, "/fixture/ManagedInterop.exe");
const { selection: _selection, ...legacy } = inspectManagedMembersBytes(
bytes,
binary,
);
expect(managedMemberInspectionSchema.parse(legacy).selection).toBeNull();
expect(project(legacy).coverage).toMatchObject({
status: "complete-within-inputs",
});
});
});
@@ -191,6 +191,38 @@ describe("target-bound provider routing", () => {
});
});
describe("selected provider capability provenance", () => {
it("labels selected-provider capabilities with the resolved identity", async () => {
const target = await databaseTarget();
const alpha = deepProvider("alpha");
const session = selectableSession([alpha.provider], auxiliaryProvider());
expect((await session.open(target, { providerId: "alpha" })).ok).toBe(true);
const resolved = { id: "alpha", name: "alpha provider", version: "1" };
const status = bindingStatus(session);
expect(status).toMatchObject({
analysis_provider_binding: { provider: resolved },
analysis_provider_candidates: [
{
provider: resolved,
selected: true,
capabilities: [{ provider: resolved }],
},
],
});
expect(
z
.object({ capabilities: z.array(z.object({ provider: z.unknown() })) })
.parse(status)
.capabilities.map(({ provider }) => provider),
).toEqual([
{ id: "alpha", name: "alpha provider", version: "1" },
{ id: "auxiliary", name: "auxiliary provider", version: "1" },
]);
await session.close();
});
});
interface ClientState {
readonly calls: string[];
closed: boolean;
+24 -1
View File
@@ -1,7 +1,8 @@
/* Relocatable (ET_REL) static-analysis fixture, built with -c -G0 and never
* executed or linked by REA. It exercises the relocations Linux MIPS kernel
* modules use: R_MIPS_26 calls, HI16/LO16 address pairs (one HI16 shared by
* several LO16s, and a LO16 >= 0x8000 that forces a HI16 carry), R_MIPS_32
* several LO16s, two HI16s resolved by one LO16, and a LO16 >= 0x8000 that
* forces a HI16 carry), R_MIPS_32
* data words, and undefined external code and data symbols. powf is an
* external whose float prototype Ghidra's C library archive supplies by name,
* so soft-float builds must give it the soft-float prototype too.
@@ -19,6 +20,8 @@ struct rea_mips_rel_pair rea_mips_rel_pair = { 0x1111, 0x2222 };
/* Places rea_mips_rel_carry past a signed 16-bit low-half boundary. */
char rea_mips_rel_padding[0x8000] = { 1 };
int rea_mips_rel_carry = 0x3333;
/* Referenced only by rea_mips_rel_highs, so its single LO16 stays unique. */
int rea_mips_rel_highs_target = 0x4444;
static const char rea_mips_rel_marker[] = "rea-mips-relocatable-fixture";
__attribute__((noinline)) int rea_mips_rel_leaf(int value)
@@ -45,6 +48,26 @@ __attribute__((noinline)) int rea_mips_rel_scaled(int value)
return value ^ *(int *)&scaled;
}
/* Most GCC-built kernel modules checked contain LO16s that resolve several
* pending HI16s; Clang does not produce that from C. Two %hi and exactly one
* %lo of a symbol nothing else references: any assembler that orders each
* HI16 before a matching LO16 (GNU as, every LLVM version) must emit both
* HI16s ahead of that single LO16, which therefore resolves both.
*/
__asm__(".text\n"
".globl rea_mips_rel_highs\n"
".type rea_mips_rel_highs, @function\n"
".set push\n"
".set noreorder\n"
"rea_mips_rel_highs:\n"
" lui $2, %hi(rea_mips_rel_highs_target)\n"
" lui $3, %hi(rea_mips_rel_highs_target)\n"
" addiu $2, $2, %lo(rea_mips_rel_highs_target)\n"
" jr $31\n"
" move $3, $2\n"
".set pop\n"
".size rea_mips_rel_highs, .-rea_mips_rel_highs\n");
int rea_mips_rel_entry(int value)
{
return rea_mips_rel_leaf(value) + rea_mips_rel_far(value) +
@@ -0,0 +1,22 @@
/* Build an older-style shared image from source without ABI declarations. */
PHDRS {
headers PT_PHDR PHDRS;
text PT_LOAD FILEHDR PHDRS FLAGS(5);
data PT_LOAD FLAGS(6);
dynamic PT_DYNAMIC FLAGS(6);
}
SECTIONS {
. = SIZEOF_HEADERS;
.hash : { *(.hash) } :text
.gnu.hash : { *(.gnu.hash) } :text
.dynsym : { *(.dynsym) } :text
.dynstr : { *(.dynstr) } :text
.rel.dyn : { *(.rel.*) } :text
.text : { *(.text*) } :text
. = ALIGN(0x10000);
.dynamic : { *(.dynamic) } :data :dynamic
.got : { *(.got*) } :data
.data : { *(.data*) } :data
.bss : { *(.bss*) *(COMMON) } :data
/DISCARD/ : { *(.MIPS.abiflags) *(.reginfo) *(.pdr) *(.mdebug.*) *(.comment) *(.note.*) }
}
@@ -0,0 +1,156 @@
import assert from "node:assert/strict";
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
const execute = promisify(execFile);
const source = fileURLToPath(new URL("./mips16-shared.S", import.meta.url));
const linkerScript = fileURLToPath(
new URL("./mips16-recordless.ld", import.meta.url),
);
const hash = (bytes) => createHash("sha256").update(bytes).digest("hex");
/** BYO GNU cross-binutils; generated controls are never executed or byte-patched. */
export async function buildMips16SharedFixture(directory, byteOrder, variant) {
assert(["little", "big"].includes(byteOrder));
assert(
[
"declared",
"recordless",
"symbol-relative",
"section-relocations",
].includes(variant),
);
const assembler = process.env.REA_MIPS_AS ?? "mips-linux-gnu-as";
const linker = process.env.REA_MIPS_LD ?? "mips-linux-gnu-ld";
const endian = byteOrder === "little" ? "-EL" : "-EB";
const prefix = join(directory, `${byteOrder}-${variant}`);
const object = `${prefix}.o`;
const path = `${prefix}.so`;
const assemblerVersion = (
await execute(assembler, ["--version"], { timeout: 10000 })
).stdout;
const linkerVersion = (
await execute(linker, ["--version"], { timeout: 10000 })
).stdout;
assert(
assemblerVersion.includes("GNU assembler"),
"Use GNU's MIPS assembler: other assemblers have different compressed-instruction behavior.",
);
assert(linkerVersion.includes("GNU ld"));
await execute(
assembler,
[
"-32",
"-mips32r2",
endian,
...(variant === "symbol-relative"
? ["--defsym", "REA_MIPS_SYMBOL_RELATIVE=1"]
: []),
source,
"-o",
object,
],
{ timeout: 60000 },
);
await execute(
linker,
[
endian,
"-shared",
...(variant === "section-relocations" ? ["--emit-relocs"] : []),
...(variant === "recordless" ? ["-T", linkerScript] : []),
object,
"-o",
path,
],
{ timeout: 60000 },
);
const bytes = await readFile(path);
const little = byteOrder === "little";
const u16 = (offset) =>
little ? bytes.readUInt16LE(offset) : bytes.readUInt16BE(offset);
const u32 = (offset) =>
little ? bytes.readUInt32LE(offset) : bytes.readUInt32BE(offset);
assert.equal(
bytes.subarray(0, 6).toString("hex"),
little ? "7f454c460101" : "7f454c460102",
);
assert.equal(u16(16), 3);
assert.equal(u16(18), 8);
assert.equal(u32(36), 0x74001007); // noreorder/PIC/CPIC plus o32/MIPS16/MIPS32r2.
const headers = Array.from(
{ length: u16(44) },
(_, i) => u32(28) + i * u16(42),
);
const fileOffset = (address, size) => {
const mappings = headers.filter(
(offset) =>
u32(offset) === 1 &&
address >= u32(offset + 8) &&
address - u32(offset + 8) <= u32(offset + 16) - size,
);
assert.equal(mappings.length, 1);
return u32(mappings[0] + 4) + address - u32(mappings[0] + 8);
};
const readelf = await execute(
process.env.REA_MIPS_READELF ?? "readelf",
["-W", "-h", "-l", "-s", "-r", path],
{ timeout: 10000 },
);
const symbols = {};
for (const name of [
"rea_mips16_probe",
"rea_mips32_probe",
"rea_mips16_pointer",
]) {
const addresses = new Set(
readelf.stdout
.split("\n")
.map((line) => line.trim().split(/\s+/u))
.filter(
(fields) =>
fields[0]?.endsWith(":") === true &&
["FUNC", "OBJECT"].includes(fields[3]) &&
fields.at(-1) === name,
)
.map((fields) => Number.parseInt(fields[1], 16)),
);
assert.equal(addresses.size, 1, `Missing or conflicting ${name}`);
symbols[name] = [...addresses][0];
}
assert.equal(symbols.rea_mips16_probe & 1, 1);
assert.equal(symbols.rea_mips32_probe & 1, 0);
const compressedOffset = fileOffset(symbols.rea_mips16_probe - 1, 8);
assert.equal(
bytes.subarray(compressedOffset, compressedOffset + 8).toString("hex"),
little ? "5a6a8eea074aa0e8" : "6a5aea8e4a07e8a0",
);
const standardOffset = fileOffset(symbols.rea_mips32_probe, 12);
assert.equal(
bytes.subarray(standardOffset, standardOffset + 12).toString("hex"),
little ? "030082240800e00300000000" : "2482000303e0000800000000",
);
const pointerOffset = fileOffset(symbols.rea_mips16_pointer, 4);
const rawPointer = u32(pointerOffset);
if (variant !== "symbol-relative")
assert.equal(rawPointer, symbols.rea_mips16_probe);
return {
path,
sha256: hash(bytes),
byte_order: byteOrder,
variant,
elf_flags: u32(36),
symbols,
raw_pointer: rawPointer,
source_sha256: hash(await readFile(source)),
linker_script_sha256:
variant === "recordless" ? hash(await readFile(linkerScript)) : null,
assembler_version: assemblerVersion.split("\n")[0],
linker_version: linkerVersion.split("\n")[0],
readelf_output: readelf.stdout,
};
}
+41
View File
@@ -0,0 +1,41 @@
/* Source-owned mixed-instruction shared-image control. */
.abicalls
.module fp=xx
.module nooddspreg
.text
.set noreorder
.set nomicromips
.set mips16
.globl rea_mips16_probe
.type rea_mips16_probe, @function
.ent rea_mips16_probe
rea_mips16_probe:
li $2, 90
xor $2, $4
addiu $2, 7
jrc $31
.end rea_mips16_probe
.size rea_mips16_probe, . - rea_mips16_probe
.ifndef REA_MIPS_SYMBOL_RELATIVE
.hidden rea_mips16_probe
.endif
.set nomips16
.globl rea_mips32_probe
.type rea_mips32_probe, @function
.ent rea_mips32_probe
rea_mips32_probe:
addiu $2, $4, 3
jr $31
nop
.end rea_mips32_probe
.size rea_mips32_probe, . - rea_mips32_probe
.data
.balign 4
.globl rea_mips16_pointer
.type rea_mips16_pointer, @object
.size rea_mips16_pointer, 4
rea_mips16_pointer:
.word rea_mips16_probe
.section .note.GNU-stack, "", @progbits
+74
View File
@@ -1,3 +1,5 @@
import { apiSurfaceHar } from "./historicalHar.js";
import { webNetworkCaptureSchema } from "../../src/domain/webNetworkCapture.js";
import { BINARY_LAYOUT_TEST_PROVIDER } from "./binaryDiagnostics/layout.js";
import { binaryLayoutFixture } from "./binaryDiagnostics/layout.js";
import { JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE } from "../../src/contracts/javascript/javascriptRuntimeReconciliationExample.js";
@@ -193,3 +195,75 @@ export const analysisViewJavaScriptEvidence = (
limitations: analysis.limitations,
},
);
/** Capture parent with explicit producer ordinals, including excluded URL values. */
export const analysisViewCaptureFixture = () =>
webNetworkCaptureSchema.parse({
artifact: {
path: "/fixtures/surface.har",
sha256: "c".repeat(64),
bytes: 1024,
},
format: "har",
decoder: { id: "fixture", name: "fixture", version: "1" },
container: {
reported: {},
numeric_literals: [],
redactions: [],
records_pointer: "/log/entries",
},
total_records: 15,
records: [
...apiSurfaceHar().log.entries,
{ request: { method: "GET", url: null } },
{ request: { method: "GET", url: "invalid URL" } },
].map((reported, ordinal) => ({
ordinal,
location: { kind: "json-pointer", pointer: `/log/entries/${ordinal}` },
reported,
binary_fields: [],
numeric_literals: [],
redactions: [],
limitations: [],
})),
runtime_attribution: "unknown",
limitations: [],
});
export const analysisViewCaptureEvidence = (
capture = analysisViewCaptureFixture(),
): Evidence =>
createEvidence(
capture.artifact.sha256 === null
? undefined
: {
path: capture.artifact.path,
sha256: capture.artifact.sha256,
format: "file",
},
{ id: "fixture", name: "fixture", version: "1" },
{
operation: "inspect_web_network_capture",
parameters: { sensitive_value_count: 0 },
result: capture,
confidence: "observed",
},
);
/** A small encoded capture whose many short objects expand during validation. */
export const analysisViewObjectDenseCapture = (headerCount = 100_000) => {
const capture = analysisViewCaptureFixture();
capture.records = capture.records.slice(0, 1);
capture.total_records = 1;
capture.records[0]!.reported = {
request: {
method: "GET",
url: "https://api.test/items/1",
headers: Array.from({ length: headerCount }, () => ({
name: "x",
value: "y",
})),
},
};
return capture;
};
+1
View File
@@ -26,6 +26,7 @@ const classes = [
{ length: generatedCount },
(_, index) => `fixture.Class${index}`,
),
...(mode === "duplicate-class-name" ? ["fixture.Target"] : []),
];
const methods = [
{
+16 -6
View File
@@ -14,12 +14,22 @@ export interface ApplicationMcpHarness {
}
/** Connect application workflows through the production MCP registration. */
export async function createApplicationMcpHarness(): Promise<ApplicationMcpHarness> {
const session = createTestBinarySession(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(resultOk(null)),
}));
const server = createServer({ kind: "session", session });
export async function createApplicationMcpHarness(
options: {
readonly session?: BinarySession;
readonly serverOptions?: Parameters<typeof createServer>[1];
} = {},
): Promise<ApplicationMcpHarness> {
const session =
options.session ??
createTestBinarySession(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(resultOk(null)),
}));
const server = createServer(
{ kind: "session", session },
options.serverOptions,
);
const client = new Client({
name: "application-workflow-test",
version: "1",
+4 -1
View File
@@ -103,9 +103,12 @@ export const createBrowserScenarioProvider = () =>
const composition = pathToFileURL(
root + "/dist/composition/browserScenario.js",
).href;
const bundledComposition = pathToFileURL(
root + "/dist/cli-runtime/composition__browserScenario-",
).href;
registerHooks({
load(url, context, nextLoad) {
if (url === composition)
if (url === composition || url.startsWith(bundledComposition))
return {
format: "module",
shortCircuit: true,
+2
View File
@@ -15,6 +15,8 @@ export const CLIENT_LOCATION_ENVIRONMENT = [
"APPDATA",
"CLAUDE_CONFIG_DIR",
"CODEX_HOME",
"DSH_HOME",
"DSH_AGENTS_HOME",
"COPILOT_HOME",
"GROK_HOME",
"GEMINI_CLI_HOME",
+38
View File
@@ -34,3 +34,41 @@ export const historicalHar = () => ({
],
},
});
/** Request paths exercising only the public API surface format rules. */
export const apiSurfaceHar = () => {
const fixture = historicalHar();
const entry = fixture.log.entries[0]!;
const paths = [
"/users/8812",
"/users/9031",
"/ids/550e8400-e29b-41d4-a716-446655440000",
"/ids/abcdef0123456789abcdef0123456789",
"/dates/2024-02-29",
"/api/v1/users",
"/api/v2/users",
"/api/Report2",
"/api/Report3",
"/api/CreateDocument",
"/api/ListDocuments",
"/ids/abc123",
"/dates/2023-02-29",
];
fixture.log.entries = paths.map((path, index) => ({
...entry,
request: {
...entry.request,
url: `https://api.example.test${path}?not-in-view=value`,
},
response: {
...entry.response,
status: index === 1 ? 404 : 200,
content: {
...entry.response.content,
mimeType:
index === 1 ? "text/plain" : "application/json; charset=utf-8",
},
},
}));
return fixture;
};
+58
View File
@@ -0,0 +1,58 @@
import { createHash } from "node:crypto";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { keyedArchiveResultSchema } from "../../src/domain/apple/keyedArchive.js";
import { createTestTempDirectory } from "./temporaryDirectory.js";
/** Inert XML with producer-equivalent key spellings and unchanged ordinary data. */
export const keyedArchivePrototypeKeyFixture = async () => {
const directory = await createTestTempDirectory("rea-keyed-xml-keys-");
const path = join(directory, "archive.plist");
const bytes = Buffer.from(`<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0"><dict>
<key>$archiver</key><string>NSKeyedArchiver</string>
<key>$version</key><integer>100000</integer>
<key>$objects</key><array><string>$null</string><dict>
<key >__proto__</key ><string>omitted outer value</string>
<key>kept</key><string>a&#13;b&#x85;c&#x2028;d</string>
<key>&#95;&#95;rea_prototype_key__</key><string>ordinary key</string>
<key>nested</key><dict>
<key><![CDATA[__proto__]]><!-- trailing comment --></key>
<string>omitted nested value</string>
<key>value</key><integer>7</integer>
</dict>
</dict></array>
<key>$top</key><dict><key>root</key><dict>
<key>CF$UID</key><integer>1</integer>
</dict></dict>
</dict></plist>`);
await writeFile(path, bytes);
return { path, digest: createHash("sha256").update(bytes).digest("hex") };
};
/** Require original source identity, ordinary values and the exact omission count. */
export const expectKeyedArchivePrototypeKeys = (
value: unknown,
digest: string,
) => {
const result = keyedArchiveResultSchema.parse(value);
expect(result.archive_sha256).toBe(digest);
expect(result.roots).toEqual({ root: { CF$UID: 1 } });
expect(result.objects).toHaveLength(2);
expect(result.objects[1]).toMatchObject({
id: 1,
kind: "dictionary",
value: {
kept: "a\rb\u0085c\u2028d",
__rea_prototype_key__: "ordinary key",
nested: { value: 7 },
},
});
expect(result.limitations).toContain(
"2 dictionary entries keyed __proto__ were omitted because REA results cannot represent that key.",
);
expect(JSON.stringify(result)).not.toContain("omitted outer value");
expect(JSON.stringify(result)).not.toContain("omitted nested value");
};
+14
View File
@@ -0,0 +1,14 @@
# Dylib-use otool capture
`otool-dylib-use.txt` is the actual `otool -h -l` stdout retained by the
[Apple CLI/MCP verification job](https://github.com/morluto/rea/actions/runs/38176410166/job/114579755550).
Only its first filename line was replaced with `/owned/fixture:`.
The source-built application comes from `scripts/verify/apple/macos-bundle.mjs`.
Its 23 load commands include a delayed dependency on `@rpath/libdelay.dylib`.
That dylib-use command has an `options delay-init` row instead of the legacy
`time stamp` row. The other three dylib commands retain the legacy form.
The capture establishes actual producer text, command framing and dependency
fields. Linux replay tests do not establish real macOS provider execution;
the Apple CLI/MCP verification lane supplies that coverage.
+275
View File
@@ -0,0 +1,275 @@
/owned/fixture:
Mach header
magic cputype cpusubtype caps filetype ncmds sizeofcmds flags
0xfeedfacf 16777228 0 0x00 2 23 1632 0x00200085
Load command 0
cmd LC_SEGMENT_64
cmdsize 72
segname __PAGEZERO
vmaddr 0x0000000000000000
vmsize 0x0000000100000000
fileoff 0
filesize 0
maxprot 0x00000000
initprot 0x00000000
nsects 0
flags 0x0
Load command 1
cmd LC_SEGMENT_64
cmdsize 552
segname __TEXT
vmaddr 0x0000000100000000
vmsize 0x0000000000004000
fileoff 0
filesize 16384
maxprot 0x00000005
initprot 0x00000005
nsects 6
flags 0x0
Section
sectname __text
segname __TEXT
addr 0x00000001000006b0
size 0x0000000000000080
offset 1712
align 2^2 (4)
reloff 0
nreloc 0
flags 0x80000400
reserved1 0
reserved2 0
Section
sectname __stubs
segname __TEXT
addr 0x0000000100000730
size 0x0000000000000024
offset 1840
align 2^2 (4)
reloff 0
nreloc 0
flags 0x80000408
reserved1 0 (index into indirect symbol table)
reserved2 12 (size of stubs)
Section
sectname __delay_stubs
segname __TEXT
addr 0x0000000100000754
size 0x0000000000000028
offset 1876
align 2^2 (4)
reloff 0
nreloc 0
flags 0x80000400
reserved1 0
reserved2 0
Section
sectname __delay_helper
segname __TEXT
addr 0x000000010000077c
size 0x00000000000000a0
offset 1916
align 2^2 (4)
reloff 0
nreloc 0
flags 0x80000400
reserved1 0
reserved2 0
Section
sectname __cstring
segname __TEXT
addr 0x000000010000081c
size 0x0000000000000037
offset 2076
align 2^0 (1)
reloff 0
nreloc 0
flags 0x00000002
reserved1 0
reserved2 0
Section
sectname __unwind_info
segname __TEXT
addr 0x0000000100000854
size 0x0000000000000058
offset 2132
align 2^2 (4)
reloff 0
nreloc 0
flags 0x00000000
reserved1 0
reserved2 0
Load command 2
cmd LC_SEGMENT_64
cmdsize 152
segname __DATA_CONST
vmaddr 0x0000000100004000
vmsize 0x0000000000004000
fileoff 16384
filesize 16384
maxprot 0x00000003
initprot 0x00000003
nsects 1
flags 0x10
Section
sectname __got
segname __DATA_CONST
addr 0x0000000100004000
size 0x0000000000000028
offset 16384
align 2^3 (8)
reloff 0
nreloc 0
flags 0x00000006
reserved1 3 (index into indirect symbol table)
reserved2 0
Load command 3
cmd LC_SEGMENT_64
cmdsize 152
segname __DATA
vmaddr 0x0000000100008000
vmsize 0x0000000000004000
fileoff 32768
filesize 16384
maxprot 0x00000003
initprot 0x00000003
nsects 1
flags 0x0
Section
sectname __data
segname __DATA
addr 0x0000000100008000
size 0x0000000000000004
offset 32768
align 2^2 (4)
reloff 0
nreloc 0
flags 0x00000000
reserved1 0
reserved2 0
Load command 4
cmd LC_SEGMENT_64
cmdsize 72
segname __LINKEDIT
vmaddr 0x000000010000c000
vmsize 0x0000000000008000
fileoff 49152
filesize 19280
maxprot 0x00000001
initprot 0x00000001
nsects 0
flags 0x0
Load command 5
cmd LC_DYLD_CHAINED_FIXUPS
cmdsize 16
dataoff 49152
datasize 160
Load command 6
cmd LC_DYLD_EXPORTS_TRIE
cmdsize 16
dataoff 49312
datasize 48
Load command 7
cmd LC_SYMTAB
cmdsize 24
symoff 49368
nsyms 10
stroff 49560
strsize 176
Load command 8
cmd LC_DYSYMTAB
cmdsize 80
ilocalsym 0
nlocalsym 3
iextdefsym 3
nextdefsym 2
iundefsym 5
nundefsym 5
tocoff 0
ntoc 0
modtaboff 0
nmodtab 0
extrefsymoff 0
nextrefsyms 0
indirectsymoff 49528
nindirectsyms 8
extreloff 0
nextrel 0
locreloff 0
nlocrel 0
Load command 9
cmd LC_LOAD_DYLINKER
cmdsize 32
name /usr/lib/dyld (offset 12)
Load command 10
cmd LC_UUID
cmdsize 24
uuid 2F026098-89DD-47C5-A6E4-7C567C2ACD30
Load command 11
cmd LC_BUILD_VERSION
cmdsize 32
platform 1
minos 15.0
sdk 15.5
ntools 1
tool 3
version 1167.5
Load command 12
cmd LC_SOURCE_VERSION
cmdsize 16
version 0.0
Load command 13
cmd LC_MAIN
cmdsize 24
entryoff 1712
stacksize 0
Load command 14
cmd LC_LOAD_DYLIB
cmdsize 64
name @rpath/Core.framework/Versions/A/Core (offset 24)
time stamp 2 Thu Jan 1 00:00:02 1970
current version 0.0.0
compatibility version 0.0.0
Load command 15
cmd LC_LOAD_WEAK_DYLIB
cmdsize 48
name @rpath/libgone.dylib (offset 24)
time stamp 2 Thu Jan 1 00:00:02 1970
current version 0.0.0
compatibility version 0.0.0
Load command 16
cmd LC_LOAD_DYLIB
cmdsize 56
name @rpath/libdelay.dylib (offset 28)
options delay-init
current version 0.0.0
compatibility version 1.0.0
Load command 17
cmd LC_LOAD_DYLIB
cmdsize 56
name /usr/lib/libSystem.B.dylib (offset 24)
time stamp 2 Thu Jan 1 00:00:02 1970
current version 1351.0.0
compatibility version 1.0.0
Load command 18
cmd LC_RPATH
cmdsize 48
path @executable_path/../Overrides (offset 12)
Load command 19
cmd LC_RPATH
cmdsize 48
path @executable_path/../Frameworks (offset 12)
Load command 20
cmd LC_FUNCTION_STARTS
cmdsize 16
dataoff 49360
datasize 8
Load command 21
cmd LC_DATA_IN_CODE
cmdsize 16
dataoff 49368
datasize 0
Load command 22
cmd LC_CODE_SIGNATURE
cmdsize 16
dataoff 49744
datasize 18688
+3 -2
View File
@@ -9,5 +9,6 @@ custom section. The custom payload is retained as an `@custom` annotation in dec
Upstream tag commit: `ff0ef7e0009402740c805a9744c09b05be063e48`.
The separate real-tool verifier generates its own fixtures with caller-supplied
WABT and compares exact producer output against the public CLI/MCP surfaces.
`custom-names.wat` covers newlines, quotes, Unicode, backslashes and embedded
section markers in custom names; objdump displays those names without escaping.
`custom-names.wat` covers newlines, quotes, Unicode, backslashes, embedded
section markers and NUL in custom names; objdump displays those names without
escaping and ends each at its first NUL.
+2 -1
View File
@@ -1,4 +1,5 @@
(module
(@custom "test\0aline" "payload")
(@custom "fake\22\0aSection Details:\0a Type start=0x0000000a end=0x0000000b (size=0x00000001) count: 0\0a\22end" "payload")
(@custom "unicode-\c3\a9\\\t" "payload"))
(@custom "unicode-\c3\a9\\\t" "payload")
(@custom "visible\00hidden" "payload"))
+2 -1
View File
@@ -12,9 +12,10 @@ export const readJavaScriptArtifactFiles = (
reader: ArtifactReader,
snapshot: ArtifactInventorySnapshot,
signal?: AbortSignal,
sourcePaths?: readonly string[],
) =>
withArtifactResourceScope((scope) =>
readOwned(reader, snapshot, scope, signal),
readOwned(reader, snapshot, scope, signal, sourcePaths),
);
/** Run a JavaScript analysis with an awaited, test-owned artifact scope. */