fix(verification): integrate Linux Hopper lane with current contracts

Integrate main ae8051302 while retaining the Linux setup, orphan detection,
launcher restoration and explicit string-recognition coverage corrections.
Move verification guidance to its current owner and use the test-scoped
temporary-directory helper.

The checkout matches all 3,175 exported source-file digests of the tested
candidate. Git stores the Windows captureGhidraLaunch.cmd fixture with LF;
its exported checkout uses CRLF per .gitattributes. It is outside Linux
Hopper execution. No native run is attributed to different runtime bytes.
Real Hopper conformance: 9e7de373-4686-4820-ae48-801e536589b7.
Uninterrupted Linux setup: 93584b53-944b-47cf-a6a4-b0d4ff8a4961.
The exact 97b76aa2 run remains separate: ae4de7ff-dd2a-4c73-88dc-6dbf1ad7c537.

21 focused tests, check, docs:check, four fixtures, discovery, package
verification and pack dry-run passed. Linux native decoded omissions,
macOS/other builds and installed npm artifacts with Hopper remain unverified.

Refs #339, #340
This commit is contained in:
Luis Taffelli
2026-10-12 19:31:20 -03:00
1239 changed files with 146960 additions and 42763 deletions
@@ -0,0 +1,260 @@
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",
type: "commonjs",
}),
"esm/entry.mjs": [
'import "./extensionless";',
'import "./directory";',
'import "./explicit.js";',
'import "./exact.js";',
'import "./actual.cjs?cache=1";',
'import fallback from "empty-main";',
'import "nested-main";',
'import "file-only";',
'import "ancestor-empty";',
'import "ancestor-blocked";',
'import "ancestor-sub/parser";',
"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;",
"esm/actual.cjs": "module.exports = 5;",
"esm/typed.mts": 'import value from "./typed-dep.js"; void value;',
"esm/typed-dep.ts": "export default 42;",
"cjs/entry.cjs": [
'require("./extensionless");',
'require("./directory");',
'require("./feature");',
'require("./feature.cjs");',
'require("./module-only");',
'require("./valid-directory");',
'require("./default-js");',
'require("./default-json");',
'require("./default-node");',
'require("empty-main");',
'require("nested-main");',
'require("file-only");',
'require("ancestor-empty");',
'require("ancestor-blocked");',
'require("ancestor-sub/parser");',
].join("\n"),
"cjs/directory/index.cjs": "module.exports = 6;",
"cjs/extensionless.cjs": "module.exports = 1;",
"cjs/feature.cjs": "module.exports = 2;",
"cjs/module-only.mjs": "export default 42;",
"cjs/valid-directory/index.js": "module.exports = 42;",
"cjs/typed.cts":
'const value = require("./typed-dep.cjs"); module.exports = value;',
"cjs/typed-dep.cts": "module.exports = 42;",
"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;",
"node_modules/file-only.js": "module.exports = 7;",
"node_modules/ancestor-empty/index.js": "module.exports = 8;",
"node_modules/ancestor-blocked/index.js": "module.exports = 9;",
"node_modules/ancestor-sub/parser.js": "module.exports = 10;",
"esm/runtime-control.mjs": [
'const specifiers = ["./extensionless", "./directory", "./explicit.js", "./exact.js", "./actual.cjs?cache=1", "empty-main", "nested-main", "file-only", "ancestor-empty", "ancestor-blocked", "ancestor-sub/parser"];',
"const results = [];",
"for (const specifier of specifiers) {",
" try { const value = (await import(specifier)).default; results.push({ specifier, ok: true, value }); }",
" catch (error) { results.push({ specifier, ok: false, code: error.code }); }",
"}",
"console.log(JSON.stringify(results));",
].join("\n"),
"cjs/runtime-control.cjs": [
'const specifiers = ["./extensionless", "./directory", "./feature", "./feature.cjs", "./module-only", "./valid-directory", "./default-js", "./default-json", "empty-main", "nested-main", "file-only", "ancestor-empty", "ancestor-blocked", "ancestor-sub/parser"];',
"const results = [];",
"for (const specifier of specifiers) {",
" try { const value = require(specifier); results.push({ specifier, ok: true, value }); }",
" catch (error) { results.push({ specifier, ok: false, code: error.code }); }",
"}",
"console.log(JSON.stringify(results));",
].join("\n"),
});
for (const directory of ["esm", "cjs"])
await writeFixtureFiles(root, {
[`${directory}/node_modules/ancestor-empty/package.json`]: JSON.stringify(
{ main: "" },
),
[`${directory}/node_modules/ancestor-blocked/package.json`]:
JSON.stringify({ main: "missing" }),
[`${directory}/node_modules/ancestor-sub/package.json`]: "{}",
});
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, ["esm/runtime-control.mjs"], {
cwd: root,
timeout: 5_000,
}),
execute(process.execPath, ["cjs/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;
readonly value?: unknown;
}>;
const cjsResults = JSON.parse(cjsControl.stdout) as Array<{
readonly specifier: string;
readonly ok: boolean;
readonly code?: string;
readonly value?: unknown;
}>;
expect(esmResults).toEqual([
{
specifier: "./extensionless",
ok: false,
code: "ERR_MODULE_NOT_FOUND",
},
{
specifier: "./directory",
ok: false,
code: "ERR_UNSUPPORTED_DIR_IMPORT",
},
{
specifier: "./explicit.js",
ok: false,
code: "ERR_MODULE_NOT_FOUND",
},
{ specifier: "./exact.js", ok: true, value: 4 },
{ specifier: "./actual.cjs?cache=1", ok: true, value: 5 },
{ specifier: "empty-main", ok: true, value: 42 },
{ specifier: "nested-main", ok: false, code: "ERR_MODULE_NOT_FOUND" },
{ specifier: "file-only", ok: false, code: "ERR_MODULE_NOT_FOUND" },
{ specifier: "ancestor-empty", ok: false, code: "ERR_MODULE_NOT_FOUND" },
{
specifier: "ancestor-blocked",
ok: false,
code: "ERR_MODULE_NOT_FOUND",
},
{
specifier: "ancestor-sub/parser",
ok: false,
code: "ERR_MODULE_NOT_FOUND",
},
]);
expect(cjsResults).toEqual([
{
specifier: "./extensionless",
ok: false,
code: "MODULE_NOT_FOUND",
},
{
specifier: "./directory",
ok: false,
code: "MODULE_NOT_FOUND",
},
{
specifier: "./feature",
ok: false,
code: "MODULE_NOT_FOUND",
},
{ specifier: "./feature.cjs", ok: true, value: 2 },
{ specifier: "./module-only", ok: false, code: "MODULE_NOT_FOUND" },
{ specifier: "./valid-directory", ok: true, value: 42 },
{ specifier: "./default-js", ok: true, value: 3 },
{ specifier: "./default-json", ok: true, value: { value: 4 } },
{ specifier: "empty-main", ok: true, value: 42 },
{ specifier: "nested-main", ok: false, code: "MODULE_NOT_FOUND" },
{ specifier: "file-only", ok: true, value: 7 },
{ specifier: "ancestor-empty", ok: true, value: 8 },
{ specifier: "ancestor-blocked", ok: false, code: "MODULE_NOT_FOUND" },
{ specifier: "ancestor-sub/parser", ok: true, value: 10 },
]);
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", "./actual.cjs?cache=1", "esm/actual.cjs", "resolved"],
["import", "./typed-dep.js", "esm/typed-dep.ts", "resolved"],
["import", "empty-main", "node_modules/empty-main/index.js", "resolved"],
["import", "nested-main", null, "not-found"],
["import", "file-only", null, "external"],
["import", "ancestor-empty", null, "not-found"],
["import", "ancestor-blocked", null, "not-found"],
["import", "ancestor-sub/parser", null, "not-found"],
["require", "./extensionless", null, "not-found"],
["require", "./directory", null, "not-found"],
["require", "./feature", null, "not-found"],
["require", "./feature.cjs", "cjs/feature.cjs", "resolved"],
["require", "./module-only", null, "not-found"],
[
"require",
"./valid-directory",
"cjs/valid-directory/index.js",
"resolved",
],
["require", "./typed-dep.cjs", "cjs/typed-dep.cts", "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"],
["require", "file-only", "node_modules/file-only.js", "resolved"],
[
"require",
"ancestor-empty",
"node_modules/ancestor-empty/index.js",
"resolved",
],
["require", "ancestor-blocked", null, "not-found"],
[
"require",
"ancestor-sub/parser",
"node_modules/ancestor-sub/parser.js",
"resolved",
],
] 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,
}),
}),
);
},
);
@@ -18,6 +18,7 @@ import {
SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE,
} from "../../../src/contracts/javascript/javascriptApplicationWorkflowExamples.js";
import { analyzeJavaScriptApplication } from "../../support/javascriptApplicationScope.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import {
javascriptApplicationAnalysisResultSchema,
type JavaScriptApplicationAnalysisResult,
@@ -1530,6 +1531,60 @@ const analyzeComparisonSources = async (
);
};
it("retains bundled isolated-world contextBridge APIs through dedicated and generic CLI routes", async () => {
const root = await createTestTempDirectory(
"rea-context-bridge-isolated-cli-",
);
await writeFile(
join(root, "preload.js"),
`(() => {
const modules = {
2(module) { module.exports = require("electron"); },
5(module, exports, load) {
const electron = load(2);
electron.contextBridge.exposeInIsolatedWorld(1001, "isolatedApi", { ping: true });
},
};
function load(id) {
const module = { exports: {} };
modules[id].call(module.exports, module, module.exports, load);
return module.exports;
}
load(5);
})();`,
);
for (const arguments_ of [
["analyze-javascript-application", root, "--json"],
["analyze", root, "--format", "json"],
]) {
const result = javascriptApplicationAnalysisResultSchema.parse(
parseEvidence(await runCli(arguments_)).normalized_result,
);
expect(result.summary.context_bridge_apis).toBe(1);
const bridge = result.graph.nodes.find(
({ kind }) => kind === "context-bridge-api",
);
expect(bridge?.observations).toContainEqual(
expect.objectContaining({
properties: expect.objectContaining({
world: "isolated",
world_id: { status: "literal", value: 1001, expression: null },
api_key: "isolatedApi",
members: ["ping"],
resolution_basis: "wrapper-substitution",
}),
evidence: expect.objectContaining({
location: expect.objectContaining({
available: true,
value: expect.objectContaining({ source: "preload.js" }),
}),
}),
}),
);
}
});
const runCli = async (
arguments_: readonly string[],
environment: Readonly<Record<string, string>> = {},
@@ -0,0 +1,128 @@
import { createHash } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { buildBinary } from "plist";
import { encodeNibArchiveFixture } from "../../../src/artifacts/apple/NibArchive.fixture.js";
import { appleAssetCatalogResultSchema } from "../../../src/domain/apple/appleAssetCatalog.js";
import { interfaceBuilderAnalysisSchema } from "../../../src/domain/apple/interfaceBuilderGraph.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
// Exact rooted NIBArchive bytes from #2176; inert parser fixture, not ibtool output.
const reportedArchive = Buffer.from(
"TklCQXJjaGl2ZQEAAAAKAAAABAAAADIAAAAEAAAAPgAAAAQAAABgAAAABAAAAHwAAACAgIGBgYGCgoGDg4GGTlNSb290hWltYWdli05TSW1hZ2VOYW1liE5TLmJ5dGVzgAoBAAAAgQoCAAAAggoDAAAAgwiHVG9vbGJhco6ATlNJQk9iamVjdERhdGGLgE5TSW1hZ2VWaWV3h4BOU0ltYWdliIBOU1N0cmluZw==",
"base64",
);
const resourceArchive = (field: string) =>
encodeNibArchiveFixture({
classes: ["NSIBObjectData", "NSImageView", "NSImage", "NSString"],
objects: [
{ classIndex: 0, values: { NSRoot: { ref: 1 } } },
{ classIndex: 1, values: { image: { ref: 2 } } },
{ classIndex: 2, values: { [field]: { ref: 3 } } },
{ classIndex: 3, values: { "NS.bytes": "Toolbar" } },
],
});
const keyedArchive = (nested: boolean) =>
buildBinary({
$archiver: "NSKeyedArchiver",
$version: 100000,
$top: { root: { UID: 1 } },
$objects: [
"$null",
{
$class: { UID: 2 },
...(nested
? { nibValues: { NSImageName: "Toolbar" } }
: { NSImageName: "Toolbar" }),
},
{ $classname: "NSImage", $classes: ["NSImage", "NSObject"] },
],
});
cliTest.skipIf(process.platform !== "darwin")(
"retains recognized NIBArchive resource keys and provenance through CLI and MCP without a catalog",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-asset-resource-keys-");
const { call } = await connectLocalToolsMcp();
for (const [name, field, archive, recognized] of [
["reported", "NSImageName", reportedArchive, true],
["alias", "imageName", resourceArchive("imageName"), true],
["title", "title", resourceArchive("title"), false],
["keyed-direct", "NSImageName", keyedArchive(false), true],
["keyed-nested", "NSImageName", keyedArchive(true), false],
] as const) {
const app = join(root, `${name}.app`);
const contents = join(app, "Contents");
await mkdir(join(contents, "Resources"), { recursive: true });
await mkdir(join(contents, "MacOS"));
const mach = Buffer.alloc(32);
mach.writeUInt32LE(0xfeedfacf, 0);
mach.writeUInt32LE(0x0100000c, 4);
mach.writeUInt32LE(2, 12);
await writeFile(join(contents, "MacOS", "App"), mach);
await writeFile(
join(contents, "Info.plist"),
"<plist><dict><key>CFBundleExecutable</key><string>App</string></dict></plist>",
);
await writeFile(join(contents, "Resources", "Panel.nib"), archive);
const decoded = await cli.run({
arguments: ["decode-interface-builder", app, "--json"],
});
expect(decoded.exitCode, decoded.stderr).toBe(0);
const graph = interfaceBuilderAnalysisSchema.parse(
parseEvidence(decoded.json).normalized_result,
).graph;
expect(graph.truncated).toBe(false);
const resource = graph.nodes.find(
(node) =>
node.kind === "resource" && node.attributes.class_name === "NSImage",
);
expect(
name === "keyed-direct"
? resource?.attributes
: resource?.attributes.nibValues,
).toMatchObject({
[field]: "Toolbar",
});
const inspected = await cli.run({
arguments: ["inspect-asset-catalog", app, "--json"],
});
expect(inspected.exitCode, inspected.stderr).toBe(0);
const result = appleAssetCatalogResultSchema.parse(
parseEvidence(inspected.json).normalized_result,
);
expect(result.catalogs).toEqual([]);
expect(result.resource_key_matches).toEqual(
!recognized
? []
: [
{
source_node_id: resource?.id,
source_path: "Contents/Resources/Panel.nib",
source_archive_sha256: createHash("sha256")
.update(archive)
.digest("hex"),
field,
key: "Toolbar",
status: "unmatched",
renditions: [],
},
],
);
const opened = await call("open_binary", { path: app });
expect(opened.isError).not.toBe(true);
const mcp = await call("inspect_asset_catalog", {});
expect(mcp.isError).not.toBe(true);
expect(parseEvidence(mcp.structuredContent).normalized_result).toEqual(
result,
);
}
},
30_000,
);
@@ -0,0 +1,69 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
cliTest(
"reports every unresolved Electron path through CLI and MCP without launching",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-electron-invalid-paths-");
const application = join(root, "main.js");
await writeFile(application, "module.exports = {};\n");
const missing = {
executable_path: join(root, "missing-electron"),
application_path: join(root, "missing-application"),
application_root: join(root, "missing-root"),
};
const requestPath = join(root, "input.json");
await writeFile(requestPath, JSON.stringify(missing));
const response = await cli.run({
arguments: ["capture-electron-scenario", requestPath, "--format", "json"],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(response.exitCode).toBe(1);
const expectedIssues = Object.entries(missing).map(([field, path]) => ({
path: [field],
reason: "invalid_value",
message: expect.stringContaining(path),
}));
expect(response.json).toMatchObject({
code: "invalid_request",
details: { issues: expectedIssues },
});
expect(response.stdout).toContain("ENOENT");
const { call } = await connectLocalToolsMcp();
for (const [field, path] of Object.entries(missing)) {
const result = await call("capture_electron_scenario", {
executable_path: process.execPath,
application_path: application,
application_root: root,
[field]: path,
});
expect(result.isError).toBe(true);
const content = result.content.find((item) => item.type === "text");
if (content?.type !== "text") throw new Error("Missing error response");
expect(JSON.parse(content.text)).toMatchObject({
error: {
code: "invalid_request",
details: {
issues: [
{
path: [field],
reason: "invalid_value",
message: expect.stringContaining(path),
},
],
},
},
});
expect(content.text).toContain("ENOENT");
}
const session = await call("binary_session", {});
expect(session.isError, JSON.stringify(session)).not.toBe(true);
},
);
@@ -0,0 +1,88 @@
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { interfaceBuilderAnalysisSchema } from "../../../src/domain/apple/interfaceBuilderGraph.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { thinMach } from "../../../src/domain/binaryTarget.fixture.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
cliTest(
"decodes a rooted UIKit keyed-archive outlet through CLI",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-cli-uikit-outlet-");
const app = join(root, "UIKitFixture.app");
const contents = join(app, "Contents");
const resources = join(contents, "Resources");
await mkdir(resources, { recursive: true });
await mkdir(join(contents, "MacOS"));
await writeFile(
join(contents, "MacOS", "Fixture"),
thinMach(0xfeedfacf, 0x0100000c),
);
await writeFile(
join(contents, "Info.plist"),
"<plist><dict><key>CFBundleExecutable</key><string>Fixture</string></dict></plist>",
);
await writeFile(
join(resources, "Main.nib"),
await readFile(
join(process.cwd(), "tests/fixtures/interface-builder/UIKitOutlet.xml"),
),
);
const output = await cli.run({
arguments: ["decode-interface-builder", app, "--json"],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(output.exitCode, output.stderr).toBe(0);
const result = interfaceBuilderAnalysisSchema.parse(
parseEvidence(output.json).normalized_result,
);
const owner = result.graph.nodes.find(
({ attributes }) => attributes.interface_builder_object_id === "1",
);
const destination = result.graph.nodes.find(
({ attributes }) => attributes.interface_builder_object_id === "2",
);
const outlet = result.graph.nodes.find(({ kind }) => kind === "outlet");
expect(result.documents).toEqual([
expect.objectContaining({ connection_count: 1 }),
]);
expect(outlet).toMatchObject({
id: 'ib:"Contents/Resources/Main.nib":outlet:["archive:3"]',
name: "view",
attributes: {
UISource: { archiveUID: 1 },
UIDestination: { archiveUID: 2 },
UILabel: "view",
},
});
expect(owner).toBeDefined();
expect(destination).toBeDefined();
expect(
result.graph.edges.some(
({ from, to, relation }) =>
from === owner?.id && to === outlet?.id && relation === "contains",
),
).toBe(true);
expect(
result.graph.edges.some(
({ from, to, relation }) =>
from === outlet?.id &&
to === destination?.id &&
relation === "outlet_to",
),
).toBe(true);
expect(result.graph.coverage).toContainEqual(
expect.objectContaining({
facet: "connections:Contents/Resources/Main.nib",
status: "complete",
examined: 1,
omitted: 0,
}),
);
},
);
@@ -0,0 +1,147 @@
import { createPackageWithOptions } from "@electron/asar";
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import { writeJavaScriptSourceSelectionFixture } from "../../fixtures/javascriptSourceSelection.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
cliTest.for([
{ format: "directory", command: "analyze" },
{ format: "asar", command: "analyze-javascript-application" },
])(
"analyzes selected $format sources through $command with complete artifact identity",
{ timeout: 60_000 },
async ({ format, command }, { cli }) => {
const directory = await createTestTempDirectory("rea-js-source-selection-");
const files = await writeJavaScriptSourceSelectionFixture(directory);
let input = directory;
if (format === "asar") {
input = join(
await createTestTempDirectory("rea-js-selected-asar-"),
"app.asar",
);
await createPackageWithOptions(directory, input, {});
}
const requested = ["main.mjs", "package.json", "main.mjs"];
const response = await cli.run({
arguments: [
command,
input,
...requested.flatMap((path) => ["--source-path", path]),
"--format",
"json",
],
});
expect(response.exitCode).toBe(0);
const evidence = parseEvidence(response.json);
const result = javascriptApplicationAnalysisResultSchema.parse(
evidence.normalized_result,
);
expect(result.source_selection).toEqual({
requested_paths: requested,
unselected_files: 4,
});
expect(evidence.parameters.source_paths).toEqual(requested);
expect(result.statistics).toMatchObject({
relevant_files: 6,
parsed_javascript_files: 1,
invalid_utf8_files: 0,
parse_failures: 0,
text_bytes_read:
files.get("main.mjs")!.length + files.get("package.json")!.length,
});
expect(result.graph.coverage.status).toBe("partial");
expect(result.semantic_graph.coverage).toMatchObject({
status: "partial",
truncated: false,
});
expect(
result.semantic_graph.nodes.some(
({ kind, label }) => kind === "function" && label === "selected",
),
).toBe(true);
expect(
result.semantic_graph.unknowns.some(
({ reason, detail }) =>
reason === "incomplete-module" &&
detail.includes("caller-selected source_paths"),
),
).toBe(true);
for (const [path, bytes] of files) {
const properties = result.graph.nodes
.flatMap(({ observations }) =>
observations.map(({ properties }) => properties),
)
.find(
(properties) =>
properties.path === path && properties.text_status !== undefined,
);
expect(properties?.text_status).toBe(
requested.includes(path) ? "included" : "outside-analysis-scope",
);
expect(properties?.parse_status).toBe(
path === "main.mjs" ? "complete" : null,
);
expect(await readFile(join(directory, path))).toEqual(bytes);
}
const fullResponse = await cli.run({
arguments: [command, input, "--format", "json"],
});
expect(fullResponse.exitCode).toBe(0);
const full = javascriptApplicationAnalysisResultSchema.parse(
parseEvidence(fullResponse.json).normalized_result,
);
expect(full.source_selection).toBeUndefined();
expect(full.statistics.invalid_utf8_files).toBe(1);
expect(full.statistics.parse_failures).toBeGreaterThan(0);
expect([
result.root_artifact_sha256,
result.inventory_manifest_id,
result.inventory_graph_sha256,
]).toEqual([
full.root_artifact_sha256,
full.inventory_manifest_id,
full.inventory_graph_sha256,
]);
if (format === "asar")
expect(result.root_artifact_sha256).toBe(
createHash("sha256")
.update(await readFile(input))
.digest("hex"),
);
},
);
cliTest(
"rejects source selection when an explicit provider chooses the native lane",
async ({ cli }) => {
const directory = await createTestTempDirectory(
"rea-js-source-native-refusal-",
);
await writeJavaScriptSourceSelectionFixture(directory);
const response = await cli.run({
arguments: [
"analyze",
directory,
"--provider",
"ghidra",
"--source-path",
"main.mjs",
"--format",
"json",
],
});
expect(response.exitCode).toBe(1);
expect(response.json).toMatchObject({
code: "invalid_request",
details: {
issues: [{ path: ["source_paths"], reason: "invalid_value" }],
},
});
},
);
@@ -4,12 +4,10 @@ import { createRequire } from "node:module";
import { dirname, join, relative } 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";
const literalAliases = ["#/x", "#x%2Fy", "#x%2Ey", "#x\\y", "#x\0y"];
const fallbackAliases = {
@@ -158,26 +156,7 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
expect.objectContaining({ code: "ERR_PACKAGE_IMPORT_NOT_DEFINED" }),
);
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);
for (const specifier of resolvedAliases)
for (const [moduleKind, sourcePath, source] of [
["require", "main.cjs", mainSource],
@@ -0,0 +1,109 @@
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
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";
const requests = [
{ specifier: "legacy?x", plainName: "legacy", exports: false },
{ specifier: "exported#entry", plainName: "exported", exports: true },
{ specifier: "@scope/legacy?x", plainName: "@scope/legacy", exports: false },
{ specifier: "@scope#entry/pkg", plainName: "@scope/pkg", exports: true },
] as const;
// Windows cannot materialize the question-mark directories in this fixture.
cliTest.skipIf(process.platform === "win32").for(["CLI", "stdio MCP"] as const)(
"keeps ESM root URL suffixes out of dependency filesystem lookup through %s",
async (surface, { cli }) => {
const root = await createTestTempDirectory("rea-package-root-suffix-");
const sources = {
"main.mjs": requests
.map(({ specifier }) => `import ${JSON.stringify(specifier)};`)
.join("\n"),
"main.cjs": requests
.map(({ specifier }) => `require(${JSON.stringify(specifier)});`)
.join("\n"),
};
const files: Record<string, string> = { ...sources };
for (const item of requests)
for (const name of [item.specifier, item.plainName]) {
const directory = `node_modules/${name}`;
files[`${directory}/package.json`] = JSON.stringify(
item.exports ? { exports: "./entry.cjs" } : { main: "./entry.cjs" },
);
files[`${directory}/entry.cjs`] =
`module.exports = ${JSON.stringify(name)};`;
}
await Promise.all(
Object.entries(files).map(async ([path, text]) => {
const absolute = join(root, path);
await mkdir(dirname(absolute), { recursive: true });
await writeFile(absolute, text);
}),
);
if (surface === "CLI") {
const native = await promisify(execFile)(
process.execPath,
[
"--input-type=module",
"--eval",
`import { createRequire } from "node:module";
const require = createRequire(new URL("./main.cjs", import.meta.url));
const requests = ${JSON.stringify(requests.map(({ specifier }) => specifier))};
const results = await Promise.all(requests.map(async (specifier) => {
let esm;
try { esm = { value: (await import(specifier)).default, error: null }; }
catch (error) { esm = { value: null, error: error.code }; }
return { esm, require: require(specifier) };
}));
console.log(JSON.stringify(results));`,
],
{ cwd: root, timeout: 5_000 },
);
expect(JSON.parse(native.stdout)).toEqual(
requests.map(({ specifier }) => ({
esm: { value: null, error: "ERR_MODULE_NOT_FOUND" },
require: specifier,
})),
);
}
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
for (const { specifier } of requests)
for (const [moduleKind, sourcePath] of [
["import", "main.mjs"],
["require", "main.cjs"],
] as const)
expect(graph.edges).toContainEqual(
expect.objectContaining({
relation: "imports",
properties: expect.objectContaining({
module_link_kind: moduleKind,
specifier,
resolved_path:
moduleKind === "import"
? null
: `node_modules/${specifier}/entry.cjs`,
resolution_status:
moduleKind === "import" ? "external" : "resolved",
}),
evidence: expect.objectContaining({
artifact: expect.objectContaining({
sha256: createHash("sha256")
.update(sources[sourcePath])
.digest("hex"),
}),
location: expect.objectContaining({
value: expect.objectContaining({ source: sourcePath }),
}),
}),
}),
);
},
);
@@ -0,0 +1,207 @@
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
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";
type SelfNameCase = {
readonly directory: string;
readonly packageName: string;
readonly exportKey: string;
readonly specifier: string;
readonly selfValue: string;
readonly dependency?: {
readonly packagePath: string;
readonly exportKey: string;
readonly value: string;
};
readonly esmTarget: string;
readonly requireTarget: string;
readonly esmValue: string;
readonly requireValue: string;
};
const cases = [
{
directory: "scope-prefix",
packageName: "@scope",
exportKey: "./pkg",
specifier: "@scope/pkg",
selfValue: "scope self",
dependency: {
packagePath: "node_modules/@scope/pkg",
exportKey: ".",
value: "scope dependency",
},
esmTarget: "scope-prefix/node_modules/@scope/pkg/dependency.cjs",
requireTarget: "scope-prefix/self.cjs",
esmValue: "scope dependency",
requireValue: "scope self",
},
{
directory: "slash-name",
packageName: "fixture/sub",
exportKey: "./feature",
specifier: "fixture/sub/feature",
selfValue: "slash self",
dependency: {
packagePath: "node_modules/fixture",
exportKey: "./sub/feature",
value: "slash dependency",
},
esmTarget: "slash-name/node_modules/fixture/dependency.cjs",
requireTarget: "slash-name/self.cjs",
esmValue: "slash dependency",
requireValue: "slash self",
},
{
directory: "slash-exact-name",
packageName: "fixture/sub",
exportKey: ".",
specifier: "fixture/sub",
selfValue: "slash exact self",
dependency: {
packagePath: "node_modules/fixture",
exportKey: "./sub",
value: "slash exact dependency",
},
esmTarget: "slash-exact-name/node_modules/fixture/dependency.cjs",
requireTarget: "slash-exact-name/self.cjs",
esmValue: "slash exact dependency",
requireValue: "slash exact self",
},
{
directory: "valid-scoped",
packageName: "@scope/pkg",
exportKey: "./feature",
specifier: "@scope/pkg/feature",
selfValue: "valid scoped self",
esmTarget: "valid-scoped/self.cjs",
requireTarget: "valid-scoped/self.cjs",
esmValue: "valid scoped self",
requireValue: "valid scoped self",
},
{
directory: "query-self-name",
packageName: "self?x",
exportKey: ".",
specifier: "self?x",
selfValue: "query self",
esmTarget: "query-self-name/self.cjs",
requireTarget: "query-self-name/self.cjs",
esmValue: "query self",
requireValue: "query self",
},
{
directory: "fragment-self-name",
packageName: "@scope/self#entry",
exportKey: ".",
specifier: "@scope/self#entry",
selfValue: "fragment self",
esmTarget: "fragment-self-name/self.cjs",
requireTarget: "fragment-self-name/self.cjs",
esmValue: "fragment self",
requireValue: "fragment self",
},
] satisfies readonly SelfNameCase[];
const sourceFor = (specifier: string, moduleKind: "import" | "require") =>
moduleKind === "import"
? `import value from ${JSON.stringify(specifier)};\nexport default value;`
: `const value = require(${JSON.stringify(specifier)});\nmodule.exports = value;`;
const createSelfNameFixture = async () => {
const root = await createTestTempDirectory("rea-package-self-name-boundary-");
const files: Record<string, string> = {};
for (const item of cases) {
const prefix = item.directory;
files[`${prefix}/package.json`] = JSON.stringify({
name: item.packageName,
exports: { [item.exportKey]: "./self.cjs" },
});
files[`${prefix}/main.mjs`] = sourceFor(item.specifier, "import");
files[`${prefix}/main.cjs`] = sourceFor(item.specifier, "require");
files[`${prefix}/self.cjs`] =
`module.exports = ${JSON.stringify(item.selfValue)};`;
if (item.dependency !== undefined) {
const dependencyPrefix = `${prefix}/${item.dependency.packagePath}`;
files[`${dependencyPrefix}/package.json`] = JSON.stringify({
exports: { [item.dependency.exportKey]: "./dependency.cjs" },
});
files[`${dependencyPrefix}/dependency.cjs`] =
`module.exports = ${JSON.stringify(item.dependency.value)};`;
}
}
files["node-control.mjs"] = `import { createRequire } from "node:module";
const cases = ${JSON.stringify(cases.map(({ directory, specifier }) => ({ directory, specifier })))};
const esm = await Promise.all(
cases.map(async ({ directory }) =>
(await import(new URL(directory + "/main.mjs", import.meta.url))).default,
),
);
const require = cases.map(({ directory, specifier }) =>
createRequire(new URL(directory + "/main.cjs", import.meta.url))(specifier),
);
console.log(JSON.stringify({ esm, require }));`;
await Promise.all(
Object.entries(files).map(async ([path, content]) => {
const absolute = join(root, path);
await mkdir(dirname(absolute), { recursive: true });
await writeFile(absolute, content);
}),
);
return root;
};
cliTest.for(["CLI", "stdio MCP"] as const)(
"matches self references by parsed ESM name and preserves CommonJS prefix matching through %s",
async (surface, { cli }) => {
const root = await createSelfNameFixture();
if (surface === "CLI") {
const native = await promisify(execFile)(
process.execPath,
[join(root, "node-control.mjs")],
{ cwd: root, timeout: 5_000 },
);
expect(JSON.parse(native.stdout)).toEqual({
esm: cases.map(({ esmValue }) => esmValue),
require: cases.map(({ requireValue }) => requireValue),
});
}
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
for (const item of cases)
for (const [moduleKind, target] of [
["import", item.esmTarget],
["require", item.requireTarget],
] as const) {
const sourcePath = `${item.directory}/main.${moduleKind === "import" ? "mjs" : "cjs"}`;
const source = sourceFor(item.specifier, moduleKind);
expect(graph.edges).toContainEqual(
expect.objectContaining({
relation: "imports",
properties: expect.objectContaining({
module_link_kind: moduleKind,
specifier: item.specifier,
resolved_path: target,
resolution_status: "resolved",
}),
evidence: expect.objectContaining({
artifact: expect.objectContaining({
sha256: createHash("sha256").update(source).digest("hex"),
}),
location: expect.objectContaining({
value: expect.objectContaining({ source: sourcePath }),
}),
}),
}),
);
}
},
);
@@ -0,0 +1,278 @@
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
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";
type PackageSpecifierCase = {
readonly specifier: string;
readonly target: string | null;
readonly status: "resolved" | "external" | "rejected" | "not-found";
readonly value: string | number | null;
readonly error: string | null;
};
const requests = [
{
specifier: "rea-self-fixture",
target: "root.cjs",
status: "resolved",
value: 11,
error: null,
},
{
specifier: "rea-self-fixture/feature",
target: "feature.cjs",
status: "resolved",
value: 22,
error: null,
},
{
specifier: "rea-self-fixture/feature?cache=1",
target: "punctuated.cjs",
status: "resolved",
value: 33,
error: null,
},
{
specifier: "rea-self-fixture/feature?cache=2",
target: null,
status: "external",
value: null,
error: "ERR_PACKAGE_PATH_NOT_EXPORTED",
},
{
specifier: "rea-self-fixture/feature#entry",
target: null,
status: "external",
value: null,
error: "ERR_PACKAGE_PATH_NOT_EXPORTED",
},
{
specifier: "fixture/feature?cache=1",
target: null,
status: "external",
value: null,
error: "ERR_PACKAGE_PATH_NOT_EXPORTED",
},
{
specifier: "fixture/feature#entry",
target: null,
status: "external",
value: null,
error: "ERR_PACKAGE_PATH_NOT_EXPORTED",
},
{
specifier: "fixture/literal?cache=1",
target: "node_modules/fixture/literal.cjs",
status: "resolved",
value: "literal",
error: null,
},
{
specifier: "legacy/?cache=1",
target: null,
status: "rejected",
value: null,
error: "ERR_UNSUPPORTED_DIR_IMPORT",
},
{
specifier: "legacy/#entry",
target: null,
status: "rejected",
value: null,
error: "ERR_UNSUPPORTED_DIR_IMPORT",
},
{
specifier: "legacy/nested/?cache=1",
target: null,
status: "rejected",
value: null,
error: "ERR_UNSUPPORTED_DIR_IMPORT",
},
{
specifier: "legacy/nested/#entry",
target: null,
status: "rejected",
value: null,
error: "ERR_UNSUPPORTED_DIR_IMPORT",
},
{
specifier: "legacy/feature.js",
target: "node_modules/legacy/feature.js",
status: "resolved",
value: "legacy feature",
error: null,
},
{
specifier: "legacy/feature.js?cache=1",
target: "node_modules/legacy/feature.js",
status: "resolved",
value: "legacy feature",
error: null,
},
{
specifier: "legacy/feature.js#entry",
target: "node_modules/legacy/feature.js",
status: "resolved",
value: "legacy feature",
error: null,
},
{
specifier: "legacy/with%20space.js?cache=1",
target: "node_modules/legacy/with space.js",
status: "resolved",
value: "legacy spaced feature",
error: null,
},
{
specifier: "legacy/feature",
target: null,
status: "not-found",
value: null,
error: "ERR_MODULE_NOT_FOUND",
},
] satisfies readonly PackageSpecifierCase[];
const createPackageSpecifierFixture = async (): Promise<{
readonly root: string;
readonly source: string;
}> => {
const root = await createTestTempDirectory("rea-package-specifier-suffix-");
const packagePath = join(root, "node_modules", "fixture");
const legacyPackagePath = join(root, "node_modules", "legacy");
await Promise.all([
mkdir(packagePath, { recursive: true }),
mkdir(join(legacyPackagePath, "nested"), { recursive: true }),
]);
await writeFile(
join(root, "package.json"),
JSON.stringify({
name: "rea-self-fixture",
exports: {
".": { import: "./root.cjs", require: "./require.cjs" },
"./feature": { import: "./feature.cjs", require: "./require.cjs" },
"./feature?cache=1": {
import: "./punctuated.cjs",
require: "./require.cjs",
},
},
}),
);
const source = requests
.map(
({ specifier }, index) =>
`import value${index} from ${JSON.stringify(specifier)};`,
)
.join("\n");
await Promise.all([
writeFile(join(root, "main.mjs"), source),
writeFile(join(root, "root.cjs"), "module.exports = 11;"),
writeFile(join(root, "feature.cjs"), "module.exports = 22;"),
writeFile(join(root, "punctuated.cjs"), "module.exports = 33;"),
writeFile(join(root, "require.cjs"), "module.exports = -1;"),
]);
await writeFile(
join(packagePath, "package.json"),
JSON.stringify({
exports: {
"./feature": "./feature.cjs",
"./literal?cache=1": "./literal.cjs",
},
}),
);
await Promise.all([
writeFile(join(packagePath, "feature.cjs"), 'module.exports = "feature";'),
writeFile(join(packagePath, "literal.cjs"), 'module.exports = "literal";'),
writeFile(
join(legacyPackagePath, "package.json"),
JSON.stringify({ name: "legacy", main: "./main.cjs" }),
),
writeFile(
join(legacyPackagePath, "main.cjs"),
'module.exports = "legacy root";',
),
writeFile(
join(legacyPackagePath, "feature.js"),
'module.exports = "legacy feature";',
),
writeFile(
join(legacyPackagePath, "with space.js"),
'module.exports = "legacy spaced feature";',
),
writeFile(
join(legacyPackagePath, "nested", "package.json"),
JSON.stringify({ main: "./main.cjs" }),
),
writeFile(
join(legacyPackagePath, "nested", "main.cjs"),
'module.exports = "legacy nested";',
),
]);
return { root, source };
};
cliTest.for(["CLI", "stdio MCP"] as const)(
"resolves package self references and suffix keys through %s",
async (surface, { cli }) => {
const { root, source } = await createPackageSpecifierFixture();
if (surface === "CLI") {
const native = await promisify(execFile)(
process.execPath,
[
"--input-type=module",
"-e",
`const requests = ${JSON.stringify(requests.map(({ specifier }) => specifier))};
const results = await Promise.all(requests.map(async (specifier) => {
try {
const result = await import(specifier);
return { value: result.default, error: null };
} catch (error) {
return { value: null, error: error.code };
}
}));
console.log(JSON.stringify(results));`,
],
{ cwd: root, timeout: 5_000 },
);
expect(JSON.parse(native.stdout)).toEqual(
requests.map(({ value, error }) => ({ value, error })),
);
}
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
for (const { specifier, target, status } of requests)
expect(graph.edges).toContainEqual(
expect.objectContaining({
relation: "imports",
properties: expect.objectContaining({
module_link_kind: "import",
specifier,
resolved_path: target,
resolution_status: status,
}),
evidence: expect.objectContaining({
...(specifier === "legacy/feature"
? {
limitations: expect.arrayContaining([
"The selected package ESM subpath target node_modules/legacy/feature does not exist in the inventoried artifact container; ESM subpath targets are exact files, so no extension or directory index was tried.",
]),
}
: {}),
artifact: expect.objectContaining({
sha256: createHash("sha256").update(source).digest("hex"),
}),
location: expect.objectContaining({
value: expect.objectContaining({ source: "main.mjs" }),
}),
}),
}),
);
},
);
@@ -2,14 +2,15 @@ import { createHash } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { dirname, join, relative } from "node:path";
import { pathToFileURL } from "node:url";
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";
const createPackageSubpathFixture = async () => {
const root = await createTestTempDirectory("rea-package-subpaths-");
@@ -28,12 +29,18 @@ const createPackageSubpathFixture = async () => {
'const literal = require("fi%xture");',
'const scalar = require("scalar");',
'const self = require("../node_modules/fi%xture/run.cjs");',
'const uri = require("file:///src/uri-dep.cjs");',
'const relativeUri = require("./uri-dep.cjs");',
].join("\n");
const selfSource = 'const self = require("fi%xture"); module.exports = self;';
const importSource = 'import literal from "fi%xture";';
const importSource = [
'import literal from "fi%xture";',
'import uri from "file:///src/uri-dep.cjs";',
].join("\n");
const files = {
"src/main.cjs": source,
"src/imports.mjs": importSource,
"src/uri-dep.cjs": "module.exports = 42;",
"src/node_modules/fixture/parser.js": "module.exports = 1;",
"src/node_modules/fixture.js": "module.exports = 'file';",
"src/node_modules/fixture/index.js": "module.exports = 'directory';",
@@ -104,11 +111,20 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
"fi%xture": "node_modules/fi%xture.js",
scalar: "node_modules/scalar.js",
"../node_modules/fi%xture/run.cjs": "node_modules/fi%xture/run.cjs",
"./uri-dep.cjs": "src/uri-dep.cjs",
};
for (const [specifier, target] of Object.entries(expectedTargets))
expect(
relative(root, nativeRequire.resolve(specifier)).replaceAll("\\", "/"),
).toBe(target);
expect(nativeRequire("./uri-dep.cjs")).toBe(42);
for (const specifier of [
"file:///src/uri-dep.cjs",
pathToFileURL(join(root, "src/uri-dep.cjs")).href,
])
expect(() => nativeRequire.resolve(specifier)).toThrow(
expect.objectContaining({ code: "MODULE_NOT_FOUND" }),
);
for (const specifier of ["exported/parser/", "exported/hidden", "blocked"])
expect(() => nativeRequire.resolve(specifier)).toThrow(
expect.objectContaining({ code: "ERR_PACKAGE_PATH_NOT_EXPORTED" }),
@@ -124,26 +140,7 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
).replaceAll("\\", "/"),
).toBe("node_modules/fi%xture/actual.cjs");
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 imports = graph.edges.filter(
({ properties }) => properties.module_link_kind === "require",
);
@@ -156,6 +153,41 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
},
])
expectResolvedImports(imports, observation);
expect(graph.edges).toContainEqual(
expect.objectContaining({
relation: "imports",
properties: expect.objectContaining({
module_link_kind: "require",
specifier: "file:///src/uri-dep.cjs",
resolved_path: null,
resolution_status: "external",
}),
evidence: sourceEvidence("src/main.cjs", source),
}),
);
expect(graph.edges).toContainEqual(
expect.objectContaining({
relation: "imports",
properties: expect.objectContaining({
kind: "require",
specifier: "file:///src/uri-dep.cjs",
resolved_path: null,
}),
evidence: sourceEvidence("src/main.cjs", source),
}),
);
expect(graph.edges).toContainEqual(
expect.objectContaining({
relation: "imports",
properties: expect.objectContaining({
module_link_kind: "import",
specifier: "file:///src/uri-dep.cjs",
resolved_path: "src/uri-dep.cjs",
resolution_status: "resolved",
}),
evidence: sourceEvidence("src/imports.mjs", importSource),
}),
);
expect(graph.edges).toContainEqual(
expect.objectContaining({
properties: expect.objectContaining({
+38 -20
View File
@@ -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(
@@ -17,22 +21,28 @@ const fixturePath = fileURLToPath(
new URL("../../fixtures/fakeLauncher.mjs", import.meta.url),
);
const expectAvailableToolInventory = async (client: Client) => {
const listed = await client.listTools();
const status = await client.callTool({
name: "binary_session",
arguments: {},
});
const expectAvailableToolInventory = async (
client: Client,
listed: Awaited<ReturnType<Client["listTools"]>>,
) => {
const binarySession = listed.tools.find(
({ name }) => name === "binary_session",
);
if (binarySession === undefined)
throw new Error("The compiled catalog omitted binary_session");
const status = await client.callTool(
{ name: "binary_session", arguments: {} },
{ toolDefinition: binarySession },
);
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
@@ -161,6 +171,9 @@ describe("production stdio runtime", () => {
15_000,
);
// Use the suite's bounded acceptance deadline, including its coverage allowance.
// This cold-start workflow computes the growing catalog's schema digests; it
// verifies catalog and lifecycle behavior, not a 15-second performance target.
it("serves the compiled catalog without an initial target or fatal record", async () => {
const transport = new StdioClientTransport({
command: process.execPath,
@@ -180,7 +193,10 @@ describe("production stdio runtime", () => {
try {
await client.connect(transport);
// Keep catalog parity independent of initial target/provider startup.
const status = await expectAvailableToolInventory(client);
// Validate each called tool against its advertised definition without
// asking the SDK to compile every unrelated output schema in the catalog.
const listed = await client.listTools();
const status = await expectAvailableToolInventory(client, listed);
expect(
z
.object({ result: z.object({ open: z.boolean() }) })
@@ -188,10 +204,15 @@ describe("production stdio runtime", () => {
).toEqual({ open: false });
// Closing the empty session produces a structured lifecycle record,
// making the fatal-record check observable without launching a provider.
const closed = await client.callTool({
name: "close_binary",
arguments: {},
});
const closeBinary = listed.tools.find(
({ name }) => name === "close_binary",
);
if (closeBinary === undefined)
throw new Error("The compiled catalog omitted close_binary");
const closed = await client.callTool(
{ name: "close_binary", arguments: {} },
{ toolDefinition: closeBinary },
);
expect(closed.isError).not.toBe(true);
} finally {
await client.close();
@@ -218,10 +239,7 @@ describe("production stdio runtime", () => {
record.level >= 50,
);
expect(fatal).toEqual([]);
// Full catalog discovery and first-call SDK schema compilation take about
// 8–9 seconds on one local CPU; the 15-second budget repeatedly expired in
// parallel CI shards. Keep a finite budget for the complete workflow.
}, 30_000);
});
it.runIf(process.platform === "darwin")(
"serves a database-kind initial target without a fatal record on macOS",
@@ -0,0 +1,233 @@
import { createHash } from "node:crypto";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { TraceMap, originalPositionFor } from "@jridgewell/trace-mapping";
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";
cliTest.for(["CLI", "stdio MCP"] as const)(
"recovers retained prefixed source-map originals and byte identity through %s",
async (surface, { cli }) => {
const root = await createTestTempDirectory("rea-retained-map-prefix-");
const original = "export const answer: number = 42;";
const mapText = `\uFEFF)]}'retained response\r\n${JSON.stringify({
version: 3,
sources: ["original.ts"],
sourcesContent: [original],
names: [],
mappings: "AAAA",
})}`;
const mapPath = join(root, "bundle.js.map");
await writeFile(
join(root, "bundle.js"),
"export const answer = 42;\n//# sourceMappingURL=bundle.js.map\n",
);
await writeFile(mapPath, mapText);
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",
identity: expect.objectContaining({
strategy: "source-map-original",
source_map_sha256: mapDigest,
original_source: "original.ts",
source_sha256: originalDigest,
}),
observations: expect.arrayContaining([
expect.objectContaining({
source_map_reference: expect.objectContaining({
source_name: "original.ts",
map_path: "bundle.js.map",
}),
properties: expect.objectContaining({
source_index: 0,
declaration_index: 0,
source_name_available: true,
content_available: true,
content_sha256: originalDigest,
}),
evidence: expect.objectContaining({
artifact: expect.objectContaining({ sha256: mapDigest }),
}),
}),
]),
}),
);
expect(graph.coverage.status).toBe("complete");
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",
}),
"unnamed-empty.js.map": JSON.stringify({
version: 3,
sources: [null, "original.ts"],
sourcesContent: [null, 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",
"unnamed-empty.js":
"export const answer = 42;\n//# sourceMappingURL=unnamed-empty.js.map\n",
});
for (const [mapPath, expectedSource] of [
["absent.js.map", "unembedded.ts"],
["mixed.js.map", "original.ts"],
["unnamed-empty.js.map", "original.ts"],
] as const)
expect(
originalPositionFor(new TraceMap(maps[mapPath], `file:///${mapPath}`), {
line: 1,
column: 0,
}).source,
).toBe(`file:///${expectedSource}`);
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
const digest = (text: string) =>
createHash("sha256").update(text).digest("hex");
expect(
graph.nodes.filter(
(node) => node.identity.strategy === "source-map-original",
),
).toHaveLength(3);
for (const [name, mapPath, content, sourceIndex] of [
["unembedded.ts", "absent.js.map", null, 0],
["original.ts", "mixed.js.map", original, 1],
["original.ts", "unnamed-empty.js.map", original, 1],
] 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({
source_index: sourceIndex,
declaration_index: sourceIndex,
source_name_available: true,
content_available: content !== null,
}),
evidence: expect.objectContaining({
artifact: expect.objectContaining({ sha256: mapDigest }),
}),
}),
]),
}),
);
}
for (const [mapPath, content] of [
["mixed.js.map", unnamed],
["unnamed-empty.js.map", null],
] as const)
expect(graph.nodes).toContainEqual(
expect.objectContaining({
kind: "unknown",
observations: expect.arrayContaining([
expect.objectContaining({
source_map_reference: null,
properties: expect.objectContaining({
source_index: 0,
declaration_index: 0,
source_name_available: false,
content_available: content !== null,
content_sha256: content === null ? null : digest(content),
}),
evidence: expect.objectContaining({
artifact: expect.objectContaining({
sha256: digest(maps[mapPath]),
}),
}),
}),
]),
}),
);
expect(graph.coverage.status).toBe("complete");
for (const [path, text] of Object.entries(maps))
expect(await readFile(join(root, path), "utf8")).toBe(text);
},
);
cliTest.for(["CLI", "stdio MCP"] as const)(
"rejects non-string source-map names without inventing originals through %s",
async (surface, { cli }) => {
const root = await createTestTempDirectory("rea-invalid-map-source-");
const mapText = JSON.stringify({
version: 3,
sources: [42, "discarded.ts"],
sourcesContent: [null, "export const answer: number = 42;"],
names: [],
mappings: "ACAA",
});
await writeFixtureFiles(root, { "invalid.js.map": mapText });
const { graph } = await analyzeJavaScriptDirectory(surface, cli, root);
expect(graph.coverage.status).toBe("partial");
expect(
graph.nodes.some(
(node) => node.identity.strategy === "source-map-original",
),
).toBe(false);
expect(graph.nodes).toContainEqual(
expect.objectContaining({
kind: "unknown",
observations: expect.arrayContaining([
expect.objectContaining({
properties: expect.objectContaining({
operation: "parse-local-source-map",
}),
evidence: expect.objectContaining({
artifact: expect.objectContaining({
sha256: createHash("sha256").update(mapText).digest("hex"),
}),
limitations: expect.arrayContaining([
"Source map contains a non-string source name.",
]),
}),
}),
]),
}),
);
expect(await readFile(join(root, "invalid.js.map"), "utf8")).toBe(mapText);
},
);
@@ -1,7 +1,9 @@
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import { writeFile } from "node:fs/promises";
import { readFile, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { join, relative } from "node:path";
import { dirname, join, relative } from "node:path";
import { promisify } from "node:util";
import { expect } from "vitest";
@@ -10,6 +12,318 @@ import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/j
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
import { writeFixtureFiles } from "../../support/javascriptApplicationFixture.js";
const execute = promisify(execFile);
const compiler = join(
dirname(createRequire(import.meta.url).resolve("typescript/package.json")),
"bin",
"tsc",
);
const typedLines = [
'export import typed = require("typed-package");',
'import type TypeOnly = require("./type-only.cjs");',
] as const;
const typedSource = typedLines.join("\n");
const aliasSource = [
'import raw = require("typed-package");',
"const alias = raw;",
"export { alias };",
].join("\n");
const mixedSource = [
'import { value as imported } from "mixed-package";',
'import required = require("mixed-package");',
"const mixed = Date.now() > 0 ? imported : required.value;",
"export { imported as staticChoice, mixed };",
"export const requireChoice = required.value;",
].join("\n");
const typescriptSourceFiles = {
"typed.cts": typedSource,
"typed.mts": typedSource,
"alias.cts": aliasSource,
"alias.mts": aliasSource,
"mixed.cts": mixedSource,
"mixed.mts": mixedSource,
};
const typedPackageFiles = {
"node_modules/typed-package/package.json": JSON.stringify({
exports: { require: "./actual.cjs", import: "./decoy.mjs" },
}),
"node_modules/typed-package/actual.cjs": "module.exports = 42;",
"node_modules/typed-package/actual.d.cts":
"declare const value: number; export = value;",
"node_modules/typed-package/decoy.mjs": "export default 99;",
"node_modules/typed-package/decoy.d.mts":
"declare const value: number; export default value;",
"node_modules/mixed-package/package.json": JSON.stringify({
exports: { require: "./actual.cjs", import: "./decoy.mjs" },
}),
"node_modules/mixed-package/actual.cjs": "exports.value = 42;",
"node_modules/mixed-package/actual.d.cts":
"export declare const value: number;",
"node_modules/mixed-package/decoy.mjs": "export const value = 99;",
"node_modules/mixed-package/decoy.d.mts":
"export declare const value: number;",
};
const expectNativeModuleControls = async (root: string): Promise<void> => {
const emitted = await createTestTempDirectory("rea-import-equals-output-");
await writeFixtureFiles(emitted, typedPackageFiles);
await execute(
process.execPath,
[
compiler,
"--module",
"NodeNext",
"--moduleResolution",
"NodeNext",
"--target",
"ES2022",
"--skipLibCheck",
"--allowJs",
"--outDir",
emitted,
join(root, "typed.cts"),
join(root, "typed.mts"),
join(root, "alias.cts"),
join(root, "alias.mts"),
join(root, "mixed.cts"),
join(root, "mixed.mts"),
],
{ cwd: root, timeout: 10_000 },
);
for (const [filename, script] of [
[
"typed.cjs",
'console.log(require("./typed.cjs").typed, require("./alias.cjs").alias);',
],
[
"typed.mjs",
'Promise.all([import("./typed.mjs"), import("./alias.mjs")]).then(([first, second]) => console.log(first.typed, second.alias));',
],
] as const) {
const typedControl = await execute(process.execPath, ["-e", script], {
cwd: emitted,
timeout: 5_000,
});
expect(typedControl.stdout.trim()).toBe("42 42");
expect(await readFile(join(emitted, filename), "utf8")).not.toContain(
"./type-only.cjs",
);
}
for (const [filename, expected] of [
["mixed.cjs", "42 42 42"],
["mixed.mjs", "99 42 99"],
] as const) {
const control = await execute(
process.execPath,
[
"-e",
`import("./${filename}").then(({staticChoice, requireChoice, mixed}) => console.log(staticChoice, requireChoice, mixed));`,
],
{ cwd: emitted, timeout: 5_000 },
);
expect(control.stdout.trim()).toBe(expected);
}
const nativeRequire = createRequire(join(root, "main.cjs"));
for (const name of ["dependency", "nested"])
expect(
relative(root, nativeRequire.resolve(`./${name}.cjs`)).replaceAll(
"\\",
"/",
),
).toBe(`${name}.cjs`);
};
const expectAliasRelationships = (
graph: ReturnType<
typeof javascriptApplicationAnalysisResultSchema.parse
>["graph"],
): void => {
for (const source of ["alias.cts", "alias.mts"]) {
expect(graph.edges).toContainEqual(
expect.objectContaining({
relation: "imports",
properties: expect.objectContaining({
module_link_kind: "export",
local_name: "alias",
exported_name: "alias",
resolution_mode: "require",
resolved_path: "node_modules/typed-package/actual.cjs",
resolution_status: "resolved",
}),
evidence: expect.objectContaining({
artifact: expect.objectContaining({
sha256: createHash("sha256").update(aliasSource).digest("hex"),
}),
location: expect.objectContaining({
value: expect.objectContaining({ source }),
}),
}),
}),
);
}
};
const expectMixedRelationships = (
graph: ReturnType<
typeof javascriptApplicationAnalysisResultSchema.parse
>["graph"],
): void => {
const exported = (source: string, name: string) =>
graph.edges.filter(
({ relation, properties, evidence }) =>
relation === "imports" &&
properties.module_link_kind === "export" &&
properties.exported_name === name &&
evidence.location.available &&
evidence.location.value.kind === "source-range" &&
evidence.location.value.source === source,
);
for (const source of ["mixed.cts", "mixed.mts"]) {
for (const [name, target] of [
["staticChoice", source.endsWith(".cts") ? "actual.cjs" : "decoy.mjs"],
["requireChoice", "actual.cjs"],
] as const)
expect(exported(source, name)).toMatchObject([
{
properties: {
resolved_path: `node_modules/mixed-package/${target}`,
resolution_status: "resolved",
},
evidence: {
artifact: {
sha256: createHash("sha256").update(mixedSource).digest("hex"),
},
},
},
]);
}
expect(exported("mixed.cts", "mixed")).toMatchObject([
{
properties: {
resolved_path: "node_modules/mixed-package/actual.cjs",
resolution_status: "resolved",
},
evidence: {
artifact: {
sha256: createHash("sha256").update(mixedSource).digest("hex"),
},
},
},
]);
expect(exported("mixed.mts", "mixed")).toEqual([]);
};
const expectImportEqualsRelationships = (
graph: ReturnType<
typeof javascriptApplicationAnalysisResultSchema.parse
>["graph"],
): void => {
for (const [sourcePath, format] of [
["typed.cts", "commonjs"],
["typed.mts", "esm"],
] as const) {
const typedLinks = graph.edges.filter(
({ relation, properties, evidence: edgeEvidence }) =>
relation === "imports" &&
properties.module_link_kind === "require" &&
edgeEvidence.location.available &&
edgeEvidence.location.value.kind === "source-range" &&
edgeEvidence.location.value.source === sourcePath,
);
expect(typedLinks).toHaveLength(1);
expect(typedLinks[0]).toMatchObject({
properties: {
specifier: "typed-package",
imported_name: null,
local_name: "typed",
resolved_path: "node_modules/typed-package/actual.cjs",
resolution_status: "resolved",
},
evidence: {
artifact: {
available: true,
sha256: createHash("sha256").update(typedSource).digest("hex"),
},
location: {
available: true,
value: {
source: sourcePath,
start: { line: 1, column: 7 },
end: { line: 1, column: typedLines[0].length },
},
},
},
});
expect(graph.edges).toContainEqual(
expect.objectContaining({
relation: "imports",
properties: expect.objectContaining({
module_link_kind: "export",
local_name: "typed",
resolution_mode: "require",
resolved_path: "node_modules/typed-package/actual.cjs",
}),
evidence: expect.objectContaining({
location: expect.objectContaining({
value: expect.objectContaining({ source: sourcePath }),
}),
}),
}),
);
expect(
graph.nodes.flatMap(({ observations }) => observations),
).toContainEqual(
expect.objectContaining({
properties: expect.objectContaining({
semantic_role: "source-module",
path: sourcePath,
export_names: ["typed"],
export_relationships: 1,
}),
}),
);
expect(
graph.edges.filter(
({ relation, evidence: edgeEvidence }) =>
relation === "exposes" &&
edgeEvidence.location.available &&
edgeEvidence.location.value.kind === "source-range" &&
edgeEvidence.location.value.source === sourcePath,
),
).toHaveLength(1);
expect(graph.edges).toContainEqual(
expect.objectContaining({
relation: "imports",
properties: expect.objectContaining({
kind: "require",
specifier: "typed-package",
resolved_path: "node_modules/typed-package/actual.cjs",
}),
}),
);
expect(
graph.nodes.flatMap(({ observations }) => observations),
).toContainEqual(
expect.objectContaining({
properties: expect.objectContaining({
semantic_role: "source-module",
path: sourcePath,
module_format: format,
import_relationships: 1,
}),
}),
);
}
expect(
graph.edges.filter(
({ relation, properties }) =>
relation === "imports" && properties.specifier === "./type-only.cjs",
),
).toHaveLength(0);
};
cliTest.for(["CLI", "stdio MCP"] as const)(
"retains unbound CommonJS semantic relationships through %s",
@@ -34,20 +348,16 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
"imports.mjs": 'import "./dependency.cjs";',
"dependency.cjs": 'throw new Error("fixture must not execute");',
"nested.cjs": 'throw new Error("fixture must not execute");',
...typescriptSourceFiles,
"type-only.d.cts": "declare const value: unknown; export = value;",
};
await Promise.all(
Object.entries(files).map(([path, text]) =>
writeFile(join(root, path), text),
),
);
const nativeRequire = createRequire(join(root, "main.cjs"));
for (const name of ["dependency", "nested"])
expect(
relative(root, nativeRequire.resolve(`./${name}.cjs`)).replaceAll(
"\\",
"/",
),
).toBe(`${name}.cjs`);
await writeFixtureFiles(root, typedPackageFiles);
await expectNativeModuleControls(root);
let document: unknown;
if (surface === "CLI") {
@@ -70,6 +380,9 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
const { graph } = javascriptApplicationAnalysisResultSchema.parse(
evidence.normalized_result,
);
expectImportEqualsRelationships(graph);
expectAliasRelationships(graph);
expectMixedRelationships(graph);
const links = graph.edges.filter(
({ relation, properties, evidence: edgeEvidence }) =>
relation === "imports" &&
@@ -0,0 +1,52 @@
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
cliTest(
"reports Webpack exports attached to renamed factory parameters",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-webpack-renamed-exports-");
await mkdir(join(root, "src"));
await writeFile(
join(root, "src", "chunk.js"),
`globalThis.webpackChunkApp.push([[1], {
17(module, __webpack_exports__, __webpack_require__) {
__webpack_require__.d(__webpack_exports__, { alpha: () => 1, "beta.gamma": () => 2 });
Object.defineProperty(__webpack_exports__, "delta", { enumerable: true, get() { return 3; } });
__webpack_require__.d(__webpack_exports__.nested, { nested_target: () => 0 });
__webpack_exports__ = { rebound: () => 0 };
__webpack_require__.d({}, { unrelated: () => 0 });
{ const exports = {}; __webpack_require__.d(exports, { shadowed_exports: () => 5 }); }
},
23(m, e, r) { r.d(e, { alpha: () => 1 }); }
}]);`,
);
const response = await cli.run({
arguments: ["analyze-javascript-application", root, "--format", "json"],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(response.exitCode).toBe(0);
const result = javascriptApplicationAnalysisResultSchema.parse(
parseEvidence(response.json).normalized_result,
);
const modules = result.graph.nodes
.filter(({ kind }) => kind === "javascript-module")
.map(({ observations }) => observations[0]?.properties);
expect(modules).toEqual(
expect.arrayContaining([
expect.objectContaining({
module_key: "17",
exports: ["alpha", "beta.gamma", "delta"],
}),
expect.objectContaining({ module_key: "23", exports: ["alpha"] }),
]),
);
expect(result.graph.coverage.status).toBe("complete");
},
);
@@ -0,0 +1,84 @@
import { execFile } from "node:child_process";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { expect, it } from "vitest";
import { artifactInspectionResultSchema } from "../../src/domain/artifactInspection.js";
import { parseEvidence } from "../../src/domain/evidence.js";
import { connectLocalToolsMcp } from "../fixtures/localToolsMcp.js";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
const execute = promisify(execFile);
const cli = fileURLToPath(new URL("../../scripts/rea.mjs", import.meta.url));
const plist =
'<?xml version="1.0"?><plist version="1.0"><dict><key>label</key><string>hello</string></dict></plist>';
it("compares identical complete plist inventories across CLI and MCP and creates no unknowns", async () => {
const root = await createTestTempDirectory("rea-plist-compare-acceptance-");
const leftPath = join(root, "left.plist");
const rightPath = join(root, "right.plist");
await Promise.all([writeFile(leftPath, plist), writeFile(rightPath, plist)]);
const cliResult = await execute(process.execPath, [
cli,
"inspect-artifact",
leftPath,
"--json",
]);
const cliInspection = artifactInspectionResultSchema.parse(
parseEvidence(JSON.parse(cliResult.stdout)).normalized_result,
);
const cliInventory = cliInspection.substeps[0]?.evidence;
if (cliInventory === undefined)
throw new Error("CLI inspection did not retain inventory Evidence");
expect(cliInventory.normalized_result).toMatchObject({
coverage_status: "complete",
limitations: ["Artifact has no child container entries."],
});
const { call } = await connectLocalToolsMcp();
const opened = await call("open_binary", { path: rightPath });
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
const inspected = await call("inspect_artifact", {});
expect(inspected.isError, JSON.stringify(inspected)).not.toBe(true);
const mcpInspection = artifactInspectionResultSchema.parse(
parseEvidence(inspected.structuredContent).normalized_result,
);
const mcpInventory = mcpInspection.substeps[0]?.evidence;
if (mcpInventory === undefined)
throw new Error("MCP inspection did not retain inventory Evidence");
expect(mcpInventory.normalized_result).toMatchObject({
coverage_status: "complete",
limitations: ["Artifact has no child container entries."],
});
const compared = await call("compare_artifacts", {
left: cliInventory,
right: mcpInventory,
});
expect(compared.isError, JSON.stringify(compared)).not.toBe(true);
const comparison = parseEvidence(compared.structuredContent);
expect(comparison.normalized_result).toMatchObject({
status: "unchanged",
summary: { unchanged: 1, unknown: 0 },
changes: [],
});
const behavior = await call("find_changed_behavior", {
comparisons: [comparison],
});
expect(behavior.isError, JSON.stringify(behavior)).not.toBe(true);
expect(behavior.structuredContent).toMatchObject({
normalized_result: {
behavior_status: "unknown",
findings: { items: [] },
},
});
const unknowns = await call("list_unknowns", {
domain: "artifact-comparison",
});
expect(unknowns.isError, JSON.stringify(unknowns)).not.toBe(true);
expect(unknowns.structuredContent).toMatchObject({ result: { items: [] } });
});
@@ -0,0 +1,148 @@
import { execFile } from "node:child_process";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { Uint8ArrayReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { expect, it } from "vitest";
import { artifactInspectionResultSchema } from "../../src/domain/artifactInspection.js";
import { artifactInventoryResultSchema } from "../../src/domain/artifactGraph.js";
import { parseEvidence } from "../../src/domain/evidence.js";
import {
fatImage,
CPU,
machoImage,
} from "../../src/artifacts/apple/MachoImage.fixture.js";
import { javaClassFile } from "../fixtures/javaClassFile.js";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
const execute = promisify(execFile);
const cli = fileURLToPath(new URL("../../scripts/rea.mjs", import.meta.url));
const archive = async (
entries: readonly (readonly [string, Uint8Array])[],
): Promise<Buffer> => {
const writer = new ZipWriter(new Uint8ArrayWriter());
for (const [name, bytes] of entries)
await writer.add(name, new Uint8ArrayReader(bytes));
return Buffer.from(await writer.close());
};
const inspectArchive = async (path: string) => {
const result = await execute(process.execPath, [
cli,
"inspect-artifact",
path,
"--json",
]);
const inspection = artifactInspectionResultSchema.parse(
parseEvidence(JSON.parse(result.stdout)).normalized_result,
);
const evidence = inspection.substeps[0]?.evidence;
if (evidence === undefined)
throw new Error("CLI inspection did not retain inventory Evidence");
return artifactInventoryResultSchema.parse(evidence.normalized_result);
};
it("keeps valid JVM classes from being classified as Mach-O while identifying FAT controls", async () => {
const directory = await createTestTempDirectory("rea-jvm-inventory-");
const javaEntries = [
["Hello.class", javaClassFile()],
["pkg/Big.class", javaClassFile(4000)],
] as const;
const fatControls = [
[
"fat-be32.bin",
fatImage([{ cpu: CPU.arm64, bytes: machoImage({ cpu: CPU.arm64 }) }]),
],
[
"fat-le32.bin",
fatImage(
[{ cpu: CPU.arm64, bytes: machoImage({ cpu: CPU.arm64 }) }],
false,
true,
),
],
[
"fat-be64.bin",
fatImage(
[{ cpu: CPU.arm64, bytes: machoImage({ cpu: CPU.arm64 }) }],
true,
),
],
[
"fat-le64.bin",
fatImage(
[{ cpu: CPU.arm64, bytes: machoImage({ cpu: CPU.arm64 }) }],
true,
true,
),
],
] as const;
const jarPath = join(directory, "classes.jar");
await writeFile(
jarPath,
await archive([
["META-INF/MANIFEST.MF", Buffer.from("Manifest-Version: 1.0\n\n")],
...javaEntries,
]),
);
const jar = await inspectArchive(jarPath);
expect(
jar.occurrences
.filter(({ logical_path }) => logical_path.endsWith(".class"))
.map(({ logical_path, artifact_kind, artifact_format }) => ({
logical_path,
artifact_kind,
artifact_format,
})),
).toEqual([
{
logical_path: "Hello.class",
artifact_kind: "resource",
artifact_format: "file",
},
{
logical_path: "pkg/Big.class",
artifact_kind: "unknown",
artifact_format: "unknown",
},
]);
const jarClassIds = new Set(
jar.occurrences
.filter(({ logical_path }) => logical_path.endsWith(".class"))
.map(({ artifact_id }) => artifact_id),
);
expect(
jar.nodes
.filter(({ artifact_id }) => jarClassIds.has(artifact_id))
.map(({ format }) => format)
.sort(),
).toEqual(["file", "unknown"]);
const mixedPath = join(directory, "mixed.zip");
await writeFile(mixedPath, await archive([...javaEntries, ...fatControls]));
const mixed = await inspectArchive(mixedPath);
const formatsByPath = new Map(
mixed.occurrences.map(
({ logical_path, artifact_kind, artifact_format }) => [
logical_path,
{ artifact_kind, artifact_format },
],
),
);
for (const [name] of javaEntries)
expect(formatsByPath.get(name)).toEqual(
name === "Hello.class"
? { artifact_kind: "resource", artifact_format: "file" }
: { artifact_kind: "unknown", artifact_format: "unknown" },
);
for (const [name] of fatControls)
expect(formatsByPath.get(name)).toEqual({
artifact_kind: "executable",
artifact_format: "mach-o-universal",
});
});
+154
View File
@@ -0,0 +1,154 @@
import { createHash } from "node:crypto";
import { expect } from "vitest";
import { toolContract } from "../../src/contracts/toolContracts.js";
import { parseEvidence } from "../../src/domain/evidence.js";
import {
aotFixtureImage,
engineFixtureImage,
REFERENCE_HASH,
} from "../../src/flutter/FlutterBuild.fixture.js";
import {
createFlutterApk,
createDuplicateFlutterApk,
} from "../fixtures/flutterApk.js";
import { connectLocalToolsMcp } from "../fixtures/localToolsMcp.js";
import { parseMcpToolError } from "../fixtures/mcpToolError.js";
import { cliTest } from "../support/cli/cliFixture.js";
cliTest(
"CLI and stdio MCP retain Flutter identity, selected ABI and duplicate-member refusals",
async ({ cli }) => {
const image = aotFixtureImage();
Buffer.from("Login\0").copy(image, 0x2300);
const engine = engineFixtureImage({
notes: Buffer.from(
"040000000800000003000000474e55000123456789abcdef",
"hex",
),
prefix: Buffer.from(
"040000000800000003000000474e55001111111111111111",
"hex",
),
labels: ["Android (test) clang version 9.0.8"],
});
const path = await createFlutterApk("selected target.apk", [
{ path: "lib/arm64-v8a/libapp.so", bytes: image },
{
path: "lib/arm64-v8a/libflutter.so",
bytes: engine,
},
{ path: "lib/x86_64/libapp.so", bytes: image },
{
path: "lib/x86_64/libflutter.so",
bytes: engine,
},
]);
const { call } = await connectLocalToolsMcp();
for (const [name, abi] of [
["identify_flutter_build", undefined],
["inspect_dart_aot", undefined],
["inspect_dart_aot", "x86_64"],
] as const) {
const result = await cli.run({
arguments: [
name.replaceAll("_", "-"),
path,
"--json",
...(abi === undefined ? [] : ["--abi", abi]),
],
});
expect(result.exitCode, result.stderr).toBe(0);
const evidence = toolContract(name).outputSchema.parse(result.json);
const response = await call(name, {
path,
...(abi === undefined ? {} : { abi }),
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
const mcp = parseEvidence(response.structuredContent);
expect(mcp.normalized_result).toEqual(evidence.normalized_result);
expect(mcp.subject).toEqual(evidence.subject);
expect(mcp.subject).toMatchObject({
local_path: path,
format: "apk",
digest: { sha256: evidence.normalized_result.target.sha256 },
});
expect(mcp.evidence_id).toBe(evidence.evidence_id);
if (name === "inspect_dart_aot") {
expect(evidence.normalized_result).toMatchObject({
abi: abi ?? "arm64-v8a",
libapp: {
coverage: "complete",
snapshot_hash: REFERENCE_HASH,
sha256: createHash("sha256").update(image).digest("hex"),
},
string_pool: {
coverage: "complete",
class_like_tokens: expect.arrayContaining(["Login"]),
},
});
} else {
const identified = toolContract(
"identify_flutter_build",
).outputSchema.parse(result.json).normalized_result;
expect(identified.coverage).toBe("complete");
for (const abi of identified.abis) {
expect(abi.libflutter).toMatchObject({
build_id: "0123456789abcdef",
build_id_candidates: ["0123456789abcdef"],
});
}
}
}
const duplicate = await createDuplicateFlutterApk();
for (const name of [
"identify_flutter_build",
"inspect_dart_aot",
] as const) {
const result = await cli.run({
arguments: [name.replaceAll("_", "-"), duplicate, "--json"],
});
expect(result.exitCode).toBe(1);
const mcp = parseMcpToolError(await call(name, { path: duplicate }));
expect(mcp.error).toEqual(result.json);
expect(mcp.error).toMatchObject({
code: "invalid_request",
details: { issues: [{ message: expect.stringContaining(duplicate) }] },
});
}
},
);
cliTest(
"CLI and MCP retain unsupported snapshot kinds as partial evidence",
async ({ cli }) => {
const image = aotFixtureImage();
for (const offset of [0x1000, 0x2000])
image.writeBigUInt64LE(4n, offset + 12);
const path = await createFlutterApk("unsupported-kind.apk", [
{ path: "lib/arm64-v8a/libapp.so", bytes: image },
]);
const result = await cli.run({
arguments: ["inspect-dart-aot", path, "--json"],
});
expect(result.exitCode, result.stderr).toBe(0);
const evidence = toolContract("inspect_dart_aot").outputSchema.parse(
result.json,
);
const { call } = await connectLocalToolsMcp();
const response = await call("inspect_dart_aot", { path });
expect(response.isError, JSON.stringify(response)).not.toBe(true);
expect(parseEvidence(response.structuredContent).normalized_result).toEqual(
evidence.normalized_result,
);
expect(evidence.normalized_result).toMatchObject({
coverage: "partial",
libapp: { coverage: "partial", snapshot_hash: REFERENCE_HASH },
string_pool: { coverage: "complete" },
});
expect(
evidence.normalized_result.libapp.sections
.filter((section) => section.name.endsWith("Data"))
.map((section) => section.kind),
).toEqual([4, 4]);
},
);
+223
View File
@@ -0,0 +1,223 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { createHash } from "node:crypto";
import { expect } from "vitest";
import { toolContract } from "../../src/contracts/toolContracts.js";
import {
createGoBinaryByteStringFixture,
createGoBinaryDiagnosticFixtures,
createGoBinaryFixture,
createGoBinaryPathFailureFixture,
GO_MODULE_TEXT,
} from "../fixtures/go/image.js";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
import { cliTest } from "../support/cli/cliFixture.js";
for (const expectedErrno of ["ELOOP", "ENAMETOOLONG"] as const) {
cliTest.skipIf(expectedErrno === "ELOOP" && process.platform === "win32")(
`reports native ${expectedErrno} path failure as invalid selected-path input through the public Go CLI`,
async ({ cli }) => {
const root = await createTestTempDirectory("rea-go-cli-path-failure-");
const { path, errno } = await createGoBinaryPathFailureFixture(
root,
expectedErrno,
);
const result = await cli.run({
arguments: ["inspect-go-binary", path, "--json"],
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "invalid_request",
details: {
operation: "inspect_go_binary",
issues: [
{
path: ["path"],
reason: "invalid_value",
message: expect.stringContaining(errno),
},
],
},
});
expect(result.json).toMatchObject({
details: { issues: [{ message: expect.stringContaining(path) }] },
});
},
);
}
cliTest(
"preserves invalid embedded Go text bytes through the public CLI",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-go-cli-byte-strings-");
const path = join(root, "byte-strings.elf");
const fixture = createGoBinaryByteStringFixture();
await writeFile(path, fixture.bytes);
const result = await cli.run({
arguments: ["inspect-go-binary", path, "--json"],
});
expect(result.exitCode, result.stderr).toBe(0);
const evidence = toolContract("inspect_go_binary").outputSchema.parse(
result.json,
);
expect(evidence.normalized_result.build_info).toEqual(
fixture.expectedBuildInfo,
);
},
);
for (const fixture of createGoBinaryDiagnosticFixtures()) {
cliTest(
`reports ${fixture.code} for ${fixture.name} through the public Go CLI`,
async ({ cli }) => {
const root = await createTestTempDirectory("rea-go-cli-mz-");
const path = join(root, `${fixture.name}.exe`);
await writeFile(path, fixture.bytes);
const result = await cli.run({
arguments: ["inspect-go-binary", path, "--json"],
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: fixture.code,
details: {
...fixture.details,
...(fixture.code === "unsupported_target" ? { path } : {}),
},
});
},
);
}
cliTest(
"reports a readable unsupported carrier through the public Go CLI",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-go-cli-");
const path = join(root, "text.bin");
await writeFile(path, "This is not an executable container.");
const result = await cli.run({
arguments: ["inspect-go-binary", path, "--json"],
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "unsupported_target",
details: { operation: "inspect_go_binary", path },
});
},
);
for (const format of ["elf", "pe", "macho"] as const) {
for (const encoding of ["inline", "pointer"] as const) {
cliTest(
`inspects authored ${format} ${encoding} build metadata through the compiled CLI`,
async ({ cli }) => {
const root = await createTestTempDirectory("rea-go-cli-");
const fixture = createGoBinaryFixture({ format, encoding });
const path = join(root, "application.bin");
await writeFile(path, fixture.bytes);
const result = await cli.run({
arguments: ["inspect-go-binary", "application.bin", "--json"],
cwd: root,
});
expect(result.exitCode, result.stderr).toBe(0);
const evidence = toolContract("inspect_go_binary").outputSchema.parse(
result.json,
);
expect(evidence.raw_result).toBeNull();
expect(evidence.subject?.local_path).toBe(path);
expect(evidence.subject?.digest.sha256).toBe(
createHash("sha256").update(fixture.bytes).digest("hex"),
);
const report = evidence.normalized_result;
expect(report).toMatchObject({
format,
bits: 64,
byte_order: "little",
artifact: { path, bytes: fixture.bytes.length },
});
expect(report.build_info).toMatchObject({
header_offset: fixture.headerOffset,
encoding,
go_version: "go1.26.0",
module_text: GO_MODULE_TEXT,
module_bytes_base64: fixture.moduleBytes.toString("base64"),
module: {
path: "example.com/tool/cmd/tool",
main: {
path: "example.com/tool",
version: "(devel)",
sum: "",
replacement: null,
},
dependencies: [
{
path: "example.com/dependency",
version: "v1.2.3",
sum: "h1:sample",
replacement: { path: "../dependency", version: "", sum: "" },
},
],
complete: true,
unparsed_lines: [],
},
});
expect(report.build_info?.module.settings).toContainEqual({
key: "-ldflags",
value: "-s -w",
});
if (report.build_info === null)
throw new Error("Fixture build metadata must be present");
const version = report.build_info.version_location;
const module = report.build_info.module_location;
expect(
fixture.bytes
.subarray(version.offset, version.offset + version.bytes)
.toString("utf8"),
).toBe(report.build_info.go_version);
expect(
fixture.bytes.subarray(module.offset, module.offset + module.bytes),
).toEqual(Buffer.from(report.build_info.module_bytes_base64, "base64"));
},
);
}
}
cliTest("preserves MIPS identity in Go CLI Evidence", async ({ cli }) => {
const root = await createTestTempDirectory("rea-go-cli-mips-");
const fixture = createGoBinaryFixture();
fixture.bytes.writeUInt16LE(8, 18); // ELF EM_MIPS.
const path = join(root, "application.elf");
await writeFile(path, fixture.bytes);
const result = await cli.run({
arguments: ["inspect-go-binary", path, "--json"],
});
expect(result.exitCode, result.stderr).toBe(0);
const evidence = toolContract("inspect_go_binary").outputSchema.parse(
result.json,
);
expect(evidence.subject?.architecture).toBe("mips");
expect(evidence.normalized_result).toMatchObject({
architecture: "mips",
bits: 64,
byte_order: "little",
});
});
cliTest(
"reports missing build information as unknown and preserves unsupported carriers distinctly",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-go-cli-");
const path = join(root, "metadata-free.elf");
await writeFile(path, createGoBinaryFixture({ omitBuildInfo: true }).bytes);
const result = await cli.run({
arguments: ["inspect-go-binary", path, "--json"],
});
expect(result.exitCode).toBe(0);
const report = toolContract("inspect_go_binary").outputSchema.parse(
result.json,
).normalized_result;
expect(report.build_info).toBeNull();
expect(report.limitations.join(" ")).toContain(
"does not establish that the binary is not Go",
);
},
);
+65
View File
@@ -177,6 +177,38 @@ cliTest(
},
);
cliTest(
"managed CLI rejects repeated or empty type selections as invalid input",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-managed-cli-types-");
const path = join(root, "fixture.dll");
await writeFile(path, buildManagedPeFixture());
for (const [types, message] of [
[["Fixture.Empty0", "Fixture.Empty0"], "must not repeat a name"],
[[""], ">=1 characters"],
] as const) {
const result = await cli.run({
arguments: [
"inspect-managed-members",
path,
...types.flatMap((type) => ["--type", type]),
"--json",
],
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "VALIDATION_ERROR",
fieldErrors: [
expect.objectContaining({
path: expect.stringMatching(/^type/u),
message: expect.stringContaining(message),
}),
],
});
}
},
);
cliTest(
"managed CLI bounds CIL claims by section virtual ranges",
async ({ cli }) => {
@@ -275,3 +307,36 @@ cliTest(
}
},
);
cliTest(
"managed CLI reports a section table past EOF as invalid input",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-managed-cli-sections-");
const path = join(root, "fixture.dll");
const bytes = buildManagedPeFixture();
const pe = bytes.readUInt32LE(0x3c);
const sections = pe + 24 + bytes.readUInt16LE(pe + 20);
bytes.writeUInt32LE(bytes.length + 0x1000, sections + 20);
await writeFile(path, bytes);
for (const command of [
"inspect-managed-artifact",
"inspect-managed-members",
"inspect-managed-native-boundaries",
]) {
const result = await cli.run({ arguments: [command, path, "--json"] });
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "invalid_request",
details: {
issues: [
{
path: ["path"],
reason: "invalid_format",
message: expect.stringContaining("pe.section-data"),
},
],
},
});
}
},
);
@@ -30,7 +30,7 @@ type CaptureOutcome =
| { readonly kind: "partial"; readonly partial: unknown };
const captureScenario = (
mode: "cooperative" | "ignoring" | "descendant",
mode: "cooperative" | "ignoring" | "delayed-ignoring" | "descendant",
root: string,
additions: CaptureScenario = {},
finalExitCode?: number,
@@ -453,11 +453,13 @@ captureTest(
"rea-finalization-cli-cancel-",
);
const cliScenarioPath = join(cliRoot, "scenario.json");
// Match the other finalization cases' observation window. The old 300 ms
// deadline could signal the fixture before it installed its handlers.
await writeFile(
cliScenarioPath,
JSON.stringify(
captureScenario("ignoring", cliRoot, {
timeout_ms: 300,
captureScenario("delayed-ignoring", cliRoot, {
timeout_ms: 1_500,
finalization_ms: 20_000,
}),
),
@@ -527,18 +529,36 @@ captureTest(
const mcpRoot = await createTestTempDirectory(
"rea-finalization-mcp-cancel-",
);
const { client } = await connectLocalToolsMcp();
const { client, call: callTool } = await connectLocalToolsMcp();
const controller = new AbortController();
const call = client.callTool(
{
name: "capture_process_scenario",
arguments: captureScenario("ignoring", mcpRoot, {
timeout_ms: 300,
finalization_ms: 20_000,
}),
},
{ signal: controller.signal },
let reportStarted: (() => void) | undefined;
const captureStarted = new Promise<void>((resolve) => {
reportStarted = resolve;
});
const call = callTool(
"capture_process_scenario",
captureScenario("delayed-ignoring", mcpRoot, {
timeout_ms: 1_500,
finalization_ms: 20_000,
}),
{ signal: controller.signal, onprogress: () => reportStarted?.() },
);
// Observe rejection immediately: a failed readiness wait must not leave a
// pending request to reject unhandled when the fixture closes its client.
// The original promise remains available for the cancellation assertion.
const observedCall = call.catch(() => undefined);
onTestFinished(async () => {
controller.abort();
await observedCall;
});
// Start the fixture's readiness wait after the server begins this capture;
// SDK schema preparation before dispatch is not target startup time.
await Promise.race([
captureStarted,
call.then(() => {
throw new Error("MCP capture completed before reporting startup");
}),
]);
const mcpFixturePid = await waitForFinalization(mcpRoot);
const mcpStarted = Date.now();
controller.abort(new Error("cancel finalization acceptance fixture"));
@@ -548,7 +568,7 @@ captureTest(
).rejects.toThrow("cancel finalization acceptance fixture");
await waitForProcessExit(mcpFixturePid);
await expect(
client.listTools(),
client.listTools(undefined, { cacheMode: "refresh" }),
"the server accepts a follow-up request after cancelling the capture",
).resolves.toMatchObject({ tools: expect.any(Array) });
expect(
@@ -0,0 +1,154 @@
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { expect } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
const cases = [
{
client: "cursor",
path: ".cursor/mcp.json",
text: "[]",
diagnostic: "The configuration root must be an object",
},
{
client: "cursor",
path: ".cursor/mcp.json",
text: "null",
diagnostic: "The configuration root must be an object",
},
{
client: "cursor",
path: ".cursor/mcp.json",
text: '{"mcpServers":null,"keep":1}',
diagnostic: '"mcpServers" must be an object',
},
{
client: "cursor",
path: ".cursor/mcp.json",
text: '{"mcpServers":"x","keep":1}',
diagnostic: '"mcpServers" must be an object',
},
{
client: "pi",
path: ".pi/agent/mcp.json",
text: '{"mcpServers":[]}',
diagnostic: '"mcpServers" must be an object',
},
{
client: "codex",
path: ".codex/config.toml",
text: 'mcp_servers = "x"\n',
diagnostic: '"mcp_servers" must be an object',
},
{
client: "opencode",
path: ".config/opencode/opencode.json",
text: '{"mcp":{"servers":null}}',
diagnostic: '"mcp.servers" must be an object',
},
{
client: "hermes",
path: ".hermes/config.yaml",
text: "- item\n",
diagnostic: "The configuration root must be an object",
},
{
client: "hermes",
path: ".hermes/config.yaml",
text: "mcp_servers: null\nkeep: 1\n",
diagnostic: '"mcp_servers" must be an object',
},
{
client: "cursor",
path: ".cursor/mcp.json",
text: "not-json",
diagnostic: "Configuration is not valid JSON",
syntax: "JSON",
},
{
client: "hermes",
path: ".hermes/config.yaml",
text: "mcp_servers: [\n",
diagnostic: "Configuration is not valid YAML",
syntax: "YAML",
},
{
client: "dsh",
path: ".dsh/cordis.patch.yml",
text: "- insert: [\n",
diagnostic: "Configuration is not valid YAML",
syntax: "YAML",
},
] as const;
for (const scenario of cases)
cliTest(
`setup and uninstall explain ${scenario.client} configuration ${scenario.text}`,
async ({ cli }) => {
const home = await createTestTempDirectory(
"rea-client-config-diagnostic-",
);
const config = join(home, scenario.path);
await mkdir(dirname(config), { recursive: true });
await writeFile(config, scenario.text);
const environment = {
HOME: home,
USERPROFILE: home,
XDG_CONFIG_HOME: join(home, ".config"),
HERMES_HOME: join(home, ".hermes"),
DSH_HOME: join(home, ".dsh"),
};
const setup = await cli.run({
arguments: [
"setup",
"--client",
scenario.client,
"--skill=false",
"--yes",
"--json",
],
cwd: home,
environment,
});
expect(setup.exitCode).toBe(1);
expect(setup.json).toMatchObject({
status: "needs_human",
plannedActions: [],
appliedActions: [],
});
if ("syntax" in scenario) {
expect(setup.json).toMatchObject({ remediation: expect.any(String) });
if (scenario.syntax === "JSON")
expect(setup.stdout).toContain("Invalid JSON/JSONC");
} else {
expect(setup.json).toMatchObject({
remediation: expect.stringContaining(scenario.diagnostic),
});
expect(setup.stdout).not.toContain("invalid_type");
}
const uninstall = await cli.run({
arguments: ["uninstall", "--json"],
cwd: home,
environment,
});
expect(uninstall.exitCode).toBe(1);
expect(uninstall.json).toMatchObject({
status: "failed",
items: expect.arrayContaining([
expect.objectContaining({
name: scenario.client,
status: "failed",
detail: expect.stringContaining(scenario.diagnostic),
}),
]),
});
if (!("syntax" in scenario))
expect(uninstall.stdout).not.toContain("not valid JSON");
expect(await readFile(config, "utf8")).toBe(scenario.text);
expect(await readdir(dirname(config))).toEqual([
scenario.path.split("/").at(-1),
]);
},
);
@@ -0,0 +1,299 @@
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);
},
);
cliTest.for([
{
label: "group-owned rows",
patch: `- id: tools
insert:
- id: other
name: caller-plugin
- id: rea-mcp
name: '@deepseek-ai/dsh-mcp-client'
config: {serverName: rea, transport: stdio, command: stale, args: [mcp]}
`,
remediation: "group with unknown activity",
removal: "removed",
},
{
label: "expression-backed inserts",
patch: "- insert: !!js process.env.DSH_ROWS\n",
remediation: "unknown structure",
removal: "retained",
},
])(
"DSH CLI rejects setup and preserves ownership for $label",
async ({ patch, remediation, removal }, { cli }) => {
const home = await createTestTempDirectory("rea-dsh-ownership-");
const profile = join(home, ".dsh");
const config = join(profile, "cordis.patch.yml");
await mkdir(profile);
await writeFile(config, patch);
const run = (args: readonly string[]) =>
cli.run({
arguments: [...args, "--json"],
cwd: home,
environment: { HOME: home, USERPROFILE: home, DSH_HOME: profile },
});
const setup = await run(["setup", "--client", "dsh", "--yes"]);
expect(setup.exitCode).not.toBe(0);
expect(setup.json).toMatchObject({
status: "needs_human",
appliedActions: [],
remediation: expect.stringContaining(remediation),
});
expect(await readFile(config, "utf8")).toBe(patch);
await expect(readFile(`${config}.rea.backup`)).rejects.toMatchObject({
code: "ENOENT",
});
const uninstall = await run(["uninstall"]);
expect(uninstall.exitCode).toBe(0);
expect(uninstall.json).toMatchObject({
status: "complete",
items: expect.arrayContaining([
expect.objectContaining({ name: "dsh", status: removal }),
]),
});
if (removal === "removed") {
expect(parse(await readFile(config, "utf8"))).toEqual([
{ id: "tools", insert: [{ id: "other", name: "caller-plugin" }] },
]);
expect(await readFile(`${config}.rea.backup`, "utf8")).toBe(patch);
} else {
expect(await readFile(config, "utf8")).toBe(patch);
await expect(readFile(`${config}.rea.backup`)).rejects.toMatchObject({
code: "ENOENT",
});
}
},
);
@@ -0,0 +1,139 @@
import { access, mkdir, readFile } from "node:fs/promises";
import { userInfo } from "node:os";
import { isAbsolute, join, relative, sep } from "node:path";
import { parse } from "jsonc-parser";
import { expect } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
cliTest(
"setup dry run resolves empty home values without writing to the cwd",
async ({ cli }) => {
const directory = await createTestTempDirectory("rea-empty-home-dry-run-");
const workingDirectory = join(directory, "cwd");
await mkdir(workingDirectory);
const hostHome = userInfo().homedir;
const result = await cli.run({
arguments: [
"setup",
"--client",
"cursor",
"--skill=false",
"--dry-run",
"--json",
],
cwd: workingDirectory,
environment: {
HOME: "",
USERPROFILE: "",
HOMEDRIVE: "",
HOMEPATH: "",
XDG_CONFIG_HOME: "",
},
});
expect(result.exitCode, result.stdout).toBe(0);
const output = result.json as {
plannedActions?: Array<{ kind?: unknown; target?: unknown }>;
status?: unknown;
};
expect(["planned", "ready"]).toContain(output.status);
const configTargets = (output.plannedActions ?? [])
.filter((action) => action.kind === "configure_client")
.map((action) => action.target);
for (const target of configTargets) {
expect(typeof target).toBe("string");
if (typeof target !== "string") continue;
expect(isAbsolute(target)).toBe(true);
const relativeTarget = relative(hostHome, target);
expect(
relativeTarget === "" ||
(!relativeTarget.startsWith(`..${sep}`) && relativeTarget !== ".."),
).toBe(true);
}
expect(configTargets).not.toContain(
join(workingDirectory, ".cursor", "mcp.json"),
);
await expect(
access(join(workingDirectory, ".cursor", "mcp.json")),
).rejects.toMatchObject({
code: "ENOENT",
});
},
);
cliTest.skipIf(process.platform === "win32")(
"setup, doctor, and uninstall use the nonempty fallback home when HOME is empty",
async ({ cli }) => {
const directory = await createTestTempDirectory(
"rea-empty-home-lifecycle-",
);
const home = join(directory, "fallback-home");
const workingDirectory = join(directory, "cwd");
await mkdir(home);
await mkdir(workingDirectory);
const environment = {
HOME: "",
USERPROFILE: home,
XDG_CONFIG_HOME: join(home, ".config"),
};
const run = (arguments_: readonly string[]) =>
cli.run({
arguments: arguments_,
cwd: workingDirectory,
environment,
});
const setup = await run(["setup", "--client", "cursor", "--yes", "--json"]);
expect(setup.exitCode, setup.stderr).toBe(0);
expect(setup.json).toMatchObject({ status: "ready" });
await access(join(home, ".cursor", "mcp.json"));
await access(
join(home, ".agents", "skills", "reverse-engineer-anything", "SKILL.md"),
);
await expect(
access(join(workingDirectory, ".cursor", "mcp.json")),
).rejects.toMatchObject({
code: "ENOENT",
});
await expect(
access(join(workingDirectory, ".agents", "skills")),
).rejects.toMatchObject({ code: "ENOENT" });
const doctor = await run([
"doctor",
"--client",
"cursor",
"--skill",
"--json",
]);
expect(doctor.exitCode, doctor.stdout).toBe(0);
expect(doctor.json).toMatchObject({ healthy: true });
const uninstall = await run(["uninstall", "--json"]);
expect(uninstall.exitCode, uninstall.stderr).toBe(0);
expect(uninstall.json).toMatchObject({ status: "complete" });
const remainingConfig = parse(
await readFile(join(home, ".cursor", "mcp.json"), "utf8"),
);
expect(remainingConfig).not.toHaveProperty("mcpServers.rea");
await expect(
access(
join(
home,
".agents",
"skills",
"reverse-engineer-anything",
"SKILL.md",
),
),
).rejects.toMatchObject({ code: "ENOENT" });
await expect(
access(join(workingDirectory, ".cursor", "mcp.json")),
).rejects.toMatchObject({
code: "ENOENT",
});
},
);
+597
View File
@@ -0,0 +1,597 @@
import { createHash } from "node:crypto";
import { readFile, stat, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { DatabaseSync } from "node:sqlite";
import { expect, onTestFinished } from "vitest";
import { z } from "zod";
import {
expandProviderCapabilities,
expandToolAvailability,
providerCapabilitySet,
toolAvailabilityInventory,
} from "../../src/contracts/toolOutputSchemaPrimitives.js";
import { SQLITE_NATIVE_LIMITS_AVAILABLE } from "../fixtures/sqlite/database.js";
import { connectLocalToolsMcp } from "../fixtures/localToolsMcp.js";
import { parseMcpToolError } from "../fixtures/mcpToolError.js";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
import { cliTest } from "../support/cli/cliFixture.js";
const digest = (bytes: Buffer): string =>
createHash("sha256").update(bytes).digest("hex");
cliTest.runIf(SQLITE_NATIVE_LIMITS_AVAILABLE)(
"bounds default context and projects exact columns without evaluating unrelated cells",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-sqlite-selective-");
const path = join(root, "selected.db");
const database = new DatabaseSync(path);
try {
database.exec(`
CREATE TABLE selected(id INTEGER, "" TEXT, payload BLOB GENERATED ALWAYS AS (zeroblob(72*1024*1024)) VIRTUAL);
CREATE TABLE unrelated(value TEXT);
CREATE VIEW unrelated_view AS SELECT value FROM unrelated;
CREATE INDEX selected_id ON selected(id);
CREATE TRIGGER selected_trigger AFTER INSERT ON selected BEGIN SELECT 1; END;
WITH RECURSIVE numbers(n) AS (SELECT 1 UNION ALL SELECT n+1 FROM numbers WHERE n<21)
INSERT INTO selected(id, "") SELECT n, 'retained' FROM numbers;
`);
} finally {
database.close();
}
const before = await readFile(path);
const { call } = await connectLocalToolsMcp();
const inventory = await call("inspect_sqlite_database", { path });
expect(inventory.isError).not.toBe(true);
const schema = z
.object({
normalized_result: z.object({
schema: z.object({
scope: z.literal("inventory"),
tables: z.array(
z.object({
name: z.string(),
columns: z.array(z.unknown()),
columns_completeness: z.literal("not_requested"),
}),
),
}),
}),
})
.parse(inventory.structuredContent).normalized_result.schema;
expect(schema.tables.map((table) => table.name)).toEqual([
"selected",
"unrelated",
]);
expect(schema.tables.every((table) => table.columns.length === 0)).toBe(
true,
);
expect(JSON.stringify(inventory.structuredContent)).not.toContain(
"zeroblob",
);
const selected = await call("inspect_sqlite_database", {
path,
table: "selected",
columns: ["", "id", "id"],
});
expect(selected.isError).not.toBe(true);
expect(selected.structuredContent).toMatchObject({
normalized_result: {
schema: {
scope: "selected_table",
tables: [{ name: "selected" }],
views: [],
indexes: [{ name: "selected_id" }],
triggers: [{ name: "selected_trigger" }],
},
rows: {
columns: ["", "id", "id"],
row_limit: 20,
returned_rows: 20,
truncated: true,
values: expect.arrayContaining([
[
{
type: "text",
value: "retained",
bytes_hex: "72657461696e6564",
encoding: "UTF-8",
},
{ type: "integer", value: "1" },
{ type: "integer", value: "1" },
],
]),
},
},
});
const cliResult = await cli.run({
arguments: [
"inspect-sqlite-database",
path,
"--table",
"selected",
"--column",
"id",
"--column",
"",
"--row-limit",
"1",
"--json",
],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(cliResult.exitCode, cliResult.stdout + cliResult.stderr).toBe(0);
expect(cliResult.json).toMatchObject({
normalized_result: { rows: { columns: ["id", ""], returned_rows: 1 } },
});
for (const input of [
{ path, columns: ["id"] },
{ path, schema_scope: "selected_table" },
{ path, table: "selected", columns: [] },
{ path, table: "selected", columns: ["ID"] },
])
expect((await call("inspect_sqlite_database", input)).isError).toBe(true);
expect(await readFile(path)).toEqual(before);
},
);
cliTest(
"discovers SQLite runtime availability before inspecting a database through CLI and MCP",
async ({ cli }) => {
const result = await cli.run({
arguments: ["capabilities", "--json"],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(result.exitCode, result.stdout + result.stderr).toBe(0);
const status = z
.object({
open: z.literal(false),
capabilities: z.array(providerCapabilitySet),
})
.parse(result.json);
expect(expandProviderCapabilities(status.capabilities)).toEqual(
expect.arrayContaining([
expect.objectContaining({
operation: "inspect_sqlite_database",
available: SQLITE_NATIVE_LIMITS_AVAILABLE,
reason: SQLITE_NATIVE_LIMITS_AVAILABLE
? null
: expect.stringContaining("Node.js 24.x >=24.15 or 26+"),
availability_code: SQLITE_NATIVE_LIMITS_AVAILABLE
? null
: "unsupported_version",
limitations: [expect.stringContaining("DatabaseSync.limits")],
effects: {
mutates_artifact: false,
launches_process: true,
may_show_ui: false,
may_access_network: false,
may_write_filesystem: true,
changes_permissions: false,
requires_root: false,
},
}),
]),
);
const { call } = await connectLocalToolsMcp();
const response = await call("binary_session", {});
expect(response.isError).not.toBe(true);
const sessionStatus = z
.object({
result: z.object({ tool_availability: toolAvailabilityInventory }),
})
.parse(response.structuredContent);
expect(
expandToolAvailability(sessionStatus.result.tool_availability),
).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: "inspect_sqlite_database",
available: SQLITE_NATIVE_LIMITS_AVAILABLE,
remediation: SQLITE_NATIVE_LIMITS_AVAILABLE
? null
: expect.stringContaining("Node.js 24.x >=24.15 or 26+"),
}),
]),
);
},
);
cliTest.skipIf(SQLITE_NATIVE_LIMITS_AVAILABLE)(
"reports the required native SQLite limits capability through CLI and MCP",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-sqlite-unavailable-");
const path = join(root, "selected.db");
const database = new DatabaseSync(path);
try {
database.exec("CREATE TABLE items(value INTEGER)");
} finally {
database.close();
}
const result = await cli.run({
arguments: ["inspect-sqlite-database", path, "--json"],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "capability_unavailable",
message: expect.stringContaining("DatabaseSync.limits"),
});
const { call } = await connectLocalToolsMcp();
const response = await call("inspect_sqlite_database", { path });
expect(response.isError).toBe(true);
expect(parseMcpToolError(response).error).toMatchObject({
code: "capability_unavailable",
message: expect.stringContaining("DatabaseSync.limits"),
});
},
);
cliTest.runIf(SQLITE_NATIVE_LIMITS_AVAILABLE)(
"accepts small samples above 1000 rows within the real resource budgets",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-sqlite-row-budget-");
const path = join(root, "rows.db");
const database = new DatabaseSync(path);
try {
database.exec(`CREATE TABLE items(value INTEGER);
WITH RECURSIVE numbers(value) AS (SELECT 1 UNION ALL SELECT value + 1 FROM numbers WHERE value < 1002)
INSERT INTO items SELECT value FROM numbers;`);
} finally {
database.close();
}
const { call } = await connectLocalToolsMcp();
for (const limit of [1001, Number.MAX_SAFE_INTEGER]) {
const result = await cli.run({
arguments: [
"inspect-sqlite-database",
path,
"--table",
"items",
"--row-limit",
String(limit),
"--json",
],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(result.exitCode, result.stdout + result.stderr).toBe(0);
expect(result.json).toMatchObject({
normalized_result: {
rows: {
row_limit: limit,
returned_rows: Math.min(limit, 1002),
truncated: limit < 1002,
},
},
});
const response = await call("inspect_sqlite_database", {
path,
table: "items",
row_limit: limit,
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
expect(response.structuredContent).toEqual(result.json);
}
},
);
const sourceState = async (path: string) => {
const bytes = await readFile(path);
const metadata = await stat(path, { bigint: true });
return {
bytes,
device: metadata.dev,
inode: metadata.ino,
size: metadata.size,
modified: metadata.mtimeNs,
changed: metadata.ctimeNs,
};
};
const createLosslessSnapshot = (path: string, journalMode: string): void => {
const database = new DatabaseSync(path);
try {
database.exec(`PRAGMA journal_mode=${journalMode}`);
database.exec(`
CREATE TABLE "odd "" table" (
id INTEGER PRIMARY KEY,
payload BLOB,
amount REAL,
missing TEXT,
text_value TEXT,
negative_zero,
generated TEXT GENERATED ALWAYS AS (hex(payload)) VIRTUAL
);
CREATE UNIQUE INDEX "quoted "" index" ON "odd "" table"(payload, id);
CREATE VIEW readable AS SELECT id FROM "odd "" table";
CREATE TRIGGER observed AFTER INSERT ON "odd "" table" BEGIN SELECT 1; END;
CREATE TABLE keyed(k TEXT PRIMARY KEY) WITHOUT ROWID, STRICT;
`);
const insert = database.prepare(
'INSERT INTO "odd "" table"(id,payload,amount,missing,text_value,negative_zero) VALUES(?,?,?,NULL,CAST(X\'80ff\' AS TEXT),?)',
);
insert.setReadBigInts(true);
expect(
insert.run(
9007199254740993n,
Buffer.from("deadbeef", "hex"),
Infinity,
-0,
).lastInsertRowid,
).toBe(9007199254740993n);
insert.run(9007199254740994n, Buffer.from("deadbeef", "hex"), Infinity, -0);
} finally {
database.close();
}
};
cliTest
.runIf(SQLITE_NATIVE_LIMITS_AVAILABLE)
.for(["DELETE", "PERSIST", "TRUNCATE"])(
"inspects a real %s SQLite schema and lossless selected records identically through CLI and MCP",
async (journalMode, { cli }) => {
const root = await createTestTempDirectory("rea-sqlite-public-");
const path = join(root, "selected.db");
createLosslessSnapshot(path, journalMode);
const original = await readFile(path);
const result = await cli.run({
arguments: [
"inspect-sqlite-database",
"selected.db",
"--schema-scope",
"database",
"--table",
'odd " table',
"--row-limit",
"1",
"--json",
],
cwd: root,
environment: {
REA_LOG_LEVEL: "silent",
REA_ANALYSIS_PROVIDER: "ghidra",
REA_GHIDRA_HOME: "/unconfigured/ghidra",
},
});
expect(result.exitCode, result.stdout + result.stderr).toBe(0);
expect(result.json).toMatchObject({
operation: "inspect_sqlite_database",
confidence: "observed",
subject: { local_path: path, digest: { sha256: digest(original) } },
normalized_result: {
artifact: { path, sha256: digest(original), bytes: original.length },
wal: null,
schema: {
completeness: "complete",
tables: expect.arrayContaining([
expect.objectContaining({
name: 'odd " table',
columns: expect.arrayContaining([
expect.objectContaining({
name: "id",
primary_key_position: 1,
}),
expect.objectContaining({ name: "generated", hidden: 2 }),
]),
}),
expect.objectContaining({
name: "keyed",
without_rowid: true,
strict: true,
}),
]),
indexes: expect.arrayContaining([
expect.objectContaining({
name: 'quoted " index',
table: 'odd " table',
}),
]),
views: [
{ name: "readable", sql: expect.stringContaining("SELECT id") },
],
triggers: [
{
name: "observed",
table: 'odd " table',
sql: expect.stringContaining("AFTER INSERT"),
},
],
},
rows: {
table: 'odd " table',
columns: [
"id",
"payload",
"amount",
"missing",
"text_value",
"negative_zero",
"generated",
],
returned_rows: 1,
row_limit: 1,
truncated: true,
values: [
[
{
type: "integer",
value: expect.stringMatching(/^900719925474099[34]$/),
},
{ type: "blob", hex: "deadbeef" },
{ type: "real", value: "Infinity" },
{ type: "null" },
{ type: "text", value: "\ufffd\ufffd", bytes_hex: "80ff" },
{ type: "real", value: "-0" },
{
type: "text",
value: "DEADBEEF",
bytes_hex: "4445414442454546",
},
],
],
},
},
});
const { call } = await connectLocalToolsMcp();
const response = await call("inspect_sqlite_database", {
path,
table: 'odd " table',
schema_scope: "database",
row_limit: 1,
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
expect(response.structuredContent).toEqual(result.json);
expect(await readFile(path)).toEqual(original);
},
);
cliTest.runIf(SQLITE_NATIVE_LIMITS_AVAILABLE)(
"includes uncheckpointed committed WAL data without modifying the source database or sidecars",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-sqlite-wal-public-");
const path = join(root, "wal.db");
const database = new DatabaseSync(path);
onTestFinished(() => database.close());
database.exec(
"PRAGMA journal_mode=WAL; PRAGMA wal_autocheckpoint=0; CREATE TABLE committed(value TEXT); INSERT INTO committed VALUES('only in WAL');",
);
const files = [path, `${path}-wal`, `${path}-shm`];
const before = await Promise.all(files.map(sourceState));
const db = before[0];
const wal = before[1];
expect(db).toBeDefined();
expect(wal).toBeDefined();
const result = await cli.run({
arguments: [
"inspect-sqlite-database",
path,
"--table",
"committed",
"--json",
],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(result.exitCode, result.stdout + result.stderr).toBe(0);
expect(result.json).toMatchObject({
normalized_result: {
artifact: { sha256: db === undefined ? "missing" : digest(db.bytes) },
wal: {
path: `${path}-wal`,
sha256: wal === undefined ? "missing" : digest(wal.bytes),
},
rows: {
values: [
[
{
type: "text",
value: "only in WAL",
bytes_hex: Buffer.from("only in WAL").toString("hex"),
},
],
],
returned_rows: 1,
truncated: false,
},
},
});
const { call } = await connectLocalToolsMcp();
const response = await call("inspect_sqlite_database", {
path,
table: "committed",
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
expect(response.structuredContent).toEqual(result.json);
const after = await Promise.all(files.map(sourceState));
expect(after).toEqual(before);
},
);
cliTest.runIf(SQLITE_NATIVE_LIMITS_AVAILABLE)(
"returns actionable public errors for corrupt input, unknown or ambiguous tables and invalid record choices",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-sqlite-errors-public-");
const path = join(root, "invalid.db");
await writeFile(path, "not a SQLite database");
const { call } = await connectLocalToolsMcp();
const corrupt = await cli.run({
arguments: ["inspect-sqlite-database", path, "--json"],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(corrupt.exitCode).toBe(1);
expect(corrupt.json).toMatchObject({ code: "invalid_request" });
expect((await call("inspect_sqlite_database", { path })).isError).toBe(
true,
);
const valid = join(root, "valid.db");
const database = new DatabaseSync(valid);
try {
database.exec(
"CREATE TABLE present(value TEXT); CREATE VIRTUAL TABLE search USING fts5(body);",
);
} finally {
database.close();
}
const bytes = await readFile(valid);
const declaration = bytes.indexOf(Buffer.from("USING fts5"));
if (declaration < 0) throw new Error("Virtual declaration missing");
bytes.write("zzzz", declaration + Buffer.byteLength("USING "), "utf8");
await writeFile(valid, bytes);
const schema = await call("inspect_sqlite_database", { path: valid });
expect(schema.isError).not.toBe(true);
expect(schema.structuredContent).toMatchObject({
normalized_result: {
schema: {
tables: expect.arrayContaining([
expect.objectContaining({ name: "search_data", kind: "unknown" }),
]),
},
},
});
const ambiguous = await cli.run({
arguments: [
"inspect-sqlite-database",
valid,
"--table",
"search_data",
"--json",
],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(ambiguous.exitCode).toBe(1);
expect(ambiguous.stdout).toContain("shadow table");
expect(
(
await call("inspect_sqlite_database", {
path: valid,
table: "search_data",
})
).isError,
).toBe(true);
const missing = await cli.run({
arguments: [
"inspect-sqlite-database",
valid,
"--table",
"absent",
"--json",
],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(missing.exitCode).toBe(1);
expect(missing.stdout).toContain("absent");
expect(
(await call("inspect_sqlite_database", { path: valid, table: "absent" }))
.isError,
).toBe(true);
for (const input of [
{ path: valid, row_limit: 1 },
{ path: valid, table: "present", row_limit: 0 },
{ path: valid, query: "DELETE FROM present" },
]) {
expect(
(await call("inspect_sqlite_database", input)).isError,
JSON.stringify(input),
).toBe(true);
}
},
);
@@ -19,6 +19,25 @@ const electron = {
executable_path: "/tmp/Electron",
application_path: "/tmp/main.js",
};
const runCliExpectingInputError = async (
scenarioPath: string,
): Promise<unknown> => {
const failure = await execute(process.execPath, [
cli,
"capture-process",
scenarioPath,
"--json",
]).then(
() => undefined,
(cause: unknown) => cause,
);
expect(failure).toMatchObject({ code: 1 });
if (!(failure instanceof Error) || !("stdout" in failure))
throw new Error("Expected the CLI to report an input error on stdout");
return JSON.parse(String(failure.stdout)) as unknown;
};
const pathRequests: readonly [string, Record<string, unknown>][] = [
["open_binary", { path: nul }],
["open_binary", { path: process.execPath, snapshot_path: nul }],
@@ -96,6 +115,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 },
@@ -225,25 +254,80 @@ captureTest(
});
expect(parseMcpToolError(failed)).toMatchObject({
error: {
code: "process_capture_failed",
message: expect.stringContaining(missing),
details: { execution_failure: expect.stringContaining(missing) },
code: "invalid_request",
details: {
operation: "capture_process_scenario",
issues: [
{
path: ["executable"],
message: expect.stringContaining(`${missing} (ENOENT)`),
},
],
},
},
});
await writeFile(
join(root, "scenario.json"),
JSON.stringify({ executable: missing }),
);
await expect(
execute(process.execPath, [
cli,
"capture-process",
join(root, "scenario.json"),
"--json",
]),
).rejects.toMatchObject({
code: 1,
stdout: expect.stringContaining(missing),
const executableCliFailure = await runCliExpectingInputError(
join(root, "scenario.json"),
);
expect(executableCliFailure).toMatchObject({
code: "invalid_request",
details: {
operation: "capture_process_scenario",
issues: [
{
path: ["executable"],
message: expect.stringContaining(`${missing} (ENOENT)`),
},
],
},
});
const missingWorkingDirectory = join(root, "missing-working-directory");
const cwdFailure = await call("capture_process_scenario", {
executable: process.execPath,
working_directory: missingWorkingDirectory,
});
expect(parseMcpToolError(cwdFailure)).toMatchObject({
error: {
code: "invalid_request",
details: {
operation: "capture_process_scenario",
issues: [
{
path: ["working_directory"],
message: expect.stringContaining(
`${missingWorkingDirectory} (ENOENT)`,
),
},
],
},
},
});
const cwdScenario = join(root, "missing-working-directory.json");
await writeFile(
cwdScenario,
JSON.stringify({
executable: process.execPath,
working_directory: missingWorkingDirectory,
}),
);
expect(await runCliExpectingInputError(cwdScenario)).toMatchObject({
code: "invalid_request",
details: {
operation: "capture_process_scenario",
issues: [
{
path: ["working_directory"],
message: expect.stringContaining(
`${missingWorkingDirectory} (ENOENT)`,
),
},
],
},
});
},
60_000,
+3 -1
View File
@@ -35,7 +35,9 @@ cliTest(
environment,
timeoutMs: 15000,
});
expect(cliResponse.exitCode).toBe(0);
expect(cliResponse.exitCode, cliResponse.stdout + cliResponse.stderr).toBe(
0,
);
expect(cliResponse.json).toMatchObject({
normalized_result: {
engine: null,
@@ -40,7 +40,7 @@ cliTest(
},
timeoutMs: 45000,
});
expect(response.exitCode).toBe(0);
expect(response.exitCode, response.stdout + response.stderr).toBe(0);
expect(response.json).toMatchObject({
normalized_result: {
source: { script_index: 0 },
@@ -0,0 +1,101 @@
import { EventEmitter } from "node:events";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { PassThrough } from "node:stream";
import { expect, it, onTestFinished, vi } from "vitest";
import { PwntoolsLayoutProvider } from "../../../src/native/pwntools/PwntoolsLayoutProvider.js";
import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js";
import {
createTestWorkspace,
removeTestWorkspace,
} from "../../support/workspace/workspaceFixture.js";
// Exercise the decoder's launch/cleanup contract independently of the host's
// process table. The interpreter has exec'd over its caller-selected wrapper.
it
.runIf(process.platform === "linux" && process.arch === "x64")
.each(["owned", "wrong-token", "wrong-parent"] as const)(
"cancels an exec wrapper only with current ownership: %s",
async (identity) => {
const { root } = await createTestWorkspace("rea-pwntools-wrapper-");
onTestFinished(() => removeTestWorkspace(root));
const path = join(root, "input");
await writeFile(path, "source-owned-seam-bytes");
const controller = new AbortController();
class DecoderProcess extends EventEmitter {
readonly pid = 41234;
readonly stdout = new PassThrough();
readonly stderr = new PassThrough();
exitCode: number | null = null;
signalCode: NodeJS.Signals | null = null;
kill(): boolean {
throw new Error("Cleanup must validate ownership before signaling");
}
}
const child = new DecoderProcess();
let live = true;
const signalGroup = vi.fn(() => {
live = false;
child.signalCode = "SIGTERM";
child.stdout.end();
child.stderr.end();
child.emit("exit", null, "SIGTERM");
child.emit("close", null, "SIGTERM");
});
const provider = new PwntoolsLayoutProvider(
{ REA_PWNTOOLS_PYTHON: process.execPath },
async (spawn) => {
const ownership = {
runId: spawn.runId,
leaderPid: child.pid,
processGroupId: child.pid,
expectedParentPid: process.pid,
...(spawn.expectedCommand === null
? {}
: { expectedCommand: spawn.expectedCommand ?? spawn.command }),
};
setImmediate(() => controller.abort());
return {
process: child,
ownership,
cleanup: () =>
cleanupOwnedProcessGroup(ownership, {
listProcesses: async () =>
live
? [
{
pid: child.pid,
parentPid:
identity === "wrong-parent"
? process.pid + 1
: process.pid,
processGroupId: child.pid,
state: "S",
command:
"/selected/python -I bridge/pwntools/layout.py",
},
]
: [],
environment: async () => ({
REA_PROCESS_RUN_ID:
identity === "wrong-token" ? "another-run" : spawn.runId,
}),
signalGroup,
}),
};
},
);
const result = await provider.inspect(
{ path },
{ signal: controller.signal },
);
expect(result).toMatchObject({
ok: false,
error:
identity === "owned"
? { _tag: "AnalysisCancelledError" }
: { _tag: "ProviderAdapterError", cleanupIncomplete: true },
});
expect(signalGroup).toHaveBeenCalledTimes(identity === "owned" ? 1 : 0);
},
);
@@ -11,6 +11,7 @@ import { PWNTOOLS_PROVIDER_IDENTITY } from "../../../src/native/pwntools/Pwntool
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
import { waitForProviderProcessReady } from "../../fixtures/providerProcess.js";
import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js";
import { binaryLayoutFixture } from "../../fixtures/binaryDiagnostics/layout.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
@@ -94,6 +95,7 @@ it.runIf(!unsupportedHost)(
async () => {
const { path } = await fixture();
let ownedPath = "";
let cleanupAllowed = false;
const provider = new PwntoolsLayoutProvider(
{ REA_PWNTOOLS_PYTHON: process.execPath },
async (spawn) => {
@@ -106,22 +108,37 @@ it.runIf(!unsupportedHost)(
return {
...launched,
cleanup: async () => {
await launched.cleanup?.();
if (cleanupAllowed)
return cleanupOwnedProcessGroup(launched.ownership);
throw new Error("injected post-cleanup reporting failure");
},
};
},
);
onTestFinished(async () => {
cleanupAllowed = true;
await provider.close();
});
const result = await provider.inspect({ path });
if (result.ok) throw new Error("Expected compounded lifecycle failure");
expect(result.error).toMatchObject({
cleanupIncomplete: true,
diagnostics: {
reason: "injected post-cleanup reporting failure",
previous_error: { failure_kind: "output-limit" },
captured_output: { truncated: true, stderr: "" },
primary_error: {
code: "unreadable_output",
details: { captured_output: { truncated: true, stderr: "" } },
},
cleanup_error: {
code: "cleanup_incomplete",
details: {
diagnostics: { reason: "injected post-cleanup reporting failure" },
},
},
},
});
await expect(access(ownedPath)).resolves.toBeUndefined();
cleanupAllowed = true;
await provider.close();
await expect(access(ownedPath)).rejects.toMatchObject({ code: "ENOENT" });
},
);
@@ -418,8 +435,11 @@ it.runIf(!unsupportedHost)(
cleanupIncomplete: true,
cleanupResources: [root],
diagnostics: {
reason: "root cleanup failed",
previous_error: { category: "invalid_input" },
primary_error: { category: "invalid_input" },
cleanup_error: {
code: "cleanup_incomplete",
details: { diagnostics: { reason: "root cleanup failed" } },
},
},
},
});
@@ -1,3 +1,4 @@
import type { AnalysisError } from "../../../src/domain/analysisErrorBase.js";
import type { RecordedCrash } from "../../../src/domain/native/recordedCrash.js";
import { access, mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -9,7 +10,10 @@ import {
} from "../../support/workspace/workspaceFixture.js";
import { PwntoolsRecordedCrashProvider } from "../../../src/native/pwntools/PwntoolsRecordedCrashProvider.js";
import { PWNTOOLS_PROVIDER_IDENTITY } from "../../../src/native/pwntools/PwntoolsRelease.js";
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
import {
spawnOwnedProviderProcess,
type SpawnedOwnedProviderProcess,
} from "../../../src/process/ProviderProcess.js";
import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js";
import { waitForProviderProcessReady } from "../../fixtures/providerProcess.js";
import {
@@ -27,6 +31,19 @@ const requestSchema = z.object({
});
const host = process.platform === "linux" && process.arch === "x64";
const withCleanupGate = (
launched: SpawnedOwnedProviderProcess,
cleanupAllowed: () => boolean,
): SpawnedOwnedProviderProcess => ({
...launched,
cleanup: async () => {
const result = await cleanupOwnedProcessGroup(launched.ownership);
if (!cleanupAllowed())
throw new Error("source-owned post-cleanup reporting failure");
return result;
},
});
it
.runIf(host)
.each([
@@ -132,6 +149,7 @@ it
"invalid-context",
"cancelled",
"cleanup-failure",
"decoder-cleanup-failure",
] as const)(
"owns optional context from the same snapshot: %s",
async (scenario) => {
@@ -139,6 +157,8 @@ it
const controller = new AbortController();
let owned = "";
let snapshotPath = "";
let cleanupAllowed = false;
let launches = 0;
const venv = join(root, "venv");
const plugin = join(root, "gdbinit.py");
await mkdir(venv);
@@ -155,6 +175,7 @@ it
}),
},
async (spawn) => {
launches++;
const request = requestSchema.parse(
JSON.parse(await readFile(spawn.arguments.at(-1) ?? "", "utf8")),
);
@@ -177,11 +198,14 @@ it
value: raw,
}),
);
return spawnOwnedProviderProcess({
const launched = await spawnOwnedProviderProcess({
...spawn,
command: process.execPath,
arguments: ["-e", "process.stdout.write('basic stage diagnostic')"],
});
return scenario === "decoder-cleanup-failure"
? withCleanupGate(launched, () => cleanupAllowed)
: launched;
}
expect(request.snapshot_path).toBe(snapshotPath);
const context = recordedCrashDebuggerFixture();
@@ -207,17 +231,15 @@ it
await waitForProviderProcessReady(launched.process);
setImmediate(() => controller.abort());
}
if (scenario === "cleanup-failure")
return {
...launched,
cleanup: async () => {
await cleanupOwnedProcessGroup(launched.ownership);
throw new Error("source-owned post-cleanup reporting failure");
},
};
return launched;
return scenario === "cleanup-failure"
? withCleanupGate(launched, () => cleanupAllowed)
: launched;
},
);
onTestFinished(async () => {
cleanupAllowed = true;
await provider.close();
});
const result = await provider.inspect(
{
path,
@@ -234,46 +256,90 @@ it
});
} else {
if (result.ok) throw new Error("Expected optional debugger failure");
const projected = projectAnalysisError(result.error);
if (scenario === "unconfigured")
expect(projected).toMatchObject({
details: { captured_output: { stdout: "basic stage diagnostic" } },
});
else if (
scenario === "invalid-context" ||
scenario === "cancelled" ||
scenario === "cleanup-failure"
) {
const serialized = JSON.stringify(projected);
expect(serialized).toContain("basic stage diagnostic");
expect(serialized).toContain(
scenario === "cancelled" ? "ready" : "debugger stage diagnostic",
);
expect(result.error._tag).toBe(
scenario === "invalid-context"
? "AnalysisOutputError"
: scenario === "cancelled"
? "AnalysisCancelledError"
: "ProviderAdapterError",
);
if (scenario === "cleanup-failure")
expect(result.error).toBeInstanceOf(ProviderCleanupError);
} else
expect(projected).toMatchObject({
category: "execution_failure",
details: {
diagnostics: {
preceding_output: { stdout: "basic stage diagnostic" },
stderr: "debugger failed",
},
},
});
expectOptionalContextFailure(scenario, result.error);
}
expect(await readFile(path)).toEqual(bytes);
if (
scenario === "cleanup-failure" ||
scenario === "decoder-cleanup-failure"
) {
await expect(access(owned)).resolves.toBeUndefined();
expect(await readFile(snapshotPath)).toEqual(bytes);
const refused = await provider.inspect({
path,
include_debugger_context: true,
});
if (refused.ok)
throw new Error("Unreleased ownership must block a launch");
expect(refused.error.cleanupResources).toContain(owned);
expect(launches).toBe(scenario === "decoder-cleanup-failure" ? 1 : 2);
await expect(provider.close()).rejects.toMatchObject({
cleanupIncomplete: true,
});
await expect(access(owned)).resolves.toBeUndefined();
cleanupAllowed = true;
await provider.close();
}
await expect(access(owned)).rejects.toMatchObject({ code: "ENOENT" });
},
);
const expectOptionalContextFailure = (
scenario: string,
error: AnalysisError,
) => {
const projected = projectAnalysisError(error);
if (scenario === "unconfigured")
expect(projected).toMatchObject({
details: { captured_output: { stdout: "basic stage diagnostic" } },
});
else if (scenario === "decoder-cleanup-failure")
expect(projected).toMatchObject({
code: "cleanup_incomplete",
details: {
diagnostics: { captured_output: { stdout: "basic stage diagnostic" } },
},
});
else if (
scenario === "invalid-context" ||
scenario === "cancelled" ||
scenario === "cleanup-failure"
) {
const serialized = JSON.stringify(projected);
expect(serialized).toContain("basic stage diagnostic");
expect(serialized).toContain(
scenario === "cancelled" ? "ready" : "debugger stage diagnostic",
);
expect(error._tag).toBe(
scenario === "invalid-context"
? "AnalysisOutputError"
: scenario === "cancelled"
? "AnalysisCancelledError"
: "ProviderAdapterError",
);
if (scenario === "cleanup-failure" || scenario === "invalid-context") {
if (scenario === "cleanup-failure")
expect(error).toBeInstanceOf(ProviderCleanupError);
expect(projected).toMatchObject({
details: {
partial_observation: {
debugger: { status: "unavailable", requested: true },
},
},
});
}
} else
expect(projected).toMatchObject({
category: "execution_failure",
details: {
diagnostics: {
preceding_output: { stdout: "basic stage diagnostic" },
stderr: "debugger failed",
},
},
});
};
const fixture = async (includeSignal = false, opaqueOwner = false) => {
const workspace = await createTestWorkspace("rea-recorded-core-seam-");
onTestFinished(() => removeTestWorkspace(workspace.root));
@@ -14,6 +14,36 @@ import {
import { trackBrowser } from "./cdpBrowserProvider.support.js";
describe("CdpBrowserProvider: cancellation and session events", () => {
it("honors cancellation during the final progress callback before publishing inspection", async () => {
const browser = await startFakeCdpBrowser();
trackBrowser(browser);
const controller = new AbortController();
const result = await new CdpBrowserProvider().inspectPage(
inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
observation_ms: 0,
}),
{
signal: controller.signal,
progress: {
report(update) {
if (update.completed === 3) controller.abort();
return Promise.resolve();
},
},
},
);
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisCancelledError",
operation: "inspect_web_page",
},
});
});
it("projects direct-session cancellation onto the requested operation", async () => {
const browser = await startFakeCdpBrowser({
pageScopedVersionWebSocket: true,
@@ -29,6 +29,7 @@ it("preserves unavailable response observations and captures completed peers", a
headers: { "Content-Type": "application/json" },
postData: '{"selected":true}',
},
initiator: { type: "script" },
},
},
{
@@ -130,6 +131,381 @@ it("preserves unavailable response observations and captures completed peers", a
).toEqual(["missing-body", "available"]);
});
it("marks JSON response bodies unavailable when their events arrive during body capture", async () => {
const browser = await startFakeCdpBrowser({
commandEvents(command, origin) {
const session =
command.sessionId === undefined ? {} : { sessionId: command.sessionId };
if (command.method === "Network.enable") {
const url = `${origin}/initial.json`;
return [
{
...session,
method: "Network.requestWillBeSent",
params: {
requestId: "initial",
request: { url, method: "GET" },
initiator: { type: "other" },
},
},
{
...session,
method: "Network.responseReceived",
params: {
requestId: "initial",
response: { url, status: 200, mimeType: "application/json" },
},
},
{
...session,
method: "Network.loadingFinished",
params: { requestId: "initial", encodedDataLength: 16 },
},
];
}
if (command.method !== "Network.getResponseBody") return undefined;
const url = `${origin}/late.json`;
return [
{
...session,
method: "Network.requestWillBeSent",
params: {
requestId: "late",
request: { url, method: "GET" },
initiator: { type: "other" },
},
},
{
...session,
method: "Network.responseReceived",
params: {
requestId: "late",
response: { url, status: 200, mimeType: "application/json" },
},
},
{
...session,
method: "Network.loadingFinished",
params: { requestId: "late", encodedDataLength: 14 },
},
];
},
commandResult(command) {
return command.method === "Network.getResponseBody"
? { body: '{"initial":true}', 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: "initial",
body_shapes: {
status: "included",
request: null,
response: expect.any(Object),
},
}),
expect.objectContaining({
request_id: "late",
body_shapes: { status: "unavailable", request: null, response: null },
}),
]);
expect(result.value.completeness.unavailable_sections).toContain(
"json_body_shapes",
);
});
it("does not attach a redirect response body to the reused request ID", async () => {
const browser = await startFakeCdpBrowser({
commandEvents(command, origin) {
const session =
command.sessionId === undefined ? {} : { sessionId: command.sessionId };
if (command.method === "Network.enable") {
const url = `${origin}/before-redirect.json`;
return [
{
...session,
method: "Network.requestWillBeSent",
params: {
requestId: "reused",
request: { url, method: "GET" },
initiator: { type: "other" },
},
},
{
...session,
method: "Network.responseReceived",
params: {
requestId: "reused",
response: { url, status: 302, mimeType: "application/json" },
},
},
{
...session,
method: "Network.loadingFinished",
params: { requestId: "reused", encodedDataLength: 12 },
},
];
}
if (command.method !== "Network.getResponseBody") return undefined;
const previousUrl = `${origin}/before-redirect.json`;
const nextUrl = `${origin}/after-redirect.json`;
return [
{
...session,
method: "Network.requestWillBeSent",
params: {
requestId: "reused",
request: { url: nextUrl, method: "GET" },
initiator: { type: "other" },
redirectResponse: {
url: previousUrl,
status: 302,
mimeType: "application/json",
encodedDataLength: 12,
},
},
},
{
...session,
method: "Network.responseReceived",
params: {
requestId: "reused",
response: {
url: nextUrl,
status: 200,
mimeType: "application/json",
},
},
},
{
...session,
method: "Network.loadingFinished",
params: { requestId: "reused", encodedDataLength: 14 },
},
];
},
commandResult(command) {
return command.method === "Network.getResponseBody"
? { body: '{"belongs":"redirect"}', 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: "reused",
url: `${browser.allowedOrigin}/after-redirect.json`,
redirects: [expect.objectContaining({ status: 302 })],
body_shapes: { status: "unavailable", request: null, response: null },
}),
]);
expect(result.value.completeness.unavailable_sections).toContain(
"json_body_shapes",
);
});
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,
});
expect(result.value.completeness.excluded).not.toContainEqual(
expect.objectContaining({
section: "json_body_shapes",
reason: "provider_unavailable",
}),
);
});
it.each([
{
options: {
@@ -169,7 +545,339 @@ it.each([
},
);
describe("CdpBrowserProvider: network 1", () => {
describe("malformed CDP network request metadata", () => {
it("omits requests with missing required metadata and reports the malformed events", async () => {
const browser = await startFakeCdpBrowser({
commandEvents(command, origin) {
if (command.method !== "Network.enable") return undefined;
const session =
command.sessionId === undefined
? {}
: { sessionId: command.sessionId };
return [
{
...session,
method: "Network.requestWillBeSent",
params: {
requestId: "valid",
request: { url: `${origin}/valid`, method: "GET" },
initiator: { type: "future-protocol-type" },
},
},
{
...session,
method: "Network.requestWillBeSent",
params: {
requestId: "missing-method",
request: { url: `${origin}/missing-method` },
initiator: { type: "script" },
},
},
{
...session,
method: "Network.requestWillBeSent",
params: {
requestId: "empty-method",
request: { url: `${origin}/empty-method`, method: "" },
initiator: { type: "script" },
},
},
{
...session,
method: "Network.requestWillBeSent",
params: {
requestId: "missing-initiator-type",
request: {
url: `${origin}/missing-initiator-type`,
method: "POST",
},
initiator: {},
},
},
{
...session,
method: "Network.requestWillBeSent",
params: {
requestId: "missing-request",
request: null,
initiator: { type: "script" },
},
},
];
},
});
trackBrowser(browser);
const result = await new CdpBrowserProvider().inspectPage(
inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
observation_ms: 0,
}),
);
if (!result.ok) throw result.error;
expect(result.value.network.requests).toEqual([
expect.objectContaining({
request_id: "valid",
method: "GET",
initiator: expect.objectContaining({ type: "future-protocol-type" }),
}),
]);
expect(result.value.completeness.excluded).toContainEqual({
section: "network_requests",
reason: "invalid_protocol_value",
count: 4,
});
});
});
describe("malformed reused CDP request IDs", () => {
it("keeps the last valid request and redirects after a malformed replacement", async () => {
const browser = await startFakeCdpBrowser({
commandEvents(command, origin) {
if (command.method !== "Network.enable") return undefined;
const session =
command.sessionId === undefined
? {}
: { sessionId: command.sessionId };
return [
{
...session,
method: "Network.requestWillBeSent",
params: {
requestId: "redirecting",
request: { url: `${origin}/first`, method: "POST" },
initiator: { type: "parser" },
},
},
{
...session,
method: "Network.requestWillBeSent",
params: {
requestId: "redirecting",
request: { url: `${origin}/second`, method: "GET" },
initiator: { type: "other" },
redirectResponse: {
url: `${origin}/first`,
status: 301,
mimeType: "text/plain",
encodedDataLength: 12,
},
},
},
{
...session,
method: "Network.responseReceived",
params: {
requestId: "redirecting",
response: {
url: `${origin}/second`,
status: 202,
mimeType: "application/json",
},
},
},
{
...session,
method: "Network.requestWillBeSent",
params: {
requestId: "redirecting",
request: { url: `${origin}/third` },
initiator: { type: "other" },
redirectResponse: {
url: `${origin}/second`,
status: 302,
mimeType: "text/plain",
encodedDataLength: 18,
},
},
},
{
...session,
method: "Network.responseReceived",
params: {
requestId: "redirecting",
response: {
url: `${origin}/third`,
status: 418,
mimeType: "application/json",
},
},
},
{
...session,
method: "Network.loadingFinished",
params: { requestId: "redirecting", encodedDataLength: 777 },
},
];
},
});
trackBrowser(browser);
const result = await new CdpBrowserProvider().inspectPage(
inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
observation_ms: 0,
include_json_body_shapes: true,
}),
);
if (!result.ok) throw result.error;
expect(result.value.network.requests).toEqual([
expect.objectContaining({
request_id: "redirecting",
url: `${browser.allowedOrigin}/second`,
method: "GET",
status: 202,
mime_type: "application/json",
encoded_data_length: null,
redirects: [
expect.objectContaining({
url: `${browser.allowedOrigin}/first`,
response_url: `${browser.allowedOrigin}/first`,
method: "POST",
status: 301,
}),
],
}),
]);
expect(result.value.completeness.excluded).toContainEqual({
section: "network_requests",
reason: "invalid_protocol_value",
count: 1,
});
expect(result.value.completeness.excluded).toContainEqual({
section: "json_body_shapes",
reason: "invalid_protocol_value",
count: 1,
});
expect(
browser.commands.filter(
({ method }) => method === "Network.getResponseBody",
),
).toEqual([]);
});
});
describe("CDP network length metadata", () => {
it("retains valid zero lengths and excludes malformed loading lengths", async () => {
const browser = await startFakeCdpBrowser({
commandEvents(command, origin) {
if (command.method !== "Network.enable") return undefined;
const session =
command.sessionId === undefined
? {}
: { sessionId: command.sessionId };
const request = (requestId: string, path: string) => ({
...session,
method: "Network.requestWillBeSent",
params: {
requestId,
request: { url: `${origin}${path}`, method: "GET" },
initiator: { type: "parser" },
},
});
return [
request("zero", "/zero"),
request("missing", "/missing"),
request("negative", "/negative"),
request("prior", "/prior"),
request("redirect-zero", "/redirect-zero-first"),
request("redirect-invalid", "/redirect-invalid-first"),
{
...session,
method: "Network.loadingFinished",
params: { requestId: "zero", encodedDataLength: 0 },
},
{
...session,
method: "Network.loadingFinished",
params: { requestId: "missing" },
},
{
...session,
method: "Network.loadingFinished",
params: { requestId: "negative", encodedDataLength: -1 },
},
{
...session,
method: "Network.loadingFinished",
params: { requestId: "prior", encodedDataLength: 27 },
},
{
...session,
method: "Network.loadingFinished",
params: { requestId: "prior", encodedDataLength: -1 },
},
{
...session,
method: "Network.requestWillBeSent",
params: {
requestId: "redirect-zero",
request: { url: `${origin}/redirect-zero-final`, method: "GET" },
initiator: { type: "parser" },
redirectResponse: {
url: `${origin}/redirect-zero-first`,
status: 301,
encodedDataLength: 0,
},
},
},
{
...session,
method: "Network.requestWillBeSent",
params: {
requestId: "redirect-invalid",
request: {
url: `${origin}/redirect-invalid-final`,
method: "GET",
},
initiator: { type: "parser" },
redirectResponse: {
url: `${origin}/redirect-invalid-first`,
status: 301,
encodedDataLength: -1,
},
},
},
];
},
});
trackBrowser(browser);
const result = await new CdpBrowserProvider().inspectPage(
inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
observation_ms: 0,
}),
);
if (!result.ok) throw result.error;
const requests = new Map(
result.value.network.requests.map((item) => [item.request_id, item]),
);
expect(requests.get("zero")?.encoded_data_length).toBe(0);
expect(requests.get("missing")?.encoded_data_length).toBeNull();
expect(requests.get("negative")?.encoded_data_length).toBeNull();
expect(requests.get("prior")?.encoded_data_length).toBe(27);
expect(
requests.get("redirect-zero")?.redirects?.[0]?.encoded_data_length,
).toBe(0);
expect(
requests.get("redirect-invalid")?.redirects?.[0]?.encoded_data_length,
).toBeNull();
expect(result.value.completeness.excluded).toContainEqual({
section: "network_requests",
reason: "invalid_protocol_value",
count: 4,
});
});
});
describe("same-origin redirect chains", () => {
it("retains same-origin redirect hops on the one final request", async () => {
const browser = await startFakeCdpBrowser({ redirectWithinOrigin: true });
trackBrowser(browser);
@@ -222,7 +930,9 @@ describe("CdpBrowserProvider: network 1", () => {
count: expect.any(Number),
});
});
});
describe("redirect origin policy", () => {
it("drops network evidence when a request redirects outside the approved origin", async () => {
const browser = await startFakeCdpBrowser({
redirectToDisallowedOrigin: true,
@@ -14,7 +14,7 @@ describe("CDP target inventory", () => {
type: "page",
title: `Page ${String(index)}`,
url: `https://allowed.example/page/${String(index)}`,
attached: false,
...(index === 0 ? {} : { attached: index === 1 ? false : true }),
webSocketDebuggerUrl: `ws://127.0.0.1:${String(port)}/devtools/page/${id}`,
};
});
@@ -60,6 +60,14 @@ describe("CDP target inventory", () => {
expect(result.value.targets).toHaveLength(targets.length);
expect(result.value.targets[0]?.target_id).toBe("target-0000");
expect(result.value.targets.at(-1)?.target_id).toBe("target-1100");
expect(
result.value.targets.slice(0, 3).map(({ attached }) => attached),
).toEqual([null, false, true]);
expect(
result.value.limitations.some((item) =>
item.includes("attachment state"),
),
).toBe(true);
} finally {
if (server.listening)
await new Promise<void>((resolve, reject) => {
@@ -83,6 +83,7 @@ describe("CdpElectronProvider target selection", () => {
const browser = await startFakeCdpBrowser({
electronFileUrl: pathToFileURL(index).href,
duplicateElectronInventory: true,
omitElectronTargetAttachmentState: true,
});
browsers.push(browser);
const provider = new CdpElectronProvider();
@@ -96,8 +97,14 @@ describe("CdpElectronProvider target selection", () => {
expect.objectContaining({
target_id: "electron-page",
file_path: index,
attached: null,
}),
]);
expect(
listed.value.limitations.some((item) =>
item.includes("attachment state"),
),
).toBe(true);
expect(listed.value.excluded).toEqual({
unsupported_url: 3,
non_page: 2,
@@ -112,6 +119,12 @@ describe("CdpElectronProvider target selection", () => {
);
if (!inspected.ok) throw inspected.error;
expect(inspected.value.target.file_path).toBe(index);
expect(inspected.value.target.attached).toBeNull();
expect(
inspected.value.limitations.some((item) =>
item.includes("attachment state"),
),
).toBe(true);
expect(inspected.value.frames).toEqual([
expect.objectContaining({ file_path: index }),
]);
@@ -316,6 +316,7 @@ const captureBody = (source: BodySource, body: string): WebPageInspection => {
headers: { "Content-Type": "application/json" },
postData: source === "request" ? body : "{}",
},
initiator: { type: "script" },
},
});
const responseBody = source === "request" ? "{}" : body;
@@ -338,8 +339,10 @@ const captureBody = (source: BodySource, body: string): WebPageInspection => {
encodedDataLength: Buffer.byteLength(responseBody),
},
});
expect(events.responseBodyRequestIds()).toEqual(["request-1"]);
events.ingestResponseBody("request-1", {
const candidate = events.responseBodyRequests()[0];
expect(candidate?.requestId).toBe("request-1");
expect(candidate).toBeDefined();
events.ingestResponseBody(candidate!, {
body:
source === "base64 response"
? Buffer.from(responseBody).toString("base64")
@@ -0,0 +1,46 @@
import { expect, it } from "vitest";
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js";
import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
it.each(["omitted", "null"] as const)(
"excludes TargetInfo workers with %s required attached state",
async (attachmentState) => {
const browser = await startFakeCdpBrowser({
commandResult: (command, origin) => {
if (command.method !== "Target.getTargets") return undefined;
return {
targetInfos: [
{
targetId: "worker-1",
type: "service_worker",
url: `${origin}/worker.js`,
openerId: "allowed-page",
...(attachmentState === "null" ? { attached: null } : {}),
},
],
};
},
});
try {
const result = await new CdpBrowserProvider().inspectPage(
inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
observation_ms: 0,
}),
);
if (!result.ok) throw result.error;
expect(result.value.workers).toEqual([]);
expect(result.value.completeness.excluded).toContainEqual({
section: "workers",
reason: "invalid_protocol_value",
count: 1,
});
} finally {
await browser.close();
}
},
);
@@ -1,6 +1,49 @@
import { execFile } from "node:child_process";
import { readdir } from "node:fs/promises";
import { promisify } from "node:util";
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
it.skipIf(process.platform === "win32")(
"rejects an exited fixture before returning a lease and removes its profile",
async () => {
const root = await createTestTempDirectory("rea-runtime-startup-failure-");
const helper = new URL(
"../../../scripts/lib/browser-runtime-fixture-lifecycle.mjs",
import.meta.url,
);
const script = `
const { startRuntimeFixtureBrowser } = await import(${JSON.stringify(helper.href)});
// Node rejects Chrome's arguments immediately, exercising actual process exit.
try {
const fixture = await startRuntimeFixtureBrowser(process.execPath, 'http://127.0.0.1');
await fixture.close();
throw new Error('Expected startup failure');
} catch (error) {
if (error._tag !== 'BrowserStartupError') throw error;
console.log(JSON.stringify({
failure: error.failure,
exitCode: error.exitCode,
stderr: error.stderr,
}));
}
`;
const { stdout } = await promisify(execFile)(
process.execPath,
["--input-type=module", "-e", script],
{
env: { ...process.env, TMPDIR: root, TMP: root, TEMP: root },
timeout: 10_000,
},
);
expect(JSON.parse(stdout)).toEqual({
failure: "exited",
exitCode: expect.any(Number),
stderr: expect.stringContaining("bad option"),
});
expect(await readdir(root)).toEqual([]);
},
);
it("attempts every fixture cleanup and retains the primary capture failure", async () => {
const helper = new URL(
@@ -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", () => {
@@ -1110,58 +1161,73 @@ describe("source-map output admission", () => {
);
},
);
});
it.each([
{ localOrigin: "http://[::1]:1", expectedStatus: "included" },
{ localOrigin: "http://127.0.0.1:9222", expectedStatus: "partial" },
])(
"admits a maximum-size map set according to its actual output at $localOrigin",
async ({ localOrigin, expectedStatus }) => {
const mapUrl = `${localOrigin}/m`;
const requests = Array.from({ length: 50_000 }, (_, index) => ({
...request,
scriptKey: `scr_${index.toString(16).padStart(64, "0")}`,
declaredUrl: mapUrl,
fetchUrl: mapUrl,
}));
const map = JSON.stringify({
version: 3,
names: [],
sources: ["x"],
mappings: "AAAA",
});
const result = await fetchWebSourceMaps(
requests,
input({ allowed_origins: [localOrigin] }),
undefined,
{
timeoutMs: 120_000,
fetch: () => Promise.resolve(new Response(map, { status: 200 })),
},
);
describe("source-map set output admission", () => {
it("admits a maximum-size map set according to its serialized output size", async () => {
const localOrigin = "http://127.0.0.1:9222";
const mapUrl = `${localOrigin}/m`;
const requests = Array.from({ length: 50_000 }, (_, index) => ({
...request,
scriptKey: `scr_${index.toString(16).padStart(64, "0")}`,
declaredUrl: mapUrl,
fetchUrl: mapUrl,
}));
const map = JSON.stringify({
version: 3,
names: [],
sources: ["x"],
mappings: "AAAA",
});
const result = await fetchWebSourceMaps(
requests,
input({ allowed_origins: [localOrigin] }),
undefined,
{
timeoutMs: 120_000,
fetch: () => Promise.resolve(new Response(map, { status: 200 })),
},
);
expect(result.status).toBe(expectedStatus);
if (expectedStatus === "included") {
expect(result.limitation).toBeUndefined();
expect(result.items).toHaveLength(requests.length);
} else {
expect(result.items.length).toBeLessThan(requests.length);
expect(result.limitation).toContain(
`${String(requests.length - result.items.length)} requested maps`,
);
expect(
(Buffer.byteLength(JSON.stringify(result.items[0])) + 1) *
requests.length,
).toBeGreaterThan(32 * 1_024 * 1_024);
}
expect(result.processed).toBe(result.items.length);
expect(result.requested).toBe(requests.length);
expect(Buffer.byteLength(JSON.stringify(result))).toBeLessThanOrEqual(
32 * 1_024 * 1_024,
const outputLimitBytes = 32 * 1_024 * 1_024;
const itemSizes = new Set(
result.items.map((item) => Buffer.byteLength(JSON.stringify(item))),
);
expect(itemSizes.size).toBe(1);
const firstItem = result.items[0];
if (firstItem === undefined) throw new Error("no source map was admitted");
const itemBytes = Buffer.byteLength(JSON.stringify(firstItem));
const completeEnvelope = JSON.stringify({
...result,
status: "included",
processed: requests.length,
items: [],
limitation: undefined,
});
const projectedCompleteBytes =
Buffer.byteLength(completeEnvelope) +
itemBytes * requests.length +
requests.length -
1;
const completeOutputFits = projectedCompleteBytes <= outputLimitBytes;
expect(result.status).toBe(completeOutputFits ? "included" : "partial");
if (completeOutputFits) {
expect(result.limitation).toBeUndefined();
expect(result.items).toHaveLength(requests.length);
} else {
expect(result.items.length).toBeLessThan(requests.length);
expect(result.limitation).toContain(
`${String(requests.length - result.items.length)} requested maps`,
);
},
120_000,
);
expect(projectedCompleteBytes).toBeGreaterThan(outputLimitBytes);
}
expect(result.processed).toBe(result.items.length);
expect(result.requested).toBe(requests.length);
expect(Buffer.byteLength(JSON.stringify(result))).toBeLessThanOrEqual(
outputLimitBytes,
);
}, 120_000);
it("reserves large failure contexts and reports unprocessed requests as unknown", async () => {
const largeDeclaredUrl = `${origin}/${"u".repeat(8 * 1_024 * 1_024)}`;
@@ -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(
@@ -0,0 +1,107 @@
import { expect, it, onTestFinished, vi } from "vitest";
import { writeFile } from "node:fs/promises";
import type { FileHandle } from "node:fs/promises";
import { join } from "node:path";
import { TsharkCaptureProvider } from "../../../src/captures/TsharkCaptureProvider.js";
import { PacketCaptureService } from "../../../src/application/captures/PacketCaptureService.js";
import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const cleanup = vi.hoisted(() => ({
path: "",
denied: false,
handles: [] as FileHandle[],
}));
vi.mock("node:fs/promises", async (importOriginal) => {
const filesystem = await importOriginal<typeof import("node:fs/promises")>();
return {
...filesystem,
open: async (...args: Parameters<typeof filesystem.open>) => {
const handle = await filesystem.open(...args);
if (args[0] === cleanup.path) {
cleanup.handles.push(handle);
const close = handle.close.bind(handle);
handle.close = async () => {
if (cleanup.denied && handle.fd >= 0)
throw new Error("Descriptor close deliberately denied");
await close();
};
}
return handle;
},
};
});
it
.runIf(process.platform === "linux")
.each(["capture", "tool", "limiter", "kernel"])(
"retains failed %s descriptors and retries them before further acquisition and shutdown",
async (member) => {
const directory = await createTestTempDirectory("rea-capture-descriptor-");
const path = join(directory, "recording.pcap");
const command = join(directory, "tshark.mjs");
const limiter = join(directory, "limiter");
await writeFile(path, "recording bytes");
await writeFile(limiter, "limiter", { mode: 0o700 });
await writeFile(
command,
`if(process.argv.includes('--version'))console.log('TShark (Wireshark) 4.0.17');else console.log('[{"_source":{"layers":{"frame.number":["1"]}}}]');`,
{ mode: 0o700 },
);
let launches = 0;
const provider = new TsharkCaptureProvider(
{
...process.env,
REA_TSHARK_COMMAND: command,
REA_TSHARK_PRLIMIT_COMMAND: limiter,
},
(input) => {
launches += 1;
return spawnOwnedProviderProcess({
...input,
command: process.execPath,
arguments: [command, ...input.arguments],
expectedCommand: process.execPath,
});
},
() => PrivateRuntimeRoot.create({ parent: directory }),
);
cleanup.path =
member === "capture"
? path
: member === "tool"
? command
: member === "limiter"
? limiter
: "/proc/self/limits";
cleanup.denied = true;
cleanup.handles = [];
onTestFinished(async () => {
cleanup.denied = false;
await provider.close();
for (const handle of cleanup.handles) await handle.close();
cleanup.path = "";
});
const service = new PacketCaptureService(provider);
const first = await service.inspect({ path, fields: ["frame.number"] });
expect(first).toMatchObject({
ok: false,
error: { cleanupIncomplete: true, cleanupResources: [cleanup.path] },
});
expect(cleanup.handles).toHaveLength(1);
expect(cleanup.handles[0]?.fd).toBeGreaterThanOrEqual(0);
const launchCount = launches;
expect(
await service.inspect({ path, fields: ["frame.number"] }),
).toMatchObject({ ok: false, error: { cleanupIncomplete: true } });
expect(cleanup.handles).toHaveLength(1);
expect(launches).toBe(launchCount);
await expect(provider.close()).rejects.toMatchObject({
cleanupIncomplete: true,
});
cleanup.denied = false;
await provider.close();
expect(cleanup.handles[0]?.fd).toBe(-1);
},
);
@@ -0,0 +1,467 @@
import { OwnedCommandFailure } from "../../../src/process/OwnedCommand.js";
import { it, expect, onTestFinished } from "vitest";
import { writeFile, readdir, chmod, symlink } from "node:fs/promises";
import { join } from "node:path";
import { readStableArtifact } from "../../../src/artifacts/readStableArtifact.js";
import { TsharkCaptureProvider } from "../../../src/captures/TsharkCaptureProvider.js";
import { PacketCaptureService } from "../../../src/application/captures/PacketCaptureService.js";
import { packetCaptureSchema } from "../../../src/domain/captures/packetCapture.js";
import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { createDeferred } from "../../fixtures/binarySession.js";
// A command-boundary simulator: real process ownership/filesystem, not real TShark coverage.
const fixture = async (mode = "ok", failCleanup = false) => {
const directory = await createTestTempDirectory("rea-capture-test-");
const path = join(directory, "recorded bytes.pcap");
await writeFile(path, "recording bytes");
const script = join(directory, "producer.mjs");
await writeFile(
script,
`import {readFileSync, writeFileSync, chmodSync, truncateSync} from 'node:fs';
if (process.argv.includes('--version')) { console.log('TShark (Wireshark) 4.6.9 (fixture)'); console.error('version warning'); }
else if (${JSON.stringify(mode)} === 'nonzero') { console.error('invalid decoder'); process.exitCode = 1; }
else if (${JSON.stringify(mode)} === 'malformed-copy') { chmodSync('capture', 0o600); writeFileSync('capture', 'changed'); }
else if (${JSON.stringify(mode)} === 'oversized-copy') { chmodSync('capture', 0o600); truncateSync('capture', 32 * 1024 * 1024 + 1); console.log('[]'); }
else if (${JSON.stringify(mode)} === 'overflow') process.stdout.write('x'.repeat(5 * 1024 * 1024));
else if (${JSON.stringify(mode)} === 'wait') { console.log('ready'); setInterval(() => {}, 1000); }
else if (${JSON.stringify(mode)} === 'invalid-json') console.log('not json');
else if (${JSON.stringify(mode)} === 'many') console.log(JSON.stringify(Array.from({length:90},(_,i)=>({_source:{layers:{"frame.number":[String(i+1)],"ip.addr":["192.0.2.1"]}}}))));
else { if(readFileSync('capture', 'utf8') !== 'recording bytes') throw Error('wrong copy'); console.log(JSON.stringify([{_source:{layers:{"frame.number":["1"],"ip.addr":["192.0.2.1","192.0.2.2"]}}}])); console.error('producer warning'); }
`,
);
await chmod(script, 0o700);
const configuredCommand =
mode === "symlink" ? join(directory, "configured-tool") : script;
if (mode === "symlink") await symlink(script, configuredCommand);
const controller = new AbortController();
let calls = 0;
let mayClean = !failCleanup;
const acquired = createDeferred<void>();
const release = createDeferred<void>();
const provider = new TsharkCaptureProvider(
{
...process.env,
REA_TSHARK_COMMAND: configuredCommand,
REA_TSHARK_PRLIMIT_COMMAND: configuredCommand,
},
async (input) => {
calls++;
if (mode === "file-limit" && !input.arguments.includes("--version")) {
const stdout = { text: "", bytes: 0, observedBytes: 0 };
const stderr = {
text: "before file limit\n",
bytes: 18,
observedBytes: 18,
};
throw new OwnedCommandFailure("process", "Synthetic SIGXFSZ snapshot", {
stdout,
stderr,
exitCode: null,
signal: "SIGXFSZ",
});
}
const spawned = await spawnOwnedProviderProcess({
...input,
command: process.execPath,
arguments: [script, ...input.arguments],
expectedCommand: process.execPath,
});
if (mode === "wait" && !input.arguments.includes("--version"))
spawned.process.stdout?.once("data", () => controller.abort());
return spawned;
},
async () => {
if (mode === "workspace-full")
throw Object.assign(new Error("No space left on device"), {
code: "ENOSPC",
});
const root = await PrivateRuntimeRoot.create({
parent: directory,
prefix: "decoder-",
});
if (mode === "gated") {
acquired.resolve();
await release.promise;
}
if (mode === "snapshot-write-failure")
await writeFile(join(root.path, "capture"), "existing");
return {
path: root.path,
close: async () => {
if (!mayClean) throw new Error("cleanup fixture failure");
await root.close();
},
};
},
"linux",
async (...args) => {
if (mode === "oversized-tool" && calls === 2 && args[0] === script) {
const { truncate } = await import("node:fs/promises");
await truncate(script, 64 * 1024 * 1024 + 1);
}
if (mode === "post-run-abort" && calls === 2) controller.abort();
return readStableArtifact(...args);
},
async (limits) => ({ ...limits, file_bytes: 1048576 }),
);
onTestFinished(async () => {
release.resolve();
mayClean = true;
await provider.close();
});
const service = new PacketCaptureService(provider);
return {
service,
directory,
path,
controller,
calls: () => calls,
acquired: acquired.promise,
release: () => release.resolve(),
allowCleanup: () => {
mayClean = true;
},
};
};
it("refuses new acquisition after provider shutdown", async () => {
const f = await fixture();
await f.service.close();
expect(
await f.service.inspect({ path: f.path, fields: ["ip.addr"] }),
).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
expect(f.calls()).toBe(0);
});
it("pages matching observations without changing dissection scope or frame identities", async () => {
const f = await fixture("many");
const input = { path: f.path, fields: ["ip.addr"] };
for (const [options, first, count] of [
[{}, 1, 50],
[{ match_offset: 50, match_limit: 30 }, 51, 30],
[{ match_limit: null }, 1, 90],
[{ match_offset: 100 }, undefined, 0],
] as const) {
const result = await f.service.inspect({ ...input, ...options });
if (!result.ok) throw result.error;
const report = packetCaptureSchema.parse(result.value.normalized_result);
expect(report.packets).toHaveLength(count);
expect(report.packets[0]?.["frame.number"][0]).toBe(
first === undefined ? undefined : String(first),
);
expect(report.output_window.matching_packets).toBe(90);
expect(report.output_window.returned_packets).toBe(count);
expect(report.read_scope).toBe("to-eof");
expect(report.tool.arguments).not.toContain("-c");
}
});
it("bounds admission without queuing additional snapshots or delaying cancellation", async () => {
const f = await fixture("gated");
const input = { path: f.path, fields: ["ip.addr"] };
const first = f.service.inspect(input);
await f.acquired;
const second = f.service.inspect(input);
const cancelled = f.service.inspect(input, { signal: AbortSignal.abort() });
f.release();
expect(await first).toMatchObject({ ok: true });
expect(await second).toMatchObject({
ok: false,
error: { _tag: "AnalysisResourceConstraintError", resource: "capacity" },
});
expect(await cancelled).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
expect(f.calls()).toBe(2);
expect(await f.service.inspect(input)).toMatchObject({ ok: true });
});
it("inspects an immutable copy, preserves options and warnings, and releases its directory", async () => {
const f = await fixture();
const result = await f.service.inspect({
path: f.path,
fields: ["ip.addr"],
display_filter: "udp",
packet_limit: 10,
decode_as: ["udp.port==5555,dns"],
});
if (!result.ok) throw result.error;
const report = packetCaptureSchema.parse(result.value.normalized_result);
expect(report.packets).toEqual([
{ "frame.number": ["1"], "ip.addr": ["192.0.2.1", "192.0.2.2"] },
]);
expect(report.diagnostics).toBe("producer warning\n");
expect(report.tool.version_diagnostics).toBe("version warning\n");
expect(report.read_scope).toBe("up-to-input-packet-limit");
expect(report.tool.arguments).toEqual([
"-n",
"-r",
"capture",
"-T",
"json",
"--no-duplicate-keys",
"--temp-dir=.",
"-2",
"-c",
"10",
"-Y",
"udp",
"-d",
"udp.port==5555,dns",
"-e",
"frame.number",
"-e",
"ip.addr",
]);
expect((await readdir(f.directory)).sort()).toEqual([
"producer.mjs",
"recorded bytes.pcap",
]);
});
it.each([
["invalid-json", "AnalysisOutputError"],
["nonzero", "ProviderAdapterError"],
["malformed-copy", "AnalysisArtifactChangedError"],
["overflow", "AnalysisResourceConstraintError"],
["wait", "AnalysisCancelledError"],
])(
"preserves %s failure and releases the process and snapshot",
async (mode, tag) => {
const f = await fixture(mode);
const result = await f.service.inspect(
{ path: f.path, fields: ["ip.addr"] },
{ signal: f.controller.signal },
);
if (result.ok) throw new Error("Expected capture analysis failure");
expect(result.error._tag).toBe(tag);
expect(result.error.cleanupIncomplete).toBe(false);
expect(
(await readdir(f.directory)).filter((name) =>
name.startsWith("decoder-"),
),
).toEqual([]);
},
);
it("retains a completed observation and cleanup ownership for retry", async () => {
const f = await fixture("ok", true);
const result = await f.service.inspect({ path: f.path, fields: ["ip.addr"] });
if (result.ok) throw new Error("Expected cleanup failure");
expect(result.error.cleanupIncomplete).toBe(true);
expect(result.error.partialObservation).toMatchObject({
operation: "inspect_packet_capture",
});
const retry = await f.service.inspect({ path: f.path, fields: ["ip.addr"] });
expect(retry.ok).toBe(false);
expect(f.calls()).toBe(2);
f.allowCleanup();
await f.service.close();
expect(
(await readdir(f.directory)).filter((name) => name.startsWith("decoder-")),
).toEqual([]);
});
it("rejects cancelled and invalid requests before any provider work", async () => {
const f = await fixture();
for (const input of [
{ path: "relative.pcap", fields: ["ip.addr"] },
{ path: f.path, fields: ["ip.addr"], interface: "lo0" },
]) {
const result = await f.service.inspect(input);
expect(result.ok).toBe(false);
}
const result = await f.service.inspect(
{ path: f.path, fields: ["ip.addr"] },
{ signal: AbortSignal.abort() },
);
if (result.ok) throw new Error("Expected cancellation");
expect(result.error._tag).toBe("AnalysisCancelledError");
expect(f.calls()).toBe(0);
});
it("retains a completed observation when cancellation arrives at the service boundary", async () => {
const f = await fixture();
const input = {
path: f.path,
fields: ["ip.addr"],
display_filter: null,
decode_as: [],
packet_limit: null,
two_pass: true,
match_offset: 0,
match_limit: 50,
};
const execution = await f.service.provider.inspect(input);
if (!execution.ok) throw execution.error;
const service = new PacketCaptureService({
inspect: async () => {
f.controller.abort();
return execution;
},
close: async () => {},
});
const result = await service.inspect(input, { signal: f.controller.signal });
if (result.ok) throw new Error("Expected late cancellation");
expect(result.error._tag).toBe("AnalysisCancelledError");
expect(result.error.partialObservation).toMatchObject({
operation: "inspect_packet_capture",
normalized_result: {
packets: [
{ "frame.number": ["1"], "ip.addr": ["192.0.2.1", "192.0.2.2"] },
],
},
});
});
it.each([
["workspace-full", "AnalysisResourceConstraintError"],
["snapshot-write-failure", "ProviderAdapterError"],
])(
"reports %s against the private workspace, not the selected input",
async (mode, tag) => {
const f = await fixture(mode);
const result = await f.service.inspect({
path: f.path,
fields: ["ip.addr"],
});
if (result.ok) throw new Error("Expected workspace failure");
expect(result.error._tag).toBe(tag);
if (result.error._tag === "ProviderAdapterError")
expect(result.error).toMatchObject({
diagnostics: {
stage: "workspace",
system_code: "EEXIST",
},
});
if (result.error._tag === "AnalysisResourceConstraintError")
expect(result.error).toMatchObject({
reportedLimits: {
system_code: "ENOSPC",
},
});
expect(f.calls()).toBe(mode === "workspace-full" ? 0 : 1);
expect(
(await readdir(f.directory)).filter((name) =>
name.startsWith("decoder-"),
),
).toEqual([]);
},
);
it("refuses unsupported hosts before launching or allocating a workspace", async () => {
const provider = new TsharkCaptureProvider(
{ REA_TSHARK_COMMAND: process.execPath },
async () => {
throw new Error("Must not launch");
},
async () => {
throw new Error("Must not allocate");
},
"darwin",
);
const result = await new PacketCaptureService(provider).inspect({
path: "/recording.pcap",
fields: ["ip.addr"],
});
if (result.ok) throw new Error("Expected host refusal");
expect(result.error).toMatchObject({
_tag: "AnalysisCapabilityUnavailableError",
reason: expect.stringContaining("Linux"),
});
});
it("preserves complete Evidence when aborted during post-run integrity checks", async () => {
const f = await fixture("post-run-abort");
const result = await f.service.inspect(
{ path: f.path, fields: ["ip.addr"] },
{ signal: f.controller.signal },
);
if (result.ok) throw new Error("Expected late cancellation");
expect(result.error._tag).toBe("AnalysisCancelledError");
expect(result.error.partialObservation).toMatchObject({
normalized_result: {
packets: [
{ "frame.number": ["1"], "ip.addr": ["192.0.2.1", "192.0.2.2"] },
],
diagnostics: "producer warning\n",
},
});
expect(
(await readdir(f.directory)).filter((name) => name.startsWith("decoder-")),
).toEqual([]);
});
it("preserves configured symlink paths separately from resolved tool identities", async () => {
const f = await fixture("symlink");
const result = await f.service.inspect({ path: f.path, fields: ["ip.addr"] });
if (!result.ok) throw result.error;
expect(result.value.normalized_result).toMatchObject({
tool: {
configured_path: join(f.directory, "configured-tool"),
path: join(f.directory, "producer.mjs"),
},
resource_limiter: {
configured_path: join(f.directory, "configured-tool"),
path: join(f.directory, "producer.mjs"),
},
});
});
it.each(["oversized-copy", "oversized-tool"])(
"identifies the mutated %s without blaming the admitted source",
async (mode) => {
const f = await fixture(mode);
const result = await f.service.inspect({
path: f.path,
fields: ["ip.addr"],
});
if (result.ok) throw new Error("Expected changed artifact");
expect(result.error).toMatchObject({
_tag: "AnalysisArtifactChangedError",
path:
mode === "oversized-tool"
? join(f.directory, "producer.mjs")
: expect.stringMatching(/decoder-.*[/\\]capture$/u),
});
expect(
(await readdir(f.directory)).filter((name) =>
name.startsWith("decoder-"),
),
).toEqual([]);
},
);
it("preserves termination signal and effective file ceiling as a resource failure", async () => {
const f = await fixture("file-limit");
const result = await f.service.inspect({ path: f.path, fields: ["ip.addr"] });
if (result.ok) throw new Error("Expected resource failure");
expect(result.error).toMatchObject({
_tag: "AnalysisResourceConstraintError",
resource: "file-size",
reportedLimits: { file_bytes: 1048576 },
capturedOutput: { signal: "SIGXFSZ", stderr: "before file limit\n" },
});
});
it("rejects oversized selector lists and UTF-8 argv expansion before provider work", async () => {
const f = await fixture();
for (const selections of [
{ fields: Array.from({ length: 1025 }, () => "ip.addr") },
{ fields: ["x".repeat(8193)] },
{ fields: ["x".repeat(8192)], display_filter: "界".repeat(8192) },
{
fields: ["ip.addr"],
decode_as: Array.from({ length: 1025 }, () => "udp.port==5555,dns"),
},
]) {
const result = await f.service.inspect({ path: f.path, ...selections });
if (result.ok) throw new Error("Expected invalid selectors");
expect(result.error._tag).toBe("AnalysisInputError");
}
expect(f.calls()).toBe(0);
});
@@ -0,0 +1,41 @@
import { expect, it } from "vitest";
import { parsePacketOutput } from "../../../src/captures/parsePacketOutput.js";
it("preserves repeated field values and missing fields while discarding export index metadata", () => {
const output = JSON.stringify([
{
_index: "packets-2026",
_score: null,
_source: {
layers: {
"frame.number": ["2"],
"ip.addr": ["192.0.2.1", "192.0.2.2"],
},
},
},
{ _source: { layers: { "frame.number": ["7"] } } },
]);
expect(parsePacketOutput(output, ["ip.addr"])).toEqual([
{ "frame.number": ["2"], "ip.addr": ["192.0.2.1", "192.0.2.2"] },
{ "frame.number": ["7"] },
]);
});
it.each(
[
[{ "ip.addr": ["192.0.2.1"] }],
[{ "frame.number": ["1"], "ip.addr": "192.0.2.1" }],
[{ "frame.number": ["0"] }],
[{ "frame.number": ["1", "2"] }],
[{ "frame.number": ["1"], "unselected.field": ["hidden"] }],
[{ "frame.number": ["2"] }, { "frame.number": ["2"] }],
[{ "frame.number": ["2"] }, { "frame.number": ["1"] }],
].map((layers) => [layers]),
)("rejects malformed, repeated or reordered producer frames: %j", (layers) => {
expect(() =>
parsePacketOutput(
JSON.stringify(layers.map((value) => ({ _source: { layers: value } }))),
["ip.addr"],
),
).toThrow();
});
@@ -0,0 +1,156 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it, onTestFinished } from "vitest";
import { TsharkCaptureProvider } from "../../../src/captures/TsharkCaptureProvider.js";
import { PacketCaptureService } from "../../../src/application/captures/PacketCaptureService.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
// Real kernel-limit verification with a synthetic producer; real TShark has its own verifier.
it.skipIf(process.platform !== "linux")(
"enforces both address-space limits before any producer allocation",
async () => {
const directory = await createTestTempDirectory("rea-tshark-limits-");
const command = join(directory, "memory-probe");
await writeFile(
command,
`#!/usr/bin/python3
import json, resource, sys
assert resource.getrlimit(resource.RLIMIT_AS) == (1073741824, 1073741824)
assert resource.getrlimit(resource.RLIMIT_FSIZE) == (67108864, 67108864)
assert resource.getrlimit(resource.RLIMIT_CORE) == (0, 0)
if '--version' in sys.argv:
print('TShark (Wireshark) 4.6.9 (resource fixture)')
else:
try:
bytearray(1073741825)
except MemoryError:
print(json.dumps([{'_source': {'layers': {'frame.number': ['1']}}}]))
else:
raise RuntimeError('allocation unexpectedly succeeded')
`,
{ mode: 0o700 },
);
const path = join(directory, "recording.pcap");
await writeFile(path, "selected fixture");
const service = new PacketCaptureService(
new TsharkCaptureProvider({
...process.env,
REA_TSHARK_COMMAND: command,
}),
);
onTestFinished(() => service.close());
const result = await service.inspect({ path, fields: ["frame.number"] });
if (!result.ok) throw result.error;
expect(result.value.normalized_result).toMatchObject({
packets: [{ "frame.number": ["1"] }],
limits: { address_space_bytes: 1073741824 },
});
},
);
it.skipIf(process.platform !== "linux")(
"preserves lower inherited file/CPU limits in the real launch",
async () => {
const directory = await createTestTempDirectory(
"rea-tshark-inherited-limits-",
);
const command = join(directory, "limit-probe");
const path = join(directory, "recording.pcap");
await writeFile(path, "selected fixture");
await writeFile(
command,
`#!/usr/bin/python3
import json, resource, sys
assert resource.getrlimit(resource.RLIMIT_FSIZE) == (1048576, 1048576)
assert resource.getrlimit(resource.RLIMIT_CPU) == (20, 20)
if '--version' in sys.argv:
print('TShark (Wireshark) 4.6.9 (resource fixture)')
else:
print(json.dumps([{'_source': {'layers': {'frame.number': ['1']}}}]))
`,
{ mode: 0o700 },
);
const runner = join(directory, "runner.mjs");
const serviceModule = new URL(
"../../../dist/application/captures/PacketCaptureService.js",
import.meta.url,
).href;
const providerModule = new URL(
"../../../dist/captures/TsharkCaptureProvider.js",
import.meta.url,
).href;
await writeFile(
runner,
`import { PacketCaptureService } from ${JSON.stringify(serviceModule)};
import { TsharkCaptureProvider } from ${JSON.stringify(providerModule)};
const service = new PacketCaptureService(new TsharkCaptureProvider({ ...process.env, REA_TSHARK_COMMAND: ${JSON.stringify(command)} }));
try {
const result = await service.inspect({ path: ${JSON.stringify(path)}, fields: ['frame.number'] });
if (!result.ok) throw result.error;
console.log(JSON.stringify(result.value.normalized_result.limits));
} finally { await service.close(); }
`,
);
const { stdout } = await promisify(execFile)(
"/usr/bin/prlimit",
[
"--fsize=1048576:2097152",
"--cpu=20:25",
"--",
process.execPath,
runner,
],
{ timeout: 30000, maxBuffer: 65536 },
);
expect(JSON.parse(stdout)).toMatchObject({
file_bytes: 1048576,
cpu_seconds: 20,
});
},
);
it.skipIf(process.platform !== "linux")(
"reports a real kernel file-limit termination with its effective ceiling",
async () => {
const directory = await createTestTempDirectory("rea-tshark-file-limit-");
const command = join(directory, "file-probe");
const path = join(directory, "recording.pcap");
await writeFile(path, "selected fixture");
await writeFile(
command,
`#!/usr/bin/python3
import signal, sys
if '--version' in sys.argv:
print('TShark (Wireshark) 4.6.9 (resource fixture)')
else:
signal.signal(signal.SIGXFSZ, signal.SIG_DFL)
print('before file limit', file=sys.stderr, flush=True)
with open('overflow', 'wb', buffering=0) as output:
output.write(b'x' * 4096)
output.write(b'x')
`,
{ mode: 0o700 },
);
const service = new PacketCaptureService(
new TsharkCaptureProvider(
{ ...process.env, REA_TSHARK_COMMAND: command },
undefined,
undefined,
process.platform,
undefined,
async (limits) => ({ ...limits, file_bytes: 4096 }),
),
);
onTestFinished(() => service.close());
const result = await service.inspect({ path, fields: ["frame.number"] });
if (result.ok) throw new Error("Expected file-limit failure");
expect(result.error).toMatchObject({
_tag: "AnalysisResourceConstraintError",
resource: "file-size",
reportedLimits: { file_bytes: 4096 },
capturedOutput: { signal: "SIGXFSZ", stderr: "before file limit\n" },
});
},
);
+73 -41
View File
@@ -1,50 +1,45 @@
import { expect, it } from "vitest";
import { chmod, lstat, readFile } from "node:fs/promises";
import { expect, it, onTestFinished } from "vitest";
import { serveCli as serve } from "./cliServeHarness.js";
import {
expectConfigurationRefusal,
serveCli as serve,
} from "./cliServeHarness.js";
import {
createTestWorkspace,
removeTestWorkspace,
} from "../../support/workspace/workspaceFixture.js";
it.each([
["inspect-adb-client"],
["list-adb-devices"],
["inspect-adb-device"],
["list-adb-packages"],
["pull-adb-package"],
["read-adb-logcat"],
["inspect-adb-package"],
["pull-adb-file"],
["push-adb-file"],
["capture-adb-screen"],
["list-adb-processes"],
["list-adb-directory"],
["list-adb-features"],
["list-adb-services"],
["inspect-adb-display"],
["inspect-adb-window"],
["read-adb-setting"],
["collect-adb-bugreport"],
["resolve-adb-packages"],
["install-adb-package"],
["uninstall-adb-package"],
["start-adb-app"],
["start-adb-activity"],
["stop-adb-app"],
])("%s advertises a schema through the public CLI", async (command) => {
const result = await serve([command, "--schema", "--json"]);
expect(result.exitCode, command).toBe(0);
const schema = JSON.parse(result.stdout) as { args?: unknown };
expect(schema).toBeTruthy();
});
it("reports a missing adb binary with recovery guidance", async () => {
const result = await serve(["inspect-adb-client", "--json"], {
REA_ADB_PATH: "/nonexistent/adb",
});
expect(result.stdout).toContain("capability_unavailable");
expect(result.stdout).toContain("REA_ADB_PATH");
});
[
["inspect-adb-client", "--json"],
"/nonexistent/adb",
"The selected adb binary was not found: /nonexistent/adb. Set REA_ADB_PATH",
],
[
["list-adb-devices", "--json"],
"/nonexistent/adb",
"The selected adb binary was not found: /nonexistent/adb. Set REA_ADB_PATH",
],
[
["list-adb-devices", "--json"],
"relative/adb",
"REA_ADB_PATH must be an absolute path to the adb binary.",
],
])(
"%j with REA_ADB_PATH=%s names the host requirement",
async (argv, binary, reason) => {
const result = await serve(argv, { REA_ADB_PATH: binary });
expectConfigurationRefusal(result, reason);
},
);
it("validates device serials before contacting any device", async () => {
const result = await serve(["inspect-adb-device", "bad serial", "--json"]);
expect(result.stdout).toContain("invalid_input");
expect(JSON.parse(result.stdout)).toMatchObject({
code: "invalid_request",
category: "invalid_input",
});
});
it("requires the output directory option on pull", async () => {
@@ -56,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" });
},
);
+205 -3
View File
@@ -1,17 +1,142 @@
import { mkdir, writeFile } from "node:fs/promises";
import { apiSurfaceHar } from "../../fixtures/historicalHar.js";
import { createHash } from "node:crypto";
import { mkdir, unlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
import { analysisViewLayoutEvidence } from "../../fixtures/analysisView.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import {
analysisViewLayoutEvidence,
analysisViewCaptureFixture,
analysisViewCaptureEvidence,
analysisViewObjectDenseCapture,
} from "../../fixtures/analysisView.js";
import { createEvidence, parseEvidence } 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(
"projects portable artifact inventory after the original ZIP is removed",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-inventory-view-cli-");
const archive = join(root, "fixture.zip");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("main.js", new TextReader("console.log('portable');\n"));
await writeFile(archive, await writer.close());
const inspected = await cli.run({
arguments: ["inspect-artifact", archive, "--json"],
});
expect(inspected.exitCode).toBe(0);
const parent = parseEvidence(inspected.json);
await unlink(archive);
const request = join(root, "view.json");
await writeFile(
request,
JSON.stringify({
source: { kind: "inline", evidence: parent },
view: {
kind: "inventory",
collection: "occurrences",
logical_paths: ["main.js"],
},
}),
);
const projected = await cli.run({
arguments: ["inspect-analysis-view", request, "--json"],
});
expect(projected.exitCode).toBe(0);
expect(projected.json).toMatchObject({
operation: "inspect_analysis_view",
evidence_links: [parent.evidence_id],
normalized_result: {
parent_evidence_id: parent.evidence_id,
kind: "inventory",
source_complete: true,
artifact: { path: archive, sha256: parent.subject?.digest.sha256 },
items: [expect.objectContaining({ logical_path: "main.js" })],
coverage: { total: 1, exhausted: true, next_offset: null },
},
});
},
);
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 +341,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");
},
);
+35 -17
View File
@@ -1,25 +1,34 @@
import { expect, it } from "vitest";
import { serveCli as serve } from "./cliServeHarness.js";
import {
expectConfigurationRefusal,
serveCli as serve,
} from "./cliServeHarness.js";
it.each(["inspect-apktool-client", "decode-android-resources"])(
"%s advertises a schema through the public CLI",
async (command) => {
const result = await serve([command, "--schema", "--json"]);
expect(result.exitCode, command).toBe(0);
const schema = JSON.parse(result.stdout) as { args?: unknown };
expect(schema).toBeTruthy();
it.each([
[
["inspect-apktool-client", "--json"],
"/nonexistent/apktool",
"The selected apktool launcher was not found: /nonexistent/apktool. Set REA_APKTOOL_COMMAND",
],
[
["decode-android-resources", "/targets/app.apk", "--json"],
"/nonexistent/apktool",
"The selected apktool launcher was not found: /nonexistent/apktool. Set REA_APKTOOL_COMMAND",
],
[
["decode-android-resources", "/targets/app.apk", "--json"],
"relative/apktool",
"REA_APKTOOL_COMMAND must be an absolute path to the apktool launcher.",
],
])(
"%j with REA_APKTOOL_COMMAND=%s names the host requirement",
async (argv, command, reason) => {
const result = await serve(argv, { REA_APKTOOL_COMMAND: command });
expectConfigurationRefusal(result, reason);
},
);
it("reports a missing apktool launcher with recovery guidance", async () => {
const result = await serve(["inspect-apktool-client", "--json"], {
REA_APKTOOL_COMMAND: "/nonexistent/apktool",
});
expect(result.stdout).toContain("capability_unavailable");
expect(result.stdout).toContain("REA_APKTOOL_COMMAND");
});
it("validates the locale option before launching apktool", async () => {
const result = await serve([
"decode-android-resources",
@@ -28,5 +37,14 @@ it("validates the locale option before launching apktool", async () => {
"not a locale",
"--json",
]);
expect(result.stdout).toContain("invalid");
expect(result.exitCode).toBe(1);
expect(JSON.parse(result.stdout)).toMatchObject({
code: "VALIDATION_ERROR",
fieldErrors: [
{
code: "invalid_format",
path: "locale",
},
],
});
});
+115 -1
View File
@@ -93,7 +93,7 @@ it(
const compared = await runCli(
[
"compare-web-captures",
JSON.stringify({ inspection }),
JSON.stringify({ inspection, scenario: { caller_metadata: true } }),
JSON.stringify({ inspection }),
"--json",
],
@@ -183,6 +183,119 @@ it(
INTEGRATION_TEST_TIMEOUT_MS,
);
describe("scenario comparison CLI diagnostics", () => {
const rule = {
rule_id: "domain",
artifacts: ["url"],
match: "app.example.test",
replacement: "normalized.test",
};
it.each([
{
name: "duplicate rule IDs",
normalization: { rules: [rule, rule] },
issue: {
path: ["normalization", "rules", 1, "rule_id"],
reason: "invalid_value",
message: "Normalization rule IDs must be unique",
},
},
{
name: "duplicate artifact kinds",
normalization: { rules: [{ ...rule, artifacts: ["url", "url"] }] },
issue: {
path: ["normalization", "rules", 0, "artifacts"],
reason: "invalid_value",
message: "Normalization rule artifact kinds must be unique",
},
},
{
name: "structurally invalid rules",
normalization: { rules: "invalid" },
issue: {
path: ["normalization", "rules"],
reason: "invalid_type",
expected: "array",
},
},
])(
"retains scenario normalization diagnostics for $name",
async ({ normalization, issue }) => {
const capture = JSON.stringify(completeScenarioCapture());
const result = await runCli([
"compare-web-captures",
capture,
capture,
"--normalization-json",
JSON.stringify(normalization),
"--json",
]);
expect(result).toMatchObject({
code: "invalid_request",
details: { operation: "compare_web_captures", issues: [issue] },
});
},
);
it("keeps malformed scenario diagnostics in the selected capture group", async () => {
const capture = completeScenarioCapture();
const result = await runCli([
"compare-web-captures",
JSON.stringify({ ...capture, duration_ms: "invalid" }),
JSON.stringify(capture),
"--json",
]);
expect(result).toMatchObject({
code: "invalid_request",
details: {
operation: "compare_web_captures",
issues: [
{
path: ["before_scenario", "duration_ms"],
reason: "invalid_type",
expected: "number",
},
],
},
});
});
it.each(["omitted", "misspelled"])(
"reports the missing scenario manifest when it is %s on both captures",
async (kind) => {
const { scenario, ...capture } = completeScenarioCapture();
const input = JSON.stringify(
kind === "omitted" ? capture : { ...capture, scneario: scenario },
);
const result = await runCli([
"compare-web-captures",
input,
input,
"--json",
]);
expect(result).toMatchObject({
code: "invalid_request",
details: {
operation: "compare_web_captures",
issues: expect.arrayContaining([
{
path: ["before_scenario", "scenario"],
reason: "missing_argument",
expected: "object",
},
{
path: ["after_scenario", "scenario"],
reason: "missing_argument",
expected: "object",
},
]),
},
});
expect(JSON.stringify(result)).not.toContain('"inspection"');
},
);
});
describe("browser CLI capture parity", () => {
it(
"runs analysis, session, WebMCP, screenshot, and comparison from explicit request scope",
@@ -352,6 +465,7 @@ const completeScenarioCapture = () => {
response_body: false,
header_values: false,
},
event_families: [],
},
duration_ms: 1,
steps: [
@@ -0,0 +1,258 @@
import { describe, expect } from "vitest";
import { workspaceCliTest as cliTest } from "../../support/cli/workspaceCliFixture.js";
const malformedEndpoint = "not a url";
const browserEndpoint = "http://127.0.0.1:9222";
const inspectorEndpoint = "http://127.0.0.1:9229";
const invalidInputs = [
{
command: "list-browser-targets",
arguments: [malformedEndpoint],
operation: "list_browser_targets",
error: "Browser observation failed",
issue: {
path: ["cdp_endpoint"],
reason: "invalid_value",
message: "Invalid CDP endpoint URL",
},
},
{
command: "inspect-web-page",
arguments: [browserEndpoint, ""],
operation: "inspect_web_page",
error: "Browser observation failed",
issue: { path: ["target_id"], reason: "out_of_range", minimum: 1 },
},
{
command: "analyze-web-bundle",
arguments: [malformedEndpoint, "target"],
operation: "analyze_web_bundle",
error: "Browser observation failed",
issue: {
path: ["cdp_endpoint"],
reason: "invalid_value",
message: "Invalid CDP endpoint URL",
},
},
{
command: "observe-web-session",
arguments: [browserEndpoint, ""],
operation: "observe_web_session",
error: "Browser observation failed",
issue: { path: ["target_id"], reason: "out_of_range", minimum: 1 },
},
{
command: "list-javascript-runtime-targets",
arguments: [""],
operation: "list_javascript_runtime_targets",
error: "JavaScript runtime observation failed",
issue: {
path: ["inspector_endpoint"],
reason: "out_of_range",
minimum: 1,
},
},
{
command: "observe-javascript-runtime",
arguments: [inspectorEndpoint, ""],
operation: "observe_javascript_runtime",
error: "JavaScript runtime observation failed",
issue: { path: ["target_id"], reason: "out_of_range", minimum: 1 },
},
{
command: "discover-webmcp-tools",
arguments: [malformedEndpoint, "target"],
operation: "discover_webmcp_tools",
error: "Browser observation failed",
issue: {
path: ["cdp_endpoint"],
reason: "invalid_value",
message: "Invalid CDP endpoint URL",
},
},
{
command: "capture-web-screenshot",
arguments: [browserEndpoint, ""],
operation: "capture_web_screenshot",
error: "Browser observation failed",
issue: { path: ["target_id"], reason: "out_of_range", minimum: 1 },
},
] as const;
describe("inspection branch diagnostics", () => {
cliTest.for([[], ["--include-script-sources"]])(
"reports only the selected inspection branch's endpoint error (%j)",
async (flags, { cli, workspace }) => {
const result = await cli.run({
arguments: [
"inspect-web-page",
malformedEndpoint,
"target",
...flags,
"--json",
],
cwd: workspace.root,
environment: { ...workspace.environment, REA_LOG_LEVEL: "silent" },
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "invalid_request",
details: {
operation: "inspect_web_page",
issues: [
{
path: ["cdp_endpoint"],
reason: "invalid_value",
message: "Invalid CDP endpoint URL",
},
],
},
});
},
);
});
describe("browser and Inspector CLI input diagnostics", () => {
cliTest.for(invalidInputs)(
"$command retains the named contract's correction details",
async (input, { cli, workspace }) => {
const result = await cli.run({
arguments: [input.command, ...input.arguments, "--json"],
cwd: workspace.root,
environment: { ...workspace.environment, REA_LOG_LEVEL: "silent" },
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
error: input.error,
code: "invalid_request",
category: "invalid_input",
message:
"Analysis input is invalid. Check the arguments and try again.",
retryable: true,
remediation: { action: "Correct the listed arguments and retry." },
details: {
operation: input.operation,
issues: expect.arrayContaining([input.issue]),
},
});
expect(result.stdout).not.toContain(malformedEndpoint);
expect(result.stderr).not.toContain(malformedEndpoint);
},
);
cliTest.for([
["list-browser-targets", "cdp_endpoint"],
["list-javascript-runtime-targets", "inspector_endpoint"],
] as const)(
"%s does not echo rejected endpoint credentials",
async ([command, field], { cli, workspace }) => {
const endpoint =
"http://rea-diagnostic-user:rea-diagnostic-secret@127.0.0.1:9222/";
const result = await cli.run({
arguments: [command, endpoint, "--json"],
cwd: workspace.root,
environment: { ...workspace.environment, REA_LOG_LEVEL: "debug" },
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "invalid_request",
details: {
issues: [
{
path: [field],
reason: "invalid_value",
message:
"CDP endpoint must be an explicit-port HTTP URL on 127.0.0.1 or ::1",
},
],
},
});
const output = result.stdout + result.stderr;
expect(output).not.toContain(endpoint);
expect(output).not.toContain("rea-diagnostic-user");
expect(output).not.toContain("rea-diagnostic-secret");
},
);
cliTest(
"retains authored cross-field correction guidance",
async ({ cli, workspace }) => {
const result = await cli.run({
arguments: [
"inspect-web-page",
browserEndpoint,
"target",
"--include-storage-fingerprints",
"--json",
],
cwd: workspace.root,
environment: { ...workspace.environment, REA_LOG_LEVEL: "silent" },
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "invalid_request",
details: {
operation: "inspect_web_page",
issues: expect.arrayContaining([
{
path: ["include_storage_fingerprints"],
reason: "invalid_value",
message: "Storage fingerprints require storage key capture",
},
]),
},
});
},
);
cliTest(
"retains correction details for invalid capture comparison inputs",
async ({ cli, workspace }) => {
const result = await cli.run({
arguments: ["compare-web-captures", "{}", "{}", "--json"],
cwd: workspace.root,
environment: { ...workspace.environment, REA_LOG_LEVEL: "silent" },
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "invalid_request",
details: {
operation: "compare_web_captures",
issues: expect.arrayContaining([
expect.objectContaining({ reason: expect.any(String) }),
]),
},
});
},
);
cliTest(
"preserves the parser diagnostic for an omitted endpoint",
async ({ cli, workspace }) => {
const result = await cli.run({
arguments: ["list-browser-targets", "--json"],
cwd: workspace.root,
environment: { ...workspace.environment, REA_LOG_LEVEL: "silent" },
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "VALIDATION_ERROR",
fieldErrors: [
{
path: "endpoint",
code: "invalid_type",
missing: true,
expected: "string",
},
],
});
},
);
});
+157
View File
@@ -0,0 +1,157 @@
import { Cli } from "incur";
import { expect, it } from "vitest";
import { registerCaptureCommands } from "../../../src/cli/captureCommands.js";
import { silentLogger } from "../../../src/logger.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js";
import { err } from "../../../src/domain/result.js";
it.each([false, true])(
"awaits cleanup retry and preserves completed output when retry failure is %s",
async (failAgain) => {
const evidence = createEvidence(
undefined,
{ id: "fixture", name: "Completed capture fixture", version: "1" },
{
operation: "inspect_packet_capture",
parameters: {},
result: { packets: [{ "frame.number": ["1"] }] },
confidence: "observed",
},
);
const original = new ProviderCleanupError(
"tshark-capture",
["original-workspace"],
{ reason: "original cleanup failure" },
{ operation: "inspect_packet_capture", partialObservation: evidence },
);
let closed = false;
const cli = Cli.create("capture-cleanup-test", { sync: false });
registerCaptureCommands(
cli,
silentLogger,
{},
{
inspect: async () => err(original),
close: async () => {
await Promise.resolve();
closed = true;
if (failAgain)
throw new ProviderCleanupError(
"tshark-capture",
["retry-workspace"],
{ reason: "retry failed" },
{ operation: "inspect_packet_capture" },
);
},
},
);
let stdout = "";
await cli.serve(
[
"inspect-packet-capture",
"recording.pcap",
"--fields",
"ip.addr",
"--format",
"json",
],
{
stdout: (text) => {
expect(closed).toBe(true);
stdout += text;
},
exit: () => {},
},
);
const output: unknown = JSON.parse(stdout);
expect(output).toMatchObject({
code: "cleanup_incomplete",
details: {
partial_observation: evidence,
resources: expect.arrayContaining(["original-workspace"]),
},
});
if (failAgain)
expect(output).toMatchObject({
details: { resources: expect.arrayContaining(["retry-workspace"]) },
});
},
);
it("rejects an oversized selector budget before the CLI invokes its service", async () => {
const cli = Cli.create("capture-selector-test", { sync: false });
let called = false;
registerCaptureCommands(
cli,
silentLogger,
{},
{
inspect: async () => {
called = true;
throw new Error("Must not inspect");
},
close: async () => {},
},
);
let stdout = "";
await cli.serve(
[
"inspect-packet-capture",
"recording.pcap",
"--fields",
"x".repeat(8192),
"--display_filter",
"界".repeat(8192),
"--format",
"json",
],
{
stdout: (text) => {
stdout += text;
},
exit: () => {},
},
);
expect(called).toBe(false);
expect(stdout).toContain("32 KiB");
});
it("rejects conflicting output options before the CLI invokes its service", async () => {
const cli = Cli.create("capture-window-test", { sync: false });
let called = false;
registerCaptureCommands(
cli,
silentLogger,
{},
{
inspect: async () => {
called = true;
throw new Error("Must not inspect");
},
close: async () => {},
},
);
let stdout = "";
await cli.serve(
[
"inspect-packet-capture",
"recording.pcap",
"--fields",
"ip.addr",
"--all_matches",
"--match_limit",
"20",
"--format",
"json",
],
{
stdout: (text) => {
stdout += text;
},
exit: () => {},
},
);
expect(called).toBe(false);
expect(stdout).toContain("mutually exclusive");
});
@@ -13,7 +13,7 @@ const registeredCommands: WeakMap<object, CommandMap> = Cli.toCommands;
const advertisedGroupSchema = z
.object({
properties: z.record(z.string(), z.unknown()).optional(),
properties: z.record(z.string(), z.unknown()),
required: z.array(z.string()).optional(),
})
.loose();
@@ -70,8 +70,27 @@ describe("CLI advertised input schemas", () => {
for (const command of createCliInventory(cli).primary) {
const advertised = await advertisedSchema(cli, command);
for (const group of INPUT_GROUPS) {
const required = (advertised[group]?.required ?? []).toSorted();
const rejected = omissionRejected(parserSchema(cli, command, group));
const parser = parserSchema(cli, command, group);
const advertisedGroup = advertised[group];
if (parser === undefined) {
if (advertisedGroup !== undefined)
mismatches.push(`${command} ${group}: advertised without parser`);
continue;
}
if (advertisedGroup === undefined) {
mismatches.push(`${command} ${group}: parser group not advertised`);
continue;
}
const parserProperties = Object.keys(parser.shape).toSorted();
const advertisedProperties = Object.keys(
advertisedGroup.properties,
).toSorted();
if (advertisedProperties.join() !== parserProperties.join())
mismatches.push(
`${command} ${group}: advertised properties [${advertisedProperties.join()}], parser properties [${parserProperties.join()}]`,
);
const required = (advertisedGroup.required ?? []).toSorted();
const rejected = omissionRejected(parser);
if (required.join() !== rejected.join())
mismatches.push(
`${command} ${group}: advertised [${required.join()}], parser rejects [${rejected.join()}]`,
@@ -112,3 +131,73 @@ describe("CLI advertised input schemas", () => {
);
});
});
describe("firmware CLI advertised input schema", () => {
it("keeps limits and defaults from its shared input contract", async () => {
const cli = createCli({});
const advertised = await advertisedSchema(cli, "extract-firmware");
const ajv = new Ajv2020({ strict: false });
const args = ajv.compile(advertised.args ?? {});
const options = ajv.compile(advertised.options ?? {});
expect(args({ path: "firmware.bin", outputDirectory: "output" })).toBe(
true,
);
expect(args({ path: "", outputDirectory: "output" })).toBe(false);
expect(args({ path: "firmware.bin", outputDirectory: "" })).toBe(false);
expect(options({})).toBe(true);
expect(options({ maxDepth: 0 })).toBe(false);
expect(options({ maxDepth: 11 })).toBe(false);
expect(options({ maxOutputBytes: 0 })).toBe(false);
expect(options({ maxOutputBytes: 512 * 1024 * 1024 + 1 })).toBe(false);
expect(options({ maxOutputFiles: 100_001 })).toBe(false);
expect(advertised.options?.properties?.["maxDepth"]).toMatchObject({
default: 3,
});
expect(advertised.options?.properties?.["maxOutputBytes"]).toMatchObject({
default: 256 * 1024 * 1024,
});
expect(advertised.options?.properties?.["maxOutputFiles"]).toMatchObject({
default: 10_000,
});
const maxOffset = Number.MAX_SAFE_INTEGER;
expect(options({ offset: maxOffset + 1 })).toBe(false);
expect(options({ length: maxOffset + 1 })).toBe(false);
expect(
parserSchema(cli, "extract-firmware", "options")?.parse({}),
).toMatchObject({
maxDepth: 3,
maxOutputBytes: 256 * 1024 * 1024,
maxOutputFiles: 10_000,
});
});
});
describe("web module CLI advertised input schema", () => {
it("advertises the shared path and URL constraints", async () => {
const cli = createCli({});
const advertised = await advertisedSchema(cli, "trace-web-module-imports");
const ajv = new Ajv2020({ strict: false });
const args = ajv.compile(advertised.args ?? {});
const options = ajv.compile(advertised.options ?? {});
expect(
args({ manifestPath: resolve("manifest.json"), scriptIndex: 0 }),
).toBe(true);
expect(args({ manifestPath: "", scriptIndex: 0 })).toBe(false);
expect(args({ manifestPath: "manifest\u0000.json", scriptIndex: 0 })).toBe(
false,
);
expect(args({ manifestPath: "./manifest.json", scriptIndex: -1 })).toBe(
false,
);
expect(options({})).toBe(true);
expect(options({ importerUrl: "" })).toBe(false);
expect(options({ importMapPath: "" })).toBe(false);
expect(options({ importMapPath: "map\u0000.json" })).toBe(false);
expect(options({ importMapBaseUrl: "" })).toBe(false);
});
});
import { resolve } from "node:path";
@@ -0,0 +1,21 @@
import { expect } from "vitest";
import { cliTest } from "../../support/cli/cliFixture.js";
for (const level of ["loud", "INFO"])
cliTest(
`reports REA_LOG_LEVEL=${level} as invalid configuration`,
async ({ cli }) => {
for (const arguments_ of [["doctor", "--json"], ["--help"]]) {
const result = await cli.run({
arguments: arguments_,
environment: { REA_LOG_LEVEL: level },
});
expect(result.exitCode).toBe(1);
expect(result.stdout).toBe("");
expect(result.stderr).toBe(
'REA configuration is invalid: REA_LOG_LEVEL: Invalid option: expected one of "trace"|"debug"|"info"|"warn"|"error"|"fatal"|"silent".\n',
);
}
},
);
+17
View File
@@ -1,3 +1,5 @@
import { expect } from "vitest";
import { createCli } from "../../../src/cli.js";
/** Captured CLI invocation for boundary tests. */
@@ -25,3 +27,18 @@ export const serveCli = async (
});
return { stdout, exitCode };
};
/** A host tool configuration refusal names what to configure, not the target. */
export const expectConfigurationRefusal = (
result: ServedCli,
reason: string,
): void => {
const output = JSON.parse(result.stdout) as {
code?: unknown;
message?: unknown;
remediation?: { action?: unknown };
};
expect(output.code).toBe("capability_unavailable");
expect(output.message).toEqual(expect.stringContaining(reason));
expect(output.remediation?.action).toEqual(expect.stringContaining(reason));
};
+57 -1
View File
@@ -1,5 +1,6 @@
import { execFile } from "node:child_process";
import { rm } from "node:fs/promises";
import { access, rm } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
import { spawn } from "@lydell/node-pty";
@@ -73,6 +74,61 @@ const clientStates = [
const agentActions = actions.filter(({ kind }) => kind !== "install_hopper");
describe("TTY setup dry run", () => {
it("prints the plan and no-mutation notice for a TTY dry run", async () => {
const home = await createTestTempDirectory("rea-cli-setup-dry-run-");
const terminal = spawn(
process.execPath,
[
"scripts/rea.mjs",
"setup",
"--dry-run",
"--client",
"codex",
"--skill=false",
],
{
cwd: process.cwd(),
env: {
...process.env,
HOME: home,
USERPROFILE: home,
XDG_CONFIG_HOME: join(home, ".config"),
REA_LOG_LEVEL: "silent",
NO_COLOR: "1",
},
name: "xterm-256color",
cols: 120,
rows: 40,
},
);
let output = "";
terminal.onData((data) => {
output += data;
});
const exitCode = await new Promise<number>((resolvePromise, reject) => {
const timeout = setTimeout(() => {
terminal.kill();
reject(new Error(`TTY dry run timed out after output:\n${output}`));
}, 15_000);
terminal.onExit(({ exitCode: code }) => {
clearTimeout(timeout);
resolvePromise(code);
});
});
expect(exitCode, output).toBe(0);
expect(output).toContain("CREATE Codex");
expect(output).toContain(join(home, ".codex/config.toml"));
expect(output).toContain("Dry run complete. No changes were made.");
await expect(
access(join(home, ".codex/config.toml")),
).rejects.toMatchObject({
code: "ENOENT",
});
});
});
describe("interactive setup journey", () => {
it("shows detected and absent clients without preselecting detected clients", async () => {
const result = await runJourney(
+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");
@@ -9,6 +9,7 @@ import {
} from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
@@ -259,3 +260,39 @@ for (const group of groups) {
},
);
}
cliTest("uninstall names each retained skill directory", async ({ cli }) => {
const home = await createTestTempDirectory("rea-uninstall-skill-paths-");
const shared = join(home, ".agents", "skills", PRODUCT_IDENTITY.skillName);
const claude = join(home, ".claude", "skills", PRODUCT_IDENTITY.skillName);
for (const directory of [shared, claude]) {
await mkdir(directory, { recursive: true });
await writeFile(join(directory, "SKILL.md"), "---\nname: unrelated\n---\n");
}
const result = await cli.run({
arguments: ["uninstall", "--json"],
cwd: home,
environment: {
HOME: home,
USERPROFILE: home,
CLAUDE_CONFIG_DIR: join(home, ".claude"),
},
timeoutMs: 20_000,
});
expect(result.exitCode, result.stderr).toBe(0);
const report = result.json as {
items?: readonly { name: string; status: string; detail: string }[];
};
const skill = report.items?.find(({ name }) => name === "skill");
expect(skill?.status).toBe("retained");
for (const directory of [shared, claude]) {
expect(skill?.detail).toContain(
`${directory}: retained (Skill manifest is not REA-owned.)`,
);
expect(await readFile(join(directory, "SKILL.md"), "utf8")).toBe(
"---\nname: unrelated\n---\n",
);
}
});
+7 -7
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",
'export const createCli = () => ({ serve: (args) => process.stdout.write(JSON.stringify({ adapter: "cli", args })) });\n',
"dist/cli-runtime/cli.js",
'export const cliConfigurationError = () => undefined; 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",
"export const createStreamedCliJsonOutput = () => undefined;\n",
"dist/cli-runtime/cliResultOutput.js",
"export const createCliResultOutput = () => 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"]);
},
);
@@ -66,6 +66,27 @@ cliTest(
},
);
cliTest(
"reports a standalone Evidence record as the wrong input file kind",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-evidence-record-input-");
const path = join(root, "record.json");
const record = revisionBundle().records[0];
if (record === undefined) throw new Error("Missing fixture Evidence");
await writeFile(path, JSON.stringify(record));
const result = await cli.run({
arguments: ["evidence-import", path, "--json"],
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "invalid_request",
category: "invalid_input",
details: { path },
message: expect.stringContaining("this JSON is one Evidence record"),
});
},
);
cliTest(
"rejects altered Evidence and incomplete unknown history before reporting counts",
async ({ cli }) => {
+21
View File
@@ -0,0 +1,21 @@
import { expect, it } from "vitest";
import { serveCli } from "./cliServeHarness.js";
it.each(["identify-flutter-build", "inspect-dart-aot"])(
"%s advertises a schema through the public CLI",
async (command) => {
const result = await serveCli([command, "--schema", "--json"]);
expect(result.exitCode).toBe(0);
expect(JSON.parse(result.stdout)).toBeTruthy();
},
);
it("reports an unreadable target with an input refusal", async () => {
const result = await serveCli([
"identify-flutter-build",
"/nonexistent/app.apk",
"--json",
]);
expect(result.stdout).toContain("invalid_request");
});
+276
View File
@@ -0,0 +1,276 @@
import { expect, it } from "vitest";
import { createCli } from "../../../src/cli.js";
import type { FridaInstrumentationPort } from "../../../src/application/frida/FridaInstrumentationPort.js";
import { AnalysisCapabilityUnavailableError } from "../../../src/domain/analysisErrorCore.js";
import { FridaInstrumentationManager } from "../../../src/frida/FridaInstrumentationManager.js";
it("maps one-shot Frida CLI target, script, duration, and remote options", async () => {
const calls: unknown[] = [];
const provider: FridaInstrumentationPort = {
async listDevices() {
calls.push({ operation: "devices" });
return { ok: true, value: { devices: [], cleanupError: null } };
},
async listProcesses() {
return {
ok: true,
value: { deviceId: "local", processes: [], cleanupError: null },
};
},
async startSession(input) {
calls.push({ operation: "start", input });
return {
ok: true,
value: {
sessionId: "00000000-0000-4000-8000-000000000001",
deviceId: "remote",
target: "fixture",
pid: 71,
mode: input.mode,
state: "running",
},
};
},
async loadScript(sessionId, source) {
calls.push({ operation: "load", sessionId, source });
return {
ok: true,
value: {
scriptId: "00000000-0000-4000-8000-000000000002",
sourceKind: source.sourceKind,
sourcePath: source.sourceKind === "file" ? source.path : null,
sourceSha256: "a".repeat(64),
messages: [{ type: "send", payload: "observed" }],
messagesTruncated: false,
},
};
},
async resumeSession(sessionId) {
calls.push({ operation: "resume", sessionId });
return { ok: true, value: null };
},
async unloadScript() {
return { ok: true, value: null };
},
status(sessionId) {
return {
sessionId,
deviceId: "remote",
target: "fixture",
pid: 71,
mode: "attach",
state: "running",
targetResumeObserved: false,
scripts: [],
messages: [],
messagesTruncated: false,
};
},
async closeSession(sessionId) {
calls.push({ operation: "close", sessionId });
return { ok: true, value: { targetResumeObserved: false } };
},
async closeAll() {},
};
const cli = createCli({}, undefined, provider);
let stdout = "";
let exitCode = 0;
await cli.serve(
[
"instrument-with-frida",
"attach",
"71",
"--script",
"send('hello')",
"--remote-address",
"127.0.0.1:27042",
"--token",
"synthetic-secret-token",
"--keepalive-interval",
"10",
"--duration-ms",
"0",
"--json",
],
{
env: {},
exit: (code) => {
exitCode = code;
},
stdout: (text) => {
stdout += text;
},
},
);
expect(exitCode).toBe(0);
const result: unknown = JSON.parse(stdout);
expect(JSON.stringify(result)).not.toContain("synthetic-secret-token");
expect(calls).toEqual([
{
operation: "start",
input: {
mode: "attach",
pid: 71,
remote: {
address: "127.0.0.1:27042",
token: "synthetic-secret-token",
keepaliveInterval: 10,
},
source: { sourceKind: "inline", source: "send('hello')" },
durationMs: 0,
},
},
{
operation: "load",
sessionId: "00000000-0000-4000-8000-000000000001",
source: { sourceKind: "inline", source: "send('hello')" },
},
{
operation: "close",
sessionId: "00000000-0000-4000-8000-000000000001",
},
]);
stdout = "";
exitCode = 0;
await cli.serve(
["list-frida-devices", "--token", "synthetic-secret-token", "--json"],
{
env: {},
exit: (code) => {
exitCode = code;
},
stdout: (text) => {
stdout += text;
},
},
);
expect(exitCode).not.toBe(0);
expect(calls).toHaveLength(3);
expect(stdout).not.toContain("synthetic-secret-token");
});
it("awaits failed startup cleanup and retains the primary error if cleanup still fails", async () => {
for (const cleanupFails of [false, true]) {
const calls: string[] = [];
const provider: FridaInstrumentationPort =
new FridaInstrumentationManager();
provider.startSession = async () => {
calls.push("start");
return {
ok: false,
error: new AnalysisCapabilityUnavailableError(
"frida",
"start_frida_session",
"attach failed after spawn",
{
cleanup: {
reason: "first resume failed",
resources: ["paused spawn"],
},
},
),
};
};
provider.closeAll = async () => {
calls.push("cleanup");
if (cleanupFails) throw new Error("resume still failed");
};
let stdout = "";
await createCli({}, undefined, provider).serve(
[
"instrument-with-frida",
"spawn",
"/tmp/fixture",
"--script",
"send('ready')",
"--json",
],
{
env: {},
exit: () => {},
stdout: (text) => {
stdout += text;
},
},
);
expect(calls).toEqual(["start", "cleanup"]);
const output: unknown = JSON.parse(stdout);
expect(output).toMatchObject({
code: cleanupFails ? "cleanup_incomplete" : "capability_unavailable",
});
expect(stdout).toContain("attach failed after spawn");
if (cleanupFails) expect(stdout).toContain("primary_error");
}
});
it("preserves observed devices when CLI provider cleanup fails", async () => {
const provider: FridaInstrumentationPort = new FridaInstrumentationManager();
const devices = [
{ deviceId: "remote-device", name: "selected endpoint", type: "remote" },
];
provider.listDevices = async () => ({
ok: true,
value: { devices, cleanupError: null },
});
provider.closeAll = async () => {
throw new Error("remote removal failed");
};
let stdout = "";
await createCli({}, undefined, provider).serve(
["list-frida-devices", "--json"],
{
env: {},
exit: () => {},
stdout: (text) => {
stdout += text;
},
},
);
const output: unknown = JSON.parse(stdout);
expect(output).toMatchObject({
code: "cleanup_incomplete",
details: { diagnostics: { partial_observation: { devices } } },
});
});
it.each([
[
["attach", "abc", "--script", "send(1)"],
"target",
"attach mode needs a positive integer process ID.",
],
[
["attach", "71"],
"script",
"Provide exactly one of --script or --script-file.",
],
])(
"names the rejected instrument-with-frida argument for %j",
async (argv, path, message) => {
let starts = 0;
const provider = {
async startSession() {
starts += 1;
throw new Error("Frida must not start for invalid input");
},
} as unknown as FridaInstrumentationPort;
const cli = createCli({}, undefined, provider);
let stdout = "";
await cli.serve(["instrument-with-frida", ...argv, "--json"], {
env: {},
exit: () => undefined,
stdout: (text) => {
stdout += text;
},
});
expect(JSON.parse(stdout)).toMatchObject({
code: "invalid_request",
details: {
issues: [{ path: [path], reason: "invalid_value", message }],
},
});
expect(starts).toBe(0);
},
);
@@ -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 },
]),
);
},
);
+22 -21
View File
@@ -11,18 +11,6 @@ const serve = async (
): Promise<{ readonly stdout: string; readonly exitCode: number }> =>
serveCli(argv, jebEnvironment);
it.each([
["inspect-jeb-client"],
["open-jeb-project"],
["list-jeb-units"],
["decompile-jeb-item"],
])("%s advertises a schema through the public CLI", async (command) => {
const result = await serve([command, "--schema", "--json"]);
expect(result.exitCode, command).toBe(0);
const schema = JSON.parse(result.stdout) as { args?: unknown };
expect(schema).toBeTruthy();
});
it("reports an unreachable engine endpoint with recovery guidance", async () => {
const result = await serve(["inspect-jeb-client", "--json"]);
expect(result.stdout).toContain("capability_unavailable");
@@ -30,13 +18,26 @@ it("reports an unreachable engine endpoint with recovery guidance", async () =>
});
it("validates decompile item input before contacting the engine", async () => {
const result = await serve([
"decompile-jeb-item",
"not-an-address",
"--item-kind",
"method",
"--json",
]);
expect(result.stdout).toBeTruthy();
expect(result.stdout).not.toContain("capability_unavailable");
const result = await serve(["decompile-jeb-item", "", "method", "--json"]);
expect(result.exitCode).toBe(1);
expect(JSON.parse(result.stdout)).toMatchObject({
code: "VALIDATION_ERROR",
fieldErrors: [
{
code: "too_small",
path: "item-address",
},
],
});
});
it("reports an invalid endpoint without breaking other commands", async () => {
const environment = { REA_JEB_MCP_URL: "http://localhost:8425/mcp" };
const jeb = await serveCli(["inspect-jeb-client", "--json"], environment);
expect(JSON.parse(jeb.stdout)).toMatchObject({
code: "configuration_invalid",
details: { settings: [{ setting: "REA_JEB_MCP_URL" }] },
});
const capabilities = await serveCli(["capabilities", "--json"], environment);
expect(capabilities.exitCode).toBe(0);
});
+283 -12
View File
@@ -2,15 +2,19 @@ import { constants } from "node:buffer";
import { createHash } from "node:crypto";
import { Writable } from "node:stream";
import { Cli } from "incur";
import { Cli, Formatter } from "incur";
import { estimateTokenCount } from "tokenx";
import { parse as parseYaml } from "yaml";
import { describe, expect, it } from "vitest";
import { writeJsonOutput } from "../../../src/cli/jsonOutput.js";
import {
createStreamedCliJsonOutput,
createCliResultOutput,
streamCliCommandResults,
} from "../../../src/cli/streamedJsonOutput.js";
} from "../../../src/cli/cliResultOutput.js";
import { logCliCommand } from "../../../src/cliLogging.js";
import { registerManagedCommands } from "../../../src/cli/managedCommands.js";
import { analysisErrorProjectionSchema } from "../../../src/contracts/errorSchemas.js";
import { silentLogger } from "../../../src/logger.js";
const collect = async (
@@ -157,16 +161,283 @@ describe("incremental CLI JSON", () => {
);
});
describe("streamed CLI result surface", () => {
describe("CLI result output surface", () => {
it.each(["json", "yaml", "toon", "md"] as const)(
"places typed analysis failures in the full-output error envelope (%s)",
async (format) => {
const chunks: Buffer[] = [];
const destination = new Writable({
write(chunk: Buffer, _encoding, callback) {
chunks.push(chunk);
callback();
},
});
const failure = {
error: "Analysis failed",
code: "target_unavailable",
category: "unavailable",
message: "The selected artifact is missing.",
retryable: false,
remediation: { action: "Check that the path exists." },
details: { source: "artifact-open" },
input_path: "missing.dll",
input_reason: "read-failed",
};
const argv = [
"inspect-managed-artifact",
"missing.dll",
"--format",
format,
"--full-output",
"--filter-output",
"message",
];
const output = createCliResultOutput(argv, destination);
if (output === undefined)
throw new Error("Missing structured output surface");
const cli = Cli.create("rea-output-test", { sync: false });
registerManagedCommands(cli, silentLogger, async () => failure);
streamCliCommandResults(cli, output);
let fallback = "";
const previousExitCode = process.exitCode;
try {
await cli.serve(argv, {
stdout: (text) => {
if (!output.handled) fallback += text;
},
});
expect(process.exitCode).toBe(1);
} finally {
process.exitCode = previousExitCode;
}
const text = Buffer.concat(chunks).toString("utf8");
expect(output.handled).toBe(true);
expect(fallback).toBe("");
if (format === "json" || format === "yaml") {
const document = format === "json" ? JSON.parse(text) : parseYaml(text);
expect(document).toMatchObject({
ok: false,
error: {
code: failure.code,
category: failure.category,
message: failure.message,
retryable: false,
remediation: failure.remediation,
details: {
...failure.details,
input_path: failure.input_path,
input_reason: failure.input_reason,
},
},
meta: { command: "inspect-managed-artifact" },
});
expect(() =>
analysisErrorProjectionSchema.parse(document.error),
).not.toThrow();
expect(document).not.toHaveProperty("data");
} else {
expect(text).toContain("false");
expect(text).toContain(failure.code);
expect(text).not.toContain("true");
}
},
);
it.each([
{
name: "custom command failure",
value: {
status: "failed",
message: "Update was not applied.",
remediation: "Check the package manager, then retry.",
details: { stage: "install" },
},
isFailure: () => true,
},
{
name: "unhealthy doctor result",
value: { healthy: false, checks: [{ name: "provider", ok: false }] },
isFailure: undefined,
},
])("preserves $name as a full-output error payload", async (scenario) => {
const chunks: Buffer[] = [];
const destination = new Writable({
write(chunk: Buffer, _encoding, callback) {
chunks.push(chunk);
callback();
},
});
const argv = ["fixture", "--json", "--full-output"];
const output = createCliResultOutput(argv, destination);
if (output === undefined) throw new Error("Missing JSON output surface");
const cli = Cli.create("rea-output-test", { sync: false });
cli.command("fixture", {
run: () =>
logCliCommand(
silentLogger,
"fixture",
async () => scenario.value,
scenario.isFailure,
),
});
streamCliCommandResults(cli, output);
const previousExitCode = process.exitCode;
try {
await cli.serve(argv, { stdout: () => undefined });
expect(process.exitCode).toBe(1);
} finally {
process.exitCode = previousExitCode;
}
expect(JSON.parse(Buffer.concat(chunks).toString("utf8"))).toMatchObject({
ok: false,
error: scenario.value,
});
});
});
describe("full-output token windows", () => {
it("preserves Incur token-window metadata when truncating a TOON failure", async () => {
const chunks: Buffer[] = [];
const destination = new Writable({
write(chunk: Buffer, _encoding, callback) {
chunks.push(chunk);
callback();
},
});
const argv = [
"inspect-managed-artifact",
"missing.dll",
"--format",
"toon",
"--full-output",
"--token-limit",
"3",
];
const output = createCliResultOutput(argv, destination);
if (output === undefined) throw new Error("Missing TOON output surface");
const cli = Cli.create("rea-output-test", { sync: false });
registerManagedCommands(cli, silentLogger, async () => ({
code: "target_unavailable",
category: "unavailable",
message: "The selected artifact is missing.",
retryable: false,
remediation: { action: "Check that the path exists." },
details: { source: "artifact-open" },
}));
streamCliCommandResults(cli, output);
const previousExitCode = process.exitCode;
try {
await cli.serve(argv, { stdout: () => undefined });
expect(process.exitCode).toBe(1);
} finally {
process.exitCode = previousExitCode;
}
const text = Buffer.concat(chunks).toString("utf8");
expect(text).toContain("[truncated: showing tokens 0–3 of");
expect(text).toMatch(/nextOffset:?\s*3/);
expect(text).toContain("ok: false");
});
});
describe("logger classification handoff", () => {
it("honors an explicit success for data containing error-shaped fields", async () => {
const chunks: Buffer[] = [];
const destination = new Writable({
write(chunk: Buffer, _encoding, callback) {
chunks.push(chunk);
callback();
},
});
const result = {
error: {
code: "target_unavailable",
category: "unavailable",
message: "Source data describes a missing target.",
retryable: false,
remediation: { action: "Use the value as source data." },
},
source: "captured-metadata",
};
const argv = ["fixture", "--json", "--full-output"];
const output = createCliResultOutput(argv, destination);
if (output === undefined) throw new Error("Missing JSON output surface");
const cli = Cli.create("rea-output-test", { sync: false });
cli.command("fixture", {
run: () =>
logCliCommand(
silentLogger,
"fixture",
async () => result,
() => false,
),
});
streamCliCommandResults(cli, output);
const previousExitCode = process.exitCode;
try {
await cli.serve(argv, { stdout: () => undefined });
expect(process.exitCode).toBe(previousExitCode);
} finally {
process.exitCode = previousExitCode;
}
expect(JSON.parse(Buffer.concat(chunks).toString("utf8"))).toMatchObject({
ok: true,
data: result,
});
});
});
describe("full-output token counts", () => {
it("counts the full failure payload before applying output filters", async () => {
const chunks: Buffer[] = [];
const destination = new Writable({
write(chunk: Buffer, _encoding, callback) {
chunks.push(chunk);
callback();
},
});
const failure = {
code: "target_unavailable",
category: "unavailable",
message: "The selected artifact is missing.",
retryable: false,
remediation: { action: "Check that the path exists." },
details: { source: "artifact-open" },
};
const argv = [
"inspect-managed-artifact",
"missing.dll",
"--json",
"--full-output",
"--token-count",
"--filter-output",
"message",
];
const output = createCliResultOutput(argv, destination);
if (output === undefined) throw new Error("Missing JSON output surface");
const cli = Cli.create("rea-output-test", { sync: false });
registerManagedCommands(cli, silentLogger, async () => failure);
streamCliCommandResults(cli, output);
const previousExitCode = process.exitCode;
try {
await cli.serve(argv, { stdout: () => undefined });
expect(process.exitCode).toBe(1);
} finally {
process.exitCode = previousExitCode;
}
expect(output.handled).toBe(true);
expect(Buffer.concat(chunks).toString("utf8")).toBe(
`${estimateTokenCount(Formatter.format(failure, "json"))}\n`,
);
});
});
describe("CLI result output surface", () => {
it.each([
[],
["--format", "md"],
["--json", "--token-limit", "5"],
["--json", "--format", "invalid"],
])("delegates unsupported output controls %j", (...arguments_) => {
expect(createStreamedCliJsonOutput(arguments_, new Writable())).toBe(
undefined,
);
expect(createCliResultOutput(arguments_, new Writable())).toBe(undefined);
});
it("keeps ownership after a failed write so no second document is emitted", async () => {
@@ -176,7 +447,7 @@ describe("streamed CLI result surface", () => {
callback(cause);
},
});
const output = createStreamedCliJsonOutput(["--json"], destination);
const output = createCliResultOutput(["--json"], destination);
if (output === undefined) throw new Error("Missing JSON output surface");
await expect(
output.write(
@@ -228,7 +499,7 @@ describe("streamed CLI result surface", () => {
// A terminal destination exercises the indented encoding past the limit.
Object.defineProperty(destination, "isTTY", { value: true });
const argv = ["inspect-managed-members", "fixture.dll", "--json"];
const output = createStreamedCliJsonOutput(argv, destination);
const output = createCliResultOutput(argv, destination);
if (output === undefined) throw new Error("Missing JSON output surface");
streamCliCommandResults(cli, output);
let exitCode = 0;
@@ -248,7 +519,7 @@ describe("streamed CLI result surface", () => {
const chunks: Buffer[] = [];
const tokenArgv = [...argv, "--token-count", "--full-output"];
const tokenOutput = createStreamedCliJsonOutput(
const tokenOutput = createCliResultOutput(
tokenArgv,
new Writable({
write(chunk: Buffer, _encoding, callback) {
@@ -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,
);
},
);
@@ -0,0 +1,78 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { build } from "plist";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { deeplyNestedXmlPlist } from "../../fixtures/keyedArchiveXmlNesting.js";
import { cliTest } from "../../support/cli/cliFixture.js";
for (const [name, xml] of [
["dictionaries", deeplyNestedXmlPlist(3000)],
[
"quoted attributes",
deeplyNestedXmlPlist(3000).replaceAll("<dict>", '<dict note="/>">'),
],
[
"plist wrappers",
"<plist>".repeat(3000) + "<string>x</string>" + "</plist>".repeat(3000),
],
] as const) {
cliTest(
`compiled CLI reports deeply nested XML ${name} as the decode limit`,
async ({ cli }) => {
const root = await createTestTempDirectory("rea-keyed-cli-depth-");
const path = join(root, "Deep.plist");
await writeFile(path, xml);
const output = await cli.run({
arguments: ["inspect-keyed-archive", path, "--json"],
environment: { REA_LOG_LEVEL: "silent", REA_ANALYSIS_PROVIDER: "auto" },
});
expect(output.exitCode, output.stderr).toBe(1);
expect(output.json).toMatchObject({
code: "truncated",
category: "truncated",
details: {
reason: "limit",
truncated: true,
detail:
"Cannot decode selected Foundation keyed archive: Plist exceeds 128 nesting levels",
},
});
},
);
}
cliTest(
"compiled CLI decodes a shallow archive with opaque DOCTYPE markup",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-keyed-cli-doctype-");
const path = join(root, "Shallow.plist");
const archive = build({
$archiver: "NSKeyedArchiver",
$version: 100000,
$objects: ["$null", "leaf"],
$top: { root: { UID: 1 } },
});
await writeFile(
path,
archive.replace(
/<!DOCTYPE[^>]*>/u,
`<!DOCTYPE plist [<!ENTITY first "unused"><!ENTITY second "${"<dict>".repeat(130)}">]>`,
),
);
const output = await cli.run({
arguments: ["inspect-keyed-archive", path, "--json"],
environment: { REA_LOG_LEVEL: "silent", REA_ANALYSIS_PROVIDER: "auto" },
});
expect(output.exitCode, output.stderr).toBe(0);
expect(parseEvidence(output.json).normalized_result).toMatchObject({
archive_format: "xml-plist",
objects: expect.arrayContaining([
expect.objectContaining({ value: "leaf" }),
]),
});
},
);
+6 -1
View File
@@ -44,15 +44,20 @@ describe.skipIf(process.platform !== "darwin")(
});
cliTest("rejects a symbol spanning lines as input", async ({ cli }) => {
const missingTarget = join(
await createTestTempDirectory("rea-demangle-invalid-input-"),
"absent",
);
const result = await cli.run({
arguments: [
"demangle-swift",
await evidenceTarget(),
missingTarget,
"$s4main3FooV",
"$s4main\n3FooV",
"--json",
],
environment,
timeoutMs: 20_000,
});
expect(result.exitCode).not.toBe(0);
expect(result.json).toMatchObject({ code: "VALIDATION_ERROR" });
@@ -0,0 +1,336 @@
import { execFile } from "node:child_process";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { promisify } from "node:util";
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const execute = promisify(execFile);
// A recording port checks the experimental producer/consumer representation.
// Real provider verification remains in the separate native experiment receipts.
const generate = `
import {measureNativeEntry} from './experiments/analysis-efficiency/native-entry.mjs';
const sha='0'.repeat(64);
const duplicate=process.argv[1]==='duplicate';
const stale=process.argv[1]==='stale-dos';
const collision=process.argv[1];
const dos=process.argv[1]==='dos'||stale||collision==='load-collision';
const dossier={procedure:{address:'0x1000'},pseudocode:'return;',callers:[],callees:[]};
class ToolFailure extends Error {}
const build=async digit=>{
const parent='ev_'+digit.repeat(63)+'0';
let ordinal=0;
const call=async(name,args)=>{
if(stale)process.stdout.write(name+'\\n');
if(name==='open_binary'||name==='close_binary')return {};
if(name==='inspect_native_load_image')return {evidence_id:'ev_'+digit.repeat(63)+'6',normalized_result:{status:'verified',target_sha256:stale?'f'.repeat(64):sha,entry:{linear_address:'0x1000'}}};
if(name==='resolve_containing_procedure')return {evidence_id:'ev_'+digit.repeat(63)+'7',normalized_result:{found:true}};
if(name==='analyze_function')return {evidence_id:parent,subject:{digest:{sha256:sha}},normalized_result:dossier};
const id='ev_'+digit.repeat(63)+(collision==='containing-collision'?7:collision==='load-collision'?6:duplicate?1:++ordinal);
if(args.view.kind==='summary')return {evidence_id:id};
const facet=args.view.facet;
const item=facet==='pseudocode'?{text:dossier.pseudocode,unit:'utf16-code-units'}:dossier[facet];
return {evidence_id:id,normalized_result:{parent_evidence_id:parent,artifact:{sha256:sha},item,coverage:{exhausted:true},limitations:[],unknowns:[]}};
};
return measureNativeEntry({seed:dos?undefined:'0x1000',values:{path:'/selected/input','native-question':'entry-views'},call,inputSha:sha,ToolFailure});
};
process.stdout.write(JSON.stringify([await build('1'),await build('2')]));
`;
it.each([
"observed",
"missing",
"errored",
"wrong-target",
"wrong-entry",
"unreferenced",
])(
"binds the DOS model grade to its observed load image: %s",
async (scenario) => {
// Synthetic transcripts exercise grading; they are not real-provider or
// resource measurements. Real DOS transcripts are replayed separately.
const root = await createTestTempDirectory("rea-dos-grader-");
const trial = join(root, "trial");
const referenceDirectory = join(root, "reference");
await mkdir(trial);
await mkdir(referenceDirectory);
const sha = "0".repeat(64);
const imageId = "ev_" + "1".repeat(64);
const procedureId = "ev_" + "2".repeat(64);
const procedure = {
address: "0x1000",
name: "entry",
classification: "observed",
signature: null,
locals: [],
body: { ranges: [], total_bytes: 0 },
};
const loadImage = {
status: "verified",
target_sha256: sha,
entry: { linear_address: "0x1000" },
};
const reference = {
artifact_sha256: sha,
entry_address: "0x1000",
caller_count: 0,
callee_count: 0,
pseudocode_prefix: "return;",
containing_procedure: { procedure },
procedure,
load_image: loadImage,
};
const answer = {
...reference,
load_image_status: "verified",
evidence_ids: [
procedureId,
...(["missing", "errored", "unreferenced"].includes(scenario)
? []
: [imageId]),
],
};
const event = (tool: string, status: string, value: unknown) => ({
type: "item.completed",
item: {
type: "mcp_tool_call",
tool,
status,
arguments: {},
result: { structured_content: value },
},
});
const events = [
event("analyze_function", "completed", { evidence_id: procedureId }),
];
if (scenario !== "missing")
events.push(
event(
"inspect_native_load_image",
scenario === "errored" ? "failed" : "completed",
scenario === "errored"
? { error: { code: "unsupported_target" } }
: {
operation: "inspect_native_load_image",
evidence_id: imageId,
normalized_result: {
...loadImage,
target_sha256:
scenario === "wrong-target" ? "f".repeat(64) : sha,
entry: {
linear_address:
scenario === "wrong-entry" ? "0x2000" : "0x1000",
},
},
},
),
);
const resourceLog = join(root, "resource.log");
const output = join(root, "review.json");
for (const [path, value] of [
[
join(trial, "summary.json"),
{
completed_mcp_calls: [
{ tool: "close_binary", status: "completed", arguments: {} },
],
},
],
[join(trial, "trial-settings.json"), {}],
[join(trial, "cleanup.json"), { profile_removed: true }],
[join(trial, "answer.txt"), answer],
[join(referenceDirectory, "answer.json"), reference],
[
resourceLog,
{
resource_scope: "synthetic-grader-fixture",
abort: null,
resource_counters_verified: true,
resource_events_final: {
"memory.events": { high: 0, max: 0, oom: 0, oom_kill: 0 },
"pids.events": { max: 0 },
},
},
],
] as const)
await writeFile(path, JSON.stringify(value));
await writeFile(
join(trial, "events.jsonl"),
events.map((value) => JSON.stringify(value)).join("\n"),
);
const command = execute("python3", [
resolve("experiments/analysis-efficiency/review-model.py"),
"--domain",
"native",
"--trial",
trial,
"--reference",
referenceDirectory,
"--resource-log",
resourceLog,
"--output",
output,
]);
if (scenario === "observed") await command;
else await expect(command).rejects.toMatchObject({ code: 1 });
const report = JSON.parse(await readFile(output, "utf8"));
expect(report.all_selected_checks_pass).toBe(scenario === "observed");
if (["missing", "errored", "unreferenced"].includes(scenario))
expect(report.checks.load_image_source_observed_and_referenced).toBe(
false,
);
if (scenario === "wrong-target")
expect(report.checks["load_image.target_sha256"]).toBe(false);
if (scenario === "wrong-entry")
expect(report.checks["load_image.source_entry"]).toBe(false);
},
);
it("retains the DOS load-image source for its facts and derived entry seed", async () => {
const { stdout } = await execute(process.execPath, [
"--input-type=module",
"-e",
generate,
"dos",
]);
const [answer] = JSON.parse(stdout);
expect(answer).toMatchObject({
entry_address: "0x1000",
load_image: { status: "verified", entry: { linear_address: "0x1000" } },
evidence_ids: { native_load_image: "ev_" + "1".repeat(63) + "6" },
});
});
it("rejects a stale DOS load image before using its entry and closes the session", async () => {
await expect(
execute(process.execPath, [
"--input-type=module",
"-e",
generate,
"stale-dos",
]),
).rejects.toMatchObject({
stdout: "open_binary\ninspect_native_load_image\nclose_binary\n",
stderr: expect.stringContaining(
"The DOS load image belongs to a different target",
),
});
});
it.each(["containing-collision", "load-collision"])(
"rejects a retained view that reuses an earlier producer identity: %s",
async (collision) => {
await expect(
execute(process.execPath, [
"--input-type=module",
"-e",
generate,
collision,
]),
).rejects.toMatchObject({
stderr: expect.stringContaining(
"Retained native view reused an Evidence identity",
),
});
},
);
it("rejects a producer that reuses a view identity across facets", async () => {
await expect(
execute(process.execPath, [
"--input-type=module",
"-e",
generate,
"duplicate",
]),
).rejects.toMatchObject({
stderr: expect.stringContaining(
"Retained native view reused an Evidence identity",
),
});
});
it.each(["references", "item", "coverage", "limitations", "unknowns"])(
"separates native references while comparing %s exactly",
async (change) => {
const { stdout: generated } = await execute(process.execPath, [
"--input-type=module",
"-e",
generate,
]);
const [leftAnswer, rightAnswer] = JSON.parse(generated);
if (change === "item")
rightAnswer.retained_views[0].item.address = "0x1001";
if (change === "coverage")
rightAnswer.retained_views[0].coverage.exhausted = false;
if (change === "limitations")
rightAnswer.retained_views[0].limitations.push("partial");
if (change === "unknowns")
rightAnswer.retained_views[0].unknowns.push("unresolved");
const root = await createTestTempDirectory("rea-native-comparison-");
const left = join(root, "left");
const right = join(root, "right");
const summary = {
artifact: "sharex.exe",
native_question: "entry-views",
provider_search_path_sha256: "0".repeat(64),
native_workflow_source_sha256: "1".repeat(64),
calls: [],
failure: null,
};
for (const [directory, answer] of [
[left, leftAnswer],
[right, rightAnswer],
]) {
await mkdir(directory);
await writeFile(join(directory, "summary.json"), JSON.stringify(summary));
await writeFile(join(directory, "answer.json"), JSON.stringify(answer));
}
const output = join(root, "comparison.json");
const command = execute(process.execPath, [
resolve("experiments/analysis-efficiency/compare.mjs"),
"--left",
left,
"--right",
right,
"--output",
output,
]);
if (change !== "references") {
await expect(command).rejects.toMatchObject({
code: 1,
stdout: expect.stringContaining('"retained_views"'),
});
return;
}
const { stdout } = await command;
expect(JSON.parse(stdout)).toMatchObject({
settings_match: true,
facts_match: true,
preserved_run_specific_values: [
{
side: "left",
path: ["evidence_ids"],
value: leftAnswer.evidence_ids,
},
{
side: "right",
path: ["evidence_ids"],
value: rightAnswer.evidence_ids,
},
],
});
expect(leftAnswer.evidence_ids).not.toEqual(rightAnswer.evidence_ids);
expect(leftAnswer.evidence_ids.retained_views[0]).toMatchObject({
evidence_id: "ev_" + "1".repeat(64),
parent_evidence_id: "ev_" + "1".repeat(63) + "0",
});
expect(leftAnswer.evidence_ids.native_summary).toBe(
"ev_" + "1".repeat(63) + "5",
);
},
);
+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") },
});
},
@@ -47,8 +47,8 @@ describe("compiled Windows reference-source import", () => {
expect(result.json).toEqual(
scenario.fullOutput
? expect.objectContaining({
ok: true,
data: unsupportedHostOutput,
ok: false,
error: unsupportedHostOutput,
})
: unsupportedHostOutput,
);
@@ -113,16 +113,14 @@ describe("compiled reference-source import preflight failures", () => {
message: expect.stringContaining(rootReason),
};
if (scenario.fullOutput) {
// Incur's legacy wrapper remains unchanged; operation status is
// conveyed by the exit code and command log, not this `ok` field.
expect(result.json).toMatchObject({
ok: true,
data: invalidRootOutput,
ok: false,
error: invalidRootOutput,
});
} else {
expect(result.json).toMatchObject(invalidRootOutput);
}
const messagePath = scenario.fullOutput ? "data.message" : "message";
const messagePath = scenario.fullOutput ? "error.message" : "message";
expect(result.json).toHaveProperty(
messagePath,
expect.stringContaining(
@@ -0,0 +1,90 @@
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { historicalSourceGraphSchema } from "../../../src/domain/referenceSourceGraph.js";
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
import { execFileOutput } from "../../../src/process/ExecFileOutput.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
cliTest(
"imports a legacy subtree of a Git checkout with its own source facts",
async ({ cli }) => {
const repository = await createTestTempDirectory("rea-reference-legacy-");
const source = join(repository, "source");
await mkdir(source);
await Promise.all([
// `.cjs` is CommonJS, so the strict-mode rule does not apply.
writeFile(
join(source, "legacy.cjs"),
"var messages = {};\ndelete messages;\n",
),
// Deleting a plain binding is valid only in a sloppy-mode script.
writeFile(
join(source, "legacy.js"),
"var messages = {};\ndelete messages;\n",
),
// An explicit module keeps the strict-mode error.
writeFile(
join(source, "module.mjs"),
"var messages = {};\ndelete messages;\n",
),
writeFile(join(source, "index.php"), "<?php echo 'legacy';\n"),
writeFile(join(source, "Program.cs"), "class Program {}\n"),
]);
const git = (...args: string[]) =>
execFileOutput("git", args, { cwd: repository });
await git("init", "--initial-branch=main");
await git("add", ".");
await git(
"-c",
"user.name=REA fixture",
"-c",
"user.email=fixture@example.invalid",
"-c",
"commit.gpgsign=false",
"commit",
"-m",
"fixture",
);
const head = (await git("rev-parse", "HEAD")).stdout.trim();
const result = await cli.run({
arguments: ["import-reference-source", source, "--json"],
environment: {
HOME: repository,
XDG_CONFIG_HOME: repository,
XDG_CACHE_HOME: repository,
},
});
expect(result.exitCode).toBe(0);
const graph = historicalSourceGraphSchema.parse(result.json);
expect(graph.parse_failures).toEqual([
{
path: "module.mjs",
parser: "babel",
reason: "Deleting local variable in strict mode. (2:0)",
},
]);
// Outside `.mjs`/`.mts`/`.cjs` the mode stays unknown, not forced to script.
const limitations = (path: string) =>
graph.entries.find((entry) => entry.path === path)?.limitations;
for (const path of ["legacy.js"])
expect(limitations(path)).toEqual([
"Strict-mode errors apply only if this file is an ES module: Deleting local variable in strict mode. (2:0)",
]);
expect(limitations("legacy.cjs")).toEqual([]);
expect(graph.languages).toEqual(["C#", "JavaScript", "PHP"]);
for (const path of ["Program.cs", "index.php"])
expect(
graph.entries.find((entry) => entry.path === path)?.classifications,
).toContain("source");
expect(graph.vcs).toEqual({ kind: "git", head, dirty: null });
expect(graph.provenance.importer_version).toBe(
PRODUCT_IDENTITY.packageVersion,
);
},
);
+132
View File
@@ -0,0 +1,132 @@
import { Cli } from "incur";
import { expect, it } from "vitest";
import { registerSignalCommands } from "../../../src/cli/signalCommands.js";
import { silentLogger } from "../../../src/logger.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js";
import { err } from "../../../src/domain/result.js";
it.each([
{
flags: ["--decoders", "uart", "--all_lines", "--line_limit", "20"],
message: "mutually exclusive",
},
{
flags: [
"--decoders",
"x".repeat(8192),
"--input_format",
"界".repeat(8192),
],
message: "32 KiB",
},
])(
"rejects invalid selections before invoking the CLI service: $message",
async ({ flags, message }) => {
const cli = Cli.create("signal-selection-test", { sync: false });
let called = false;
registerSignalCommands(
cli,
silentLogger,
{},
{
decode: async () => {
called = true;
throw new Error("Must not decode");
},
close: async () => {},
},
);
let stdout = "";
await cli.serve(
[
"decode-signal-recording",
"recording.vcd",
...flags,
"--format",
"json",
],
{
stdout: (text) => {
stdout += text;
},
exit: () => {},
},
);
expect(called).toBe(false);
expect(stdout).toContain(message);
},
);
it.each([false, true])(
"awaits cleanup retry and preserves completed output when retry failure is %s",
async (failAgain) => {
const evidence = createEvidence(
undefined,
{ id: "fixture", name: "Completed decoder fixture", version: "1" },
{
operation: "decode_signal_recording",
parameters: {},
result: { annotations_text: "retained annotation" },
confidence: "observed",
},
);
const original = new ProviderCleanupError(
"sigrok-recording",
["original-workspace"],
{ reason: "original cleanup failure" },
{ operation: "decode_signal_recording", partialObservation: evidence },
);
let closed = false;
const cli = Cli.create("signal-cleanup-test", { sync: false });
registerSignalCommands(
cli,
silentLogger,
{},
{
decode: async () => err(original),
close: async () => {
await Promise.resolve();
closed = true;
if (failAgain)
throw new ProviderCleanupError(
"sigrok-recording",
["retry-workspace"],
{ reason: "retry failed" },
{ operation: "decode_signal_recording" },
);
},
},
);
let stdout = "";
await cli.serve(
[
"decode-signal-recording",
"recording.vcd",
"--decoders",
"uart",
"--format",
"json",
],
{
stdout: (text) => {
expect(closed).toBe(true);
stdout += text;
},
exit: () => {},
},
);
const output: unknown = JSON.parse(stdout);
expect(output).toMatchObject({
code: "cleanup_incomplete",
details: {
partial_observation: evidence,
resources: expect.arrayContaining(["original-workspace"]),
},
});
if (failAgain)
expect(output).toMatchObject({
details: { resources: expect.arrayContaining(["retry-workspace"]) },
});
},
);
@@ -1,9 +1,11 @@
import { readFile, stat, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { describe, expect, it, onTestFinished, vi } from "vitest";
import { withArtifactResourceScope } from "../../fixtures/artifactInventory.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { holdFirstFileRead } from "../../support/holdFirstFileRead.js";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
import {
@@ -28,6 +30,8 @@ import { createEvidence } from "../../../src/domain/evidence.js";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import { readJsonObjectFile } from "../../../src/application/JsonInputFile.js";
import { RegularFileChangedError } from "../../../src/filesystem/RegularFile.js";
import { OwnedFileHandle } from "../../../src/filesystem/OwnedFileHandle.js";
import { RegularFileCleanupFailure } from "../../../src/application/RegularFileRead.js";
const snapshotFixture = (): AnalysisSnapshot => {
const target = snapshotTarget(TARGET);
@@ -76,11 +80,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 +109,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);
});
});
@@ -222,20 +230,67 @@ describe("analysis snapshot member decoding", () => {
`${" ".repeat(9 * 1024 * 1024)}${JSON.stringify(snapshot)}`,
);
const controller = new AbortController();
const reads = await holdFirstFileRead(path);
onTestFinished(() => {
controller.abort();
reads.release();
});
const pending = readAnalysisSnapshot(path, controller.signal);
const timer = setTimeout(() => controller.abort(), 1);
await reads.firstRead;
controller.abort();
reads.release();
try {
expect(await pending).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
expect(reads.readCount).toBe(1);
} finally {
clearTimeout(timer);
vi.restoreAllMocks();
}
const loaded = await readAnalysisSnapshot(path);
if (!loaded.ok) throw loaded.error;
expect(loaded.value).toEqual(snapshot);
});
});
describe("analysis snapshot file ownership", () => {
it.each([false, true])(
"retains the file owner when snapshot close fails (cancelled: %s)",
async (cancelDuringClose) => {
const directory = await createTestTempDirectory("rea-snapshot-cleanup-");
const path = join(directory, "snapshot.json");
await writeFile(path, JSON.stringify(snapshotFixture()));
const controller = new AbortController();
const cleanupCause = new Error("injected snapshot file close failure");
const close = vi
.spyOn(OwnedFileHandle.prototype, "close")
.mockImplementationOnce(async () => {
if (cancelDuringClose) controller.abort();
throw cleanupCause;
});
let failure: unknown;
try {
try {
await readAnalysisSnapshot(
path,
cancelDuringClose ? controller.signal : undefined,
);
} catch (cause: unknown) {
failure = cause;
}
expect(failure).toBeInstanceOf(RegularFileCleanupFailure);
if (!(failure instanceof RegularFileCleanupFailure))
throw new Error("Expected the retained snapshot file handle owner");
expect(failure.cleanupCause).toBe(cleanupCause);
expect(failure.owner.handle.fd).toBeGreaterThanOrEqual(0);
} finally {
close.mockRestore();
if (failure instanceof RegularFileCleanupFailure)
await failure.owner.close();
}
},
);
it("rejects changed bytes between scans on the same descriptor", async () => {
const directory = await createTestTempDirectory("rea-snapshot-changed-");
@@ -9,16 +9,16 @@ import {
} from "@zip.js/zip.js";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import {
createNonApplicationZipInventory,
requireSuccessfulProjection,
} from "../../support/applicationSessionFixture.js";
} from "../../../support/applicationSessionFixture.js";
import { projectAndroidApplicationEvidence } from "../../../src/application/android/AndroidApplicationService.js";
import { createDirectAnalysis } from "../../../src/composition/directAnalysis.js";
import { androidApplicationProjectionResultSchema } from "../../../src/domain/android/androidApplication.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { projectAndroidApplicationEvidence } from "../../../../src/application/android/AndroidApplicationService.js";
import { createDirectAnalysis } from "../../../../src/composition/directAnalysis.js";
import { androidApplicationProjectionResultSchema } from "../../../../src/domain/android/androidApplication.js";
import { parseEvidence } from "../../../../src/domain/evidence.js";
const { runProviderAnalysis } = createDirectAnalysis({});
@@ -1,4 +1,4 @@
import { mkdir, writeFile } from "node:fs/promises";
import { chmod, mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
@@ -12,6 +12,7 @@ import {
artifactComparisonResultSchema,
compareArtifacts,
} from "../../../src/domain/artifactComparison.js";
import { parseArtifactInventoryEvidence } from "../../../src/domain/artifactInventoryEvidence.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
@@ -61,6 +62,184 @@ const changedArtifactComparison = async () => {
};
};
describe("leaf artifact comparison", () => {
it("accepts persisted complete leaf inventory Evidence without coverage_status", async () => {
const root = await createTestTempDirectory("rea-artifact-plist-compare-");
const leftPath = join(root, "left.plist");
const rightPath = join(root, "right.plist");
const xml =
'<?xml version="1.0"?><plist version="1.0"><dict><key>label</key><string>hello</string></dict></plist>';
await Promise.all([writeFile(leftPath, xml), writeFile(rightPath, xml)]);
const [left, right] = await Promise.all([
observe(leftPath),
observe(rightPath),
]);
// Persisted inventory Evidence predates coverage_status. The known leaf
// notice remains complete when normalized at the inventory boundary.
const parsed = artifactInventoryResultSchema.parse(left.normalized_result);
const { coverage_status: _coverageStatus, ...legacyInventory } = parsed;
const legacy = createEvidence(
{
path: left.subject!.local_path,
sha256: left.subject!.digest.sha256,
format: left.subject!.format,
},
PROVIDER,
{
operation: "inventory_artifact",
parameters: {},
result: jsonValueSchema.parse(legacyInventory),
confidence: "observed",
authority: "shipped-artifact",
},
);
expect(compareArtifacts(legacy, right)).toMatchObject({
status: "unchanged",
summary: { unchanged: 1, unknown: 0 },
changes: [],
});
});
it("keeps content and executable changes visible for complete plist roots", async () => {
const root = await createTestTempDirectory("rea-artifact-plist-deltas-");
const leftPath = join(root, "left.plist");
const rightPath = join(root, "right.plist");
const plist = (label: string) =>
`<?xml version="1.0"?><plist version="1.0"><dict><key>label</key><string>${label}</string></dict></plist>`;
await Promise.all([
writeFile(leftPath, plist("hello"), { mode: 0o644 }),
writeFile(rightPath, plist("world"), { mode: 0o644 }),
]);
const [left, changed] = await Promise.all([
observe(leftPath),
observe(rightPath),
]);
expect(compareArtifacts(left, changed)).toMatchObject({
status: "changed",
summary: { changed: 1, unknown: 0 },
changes: [
expect.objectContaining({
logical_path: ".",
classification: "changed",
dimensions: expect.arrayContaining(["content"]),
}),
],
});
if (process.platform !== "win32") {
await writeFile(rightPath, plist("hello"), { mode: 0o644 });
await chmod(rightPath, 0o755);
const executable = await observe(rightPath);
expect(compareArtifacts(left, executable)).toMatchObject({
status: "changed",
summary: { changed: 1, unknown: 0 },
changes: [
expect.objectContaining({
logical_path: ".",
classification: "changed",
dimensions: expect.arrayContaining(["executable"]),
}),
],
});
}
});
});
describe("artifact inventory coverage", () => {
it("keeps explicit and legacy unknown coverage fail-closed", async () => {
const root = await createTestTempDirectory("rea-artifact-coverage-");
const path = join(root, "complete.plist");
await writeFile(
path,
'<?xml version="1.0"?><plist version="1.0"><dict/></plist>',
);
const complete = await observe(path);
const graph = artifactInventoryResultSchema.parse(
complete.normalized_result,
);
const partial = createEvidence(
{
path: complete.subject!.local_path,
sha256: complete.subject!.digest.sha256,
format: complete.subject!.format,
},
PROVIDER,
{
operation: "inventory_artifact",
parameters: {},
result: jsonValueSchema.parse({ ...graph, coverage_status: "partial" }),
confidence: "observed",
authority: "shipped-artifact",
},
);
expect(compareArtifacts(partial, partial)).toMatchObject({
status: "unknown",
summary: { unchanged: 0, unknown: 1 },
});
const { coverage_status: _coverageStatus, ...legacyGraph } = graph;
const unknownLegacy = createEvidence(
{
path: complete.subject!.local_path,
sha256: complete.subject!.digest.sha256,
format: complete.subject!.format,
},
PROVIDER,
{
operation: "inventory_artifact",
parameters: {},
result: jsonValueSchema.parse({
...legacyGraph,
limitations: ["Producer omitted unexamined child entries."],
}),
confidence: "observed",
authority: "shipped-artifact",
},
);
expect(compareArtifacts(unknownLegacy, unknownLegacy)).toMatchObject({
status: "unknown",
summary: { unchanged: 0, unknown: 1 },
});
});
it("rejects inventory fragments that disagree on producer coverage", async () => {
const parent = await createTestTempDirectory("rea-artifact-page-coverage-");
const path = join(parent, "fixture.app");
await mkdir(path);
await writeFile(join(path, "main.js"), "main();");
const source = await observe(path);
const fragments = fragmentInventoryEvidence(source, 2);
const firstFragment = fragments[0];
const fragment = fragments[1];
if (firstFragment === undefined || fragment === undefined)
throw new Error("Missing test fragment");
const fragmentGraph = artifactInventoryResultSchema.parse(
fragment.normalized_result,
);
const mixed = createEvidence(
{
path: fragment.subject!.local_path,
sha256: fragment.subject!.digest.sha256,
format: fragment.subject!.format,
},
PROVIDER,
{
operation: "inventory_artifact",
parameters: fragment.parameters,
result: jsonValueSchema.parse({
...fragmentGraph,
coverage_status: "partial",
}),
confidence: "derived",
authority: "shipped-artifact",
},
);
expect(() =>
parseArtifactInventoryEvidence([firstFragment, mixed]),
).toThrow("Artifact inventory pages disagree on coverage status");
});
});
describe("artifact comparison", () => {
it("classifies deterministic path changes and cites both inventories", async () => {
const firstObservation = await changedArtifactComparison();
@@ -129,6 +129,7 @@ describe("entry-order validation and reader controls", () => {
["pkg/data.txt", "pkg/data.txt/"],
["pkg/data.txt/", "pkg/data.txt"],
["pkg/data.txt", "pkg"],
["pkg", "pkg/data.txt"],
["../escape.txt"],
])("keeps invalid/colliding paths rejected for %j", async (...entries) => {
const root = await createTestTempDirectory("rea-entry-order-invalid-");
@@ -158,6 +159,27 @@ describe("entry-order validation and reader controls", () => {
}
});
it("retains case-distinct file prefixes without inventing a directory", async () => {
const root = await createTestTempDirectory("rea-entry-order-case-prefix-");
const archive = join(root, "case-prefix.zip");
for (const entries of [
["Foo", "foo/bar"],
["foo/bar", "Foo"],
]) {
await writeOrderedZip(archive, entries);
const inventory = await inventoryArtifact(archive);
expect(artifactParentPaths(inventory)).toEqual({
".": null,
Foo: ".",
"foo/bar": ".",
});
for (const path of entries)
expect(artifactOccurrenceAt(inventory, path).hash_status).toBe(
"verified",
);
}
});
it("retains high-cardinality case-folded directories and their descendants", async () => {
const root = await createTestTempDirectory(
"rea-entry-order-case-capacity-",
@@ -1,16 +1,144 @@
import { readFile, writeFile } from "node:fs/promises";
import { readFile, readdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
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";
import { ArtifactProvider } from "../../../src/artifacts/ArtifactProvider.js";
import { ZipArtifactReader } from "../../../src/artifacts/ZipArtifactReader.js";
import { artifactInventoryResultSchema } from "../../../src/domain/artifactGraph.js";
import { withArtifactClient } from "../../support/artifactClientScope.js";
import {
artifactExtractionResultSchema,
artifactInventoryResultSchema,
} from "../../../src/domain/artifactGraph.js";
it("completes an empty ZIP extraction with an empty identity", async () => {
const root = await createTestTempDirectory("rea-empty-artifact-extraction-");
const archive = join(root, "empty.zip");
await writeOrderedZip(archive, []);
const archiveTarget = await parseBinaryTarget(archive);
if (!archiveTarget.ok) throw archiveTarget.error;
const output = join(root, "output");
const result = await withArtifactClient(archiveTarget.value, (client) =>
client.execute("extract_artifact", { output_root: output }),
);
if (!result.ok) throw result.error;
const extraction = artifactExtractionResultSchema.parse(result.value.result);
expect(extraction.extraction_manifest).toMatchObject({
source_manifest_id: extraction.manifest.manifest_id,
selected_occurrence_ids: [],
});
expect(extraction.artifacts).toEqual([]);
expect(extraction.containment_verified).toBe(true);
expect(await readdir(output)).toEqual([]);
});
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-");
@@ -61,6 +189,19 @@ it("binds ZIP opens to the emitted entry metadata", async () => {
await expect(
reader.open({ ...second, declaredSize: first.declaredSize }),
).rejects.toMatchObject({ reason: "integrity" });
await expect(
reader.open({
...second,
sourceIdentity: {
device: 1n,
inode: 2n,
size: 3n,
mode: 4n,
mtimeNs: 5n,
ctimeNs: 6n,
},
}),
).rejects.toMatchObject({ reason: "integrity" });
const originalKey = second.adapterKey;
Reflect.set(second, "adapterKey", first.adapterKey);
await expect(reader.open(second)).rejects.toMatchObject({
@@ -126,15 +267,12 @@ it("retains duplicate ZIP members without replacing their source identities", as
const target = await parseBinaryTarget(path);
if (!target.ok) throw target.error;
const client = new ArtifactProvider(process.env).createClient(target.value);
try {
await withArtifactClient(target.value, async (client) => {
expect(await client.execute("inventory_artifact", {})).toMatchObject({
ok: false,
error: { _tag: "ArtifactOperationError", reason: "path" },
});
} finally {
await client.close();
}
});
});
it("can enumerate case-distinct ZIP members again without losing entry identity", async () => {
@@ -187,9 +325,9 @@ it("rejects overlapping ZIP member data ranges through artifact inventory", asyn
const target = await parseBinaryTarget(path);
if (!target.ok) throw target.error;
const result = await new ArtifactProvider(process.env)
.createClient(target.value)
.execute("inventory_artifact", {});
const result = await withArtifactClient(target.value, (client) =>
client.execute("inventory_artifact", {}),
);
expect(result).toMatchObject({
ok: false,
@@ -208,9 +346,10 @@ it("preserves encrypted-member and corrupt-CRC observations", async () => {
const encryptedTarget = await parseBinaryTarget(encryptedPath);
if (!encryptedTarget.ok) throw encryptedTarget.error;
const encryptedResult = await new ArtifactProvider(process.env)
.createClient(encryptedTarget.value)
.execute("inventory_artifact", {});
const encryptedResult = await withArtifactClient(
encryptedTarget.value,
(client) => client.execute("inventory_artifact", {}),
);
if (!encryptedResult.ok) throw encryptedResult.error;
const encryptedInventory = artifactInventoryResultSchema.parse(
encryptedResult.value.result,
@@ -224,11 +363,10 @@ it("preserves encrypted-member and corrupt-CRC observations", async () => {
);
// REA does not decrypt entries, so complete extraction is unsupported.
const extractionRoot = join(root, "encrypted-output");
expect(
await new ArtifactProvider(process.env)
.createClient(encryptedTarget.value)
.execute("extract_artifact", { output_root: extractionRoot }),
).toMatchObject({
const extraction = await withArtifactClient(encryptedTarget.value, (client) =>
client.execute("extract_artifact", { output_root: extractionRoot }),
);
expect(extraction).toMatchObject({
ok: false,
error: {
_tag: "AnalysisUnsupportedTargetError",
@@ -259,9 +397,10 @@ it("preserves encrypted-member and corrupt-CRC observations", async () => {
const corruptTarget = await parseBinaryTarget(corruptPath);
if (!corruptTarget.ok) throw corruptTarget.error;
const corruptResult = await new ArtifactProvider(process.env)
.createClient(corruptTarget.value)
.execute("inventory_artifact", {});
const corruptResult = await withArtifactClient(
corruptTarget.value,
(client) => client.execute("inventory_artifact", {}),
);
expect(corruptResult).toMatchObject({
ok: false,
error: { _tag: "ArtifactOperationError", reason: "io" },
@@ -275,12 +414,75 @@ it("rejects a truncated ZIP through artifact inventory", async () => {
const target = await parseBinaryTarget(path);
if (!target.ok) throw target.error;
const result = await new ArtifactProvider(process.env)
.createClient(target.value)
.execute("inventory_artifact", {});
const result = await withArtifactClient(target.value, (client) =>
client.execute("inventory_artifact", {}),
);
expect(result).toMatchObject({
ok: false,
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;
};
@@ -182,15 +182,13 @@ describe("ASAR snapshot operation ownership", () => {
const removalStartedPromise = new Promise<void>((resolve) => {
removalStarted = resolve;
});
const reader = new AsarArtifactReader(
fixture.archive,
undefined,
async (path) => {
const reader = new AsarArtifactReader(fixture.archive, {
removeSnapshot: async (path) => {
removalStarted?.();
await removalGate;
await rm(path, { recursive: true, force: true });
},
);
});
let prepared = false;
const preparing = reader.prepareContainer().then(() => {
prepared = true;
@@ -302,15 +300,13 @@ describe("ASAR captured-byte identity", () => {
it("retains a completed inventory and snapshot ownership when cleanup fails", async () => {
const fixture = await archiveFixture();
const attempts: string[] = [];
const reader = new AsarArtifactReader(
fixture.archive,
undefined,
async (path) => {
const reader = new AsarArtifactReader(fixture.archive, {
removeSnapshot: async (path) => {
attempts.push(path);
if (attempts.length === 1) throw new Error("snapshot removal denied");
await rm(path, { recursive: true, force: true });
},
);
});
const resourceScope = new ArtifactResourceScope();
onTestFinished(() => resourceScope.close());
try {
@@ -0,0 +1,266 @@
import { fstatSync } from "node:fs";
import {
lstat,
mkdir,
open as openFile,
type FileHandle,
writeFile,
} from "node:fs/promises";
import { dirname, join } from "node:path";
import { createPackage } from "@electron/asar";
import { describe, expect, it } from "vitest";
import { AsarArtifactReader } from "../../../src/artifacts/AsarArtifactReader.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const CONTENT = "module.exports = 'owned';\n";
const createArchive = async (content = CONTENT) => {
const root = await createTestTempDirectory("rea-asar-reader-cleanup-");
const source = join(root, "source");
const archive = join(root, "fixture.asar");
await mkdir(source);
await writeFile(join(source, "main.js"), content);
await createPackage(source, archive);
return { archive };
};
type OpenedHandle = { readonly path: string; readonly fd: number };
type ReaderHooks = {
readonly beforeAdoption?: (path: string, handle: FileHandle) => Promise<void>;
readonly close?: (handle: FileHandle) => Promise<void>;
};
const createTrackedReader = (archive: string, hooks: ReaderHooks = {}) => {
const opened: OpenedHandle[] = [];
const reader = new AsarArtifactReader(archive, {
openFile: async (path, flags) => {
const handle = await openFile(path, flags);
opened.push({ path, fd: handle.fd });
await hooks.beforeAdoption?.(path, handle);
return {
get fd() {
return handle.fd;
},
stat: () => handle.stat(),
read: handle.read.bind(handle),
close: () => hooks.close?.(handle) ?? handle.close(),
};
},
});
return { reader, opened };
};
const packedMember = async (reader: AsarArtifactReader) => {
for await (const entry of reader.entries())
if (entry.path === "main.js") return entry;
throw new Error("Expected packed ASAR member");
};
const latestHandle = (opened: readonly OpenedHandle[]): OpenedHandle => {
const handle = opened.at(-1);
if (handle === undefined)
throw new Error("Expected a descriptor for the packed member");
return handle;
};
const openPackedMember = async (
reader: AsarArtifactReader,
opened: readonly OpenedHandle[],
) => {
const output = await reader.open(await packedMember(reader));
const handle = latestHandle(opened);
return { output, handle, root: dirname(handle.path) };
};
const expectDescriptorOpen = (fd: number): void => {
expect(fstatSync(fd).isFile()).toBe(true);
};
const expectDescriptorClosed = (fd: number): void => {
expect(() => fstatSync(fd)).toThrow();
};
const expectSnapshotRemoved = async (
fd: number,
root: string,
): Promise<void> => {
expectDescriptorClosed(fd);
await expect(lstat(root)).rejects.toMatchObject({ code: "ENOENT" });
};
describe("ASAR reader cleanup", () => {
it("reaps an unread packed member and its snapshot when the reader closes", async () => {
const { archive } = await createArchive();
const { reader, opened } = createTrackedReader(archive);
try {
const {
output,
handle: memberHandle,
root,
} = await openPackedMember(reader, opened);
expect(memberHandle.path).toContain("rea-asar-snapshot-");
expectDescriptorOpen(memberHandle.fd);
expect(output.destroyed).toBe(false);
await reader.close();
await expectSnapshotRemoved(memberHandle.fd, root);
} finally {
await reader.close();
}
});
it("retains the snapshot and facts after a failed close, then retries cleanup", async () => {
const { archive } = await createArchive();
let failNextClose = false;
const closeFailure = Object.assign(new Error("injected close failure"), {
code: "EIO",
errno: -5,
syscall: "close",
});
const { reader, opened } = createTrackedReader(archive, {
close: async (handle) => {
if (failNextClose) {
failNextClose = false;
throw closeFailure;
}
await handle.close();
},
});
try {
const { handle: memberHandle, root } = await openPackedMember(
reader,
opened,
);
failNextClose = true;
await expect(reader.close()).rejects.toMatchObject({
cleanup: { resources: [memberHandle.path] },
});
expectDescriptorOpen(memberHandle.fd);
expect((await lstat(root)).isDirectory()).toBe(true);
expect(await packedMember(reader)).toMatchObject({ path: "main.js" });
await reader.close();
await expectSnapshotRemoved(memberHandle.fd, root);
} finally {
await reader.close();
}
});
it("closes a member handle adopted while reader shutdown is queued", async () => {
const { archive } = await createArchive();
let pauseMemberOpen = false;
let memberOpenReached!: () => void;
let releaseMemberOpen!: () => void;
const memberOpenStarted = new Promise<void>((resolve) => {
memberOpenReached = resolve;
});
const memberOpenGate = new Promise<void>((resolve) => {
releaseMemberOpen = resolve;
});
const { reader, opened } = createTrackedReader(archive, {
beforeAdoption: async (path) => {
if (pauseMemberOpen && path.includes("rea-asar-snapshot-")) {
pauseMemberOpen = false;
memberOpenReached();
await memberOpenGate;
}
},
});
try {
const entry = await packedMember(reader);
pauseMemberOpen = true;
const opening = reader.open(entry);
await memberOpenStarted;
const closing = reader.close();
releaseMemberOpen();
const output = await opening;
const memberHandle = latestHandle(opened);
const root = dirname(memberHandle.path);
await closing;
expect(output.destroyed).toBe(true);
await expectSnapshotRemoved(memberHandle.fd, root);
} finally {
releaseMemberOpen();
await reader.close();
}
});
});
describe("ASAR preparation cleanup", () => {
it("retains a zero-byte member handle when its first close fails", async () => {
const { archive } = await createArchive("");
let failNextClose = false;
const { reader, opened } = createTrackedReader(archive, {
close: async (handle) => {
if (failNextClose) {
failNextClose = false;
throw new Error("empty member close denied");
}
await handle.close();
},
});
try {
const entry = await packedMember(reader);
failNextClose = true;
await expect(reader.open(entry)).rejects.toMatchObject({
cleanup: {
reason: "empty member close denied",
resources: [expect.any(String)],
},
});
const handle = latestHandle(opened);
expectDescriptorOpen(handle.fd);
expect((await lstat(dirname(handle.path))).isDirectory()).toBe(true);
await reader.close();
await expectSnapshotRemoved(handle.fd, dirname(handle.path));
} finally {
await reader.close();
}
});
it("preserves a malformed header failure when closing its handle also fails", async () => {
const { archive } = await createArchive();
await writeFile(archive, Buffer.alloc(16));
let failHeaderClose = false;
const closeFailure = new Error("header close denied");
const { reader, opened } = createTrackedReader(archive, {
beforeAdoption: async (path) => {
if (path !== archive) failHeaderClose = true;
},
close: async (handle) => {
if (failHeaderClose) {
failHeaderClose = false;
throw closeFailure;
}
await handle.close();
},
});
try {
await expect(packedMember(reader)).rejects.toMatchObject({
reason: "format",
message: "Truncated or invalid ASAR size pickle",
cleanup: {
reason: closeFailure.message,
resources: [expect.any(String)],
},
});
const handle = latestHandle(opened);
expectDescriptorOpen(handle.fd);
expect((await lstat(dirname(handle.path))).isDirectory()).toBe(true);
await reader.close();
await expectSnapshotRemoved(handle.fd, dirname(handle.path));
} finally {
await reader.close();
}
});
});
@@ -9,11 +9,11 @@ import {
writeFile,
truncate,
} from "node:fs/promises";
import { join } from "node:path";
import { dirname, join } from "node:path";
import { Readable } from "node:stream";
import { buffer } from "node:stream/consumers";
import { createPackageWithOptions } from "@electron/asar";
import { describe, expect, it } from "vitest";
import { describe, expect, it, onTestFinished } from "vitest";
import { scanArtifactInventory } from "../../fixtures/artifactInventory.js";
import { AsarArtifactReader } from "../../../src/artifacts/AsarArtifactReader.js";
import {
@@ -24,6 +24,7 @@ import { hashReadable } from "../../../src/artifacts/ArtifactHash.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const memberBytes = 64 * 1024 * 1024;
const maximumObservedChunkBytes = 1024 * 1024;
const expectedSha256 = (): string => {
const hash = createHash("sha256");
const zeros = Buffer.alloc(64 * 1024);
@@ -104,7 +105,13 @@ describe("ASAR entry streaming", () => {
await writeFile(join(source, "small.js"), "module.exports = 1;\n");
await createPackageWithOptions(source, archive, {});
const reader = new AsarArtifactReader(archive);
let snapshotPath: string | undefined;
const reader = new AsarArtifactReader(archive, {
openFile: async (path, flags) => {
if (path !== archive) snapshotPath = path;
return openFile(path, flags);
},
});
try {
const entries = [];
@@ -114,9 +121,11 @@ describe("ASAR entry streaming", () => {
const entry = entries.find(({ path }) => path === "small.js");
if (entry === undefined) throw new Error("Expected packed ASAR member");
const snapshot = await reader.openContainer();
const identity = await lstat(snapshot.path);
if (snapshotPath === undefined)
throw new Error("Expected snapshot acquisition");
const identity = await lstat(snapshotPath);
await buffer(snapshot);
const probe = await openFile(snapshot.path, "r");
const probe = await openFile(snapshotPath, "r");
expect(await matchingDescriptorCount(identity)).toBeGreaterThan(0);
await probe.close();
expect(await matchingDescriptorCount(identity)).toBe(0);
@@ -144,7 +153,13 @@ describe("ASAR entry streaming", () => {
await writeFile(join(source, "small.js"), "module.exports = 1;\n");
await createPackageWithOptions(source, archive, {});
const reader = new AsarArtifactReader(archive);
let snapshotPath: string | undefined;
const reader = new AsarArtifactReader(archive, {
openFile: async (path, flags) => {
if (path !== archive) snapshotPath = path;
return openFile(path, flags);
},
});
try {
const entries = [];
@@ -152,7 +167,9 @@ describe("ASAR entry streaming", () => {
const entry = entries.find(({ path }) => path === "small.js");
if (entry === undefined) throw new Error("Expected packed ASAR member");
const snapshot = await reader.openContainer();
const identity = await lstat(snapshot.path);
if (snapshotPath === undefined)
throw new Error("Expected snapshot acquisition");
const identity = await lstat(snapshotPath);
await buffer(snapshot);
const controller = new AbortController();
const opening = reader.open(entry, controller.signal);
@@ -339,23 +356,25 @@ describe("ASAR read failures", () => {
syscall: "close",
});
let closeCount = 0;
const reader = new AsarArtifactReader(archive, async (path, flags) => {
const handle = await openFile(path, flags);
expect(await matchingDescriptorCount(identity)).toBeGreaterThan(0);
return {
get fd() {
return handle.fd;
},
async stat() {
throw ioError;
},
async close() {
closeCount += 1;
if (closeCount === 1) throw closeError;
await handle.close();
},
read: handle.read.bind(handle),
};
const reader = new AsarArtifactReader(archive, {
openUnpackedFile: async (path, flags) => {
const handle = await openFile(path, flags);
expect(await matchingDescriptorCount(identity)).toBeGreaterThan(0);
return {
get fd() {
return handle.fd;
},
async stat() {
throw ioError;
},
async close() {
closeCount += 1;
if (closeCount === 1) throw closeError;
await handle.close();
},
read: handle.read.bind(handle),
};
},
});
try {
@@ -395,24 +414,37 @@ it.skipIf(process.platform === "win32")(
});
const closeFailure = new Error("native close outcome unavailable");
let closeCount = 0;
const reader = new AsarArtifactReader(archive, async (path, flags) => {
const handle = await openFile(path, flags);
return {
get fd() {
return handle.fd;
},
async stat() {
throw statFailure;
},
async close() {
closeCount += 1;
// Model Node's invalidated-descriptor rejection without leaking a
// native descriptor in the test process.
await handle.close();
throw closeFailure;
},
read: handle.read.bind(handle),
};
let snapshotRoot: string | undefined;
const reader = new AsarArtifactReader(archive, {
openFile: async (path, flags) => {
if (path !== archive && snapshotRoot === undefined) {
const root = dirname(path);
snapshotRoot = root;
// This fixture deliberately reports an unrecoverable close outcome.
// Remove its retained snapshot only after testing reader ownership.
onTestFinished(() => rm(root, { recursive: true, force: true }));
}
return openFile(path, flags);
},
openUnpackedFile: async (path, flags) => {
const handle = await openFile(path, flags);
return {
get fd() {
return handle.fd;
},
async stat() {
throw statFailure;
},
async close() {
closeCount += 1;
// Model Node's invalidated-descriptor rejection without leaking a
// native descriptor in the test process.
await handle.close();
throw closeFailure;
},
read: handle.read.bind(handle),
};
},
});
const entry = await unpackedMember(reader);
await expect(reader.open(entry)).rejects.toMatchObject({
@@ -429,6 +461,8 @@ it.skipIf(process.platform === "win32")(
});
expect(closeCount).toBe(1);
await waitForNoMatchingDescriptor(identity);
if (snapshotRoot === undefined) throw new Error("Expected ASAR snapshot");
expect((await lstat(snapshotRoot)).isDirectory()).toBe(true);
},
);
@@ -438,24 +472,26 @@ it.skipIf(process.platform === "win32")(
const { archive, unpackedPath, identity } = await createUnpackedFixture();
const controller = new AbortController();
let closeCount = 0;
const reader = new AsarArtifactReader(archive, async (path, flags) => {
const handle = await openFile(path, flags);
return {
get fd() {
return handle.fd;
},
async stat() {
const observed = await handle.stat();
controller.abort();
return observed;
},
async close() {
closeCount += 1;
if (closeCount === 1) throw new Error("first close failed");
await handle.close();
},
read: handle.read.bind(handle),
};
const reader = new AsarArtifactReader(archive, {
openUnpackedFile: async (path, flags) => {
const handle = await openFile(path, flags);
return {
get fd() {
return handle.fd;
},
async stat() {
const observed = await handle.stat();
controller.abort();
return observed;
},
async close() {
closeCount += 1;
if (closeCount === 1) throw new Error("first close failed");
await handle.close();
},
read: handle.read.bind(handle),
};
},
});
try {
@@ -483,25 +519,27 @@ it.skipIf(process.platform === "win32")(
const { archive, unpackedPath, identity } = await createUnpackedFixture();
const closeError = new Error("first close failed");
let closeCount = 0;
const reader = new AsarArtifactReader(archive, async (path, flags) => {
const handle = await openFile(path, flags);
return {
get fd() {
return handle.fd;
},
async stat() {
const observed = await handle.stat();
return Object.assign(Object.create(observed), {
ino: observed.ino + 1,
});
},
async close() {
closeCount += 1;
if (closeCount === 1) throw closeError;
await handle.close();
},
read: handle.read.bind(handle),
};
const reader = new AsarArtifactReader(archive, {
openUnpackedFile: async (path, flags) => {
const handle = await openFile(path, flags);
return {
get fd() {
return handle.fd;
},
async stat() {
const observed = await handle.stat();
return Object.assign(Object.create(observed), {
ino: observed.ino + 1,
});
},
async close() {
closeCount += 1;
if (closeCount === 1) throw closeError;
await handle.close();
},
read: handle.read.bind(handle),
};
},
});
try {
@@ -526,16 +564,15 @@ it.skipIf(process.platform === "win32")(
);
it.skipIf(process.platform === "win32")(
"retains unpacked handles and snapshots across combined cleanup failures",
"retains unpacked handles before retrying snapshot cleanup failures",
async () => {
const { archive, unpackedPath, identity } = await createUnpackedFixture();
const closeError = new Error("unpacked close denied");
const snapshotError = new Error("snapshot removal denied");
let closeCount = 0;
const snapshotPaths: string[] = [];
const reader = new AsarArtifactReader(
archive,
async (path, flags) => {
const reader = new AsarArtifactReader(archive, {
openUnpackedFile: async (path, flags) => {
const handle = await openFile(path, flags);
return {
get fd() {
@@ -556,12 +593,12 @@ it.skipIf(process.platform === "win32")(
read: handle.read.bind(handle),
};
},
async (path) => {
removeSnapshot: async (path) => {
snapshotPaths.push(path);
if (snapshotPaths.length === 1) throw snapshotError;
await rm(path, { recursive: true, force: true });
},
);
});
try {
const entry = await unpackedMember(reader);
@@ -578,19 +615,24 @@ it.skipIf(process.platform === "win32")(
);
expect(cleanupFailure).toMatchObject({
cleanup: {
resources: [unpackedPath, expect.any(String)],
resources: [unpackedPath],
reason: expect.stringContaining("unpacked close denied"),
},
});
expect(closeCount).toBe(2);
expect(snapshotPaths).toEqual([]);
expect(await matchingDescriptorCount(identity)).toBeGreaterThan(0);
await expect(reader.close()).rejects.toMatchObject({
message: snapshotError.message,
cleanup: { resources: [expect.any(String)] },
});
expect(closeCount).toBe(3);
await waitForNoMatchingDescriptor(identity);
const snapshotRoot = snapshotPaths[0];
if (snapshotRoot === undefined)
throw new Error("Expected owned ASAR snapshot root");
expect(snapshotPaths).toEqual([snapshotRoot]);
expect(cleanupFailure).toMatchObject({
cleanup: { resources: [unpackedPath, snapshotRoot] },
});
expect(closeCount).toBe(2);
expect(await matchingDescriptorCount(identity)).toBeGreaterThan(0);
expect((await lstat(snapshotRoot)).isDirectory()).toBe(true);
await reader.close();
@@ -727,7 +769,7 @@ describe("ASAR entry streaming", () => {
["packed", {}],
["unpacked", { unpack: "large.bin" }],
] as const)(
"opens a %s member without allocating its full contents",
"streams a %s member in bounded chunks with its complete digest",
async (_kind, options) => {
const root = await createTestTempDirectory("rea-asar-streaming-");
const source = join(root, "source");
@@ -745,13 +787,21 @@ describe("ASAR entry streaming", () => {
const entry = entries.find(({ path }) => path === "large.bin");
if (entry === undefined) throw new Error("Expected large ASAR member");
const before = process.memoryUsage().arrayBuffers;
const stream = await reader.open(entry);
const afterOpen = process.memoryUsage().arrayBuffers;
const observed = await hashReadable(stream);
const allocation = afterOpen - before;
let largestChunkBytes = 0;
const measuredStream = Readable.from(
(async function* () {
for await (const chunk of stream) {
largestChunkBytes = Math.max(largestChunkBytes, chunk.byteLength);
yield chunk;
}
})(),
);
const observed = await hashReadable(measuredStream);
expect(allocation).toBeLessThan(memberBytes / 2);
expect(largestChunkBytes).toBeLessThanOrEqual(
maximumObservedChunkBytes,
);
expect(observed).toMatchObject({
sha256: expectedSha256(),
bytes: memberBytes,
@@ -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"],
@@ -210,6 +245,17 @@ describe("binary target I/O: package classification", () => {
});
});
it("classifies a binary plist by its magic under any extension", async () => {
const directory = await createTestTempDirectory("rea-bplist-target-");
const path = join(directory, "Model.archive");
await writeFile(path, buildBinary({ $archiver: "NSKeyedArchiver" }));
const result = await parseBinaryTarget(path);
expect(result.ok && result.value).toMatchObject({
kind: "artifact",
format: "plist",
});
});
it("does not trust a ZIP-family extension without ZIP magic", async () => {
const directory = await createTestTempDirectory("rea-fake-archive-");
const path = join(directory, "fake.zip");
@@ -758,6 +804,32 @@ describe("binary Info.plist app bundle targets", () => {
});
describe("DOS binary target I/O", () => {
it("resolves a short-header PE signature beyond the bounded prefix", async () => {
const directory = await createTestTempDirectory(
"rea-short-stub-pe-target-",
);
const path = join(directory, "short-stub.dll");
const offset = 8192;
const stub = dosMz(64);
stub.writeUInt32LE(offset, 60);
const peRecord = pe(0x8664, offset, 0x2002).subarray(offset);
const bytes = Buffer.concat([
stub,
Buffer.alloc(offset - stub.length),
peRecord,
]);
await writeFile(path, bytes);
expect(await parseBinaryTarget(path)).toMatchObject({
ok: true,
value: {
format: "pe",
architecture: "x86_64",
executableRole: "shared-library",
},
});
});
it("validates a complete DOS file beyond the initial metadata probe", async () => {
const directory = await createTestTempDirectory("rea-dos-target-");
const path = join(directory, "legacy.exe");
+223 -2
View File
@@ -6,7 +6,7 @@ import {
rename,
writeFile,
} from "node:fs/promises";
import { dirname, join } from "node:path";
import { dirname, join, matchesGlob } from "node:path";
import { afterAll, beforeAll, expect, it } from "vitest";
import { parse } from "yaml";
@@ -157,7 +157,7 @@ it("retains complete checks when implementation is renamed into documentation",
const head = await commit(directory);
expect(await classify(directory, base, head)).toMatchObject({
code: true,
package: true,
runtime: true,
});
});
@@ -268,6 +268,62 @@ it.each([
{ code: false, evm: true, browser: false, package: false },
],
["unknown-input", { code: true, package: true, evm: true, browser: true }],
[
"src/application/Example.ts",
{
code: true,
runtime: true,
package: false,
apple: false,
evm: false,
browser: false,
},
],
[
"bridge/ghidra/Example.java",
{ code: true, runtime: true, package: false, apple: false },
],
[
"src/native/AppleExample.ts",
{ code: true, runtime: true, apple: true, package: false, evm: false },
],
[
"scripts/verify/apple/example.mjs",
{ code: true, apple: true, package: false, runtime: false },
],
[
"src/windows/Example.ts",
{ code: true, runtime: true, package: true, apple: false, evm: false },
],
["install.sh", { code: true, runtime: true, package: true, evm: false }],
[
".agents/skills/reverse-engineer-anything/SKILL.md",
{ code: true, runtime: true, docs: true, package: false, evm: false },
],
[
"scripts/verify-real-ghidra.mjs",
{ code: true, runtime: false, package: false, apple: false, evm: false },
],
[
"scripts/verify-claude-client.mjs",
{ code: true, runtime: false, package: false, browser: false },
],
[
"tests/boundary/process/darwinProcessRunTokenReader.test.ts",
{ code: true, apple: true, package: false, runtime: false },
],
[
"tests/boundary/cli/nativePlistCli.test.ts",
{ code: true, apple: true, package: false, runtime: false },
],
[
"tests/boundary/filesystem/windowsNpxRegistration.test.ts",
{ code: true, package: true, runtime: true, apple: false },
],
[
"src/process/ProcessOwnership.test.ts",
{ code: true, package: true, apple: false, evm: false, browser: false },
],
])("selects the appropriate lanes for %s", async (path, expected) => {
const { directory, base } = await fixture();
const head = await change(directory, [path]);
@@ -386,6 +442,10 @@ it("rejects skipped selected work while allowing unselected lanes to skip", asyn
});
it.each([
[
".github/workflows/sqlite-runtime.yml",
{ workflows: true, code: true, package: false, website: false },
],
[
".github/workflows/real-termux.yml",
{ workflows: true, code: false, package: false, website: false },
@@ -404,6 +464,14 @@ it.each([
{ code: true, package: true, browser: true, evm: true },
],
["docs/.vitepress/config.ts", { code: false, docs: true, package: false }],
["CHANGELOG.md", { code: false, docs: true, package: false }],
["SECURITY.md", { code: false, docs: true, package: false }],
[".github/pull_request_template.md", { code: false, docs: true }],
[
".github/ISSUE_TEMPLATE/bug.yml",
{ code: false, docs: true, workflows: false },
],
["native/windows/README.md", { code: false, docs: true, package: false }],
[
"src/contracts/evm/tools.ts",
{ code: true, docs: true, evm: true, package: false },
@@ -462,6 +530,43 @@ it("fails without emitting a plan when package metadata is malformed", async ()
expect(await readFile(join(directory, "scope-output"), "utf8")).toBe("");
});
it.each([
[
"verify:keyed-archive",
"npm run build:cached && node scripts/verify/apple/keyed-archive.mjs",
{ apple: true, package: false, evm: false, browser: false },
],
[
"verify:inspector",
"npm run build:cached && node scripts/verify/inspector/runtime-observation.mjs",
{ package: true, apple: false, evm: false, browser: false },
],
[
"verify:windows-native",
"node scripts/verify-windows-native.mjs",
{ package: true, apple: false, evm: false, browser: false },
],
])(
"routes the %s script to its glob-owned lane",
async (script, command, expected) => {
const { directory } = await fixture();
const base = await change(
directory,
["package.json"],
JSON.stringify({ scripts: { [script]: command } }),
);
const head = await change(
directory,
["package.json"],
JSON.stringify({ scripts: { [script]: `${command} --verbose` } }),
);
expect(await classify(directory, base, head)).toMatchObject({
code: true,
...expected,
});
},
);
it("retains a broad fallback when a provider script adds shared shell work", async () => {
const { directory } = await fixture();
const before = {
@@ -538,3 +643,119 @@ it.each(["compile:termux", "build:termux", "build:termux:run"])(
});
},
);
const INTEL_HOST = {
os: "macos-15-intel",
platform: "darwin",
architecture: "x64",
};
it("keeps macOS x64 package verification for ci:full and non-PR events", async () => {
const { directory, base } = await fixture();
const head = await change(directory, ["src/windows/Example.ts"]);
const matrix = z.object({ include: z.array(z.unknown()) });
const hosts = async (event: string, full: boolean) =>
matrix.parse((await classify(directory, base, head, event, full)).matrix)
.include;
const pullRequest = await hosts("pull_request", false);
expect(pullRequest).toHaveLength(3);
expect(pullRequest).not.toContainEqual(INTEL_HOST);
expect(await hosts("pull_request", true)).toContainEqual(INTEL_HOST);
for (const event of ["push", "schedule", "workflow_dispatch"])
expect(await hosts(event, false)).toContainEqual(INTEL_HOST);
});
const workflowFile = async (name: string): Promise<unknown> =>
parse(
await readFile(
new URL(`../../../.github/workflows/${name}`, import.meta.url),
"utf8",
),
);
const scopesSchema = z.object({
SCOPES: z.record(z.string(), z.array(z.string())),
MANUAL_VERIFIERS: z.array(z.string()),
});
const loadScopes = async () =>
scopesSchema.parse(
await import(
new URL("../../../scripts/ci/scopes.mjs", import.meta.url).href
),
);
const stepRuns = z.object({
on: z.unknown(),
jobs: z.record(
z.string(),
z.object({
steps: z.array(z.object({ run: z.string().optional() })).optional(),
}),
),
});
it("owns every explicit native-host test path with the lane that runs it", async () => {
const { SCOPES } = await loadScopes();
const ci = stepRuns.parse(await workflowFile("ci.yml"));
const listed = (job: string) =>
(ci.jobs[job]?.steps ?? [])
.flatMap((step) => step.run?.split(/\s+/) ?? [])
.filter((token) => token.endsWith(".test.ts"));
const unowned = (job: string, scope: string) =>
listed(job).filter(
(path) =>
!(SCOPES[scope] ?? []).some((pattern) => matchesGlob(path, pattern)),
);
expect(listed("apple-artifacts").length).toBeGreaterThan(0);
expect(listed("windows-curated").length).toBeGreaterThan(0);
expect(unowned("apple-artifacts", "apple")).toEqual([]);
expect(unowned("windows-curated", "package")).toEqual([]);
});
it("never runs a manual-only verifier from an automatic workflow", async () => {
const { MANUAL_VERIFIERS } = await loadScopes();
const scripts = z
.object({ scripts: z.record(z.string(), z.string()) })
.parse(
JSON.parse(
await readFile(
new URL("../../../package.json", import.meta.url),
"utf8",
),
),
).scripts;
const directory = new URL("../../../.github/workflows/", import.meta.url);
const commands: string[] = [];
for (const name of await readdir(directory)) {
const workflow = stepRuns.parse(await workflowFile(name));
const triggers = JSON.stringify(workflow.on);
if (
name !== "ci.yml" &&
!triggers.includes("workflow_call") &&
!triggers.includes("pull_request")
)
continue;
for (const job of Object.values(workflow.jobs))
for (const step of job.steps ?? []) if (step.run) commands.push(step.run);
}
const files = new Set<string>();
const seen = new Set<string>();
while (commands.length) {
const command = commands.pop() ?? "";
for (const [, file] of command.matchAll(/\b(scripts\/[\w./-]+\.mjs)\b/g))
if (file) files.add(file);
for (const [, script] of command.matchAll(/npm run ([\w:.-]+)/g)) {
if (!script || seen.has(script)) continue;
seen.add(script);
const body = scripts[script];
if (body) commands.push(body);
}
}
expect(files.size).toBeGreaterThan(0);
expect(
[...files].filter((file) =>
MANUAL_VERIFIERS.some((pattern) => matchesGlob(file, pattern)),
),
).toEqual([]);
});
@@ -0,0 +1,104 @@
import { readFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { expect, it } from "vitest";
import { parse } from "yaml";
import { z } from "zod";
import { executeWorkflowFixture } from "../../support/workflowGit.js";
const workflow = async (filename = "ci.yml") =>
z
.object({
jobs: z.record(
z.string(),
z
.object({
needs: z.union([z.string(), z.array(z.string())]).optional(),
})
.passthrough(),
),
})
.parse(
parse(
await readFile(
new URL(`../../../.github/workflows/${filename}`, import.meta.url),
"utf8",
),
),
);
it("binds SQLite compatibility jobs to the build's prepared runtime artifact and root layout", async () => {
const steps = z.array(
z.object({
uses: z.string().optional(),
with: z
.object({ name: z.string().optional(), path: z.string().optional() })
.optional(),
}),
);
const uploads = steps.parse((await workflow()).jobs.build?.steps).filter(
(step) =>
step.uses?.startsWith("actions/upload-artifact@") &&
step.with?.path
?.split(/\r?\n/u)
.map((path) => path.trim())
.includes("dist/"),
);
expect(uploads).toHaveLength(1);
const name = z.string().min(1).parse(uploads[0]?.with?.name);
const downloads = steps
.parse((await workflow("sqlite-runtime.yml")).jobs.sqlite?.steps)
.filter((step) => step.uses?.startsWith("actions/download-artifact@"));
expect(downloads).toHaveLength(1);
expect(downloads[0]?.with).toEqual({ name, path: "." });
});
const requiredNeeds = async () => {
const { jobs } = await workflow();
return { jobs, needs: z.array(z.string()).parse(jobs.required?.needs) };
};
it("makes the required gate wait for every CI lane, including future additions", async () => {
const { jobs, needs } = await requiredNeeds();
expect(new Set(needs)).toEqual(
new Set(Object.keys(jobs).filter((name) => name !== "required")),
);
});
it.each([
["true", "success", true],
["true", "failure", false],
["true", "cancelled", false],
["true", "skipped", false],
["true", "missing", false],
["false", "skipped", true],
] as const)(
"enforces the SQLite required gate for code=%s and result=%s",
async (code, result, passes) => {
const workflow = await requiredNeeds();
// GitHub exposes only direct dependencies in the required job's needs context.
const needs: Record<
string,
{ result: string; outputs?: Record<string, string> }
> = Object.fromEntries(
workflow.needs.map((name) => [name, { result: "success" }]),
);
needs.changes = { result: "success", outputs: { code } };
if (result === "missing") delete needs["sqlite-runtime"];
else if ("sqlite-runtime" in needs) needs["sqlite-runtime"] = { result };
const execution = executeWorkflowFixture(
process.execPath,
[
fileURLToPath(
new URL("../../../scripts/ci/required.mjs", import.meta.url),
),
],
{ env: { ...process.env, CI_JOBS: JSON.stringify(needs) } },
);
if (passes) await expect(execution).resolves.toMatchObject({ stderr: "" });
else
await expect(execution).rejects.toMatchObject({
code: 1,
stderr: expect.stringContaining("sqlite-runtime"),
});
},
);
@@ -0,0 +1,174 @@
import { execFile } from "node:child_process";
import { readFile, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { expect, it } from "vitest";
import { parse } from "yaml";
import { z } from "zod";
import { parseTestDurations } from "../../ciTestSequencer.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const execute = promisify(execFile);
const script = new URL("../../../scripts/ci/test-report.mjs", import.meta.url);
const stepsSchema = z.array(
z.object({
name: z.string().optional(),
run: z.string().optional(),
uses: z.string().optional(),
if: z.string().optional(),
env: z.record(z.string(), z.string()).optional(),
with: z.record(z.string(), z.unknown()).optional(),
}),
);
const workflow = async () =>
z
.object({
jobs: z.object({
test: z.object({ steps: stepsSchema }),
build: z.object({ steps: stepsSchema }),
docs: z.object({ steps: stepsSchema }),
static: z.object({ steps: stepsSchema }),
}),
})
.parse(
parse(
await readFile(
new URL("../../../.github/workflows/ci.yml", import.meta.url),
"utf8",
),
),
).jobs;
it("collects failed-shard diagnostics before enforcing the shard result", async () => {
const steps = (await workflow()).test!.steps;
const merge = steps.findIndex((step) => step.run?.includes("test:ci:merge"));
const upload = steps.findIndex((step) => step.with?.name === "test-results");
const gate = steps.findIndex(
(step) => step.env?.SHARD_RESULT && step.run?.includes("test "),
);
expect(merge).toBeGreaterThan(0);
expect(upload).toBeGreaterThan(merge);
expect(gate).toBeGreaterThan(upload);
expect(steps[merge]?.if).not.toContain("needs.test-shard.result");
const command = steps[gate]?.run;
if (command === undefined) throw new Error("Missing shard result gate");
for (const result of ["failure", "cancelled", "skipped", ""]) {
await expect(
execute("bash", ["-c", command], {
env: { ...process.env, CODE_REQUIRED: "true", SHARD_RESULT: result },
}),
).rejects.toMatchObject({ code: 1 });
}
await expect(
execute("bash", ["-c", command], {
env: { ...process.env, CODE_REQUIRED: "false", SHARD_RESULT: "skipped" },
}),
).resolves.toMatchObject({ stderr: "" });
});
it("keeps diagnosis available after merge failure and publishes only complete successful history", async () => {
const steps = (await workflow()).test!.steps;
const diagnosis = steps.find((step) => step.with?.name === "test-results");
expect(diagnosis?.if).toContain("!cancelled()");
expect(diagnosis?.if).not.toContain("success()");
const history = steps.find((step) => step.with?.name === "test-timings");
expect(history?.if).toContain("success()");
expect(history?.if).toContain("needs.test-shard.result == 'success'");
expect(history?.with?.path).toBe(".cache/ci-test-history/test-results.json");
const download = (await workflow()).build!.steps.find(
(step) => step.name === "Download previous timing report",
);
expect(download?.with?.name).toBe(history?.with?.name);
});
it("runs the existing onboarding and Python producer guards from their selected CI owners", async () => {
const jobs = await workflow();
const scripts = z
.object({ scripts: z.record(z.string(), z.string()) })
.parse(
JSON.parse(
await readFile(
new URL("../../../package.json", import.meta.url),
"utf8",
),
),
).scripts;
expect(
jobs.docs.steps.some((step) => step.run === "npm run docs:check"),
).toBe(true);
expect(scripts["docs:check"]).toContain(
"tests/conformance/readmeConsistency.test.ts",
);
const producer = jobs.static.steps.find(
(step) => step.run === "npm run test:python",
);
expect(producer?.if).toBe("needs.changes.outputs.code == 'true'");
expect(scripts["test:python"]).toContain(
"bridge/native/test_rea_lldb_tracer.py",
);
});
it("exports portable timing history and removes it on a failed, partial, or invalid rerun", async () => {
const root = await createTestTempDirectory("rea-ci-report-");
const summary = join(root, "summary.md");
const history = join(root, ".cache/ci-test-history/test-results.json");
const report = {
success: true,
numFailedTests: 0,
testResults: [
{
name: join(root, "tests/slow.test.ts"),
startTime: 10,
endTime: 110,
assertionResults: [{ large: "not timing data" }],
},
{ name: join(root, "tests/fast.test.ts"), startTime: 20, endTime: 30 },
],
};
const run = async (value: unknown, shards = "success", merge = "success") => {
await writeFile(join(root, "test-results.json"), JSON.stringify(value));
await writeFile(summary, "");
return execute(process.execPath, [fileURLToPath(script)], {
cwd: root,
env: {
...process.env,
GITHUB_STEP_SUMMARY: summary,
SHARD_RESULT: shards,
MERGE_RESULT: merge,
},
});
};
await run(report);
const contents = await readFile(history, "utf8");
expect(contents).not.toContain("assertionResults");
expect(contents).not.toContain(root);
expect(
parseTestDurations(contents, resolve(root, "different-checkout")),
).toEqual(
new Map([
["tests/slow.test.ts", 100],
["tests/fast.test.ts", 10],
]),
);
for (const [value, shards, merge] of [
[{ ...report, success: false, numFailedTests: 1 }, "failure", "failure"],
[report, "cancelled", "success"],
[report, "success", "failure"],
] as const) {
await run(report);
await run(value, shards, merge);
await expect(readFile(history)).rejects.toMatchObject({ code: "ENOENT" });
expect(await readFile(summary, "utf8")).toContain("diagnostic only");
}
await run(report);
await expect(
run({
...report,
testResults: [{ name: "../outside.test.ts", startTime: 1, endTime: 3 }],
}),
).rejects.toMatchObject({ code: 1 });
await expect(readFile(history)).rejects.toMatchObject({ code: "ENOENT" });
});
@@ -37,6 +37,22 @@ const getClients = (home: string) =>
);
describe("additional client configuration dialects", () => {
it("treats an empty XDG config home as unset for OpenCode setup", async () => {
const home = await createTestTempDirectory("rea-opencode-empty-xdg-");
const client = supportedClients(home, "linux", {
XDG_CONFIG_HOME: "",
}).find(({ name }) => name === "opencode");
const expectedPath = join(home, ".config/opencode/opencode.json");
if (client === undefined) throw new Error("missing opencode client");
expect(client.configPath).toBe(expectedPath);
expect(client.configPaths).toContain(expectedPath);
expect(
await configureClientConfiguration(client, {}, command),
).toMatchObject({ status: "configured" });
expect(await readFile(expectedPath, "utf8")).toContain('"mcp"');
});
it.each([
"opencode",
"antigravity",
@@ -1,5 +1,6 @@
import { constants as fsConstants } from "node:fs";
import {
chmod,
copyFile,
lstat,
mkdir,
@@ -21,6 +22,7 @@ import { PRODUCT_IDENTITY } from "../../../src/identity.js";
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
import { readConfigurationFile } from "../../../src/application/ClientConfigurationFiles.js";
import {
detectClients,
systemSetupHost,
@@ -63,10 +65,14 @@ describe("client configuration filesystem lifecycle", () => {
"commandcode",
"qwen_code",
"vscode",
"trae",
"grok_build",
"omp",
"pi",
"hermes",
"qoder",
"zcode",
"dsh",
"grok_bot",
]);
expect(
@@ -1525,6 +1531,68 @@ describe("client configuration filesystem removal", () => {
);
});
it("removes emptied skill directories and keeps ones with user files", async () => {
const home = await createTestTempDirectory("rea-uninstall-skill-dirs-");
roots.push(home);
const shared = join(home, ".agents/skills/reverse-engineer-anything");
const claude = join(home, ".claude/skills/reverse-engineer-anything");
for (const root of [shared, claude]) {
await mkdir(join(root, "references"), { recursive: true });
await writeFile(join(root, "SKILL.md"), ownedSkillManifest);
await writeFile(
join(root, "references/evidence-workflows.md"),
"managed",
);
}
await writeFile(join(claude, "notes.md"), "user");
const result = await runUninstall(
false,
systemUninstallHost(home, undefined, {
HOME: home,
CLAUDE_CONFIG_DIR: join(home, ".claude"),
}),
);
expect(result.status).toBe("complete");
await expect(lstat(shared)).rejects.toMatchObject({ code: "ENOENT" });
await expect(lstat(join(claude, "references"))).rejects.toMatchObject({
code: "ENOENT",
});
expect(await readFile(join(claude, "notes.md"), "utf8")).toBe("user");
});
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
"reports an emptied skill directory that cannot be removed",
async () => {
const home = await createTestTempDirectory("rea-uninstall-skill-perm-");
roots.push(home);
const parent = join(home, ".agents/skills");
const root = join(parent, "reverse-engineer-anything");
await mkdir(join(root, "references"), { recursive: true });
await writeFile(join(root, "SKILL.md"), ownedSkillManifest);
await chmod(parent, 0o555);
try {
const result = await runUninstall(
false,
systemUninstallHost(home, undefined, { HOME: home }),
);
expect(result.status).toBe("failed");
expect(result.items).toContainEqual(
expect.objectContaining({
name: "skill",
status: "failed",
detail: expect.stringContaining(
`Managed skill directory could not be removed: ${root}.`,
),
}),
);
} finally {
await chmod(parent, 0o755);
}
},
);
it("removes an owned entry through a symlink without replacing it", async () => {
const home = await createTestTempDirectory("rea-uninstall-symlink-");
roots.push(home);
@@ -1592,6 +1660,37 @@ describe("uninstall configuration preflight", () => {
expect(await readFile(config, "utf8")).toBe("not-json");
});
it.each([
['{"mcpServers":null,"keep":1}', '"mcpServers" must be an object'],
["[]", "The configuration root must be an object"],
['{"mcpServers":"x"}', '"mcpServers" must be an object'],
])(
"names the structural problem in valid JSON %s",
async (content, problem) => {
const home = await createTestTempDirectory("rea-uninstall-shape-");
roots.push(home);
const config = join(home, ".cursor/mcp.json");
await mkdir(dirname(config), { recursive: true });
await writeFile(config, content);
expect(await readConfigurationFile(config, "json")).toMatchObject({
ok: false,
error: {
kind: "malformed",
detail: `Configuration ${config} is malformed: ${problem}`,
},
});
const result = await runUninstall(false, systemUninstallHost(home));
expect(result.status).toBe("failed");
expect(result.items).toContainEqual({
name: "cursor",
status: "failed",
detail: `Configuration was not changed: ${problem}. Repair it, then rerun uninstall.`,
});
expect(await readFile(config, "utf8")).toBe(content);
await expect(readFile(`${config}.rea.backup`, "utf8")).rejects.toThrow();
},
);
it("stops before any removal when one client configuration is malformed", async () => {
const home = await createTestTempDirectory("rea-uninstall-stop-");
roots.push(home);
@@ -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(
@@ -1,48 +1,50 @@
import { parseConfig } from "../../src/config/parseConfig.js";
import { parseConfig } from "../../../src/config/parseConfig.js";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
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";
import { runDirectAnalysis } from "../../../src/application/DirectAnalysis.js";
import type {
AnalysisProvider,
CapabilityDescriptor,
ProviderIdentity,
} from "../../src/application/AnalysisProvider.js";
import type { DirectAnalysisDependencies } from "../../src/application/DirectAnalysisDependencies.js";
import { createAnalysisProfile } from "../../src/domain/analysisProfile.js";
import { createAnalysisExecution } from "../../src/application/AnalysisProvider.js";
import { ok } from "../../src/domain/result.js";
} from "../../../src/application/AnalysisProvider.js";
import type { DirectAnalysisDependencies } from "../../../src/application/DirectAnalysisDependencies.js";
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
import { ok } from "../../../src/domain/result.js";
import {
readAnalysisSnapshot,
writeAnalysisSnapshot,
} from "../../src/application/binary/AnalysisSnapshotFiles.js";
} from "../../../src/application/binary/AnalysisSnapshotFiles.js";
import {
createEvidence,
parseEvidence,
type Evidence,
} from "../../src/domain/evidence.js";
import { createEvidenceBundle } from "../../src/domain/evidenceBundle.js";
} from "../../../src/domain/evidence.js";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import {
REA_WORKFLOW_PROVIDER,
workflowAnalysisProfile,
} from "../../src/application/InvestigationProviders.js";
} from "../../../src/application/InvestigationProviders.js";
import {
createAnalysisSnapshotWorkflowEntry,
type AnalysisSnapshot,
} from "../../src/domain/analysisSnapshot.js";
} 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 { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
} 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,
GHIDRA_PROVIDER_IDENTITY,
} from "../../src/ghidra/GhidraProviderCapabilities.js";
} from "../../../src/ghidra/GhidraProviderCapabilities.js";
const IDENTITY = {
id: "snapshot-fixture",
@@ -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,
@@ -550,6 +604,40 @@ describe("binary overview snapshot replay", () => {
expect(second).toEqual(first);
expect(fixture.calls.toSorted()).toEqual(operations.toSorted());
expect(fixture.starts).toHaveLength(1);
const relocatedPath = join(dirname(fixture.path), "relocated.hop");
await writeFile(relocatedPath, "fixture");
const relocated = await runDirectAnalysis(
dependencies,
relocatedPath,
"binary_overview",
{},
{ snapshotPath: fixture.snapshotPath },
);
const firstEvidence = parseEvidence(first);
const relocatedEvidence = parseEvidence(relocated);
expect(relocatedEvidence).toMatchObject({
evidence_id: firstEvidence.evidence_id,
subject: {
local_path: relocatedPath,
name: basename(relocatedPath),
},
});
expect(relocatedEvidence.normalized_result).toEqual(
firstEvidence.normalized_result,
);
expect(relocatedEvidence.raw_result).toEqual(firstEvidence.raw_result);
expect(relocatedEvidence.locations).toEqual(firstEvidence.locations);
expect(fixture.calls.toSorted()).toEqual(operations.toSorted());
expect(fixture.starts).toHaveLength(1);
const persisted = await readAnalysisSnapshot(fixture.snapshotPath);
if (!persisted.ok) throw persisted.error;
expect(
persisted.value.evidence_bundle.records.find(
(record) => record.evidence_id === firstEvidence.evidence_id,
)?.subject?.local_path,
).toBe(fixture.path);
});
});
@@ -701,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,
@@ -1,4 +1,4 @@
import { lstat, open, rename, writeFile } from "node:fs/promises";
import { lstat, open, rename, rm, utimes, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { buffer } from "node:stream/consumers";
@@ -29,27 +29,26 @@ describe("DirectoryArtifactReader.open", () => {
const { path, reader } = await fixture();
try {
const entry = await sampleEntry(reader);
const metadata = await lstat(path);
const metadata = await lstat(path, { bigint: true });
const handle = await open(path, "r");
try {
const observed = await handle.stat();
const observed = await handle.stat({ bigint: true });
expect(entry.sourceIdentity).toEqual({
device: metadata.dev,
inode: metadata.ino,
size: metadata.size,
mode: metadata.mode,
mtimeNs: metadata.mtimeNs,
ctimeNs: metadata.ctimeNs,
});
expect({ device: observed.dev, inode: observed.ino }).toEqual(
entry.sourceIdentity,
);
console.info(
JSON.stringify({
platform: process.platform,
node: process.version,
pathDevice: metadata.dev,
handleDevice: observed.dev,
pathInode: metadata.ino,
handleInode: observed.ino,
}),
);
expect({
device: observed.dev,
inode: observed.ino,
size: observed.size,
mode: observed.mode,
mtimeNs: observed.mtimeNs,
ctimeNs: observed.ctimeNs,
}).toEqual(entry.sourceIdentity);
} finally {
await handle.close();
}
@@ -75,6 +74,73 @@ describe("DirectoryArtifactReader.open", () => {
}
});
it.each(["changed in place with a new size\n", "TEST PAYLOAD\n"])(
"rejects an in-place file change after enumeration: %s",
async (replacement) => {
const { path, reader } = await fixture();
try {
const entry = await sampleEntry(reader);
const before = await lstat(path);
await writeFile(path, replacement);
await utimes(path, before.atime, new Date(before.mtimeMs + 1000));
const after = await lstat(path);
expect(after.ino).toBe(before.ino);
await expect(reader.open(entry)).rejects.toMatchObject({
reason: "integrity",
message: expect.stringContaining("changed before open"),
});
} finally {
await reader.close();
}
},
);
it.each(["truncate", "grow"])(
"rejects a same-file %s between streamed chunks within the captured byte bound",
async (mutation) => {
const root = await createTestTempDirectory("rea-dir-reader-mutate-");
const path = join(root, "sample.txt");
const originalBytes = 1024 * 1024;
await writeFile(path, Buffer.alloc(originalBytes, 0x61));
const reader = new DirectoryArtifactReader(root);
try {
const entry = await sampleEntry(reader);
const stream = await reader.open(entry);
const iterator = stream[Symbol.asyncIterator]();
const first = await iterator.next();
expect(first.done).toBe(false);
let observedBytes =
first.value === undefined ? 0 : Buffer.byteLength(first.value);
await writeFile(
path,
mutation === "truncate"
? "short replacement\n"
: Buffer.alloc(2 * originalBytes, 0x62),
);
let failure: unknown;
try {
for (;;) {
const next = await iterator.next();
if (next.done) break;
observedBytes += Buffer.byteLength(next.value);
}
} catch (cause: unknown) {
failure = cause;
}
expect(failure).toMatchObject({
reason: "integrity",
message: expect.stringContaining("changed during read"),
});
expect(observedBytes).toBeLessThanOrEqual(originalBytes + 1);
} finally {
await reader.close();
await rm(root, { recursive: true, force: true });
}
},
);
});
describe("DirectoryArtifactReader input identity", () => {
it.each(["zero", "another"] as const)(
"requires the enumerated %s device to match the opened file",
async (kind) => {
@@ -84,13 +150,13 @@ describe("DirectoryArtifactReader.open", () => {
const identity = entry.sourceIdentity;
if (identity === undefined)
throw new Error("Fixture omitted source identity");
if (kind === "zero" && identity.device === 0) {
if (kind === "zero" && identity.device === 0n) {
expect(
(await buffer(await reader.open(entry))).toString("utf8"),
).toBe("test payload\n");
return;
}
const device = kind === "zero" ? 0 : identity.device === 1 ? 2 : 1;
const device = kind === "zero" ? 0n : identity.device === 1n ? 2n : 1n;
await expect(
reader.open({ ...entry, sourceIdentity: { ...identity, device } }),
).rejects.toMatchObject({ reason: "integrity" });
@@ -0,0 +1,122 @@
import { mkdir, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { systemDoctorHost } from "../../../src/application/Doctor.js";
it("threads the selected host and environment into system diagnostics", async () => {
const environment = {
HOME: "/selected/home",
HOPPER_LAUNCHER_PATH: "/selected/bin/hopper",
PATH: "/selected/bin",
};
const calls: Array<{
command: string;
arguments: readonly string[];
environment: NodeJS.ProcessEnv | undefined;
}> = [];
const host = systemDoctorHost({
platform: "linux",
architecture: "x64",
environment,
execFileOutput: async (command, arguments_, options) => {
calls.push({ command, arguments: arguments_, environment: options?.env });
if (command === "sw_vers") return { stdout: "15.0\n", stderr: "" };
if (command === "ldd") return { stdout: "linux-vdso.so.1", stderr: "" };
if (command === "which")
return { stdout: "/selected/bin/rea\n", stderr: "" };
throw new Error(`Unexpected diagnostic command: ${command}`);
},
});
expect(host.homeDirectory).toBe("/selected/home");
expect(host.platform).toBe("linux");
expect(host.architecture).toBe("x64");
await host.installationPaths?.();
await host.macosVersion();
await host.executable(process.execPath);
expect(calls.map(({ command }) => command)).toEqual([
"which",
"sw_vers",
"ldd",
]);
expect(
calls.every(({ environment: observed }) => observed === environment),
).toBe(true);
});
it("does not report a directory as an available executable", async () => {
const host = systemDoctorHost({
platform: "darwin",
architecture: "arm64",
environment: {},
execFileOutput: () => Promise.reject(new Error("unexpected command")),
});
await expect(host.executable(dirname(process.execPath))).resolves.toBe(false);
await expect(host.executable(process.execPath)).resolves.toBe(true);
});
it.each([
[{ default: { appdir: "/Applications" } }, "/Applications"],
[
{
default: { appdir: "/Applications" },
env: { appdir: "/Env Apps" },
explicit: { appdir: "~/Tools" },
},
"HOME/Tools",
],
[
{ default: { appdir: "/Applications" }, env: { appdir: "/Env Apps" } },
"/Env Apps",
],
])(
"locates the Hopper cask from its Caskroom receipt without a cask command (%j)",
async (config, expectedAppdir) => {
const root = await createTestTempDirectory("rea-doctor-caskroom-");
const caskroom = join(root, "Caskroom");
const metadata = join(caskroom, "hopper-disassembler", ".metadata");
await mkdir(metadata, { recursive: true });
await writeFile(join(metadata, "config.json"), JSON.stringify(config));
const calls: (readonly string[])[] = [];
const host = systemDoctorHost({
platform: "darwin",
environment: { HOME: join(root, "home") },
execFileOutput: async (_command, arguments_) => {
calls.push(arguments_);
return { stdout: `${caskroom}\n`, stderr: "" };
},
});
expect(await host.brewHopperPath()).toBe(
join(
expectedAppdir.replace("HOME", join(root, "home")),
"Hopper Disassembler.app/Contents/MacOS/hopper",
),
);
// A cask argument makes Homebrew fetch and cache its API data.
expect(calls).toEqual([["--caskroom"]]);
},
);
it("reports no Homebrew Hopper when the cask has no receipt", async () => {
const caskroom = await createTestTempDirectory("rea-doctor-caskroom-");
const calls: (readonly string[])[] = [];
const host = systemDoctorHost({
platform: "darwin",
environment: { HOME: caskroom },
execFileOutput: async (_command, arguments_) => {
calls.push(arguments_);
return { stdout: `${caskroom}\n`, stderr: "" };
},
});
expect(await host.brewHopperPath()).toBeUndefined();
expect(new Set(calls.map((arguments_) => arguments_.join(" ")))).toEqual(
new Set(["--caskroom"]),
);
});
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,
@@ -38,24 +39,27 @@ const bundle = (result = true) =>
),
]);
it("returns import cancellation before inspecting a selected path", async () => {
const root = await createTestTempDirectory("rea-import-pre-cancel-");
const controller = new AbortController();
controller.abort(new Error("cancel before import"));
expect(
await readImmutableEvidenceBundle(
join(root, "missing.json"),
controller.signal,
),
).toMatchObject({
ok: false,
error: {
_tag: "AnalysisCancelledError",
operation: "import_evidence_bundle",
},
});
expect(await readdir(root)).toEqual([]);
});
it.each([
["immutable", readImmutableEvidenceBundle],
["mutable", readEvidenceBundle],
] as const)(
"cancels a %s bundle read before opening its selected path",
async (_, read) => {
const root = await createTestTempDirectory("rea-bundle-pre-cancel-");
const controller = new AbortController();
controller.abort(new Error("cancel before bundle read"));
expect(
await read(join(root, "missing.json"), controller.signal),
).toMatchObject({
ok: false,
error: {
_tag: "AnalysisCancelledError",
operation: "import_evidence_bundle",
},
});
expect(await readdir(root)).toEqual([]);
},
);
it("preserves the failed-close owner when import is also cancelled", async () => {
const root = await createTestTempDirectory("rea-import-cancel-cleanup-");
@@ -99,15 +103,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 +117,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 +148,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 +163,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 +183,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 +193,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 +227,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 +240,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 +253,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 +273,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 +328,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 +349,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 +370,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 +391,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 },
@@ -416,21 +434,8 @@ describe("evidence bundle filesystem adapter", () => {
},
);
it("names the failed bundle constraint for a single record or schema mismatch", async () => {
it("names schema mismatches that prevent bundle parsing", async () => {
const directory = await createTestTempDirectory("rea-evidence-");
const record = bundle().records[0];
const single = join(directory, "record.json");
await writeFile(single, JSON.stringify(record));
expect(await readEvidenceBundle(single)).toMatchObject({
ok: false,
error: {
_tag: "EvidenceIntegrityError",
userMessage: expect.stringContaining(
`this JSON is one Evidence record (${String(record?.evidence_id)})`,
),
},
});
const partial = join(directory, "partial.json");
await writeFile(partial, JSON.stringify({ evidence_id: "typo" }));
const rejected = await readEvidenceBundle(partial);
@@ -459,3 +464,38 @@ describe("evidence bundle filesystem adapter", () => {
});
});
});
describe("standalone Evidence bundle inputs", () => {
it("classifies a record only after authenticating it", async () => {
const directory = await createTestTempDirectory("rea-evidence-");
const record = bundle().records[0];
const single = join(directory, "record.json");
await writeFile(single, JSON.stringify(record));
expect(await readEvidenceBundle(single)).toMatchObject({
ok: false,
error: {
_tag: "EvidenceFileError",
reason: "wrong-kind",
path: single,
userMessage: expect.stringContaining(
`this JSON is one Evidence record (${String(record?.evidence_id)})`,
),
},
});
const tamperedRecord = join(directory, "tampered-record.json");
await writeFile(
tamperedRecord,
JSON.stringify({ ...record, normalized_result: "changed" }),
);
expect(await readEvidenceBundle(tamperedRecord)).toMatchObject({
ok: false,
error: {
_tag: "EvidenceIntegrityError",
userMessage: expect.stringContaining(
"does not match the bundle schema",
),
},
});
});
});
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,89 @@
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, expect, it, vi } from "vitest";
import {
inspectGhidraInstallation,
ghidraInstallationDiagnostics,
} from "../../../src/ghidra/GhidraInstallation.js";
import { SUPPORTED_GHIDRA_VERSION } from "../../../src/ghidra/GhidraInstallationPolicy.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const { mockSpawnSync } = vi.hoisted(() => ({ mockSpawnSync: vi.fn() }));
vi.mock("node:child_process", async (importOriginal) => ({
...(await importOriginal<typeof import("node:child_process")>()),
spawnSync: mockSpawnSync,
}));
afterEach(() => mockSpawnSync.mockReset());
it.each([
{ major: 17, fullJdk: true, vmName: "Java HotSpot(TM) 64-Bit Server VM" },
{ major: 21, fullJdk: true, vmName: "Eclipse OpenJ9 VM" },
{ major: 21, fullJdk: false, vmName: undefined },
])(
"preserves the reported Unicode Java home and classifies JDK $major (full JDK: $fullJdk)",
async ({ major, fullJdk, vmName }) => {
const root = await createTestTempDirectory("rea-java-probe-");
const configuredHome = join(root, "selected-jdk");
const reportedHome = join(root, "Réa逆向", `JDK ${String(major)}`);
const installDir = join(root, "ghidra");
await mkdir(join(installDir, "Ghidra"), { recursive: true });
await writeFile(
join(installDir, "Ghidra", "application.properties"),
`application.version=${SUPPORTED_GHIDRA_VERSION}\napplication.java.min=17\n`,
);
if (fullJdk) {
await mkdir(join(reportedHome, "bin"), { recursive: true });
await writeFile(
join(
reportedHome,
"bin",
process.platform === "win32" ? "javac.exe" : "javac",
),
"compiler presence fixture",
{ mode: 0o755 },
);
}
const version = `${String(major)}.0.11`;
mockSpawnSync.mockReturnValue({
stdout: "",
stderr: ` java.version = ${version}\n java.home = ${reportedHome}\n sun.arch.data.model = 64\n${vmName === undefined ? "" : ` java.vm.name = ${vmName}\n`}`,
status: 0,
});
const inspection = inspectGhidraInstallation({
environment: {},
installDir,
javaHome: configuredHome,
});
expect(inspection.javaHome).toBe(reportedHome);
expect(inspection.javaVersion).toBe(version);
expect(inspection.javaVmName).toBe(vmName);
expect(ghidraInstallationDiagnostics(inspection).java_vm_name).toBe(
vmName ?? null,
);
expect(inspection.checks.find(({ name }) => name === "java")).toMatchObject(
{
status: fullJdk ? "passed" : "failed",
detail: expect.stringContaining(fullJdk ? "; JDK;" : "; runtime only;"),
},
);
expect(mockSpawnSync).toHaveBeenCalledExactlyOnceWith(
join(
configuredHome,
"bin",
process.platform === "win32" ? "java.exe" : "java",
),
expect.arrayContaining([
"-Dstdout.encoding=UTF-8",
"-Dstderr.encoding=UTF-8",
"-Dsun.stdout.encoding=UTF-8",
"-Dsun.stderr.encoding=UTF-8",
]),
expect.objectContaining({ encoding: "utf8" }),
);
},
);
@@ -4,24 +4,24 @@ import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import {
createNonApplicationZipInventory,
inventoryApplicationPackage,
requireDeterministicProjection,
requireSuccessfulProjection,
writeApplicationZip,
} from "../../support/applicationSessionFixture.js";
} from "../../../support/applicationSessionFixture.js";
import { projectHarmonyApplicationEvidence } from "../../../src/application/harmony/HarmonyApplicationService.js";
import { createDirectAnalysis } from "../../../src/composition/directAnalysis.js";
import { harmonyApplicationProjectionResultSchema } from "../../../src/domain/harmony/harmonyApplication.js";
import { artifactInventoryResultSchema } from "../../../src/domain/artifactGraph.js";
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
import { projectHarmonyApplicationEvidence } from "../../../../src/application/harmony/HarmonyApplicationService.js";
import { createDirectAnalysis } from "../../../../src/composition/directAnalysis.js";
import { harmonyApplicationProjectionResultSchema } from "../../../../src/domain/harmony/harmonyApplication.js";
import { artifactInventoryResultSchema } from "../../../../src/domain/artifactGraph.js";
import { parseBinaryTarget } from "../../../../src/application/BinaryTargetResolver.js";
import {
ZIP_PACKAGE_FORMATS,
ZIP_NON_ENTRY_TAIL_LIMITATION,
} from "../../../src/domain/zipPackageFormat.js";
} from "../../../../src/domain/zipPackageFormat.js";
const { runProviderAnalysis } = createDirectAnalysis({});
const elf = Uint8Array.from([0x7f, 0x45, 0x4c, 0x46, 2, 1, 1, 0]);
@@ -6,9 +6,15 @@ import { parse as parseYaml } from "yaml";
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
import { npxRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js";
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
import {
configureClientConfiguration,
inspectClientConfiguration,
} from "../../../src/application/SetupClientConfiguration.js";
import { supportedClients } from "../../../src/application/SupportedClients.js";
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
import {
runUninstall,
systemUninstallHost,
} from "../../../src/application/Uninstall.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { clearClientLocationEnvironment } from "../../fixtures/clientEnvironment.js";
@@ -90,18 +96,75 @@ describe("Hermes configuration paths", () => {
});
});
describe("Hermes YAML registration", () => {
const hermesClient = async () => {
const home = await createTestTempDirectory("rea-hermes-");
const client = supportedClients(home, process.platform, {}).find(
({ name }) => name === "hermes",
);
if (client?.markerPath === undefined)
throw new Error("missing Hermes client");
await mkdir(client.markerPath, { recursive: true });
return { home, client };
};
const hermesClient = async () => {
const home = await createTestTempDirectory("rea-hermes-");
const client = supportedClients(home, process.platform, {}).find(
({ name }) => name === "hermes",
);
if (client?.markerPath === undefined)
throw new Error("missing Hermes client");
await mkdir(client.markerPath, { recursive: true });
return { home, client };
};
describe("Hermes YAML shape diagnostics", () => {
it.each(
[
"!!set {rea: null}",
"!!omap [{rea: {command: rea, args: [mcp]}}]",
"!!timestamp 2001-12-15",
"!!binary cmVh",
].flatMap((value) => [
{
original: `${value}\n`,
problem: "The configuration root must be an object",
},
{
original: `mcp_servers: ${value}\n`,
problem: '"mcp_servers" must be an object',
},
]),
)(
"blocks setup and uninstall before changes for tagged non-record YAML: $original",
async ({ original, problem }) => {
const { home, client } = await hermesClient();
const cursor = join(home, ".cursor", "mcp.json");
const cursorOriginal =
'{"mcpServers":{"rea":{"command":"rea","args":["mcp"]}}}';
await mkdir(join(home, ".cursor"));
await writeFile(cursor, cursorOriginal);
await writeFile(client.configPath, original);
expect(
await inspectClientConfiguration(client, {}, command),
).toMatchObject({
status: "invalid",
remediation: `Configuration ${client.configPath} is malformed: ${problem}`,
});
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "failed",
reason: "readback",
});
const result = await runUninstall(
false,
systemUninstallHost(home, undefined, {}),
);
expect(result.status).toBe("failed");
expect(result.items).toContainEqual({
name: "hermes",
status: "failed",
detail: `Configuration was not changed: ${problem}. Repair it, then rerun uninstall.`,
});
expect(await readFile(client.configPath, "utf8")).toBe(original);
expect(await readFile(cursor, "utf8")).toBe(cursorOriginal);
await expect(
readFile(`${client.configPath}.rea.backup`, "utf8"),
).rejects.toThrow();
await expect(readFile(`${cursor}.rea.backup`, "utf8")).rejects.toThrow();
},
);
});
describe("Hermes YAML registration", () => {
it("writes mcp_servers, preserves comments, reads back, and uninstalls", async () => {
const { home, client } = await hermesClient();
await writeFile(
@@ -185,4 +248,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 });
},
);
});
@@ -17,6 +17,19 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const execFileAsync = promisify(execFile);
// install.sh:fail_node_version emits this recovery block verbatim. The fake
// `uname` in createFixture reports `x86_64` / `Linux`, so the host labels
// resolve to `linux/x64`.
const UNSUPPORTED_NODE_RECOVERY_LINUX_X64 =
"REA installation failed: Node.js 20.0.0 is unsupported.\n" +
"\n" +
"REA requires Node.js 22.x (>=22.19), 24.x (>=24.11), or 26+. Install one via:\n" +
" nvm: nvm install 24 && nvm use 24 (https://github.com/nvm-sh/nvm)\n" +
" fnm: fnm install 24 && fnm use 24 (https://github.com/Schniz/fnm)\n" +
" Direct download for linux/x64:\n" +
" https://nodejs.org/dist/latest-v24.x/ (grab the linux-x64 tarball)\n" +
"Then rerun this installer.\n";
describe("curl installer scenarios", { timeout: 20_000 }, () => {
it("installs only a pinned REA CLI with closed stdin", async () => {
const fixture = await createFixture();
@@ -87,7 +100,7 @@ describe("curl installer scenarios", { timeout: 20_000 }, () => {
"unsupported Node",
["--version", "0.3.0"],
{ FAKE_NODE_VERSION: "20.0.0" },
"REA installation failed: Node.js 20.0.0 is unsupported; use Node.js 22.x (>=22.19), 24.x (>=24.11), or 26+.\n",
UNSUPPORTED_NODE_RECOVERY_LINUX_X64,
],
[
"unreadable Node version",
@@ -321,13 +334,18 @@ describe("native macOS installer", { timeout: 20_000 }, () => {
});
describe("installer semantic version parsing", { timeout: 20_000 }, () => {
it.each(["1.2.3-01"])(
it.each([
"1.2.3-01",
"1.2.3-$(printf unexpected)",
'1.2.3-"; printf unexpected; #',
])(
"rejects malformed semantic versions before invoking npm: %s",
async (version) => {
const fixture = await createFixture();
await expect(
runInstaller(fixture, ["--version", version, "--dry-run"]),
).rejects.toMatchObject({
stdout: "",
stderr:
"REA installation failed: version must be an exact semantic version.\n",
});
@@ -1,4 +1,3 @@
import { existsSync } from "node:fs";
import { execFile } from "node:child_process";
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -10,6 +9,7 @@ import { describe, expect, it } from "vitest";
import { analyzeInterfaceBuilderBundle } from "../../../src/artifacts/apple/InterfaceBuilderAnalysis.js";
import { encodeNibArchiveFixture } from "../../../src/artifacts/apple/NibArchive.fixture.js";
import { thinMach } from "../../../src/domain/binaryTarget.fixture.js";
import { xcodeIbtoolAvailable } from "../../fixtures/ibtool.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { interfaceBuilderAnalysisSchema } from "../../../src/domain/apple/interfaceBuilderGraph.js";
@@ -913,7 +913,7 @@ describe("bounded Interface Builder archive decoding", () => {
);
});
it.skipIf(process.platform !== "darwin" || !existsSync("/usr/bin/ibtool"))(
it.skipIf(!xcodeIbtoolAvailable)(
"decodes an Xcode-compiled storyboard NIB and recovers its UI routes",
async () => {
const root = await createTestTempDirectory("rea-ib-compiled-test-");
@@ -992,8 +992,8 @@ describe("bounded Interface Builder archive decoding", () => {
);
});
describe("compiled UIKit NIB connections", () => {
it("projects UIKit runtime outlet and event connections", async () => {
describe("NIBArchive UIKit event connections", () => {
it("projects a runtime event connection and its event mask", async () => {
const root = await createTestTempDirectory("rea-ib-test-");
const bundle = join(root, "Example.app");
await mkdir(bundle, { recursive: true });
@@ -1005,7 +1005,6 @@ describe("compiled UIKit NIB connections", () => {
"UIClassSwapper",
"UIButton",
"UIRuntimeEventConnection",
"UIRuntimeOutletConnection",
"NSString",
],
objects: [
@@ -1021,18 +1020,10 @@ describe("compiled UIKit NIB connections", () => {
UIEventMask: 64,
},
},
{
classIndex: 4,
values: {
UISource: { ref: 1 },
UIDestination: { ref: 2 },
UILabel: { ref: 8 },
},
},
{ classIndex: 5, values: { "NS.bytes": "IBFilesOwner" } },
{ classIndex: 5, values: { "NS.bytes": "BuildCell" } },
{ classIndex: 5, values: { "NS.bytes": "buildTapped:" } },
{ classIndex: 5, values: { "NS.bytes": "buildButton" } },
{ classIndex: 2, values: {} },
{ classIndex: 4, values: { "NS.bytes": "IBFilesOwner" } },
{ classIndex: 4, values: { "NS.bytes": "BuildCell" } },
{ classIndex: 4, values: { "NS.bytes": "buildTapped:" } },
],
}),
);
@@ -1062,16 +1053,6 @@ describe("compiled UIKit NIB connections", () => {
.filter(({ from }) => from === action?.id)
.map(({ to }) => named(to)),
).toEqual(expect.arrayContaining(["BuildCell"]));
const outlet = analysis.graph.nodes.find(({ kind }) => kind === "outlet");
expect(outlet?.name).toBe("buildButton");
expect(
analysis.graph.edges
.filter(
({ relation, from }) =>
relation === "outlet_to" && from === outlet?.id,
)
.map(({ to }) => named(to)),
).toEqual(["UIButton"]);
expect(
analysis.graph.nodes.find(({ name }) => name === "IBFilesOwner")?.kind,
).toBe("placeholder");
@@ -3,14 +3,14 @@ import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { analyzeJavaScriptApplication } from "../../support/javascriptApplicationScope.js";
import { reconstructJavaScriptArtifact } from "../../support/javascriptApplicationScope.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { parseJavaScriptApplicationGraph } from "../../../src/domain/javascript/javascriptApplicationGraph.js";
import { analyzeJavaScriptApplicationInputSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import { writeElectronBoundaryFixture } from "../../fixtures/electronBoundaryApplication.js";
import { analyzeJavaScriptApplication } from "../../../support/javascriptApplicationScope.js";
import { reconstructJavaScriptArtifact } from "../../../support/javascriptApplicationScope.js";
import { parseEvidence } from "../../../../src/domain/evidence.js";
import { parseJavaScriptApplicationGraph } from "../../../../src/domain/javascript/javascriptApplicationGraph.js";
import { analyzeJavaScriptApplicationInputSchema } from "../../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import { writeElectronBoundaryFixture } from "../../../fixtures/electronBoundaryApplication.js";
describe("static Electron application analysis", () => {
it("accepts relative paths and rejects caller-selected analysis bounds", () => {

Some files were not shown because too many files have changed in this diff Show More