Merge remote-tracking branch 'origin/main' into codex/pr-1899-remove-duplicate-schema-test

This commit is contained in:
morluto
2026-10-12 02:38:57 +08:00
159 changed files with 8039 additions and 1135 deletions
@@ -0,0 +1,196 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { z } from "zod";
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import { ROLLDOWN_MODULE_INTEROP } from "../../../src/domain/javascript/javascriptModuleInterop.fixture.js";
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
const INTRINSIC_MUTATIONS = [
["poisoned.cjs", "({Object} = replacements);"],
[
"projected.cjs",
'const {defineProperty:change} = Object; change(Object,"create",{value:customCreate});',
],
[
"decorated.cjs",
'@(() => Object) class metadata {}; Object.defineProperty(metadata,"create",{value:customCreate});',
],
[
"uncurried.cjs",
'const change = Function.prototype.call.bind(Object.defineProperty,null); change(Object,"create",{value:customCreate});',
],
[
"generic-bind.cjs",
'const change = Function.prototype.bind.call(Object.defineProperty,null); change(Object,"create",{value:customCreate});',
],
[
"replaced-apply.cjs",
'Reflect.apply = Object.defineProperty; Reflect.apply(Object,"create",{value:customCreate});',
],
[
"bound.cjs",
'const change = Object.defineProperty.bind(null,Object,"create"); change({value:customCreate});',
],
["receiver.cjs", 'Reflect.set({},"create",customCreate,Object);'],
[
"deep-call.cjs",
'Function.prototype.call.call.call(Object.defineProperty,null,Object,"create",{value:customCreate});',
],
[
"deep-apply.cjs",
'Function.prototype.apply.apply(Object.defineProperty,[null,[Object,"create",{value:customCreate}]]);',
],
] as const;
const writePoisonedModules = async (root: string): Promise<void> => {
for (const [name, mutation] of INTRINSIC_MUTATIONS)
await writeFile(
join(root, name),
`${mutation}
${ROLLDOWN_MODULE_INTEROP}
let poisoned = require("electron");
poisoned = __toESM(poisoned, 1);
new poisoned.BrowserWindow({});
throw new Error("must not execute poisoned source");`,
);
};
cliTest.for(["CLI", "stdio MCP"] as const)(
"retains converted Electron windows and preload evidence through %s",
async (surface, { cli }) => {
const root = await createTestTempDirectory("rea-electron-interop-");
await writeFile(
join(root, "package.json"),
JSON.stringify({ main: "main.cjs" }),
);
await writeFile(
join(root, "preload.js"),
'throw new Error("must stay inert");',
);
await writePoisonedModules(root);
const source = `const metadata = {};
Object.defineProperty(metadata,"x",{value:1});
const decorateMetadata = Object.defineProperty.bind(null,metadata,"bound");
decorateMetadata({value:1});
const decorateViaCall = Function.prototype.call.bind(Object.defineProperty);
decorateViaCall(null,metadata,"uncurried",{value:1});
const localFunction = () => {};
Object.defineProperty(localFunction,"x",{value:1});
const localClass = class {};
Object.defineProperty(localClass,"x",{value:1});
const localRegExp = /local/;
Object.defineProperty(localRegExp,"x",{value:1});
Object.defineProperty(hoistedFunction,"x",{value:1});
function hoistedFunction() {}
const captured = Object.defineProperty;
Object.defineProperty = custom;
${ROLLDOWN_MODULE_INTEROP.replace("__defProp = Object.defineProperty", "__defProp = captured")}
let electron = require("electron");
electron = __toESM(electron, 1);
new electron.BrowserWindow({webPreferences:{preload:"./preload.js"}});
new electron.BrowserWindow({webPreferences:{preload:runtimePath}});
var direct;
var direct = require("electron");
var direct;
new direct.BrowserWindow({});
const fresh = __toESM(require("electron"), 1);
new fresh.BrowserWindow({});
const {BrowserWindow: ProjectedWindow} = __toESM(require("electron"));
new ProjectedWindow({});
const nonNode = __toESM(require("electron"), 0);
new nonNode.BrowserWindow({});
function identity(mod) {return mod;}
const passthrough = identity(require("electron"));
new passthrough.BrowserWindow({});
const __importStar = () => ({BrowserWindow:FakeWindow});
const fake = __importStar(require("electron"));
new fake.BrowserWindow({});
function decoy(electron) {new electron.BrowserWindow({});}
require("./poisoned.cjs");
require("./projected.cjs");
require("./decorated.cjs");
require("./bound.cjs");
require("./uncurried.cjs");
require("./generic-bind.cjs");
require("./replaced-apply.cjs");
require("./receiver.cjs");
require("./deep-call.cjs");
require("./deep-apply.cjs");
throw new Error("must not execute main");
`;
await writeFile(join(root, "main.cjs"), source);
let document: unknown;
if (surface === "CLI") {
const response = await cli.run({
arguments: ["analyze-javascript-application", root, "--json"],
});
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,
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
document = response.structuredContent;
}
const result = z
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
.parse(document).normalized_result;
expect(result.summary).toMatchObject({
browser_windows: 7,
preload_entrypoints: 1,
});
expect(result.statistics.parse_failures).toBe(0);
expect(result.statistics.parsed_javascript_files).toBe(12);
const windows = result.graph.nodes.filter(
({ kind }) => kind === "browser-window",
);
expect(windows).toHaveLength(7);
const expectedLines = source
.split("\n")
.flatMap((line, index) =>
/^\s*new (?:(?:electron|direct|fresh|passthrough|nonNode)\.BrowserWindow|ProjectedWindow)\(/u.test(
line,
)
? [index + 1]
: [],
);
const observedLines = windows.flatMap((window) => {
const location = window.observations[0]?.evidence.location;
return location?.available && location.value.kind === "source-range"
? [location.value.start.line]
: [];
});
expect(observedLines.toSorted()).toEqual(expectedLines.toSorted());
for (const window of windows) {
expect(window.observations[0]?.evidence.location).toMatchObject({
available: true,
value: { kind: "source-range", source: "main.cjs" },
});
}
expect(
windows.flatMap((window) =>
window.observations.map(({ properties }) => properties.web_preferences),
),
).toEqual(
expect.arrayContaining([
expect.arrayContaining([
expect.objectContaining({
name: "preload",
value: {
status: "dynamic",
value: null,
expression: "runtimePath",
},
}),
]),
]),
);
},
);
@@ -0,0 +1,132 @@
import { createHash } from "node:crypto";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { z } from "zod";
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.skipIf(process.versions.bun !== undefined).for([
{ laterSources: 1, heapMb: 640, methodsCount: 400, retainGraph: true },
{ laterSources: 10, heapMb: 640, methodsCount: 400, retainGraph: true },
// Even an otherwise empty parent cannot admit this graph after reserving
// transient decoding and the next checkpoint, independent of GC timing.
{ laterSources: 1, heapMb: 448, methodsCount: 600, retainGraph: false },
])(
"preserves evidence with $laterSources later checkpoints and a $heapMb MiB parent heap",
{ timeout: 90_000 },
async ({ laterSources, heapMb, methodsCount, retainGraph }, { cli }) => {
const root = await createTestTempDirectory("rea-js-checkpoint-reserve-");
const source = Array.from(
{ length: methodsCount },
(_, index) =>
`export function method_${String(index)}(input) { const value = input + ${String(index)}; const pair = { value }; return pair.value; }`,
).join("\n");
const files: readonly (readonly [string, string])[] = [
["a-large.mjs", source],
...Array.from(
{ length: laterSources },
(_, index) =>
[
`z-tiny-${String(index)}.mjs`,
`export const tiny${String(index)} = 1;\n`,
] as const,
),
];
for (const [name, text] of files) await writeFile(join(root, name), text);
const response = await cli.run({
arguments: ["analyze", root, "--format", "json"],
environment: {
NODE_OPTIONS: `--max-old-space-size=${String(heapMb)} --max-semi-space-size=8`,
},
timeoutMs: 60_000,
});
expect(response.exitCode).toBe(0);
const result = javascriptApplicationAnalysisResultSchema.parse(
parseEvidence(response.json).normalized_result,
);
expect(result.statistics.parsed_javascript_files).toBe(laterSources + 1);
expect(result.statistics.parse_failures).toBe(0);
const failures = result.graph.nodes.flatMap(({ observations }) =>
observations.flatMap(({ properties }) =>
properties.analysis_failure === undefined
? []
: [properties.analysis_failure],
),
);
const methods = result.semantic_graph.nodes.filter(
({ kind, identity }) =>
kind === "function" && identity.module_path === "a-large.mjs",
);
if (retainGraph)
expect(methods.map(({ label }) => label).sort()).toEqual(
Array.from(
{ length: methodsCount },
(_, index) => `method_${String(index)}`,
).sort(),
);
else {
expect(methods).toHaveLength(0);
expect([
result.graph.coverage.status,
result.semantic_graph.coverage.status,
]).toContain("partial");
}
expect(
result.semantic_graph.nodes.some(
({ identity, label }) =>
identity.module_path === `z-tiny-${String(laterSources - 1)}.mjs` &&
label === `tiny${String(laterSources - 1)}`,
),
).toBe(true);
for (const [name, text] of files) {
const digest = createHash("sha256").update(text).digest("hex");
const node = result.graph.nodes.find(
({ kind, identity }) =>
kind === "javascript-asset" &&
identity.strategy === "content-digest" &&
identity.sha256 === digest,
);
expect(node?.observations).toEqual(
expect.arrayContaining([
expect.objectContaining({
properties: expect.objectContaining({
path: name,
parse_status: "complete",
}),
}),
]),
);
if (retainGraph) expect(failures).toEqual([]);
expect(await readFile(join(root, name), "utf8")).toBe(text);
if (!retainGraph && name === "a-large.mjs") {
const failure = z
.object({
code: z.literal("resource_constraint"),
remediation: z.object({ action: z.string() }),
details: z.object({
reported_limits: z.object({
parent_available_result_budget_bytes: z.number(),
module_retention_estimate_bytes: z.number(),
graph_retention_estimate_bytes: z.number(),
}),
}),
})
.parse(failures[0]);
const limits = failure.details.reported_limits;
expect(
limits.module_retention_estimate_bytes +
limits.graph_retention_estimate_bytes,
).toBeGreaterThan(limits.parent_available_result_budget_bytes);
expect(failure.remediation.action).toContain("parent result budget");
expect(failure.remediation.action).toContain(
"retained static and module facts",
);
}
}
expect(response.stderr).not.toMatch(/FATAL ERROR:.*heap/iu);
},
);
@@ -0,0 +1,282 @@
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 { 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";
const literalAliases = ["#/x", "#x%2Fy", "#x%2Ey", "#x\\y", "#x\0y"];
const fallbackAliases = {
"#tab-escape": ["./.\t./outside.cjs", "./config.cjs"],
"#newline-escape": ["./.%\n2e/outside.cjs", "./config.cjs"],
"#normalized-url": "./con\tfig.cjs",
"#trimmed-url": "./config.cjs \t",
"#url-suffix": "./config.cjs?selected=one#fragment",
"#inactive-array": {
node: [{ browser: "./browser.cjs" }],
default: "./config.cjs",
},
"#nested-inactive-array": {
node: [[{ browser: "./browser.cjs" }]],
default: "./config.cjs",
},
"#parent": ["../outside.cjs", "./config.cjs"],
"#absolute": { node: [["/outside.cjs"], "./config.cjs"] },
"#url": {
import: ["https://example.invalid/outside.cjs", "./config.cjs"],
require: ["file:///outside.cjs", "./config.cjs"],
},
};
const resolvedAliases = [...literalAliases, ...Object.keys(fallbackAliases)];
const refusedAliases = {
"#empty": {
target: [],
status: "external",
limitation: "an empty imports target array",
},
"#empty-active": {
target: { node: [] },
status: "external",
limitation: "an empty imports target array",
},
"#null-last": {
target: [[], null],
status: "external",
limitation: "an explicit null imports target",
},
"#empty-last": {
target: [null, []],
status: "external",
limitation: "an empty imports target array",
},
"#inactive": {
target: [{ browser: "./browser.cjs" }],
status: "external",
limitation: "it declares browser.",
},
"#nested-inactive": {
status: "external",
target: [
[{ browser: "./browser.cjs" }, { "rea-inactive": "./inactive.cjs" }],
],
limitation: "it declares browser, rea-inactive.",
},
"#escape": {
target: "./.\t./outside.cjs",
status: "rejected",
limitation: "escapes the package root",
},
"#encoded-separator": {
target: ["./con%2ffig.cjs", "./config.cjs"],
status: "rejected",
limitation: "separator bytes",
},
"#missing-url": {
target: ["./miss\ting.cjs", "./config.cjs"],
status: "not-found",
limitation: JSON.stringify("./miss\ting.cjs"),
},
};
const allAliases = [...resolvedAliases, ...Object.keys(refusedAliases)];
const createPackageImportAliasFixture = async () => {
const root = await createTestTempDirectory("rea-package-import-aliases-");
const mainSource = [
'const config = require("#config");',
'const nested = require("./node_modules/fixture/index.cjs");',
'const missing = require("#missing");',
...allAliases.map((specifier) => `require(${JSON.stringify(specifier)});`),
].join("\n");
const moduleSource = allAliases
.map((specifier) => `import ${JSON.stringify(specifier)};`)
.join("\n");
const nestedSource = [
'const config = require("#config");',
"module.exports = config;",
].join("\n");
const files = {
"package.json": JSON.stringify({
name: "app",
imports: {
"#config": "./config.cjs",
...Object.fromEntries(
literalAliases.map((specifier) => [specifier, "./config.cjs"]),
),
...fallbackAliases,
...Object.fromEntries(
Object.entries(refusedAliases).map(([specifier, { target }]) => [
specifier,
target,
]),
),
},
}),
"main.cjs": mainSource,
"main.mjs": moduleSource,
"config.cjs": "module.exports = 'app-config';",
"node_modules/fixture/package.json": JSON.stringify({
name: "fixture",
imports: { "#config": "./local.cjs" },
}),
"node_modules/fixture/index.cjs": nestedSource,
"node_modules/fixture/local.cjs": "module.exports = 'fixture-config';",
};
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, mainSource, moduleSource, nestedSource };
};
cliTest.for(["CLI", "stdio MCP"] as const)(
"resolves exact package import aliases with package scope through %s",
async (surface, { cli }) => {
const { root, mainSource, moduleSource, nestedSource } =
await createPackageImportAliasFixture();
const nativeRequire = createRequire(join(root, "main.cjs"));
expect(
relative(root, nativeRequire.resolve("#config")).replaceAll("\\", "/"),
).toBe("config.cjs");
expect(
relative(
root,
createRequire(join(root, "node_modules/fixture/index.cjs")).resolve(
"#config",
),
).replaceAll("\\", "/"),
).toBe("node_modules/fixture/local.cjs");
expect(() => nativeRequire.resolve("#missing")).toThrow(
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;
for (const specifier of resolvedAliases)
for (const [moduleKind, sourcePath, source] of [
["require", "main.cjs", mainSource],
["import", "main.mjs", moduleSource],
] as const)
expect(graph.edges).toContainEqual(
expect.objectContaining({
properties: expect.objectContaining({
module_link_kind: moduleKind,
specifier,
resolved_path: "config.cjs",
resolution_status: "resolved",
}),
evidence: sourceEvidence(sourcePath, source),
}),
);
const imports = graph.edges.filter(
({ properties }) => properties.module_link_kind === "require",
);
for (const [specifier, { status, limitation }] of Object.entries(
refusedAliases,
))
for (const [moduleKind, sourcePath, source] of [
["require", "main.cjs", mainSource],
["import", "main.mjs", moduleSource],
] as const)
expect(graph.edges).toContainEqual(
expect.objectContaining({
properties: expect.objectContaining({
module_link_kind: moduleKind,
specifier,
resolved_path: null,
resolution_status: status,
}),
evidence: sourceEvidence(sourcePath, source, limitation),
}),
);
expect(imports).toContainEqual(
expect.objectContaining({
properties: expect.objectContaining({
specifier: "#config",
resolved_path: "config.cjs",
resolution_status: "resolved",
}),
evidence: sourceEvidence("main.cjs", mainSource),
}),
);
expect(imports).toContainEqual(
expect.objectContaining({
properties: expect.objectContaining({
specifier: "#config",
resolved_path: "node_modules/fixture/local.cjs",
resolution_status: "resolved",
}),
evidence: sourceEvidence(
"node_modules/fixture/index.cjs",
nestedSource,
),
}),
);
expect(imports).toContainEqual(
expect.objectContaining({
properties: expect.objectContaining({
specifier: "#missing",
resolved_path: null,
resolution_status: "external",
}),
evidence: expect.objectContaining({
limitations: expect.arrayContaining([
expect.stringContaining("does not define package import alias"),
]),
}),
}),
);
},
);
const sourceEvidence = (
sourcePath: string,
source: string,
limitation?: string,
): unknown =>
expect.objectContaining({
artifact: expect.objectContaining({
available: true,
sha256: createHash("sha256").update(source).digest("hex"),
}),
location: expect.objectContaining({
available: true,
value: expect.objectContaining({
kind: "source-range",
source: sourcePath,
}),
}),
...(limitation === undefined
? {}
: {
limitations: expect.arrayContaining([
expect.stringContaining(limitation),
]),
}),
});
+66
View File
@@ -7,6 +7,72 @@ import { buildManagedPeFixture } from "../../src/dotnet/ManagedPe.fixture.js";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
import { cliTest } from "../support/cli/cliFixture.js";
cliTest(
"managed CLI retains metadata and CIL after repeated local constructor owner lookups",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-managed-row-lookup-");
const path = join(root, "local-attributes.dll");
await writeFile(
path,
buildManagedPeFixture({
additionalEmptyTypes: 512,
customAttributeRowCount: 512,
customAttributeTypeRaw: (1 << 3) | 2,
typeName: "LookupAttribute",
extendsRaw: 0,
methodName: ".ctor",
methodFlags: 0x1886,
methodSignature: Buffer.from([0x20, 0x01, 0x01, 0x0e]),
ilBody: Buffer.from([0x06, 0x2a]),
}),
);
const artifact = await cli.run({
arguments: ["inspect-managed-artifact", path, "--json"],
});
expect(artifact.exitCode).toBe(0);
expect(artifact.json).toMatchObject({
normalized_result: {
coverage: { state: "complete", issues: [] },
attributes: expect.arrayContaining([
expect.objectContaining({
type_name: "Fixture.LookupAttribute",
constructor_token: "0x06000001",
}),
]),
},
});
expect(artifact.json).toHaveProperty(
"normalized_result.attributes.length",
512,
);
const members = await cli.run({
arguments: ["inspect-managed-members", path, "--json"],
});
expect(members.exitCode).toBe(0);
expect(members.json).toMatchObject({
normalized_result: {
coverage: { state: "complete", issues: [] },
types: expect.arrayContaining([
expect.objectContaining({ full_name: "Fixture.Empty0" }),
expect.objectContaining({ full_name: "Fixture.Empty511" }),
expect.objectContaining({ full_name: "Fixture.LookupAttribute" }),
]),
methods: [
expect.objectContaining({
name: ".ctor",
declaring_type: "Fixture.LookupAttribute",
body: expect.objectContaining({
status: "present",
instruction_count: 1,
}),
}),
],
},
});
expect(members.json).toHaveProperty("normalized_result.types.length", 513);
},
);
cliTest(
"managed CLI separates .NET Standard API targets from runtime evidence",
async ({ cli }) => {
@@ -0,0 +1,94 @@
import { createHash } from "node:crypto";
import { writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { expect } from "vitest";
import { parseEvidence } from "../../src/domain/evidence.js";
import { buildManagedMemberPointerFixture } from "../../src/dotnet/ManagedPe.fixture.js";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
import { cliTest } from "../support/cli/cliFixture.js";
cliTest(
"CLI and stdio MCP retain physical member identities through reordered pointers",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-managed-member-pointers-");
const path = join(root, "reordered.dll");
const bytes = buildManagedMemberPointerFixture();
const sha256 = createHash("sha256").update(bytes).digest("hex");
await writeFile(path, bytes);
const transport = new StdioClientTransport({
command: process.execPath,
args: [resolve("scripts/rea.mjs"), "mcp"],
cwd: process.cwd(),
env: { PATH: process.env.PATH ?? "", REA_LOG_LEVEL: "silent" },
stderr: "pipe",
});
transport.stderr?.on("data", () => undefined);
const client = new Client({ name: "managed-pointer-parity", version: "1" });
try {
await client.connect(transport);
for (const name of [
"inspect_managed_artifact",
"inspect_managed_members",
] as const) {
const cliResult = await cli.run({
arguments: [name.replaceAll("_", "-"), path, "--json"],
});
expect(cliResult.exitCode, cliResult.stderr).toBe(0);
const cliEvidence = parseEvidence(cliResult.json);
const response = await client.callTool({ name, arguments: { path } });
expect(response.isError, JSON.stringify(response)).not.toBe(true);
const mcpEvidence = parseEvidence(response.structuredContent);
expect(mcpEvidence.normalized_result).toEqual(
cliEvidence.normalized_result,
);
expect(mcpEvidence.subject?.digest.sha256).toBe(sha256);
expect(cliEvidence.subject?.digest.sha256).toBe(sha256);
expect(mcpEvidence.normalized_result).toMatchObject({
coverage: { state: "complete", issues: [] },
});
if (name === "inspect_managed_artifact") {
expect(mcpEvidence.normalized_result).toMatchObject({
attributes: [
expect.objectContaining({
constructor_token: "0x06000001",
type_name: "Fixture.B",
}),
],
});
} else {
expect(mcpEvidence.normalized_result).toMatchObject({
fields: [
expect.objectContaining({
token: "0x04000001",
declaring_type: "Fixture.B",
}),
expect.objectContaining({
token: "0x04000002",
declaring_type: "Fixture.A",
}),
],
methods: [
expect.objectContaining({
token: "0x06000001",
declaring_type: "Fixture.B",
}),
expect.objectContaining({
token: "0x06000002",
declaring_type: "Fixture.A",
}),
],
});
}
}
} finally {
try {
await client.close();
} finally {
await transport.close();
}
}
},
);
@@ -0,0 +1,84 @@
import { createHash } from "node:crypto";
import { writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { expect } from "vitest";
import { parseEvidence } from "../../src/domain/evidence.js";
import { buildManagedPeFixture } from "../../src/dotnet/ManagedPe.fixture.js";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
import { cliTest } from "../support/cli/cliFixture.js";
cliTest(
"CLI and stdio MCP inspect CLR ExtraData metadata without shifting table identities",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-managed-extra-data-");
const path = join(root, "extra-data.dll");
const bytes = buildManagedPeFixture({ metadataExtraData: 0x1234_5678 });
const sha256 = createHash("sha256").update(bytes).digest("hex");
await writeFile(path, bytes);
const transport = new StdioClientTransport({
command: process.execPath,
args: [resolve("scripts/rea.mjs"), "mcp"],
cwd: process.cwd(),
env: { PATH: process.env.PATH ?? "", REA_LOG_LEVEL: "silent" },
stderr: "pipe",
});
transport.stderr?.on("data", () => undefined);
const client = new Client({
name: "managed-extra-data-parity",
version: "1",
});
try {
await client.connect(transport);
for (const name of [
"inspect_managed_artifact",
"inspect_managed_members",
] as const) {
const cliResult = await cli.run({
arguments: [name.replaceAll("_", "-"), path, "--json"],
});
expect(cliResult.exitCode, cliResult.stderr).toBe(0);
const cliEvidence = parseEvidence(cliResult.json);
const response = await client.callTool({ name, arguments: { path } });
expect(response.isError, JSON.stringify(response)).not.toBe(true);
const mcpEvidence = parseEvidence(response.structuredContent);
expect(mcpEvidence.normalized_result).toEqual(
cliEvidence.normalized_result,
);
expect(mcpEvidence.subject?.digest.sha256).toBe(sha256);
expect(cliEvidence.subject?.digest.sha256).toBe(sha256);
expect(mcpEvidence.normalized_result).toMatchObject({
module: {
name: "Fixture.dll",
mvid: "00112233-4455-6677-8899-aabbccddeeff",
},
coverage: { state: "complete", issues: [] },
});
if (name === "inspect_managed_artifact") {
expect(mcpEvidence.normalized_result).toMatchObject({
assembly: { name: "Fixture.Managed" },
});
} else {
expect(mcpEvidence.normalized_result).toMatchObject({
types: [expect.objectContaining({ full_name: "Fixture.Program" })],
methods: [
expect.objectContaining({
token: "0x06000001",
name: "Main",
declaring_type: "Fixture.Program",
}),
],
});
}
}
} finally {
try {
await client.close();
} finally {
await transport.close();
}
}
},
);
@@ -0,0 +1,156 @@
import { access, readFile, readdir, writeFile } from "node:fs/promises";
import { join, relative, resolve } from "node:path";
import { expect } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
cliTest(
"skill-only setup verifies its selected client copy on install, rerun and repair",
async ({ cli }) => {
const directory = await createTestTempDirectory("rea-selected-skill-");
const selected = join(
directory,
".claude/skills/reverse-engineer-anything",
);
const shared = join(directory, ".agents/skills/reverse-engineer-anything");
const run = (args: readonly string[]) =>
cli.run({
arguments: [...args, "--json"],
cwd: directory,
environment: { USERPROFILE: directory },
});
const preview = await run([
"setup",
"--skill-client",
"claude_code",
"--dry-run",
]);
expect(preview.exitCode, preview.stdout).toBe(0);
expect(preview.json).toMatchObject({
status: "planned",
doctor: {
scope: {
clients: [],
skill: true,
skill_clients: ["claude_code"],
},
},
});
const registered = await run([
"setup",
"--client",
"claude_code",
"--skill=false",
"--yes",
]);
expect(registered.exitCode, registered.stderr).toBe(0);
const configuration = join(directory, ".claude.json");
const before = await readFile(configuration, "utf8");
const args = ["setup", "--skill-client", "claude_code", "--yes"];
const installed = await run(args);
expect(installed.exitCode, installed.stdout).toBe(0);
expect(installed.json).toMatchObject({
status: "ready",
appliedActions: ["installed_skill"],
doctor: {
healthy: true,
scope: { clients: [], skill: true, skill_clients: ["claude_code"] },
identity: { skill: { state: "aligned" } },
},
});
const bundle = resolve("skills/reverse-engineer-anything");
const assertAligned = async () => {
for (const entry of await readdir(bundle, {
recursive: true,
withFileTypes: true,
})) {
if (!entry.isFile()) continue;
const path = relative(bundle, join(entry.parentPath, entry.name));
expect(await readFile(join(selected, path))).toEqual(
await readFile(join(bundle, path)),
);
}
};
await assertAligned();
const repeated = await run(args);
expect(repeated.exitCode, repeated.stdout).toBe(0);
expect(repeated.json).toMatchObject({
status: "ready",
appliedActions: [],
});
await writeFile(
join(selected, "references/native-and-artifacts.md"),
"damaged selected copy\n",
);
const damaged = await run(["doctor", "--client", "claude_code", "--skill"]);
expect(damaged.json).toMatchObject({
healthy: false,
identity: { skill: { state: "stale" } },
});
const repaired = await run(args);
expect(repaired.exitCode, repaired.stdout).toBe(0);
expect(repaired.json).toMatchObject({
status: "ready",
appliedActions: ["installed_skill"],
});
await assertAligned();
await expect(access(shared)).rejects.toMatchObject({ code: "ENOENT" });
expect(await readFile(configuration, "utf8")).toBe(before);
const sharedControl = await run([
"setup",
"--skill-client",
"shared",
"--yes",
]);
expect(sharedControl.exitCode, sharedControl.stdout).toBe(0);
expect(sharedControl.json).toMatchObject({ status: "ready" });
await access(join(shared, "SKILL.md"));
},
);
cliTest(
"setup keeps registration and skill readiness selections independent",
async ({ cli }) => {
const directory = await createTestTempDirectory("rea-independent-skill-");
const result = await cli.run({
arguments: [
"setup",
"--client",
"codex",
"--skill-client",
"claude_code",
"--yes",
"--json",
],
cwd: directory,
environment: { USERPROFILE: directory },
});
expect(result.exitCode, result.stdout).toBe(0);
expect(result.json).toMatchObject({
status: "ready",
doctor: {
healthy: true,
scope: {
clients: ["codex"],
skill_clients: ["claude_code"],
skill: true,
},
identity: { skill: { state: "aligned" } },
},
});
await access(join(directory, ".codex/config.toml"));
await access(
join(directory, ".claude/skills/reverse-engineer-anything/SKILL.md"),
);
await expect(access(join(directory, ".claude.json"))).rejects.toMatchObject(
{ code: "ENOENT" },
);
await expect(
access(join(directory, ".agents/skills/reverse-engineer-anything")),
).rejects.toMatchObject({ code: "ENOENT" });
},
);
@@ -29,6 +29,11 @@ const chromeExecutable = [
existsSync(candidate),
);
// Match the real-browser verifier: a cold Chrome launch on a loaded coverage
// runner can exceed 20 seconds before publishing DevToolsActivePort.
const CHROME_STARTUP_TIMEOUT_MS = 60_000;
const CHROME_TEST_TIMEOUT_MS = CHROME_STARTUP_TIMEOUT_MS + 30_000;
// Issue 1586's page, plus the HTML, image, use, and foreign-origin cases the
// real snapshot must distinguish. The XHTML page is the prefixed-svg gap
// reported on PR 1602. The tests are skipped when no Chrome-family executable
@@ -90,7 +95,7 @@ it.skipIf(chromeExecutable === undefined)(
executable,
activePortPath: join(profile, "DevToolsActivePort"),
stderr: () => stderr,
timeoutMs: 20_000,
timeoutMs: CHROME_STARTUP_TIMEOUT_MS,
});
const endpoint = `http://127.0.0.1:${String(port)}`;
const provider = new CdpBrowserProvider();
@@ -158,6 +163,7 @@ it.skipIf(chromeExecutable === undefined)(
});
}
},
CHROME_TEST_TIMEOUT_MS,
);
const xhtmlPage = `<?xml version="1.0" encoding="UTF-8"?>
@@ -261,7 +267,7 @@ for (const { format, page, contentType, nodeNames, link, destinations } of [
executable,
activePortPath: join(profile, "DevToolsActivePort"),
stderr: () => stderr,
timeoutMs: 20_000,
timeoutMs: CHROME_STARTUP_TIMEOUT_MS,
});
const endpoint = `http://127.0.0.1:${String(port)}`;
const provider = new CdpBrowserProvider();
@@ -312,6 +318,7 @@ for (const { format, page, contentType, nodeNames, link, destinations } of [
});
}
},
CHROME_TEST_TIMEOUT_MS,
);
}
@@ -446,6 +446,92 @@ describe("web capture WebSocket payload byte coverage", () => {
});
describe("web capture diff", () => {
it("treats unavailable HTTP response facts as unknown while retaining observed changes", async () => {
const browser = await startFakeCdpBrowser();
browsers.push(browser);
const captured = await new CdpBrowserProvider().inspectPage(
inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
observation_ms: 0,
}),
);
if (!captured.ok) throw captured.error;
const before = structuredClone(captured.value);
const request = before.network.requests[0];
if (request === undefined) throw new Error("Missing network request");
request.status = null;
request.mime_type = null;
request.encoded_data_length = null;
markSectionsComplete(before, [
"network_requests",
"websocket_connections",
"websocket_frames",
"json_body_shapes",
]);
for (const item of before.network.requests)
item.body_shapes.status = "not_approved";
const after = structuredClone(before);
const responseObserved = after.network.requests[0];
if (responseObserved === undefined)
throw new Error("Missing network request");
responseObserved.status = 200;
responseObserved.mime_type = "application/json";
responseObserved.encoded_data_length = 100;
expect(compareNetwork(before, after)).toMatchObject({
status: "unknown",
total_changes: 0,
changes: [],
});
expect(compareNetwork(after, before)).toMatchObject({
status: "unknown",
total_changes: 0,
});
expect(compareNetwork(before, before).status).toBe("unknown");
for (const field of [
"status",
"mime_type",
"encoded_data_length",
] as const) {
const partial = structuredClone(after);
partial.network.requests[0]![field] = null;
expect(compareNetwork(partial, after).status).toBe("unknown");
expect(compareNetwork(after, partial).status).toBe("unknown");
}
const inventoryBefore = structuredClone(before);
inventoryBefore.network.requests = [];
expect(compareNetwork(inventoryBefore, before)).toMatchObject({
status: "changed",
total_changes: 1,
changes: [expect.objectContaining({ change: "added" })],
});
const statusChanged = structuredClone(after);
statusChanged.network.requests[0]!.status = 500;
expect(compareNetwork(after, statusChanged)).toMatchObject({
status: "changed",
changes: [expect.objectContaining({ change: "modified" })],
});
after.network.requests[0]!.encoded_data_length = null;
expect(compareNetwork(after, statusChanged).status).toBe("changed");
const repeated = structuredClone(statusChanged);
const duplicate = structuredClone(repeated.network.requests[0]!);
duplicate.status = 200;
duplicate.mime_type = "text/plain";
repeated.network.requests.push(duplicate);
const reassociated = structuredClone(repeated);
reassociated.network.requests[0]!.mime_type = "text/plain";
reassociated.network.requests.at(-1)!.mime_type = "application/json";
expect(compareNetwork(repeated, reassociated).status).toBe("changed");
repeated.network.requests[0]!.status = null;
expect(compareNetwork(repeated, reassociated).status).toBe("unknown");
});
it("ignores transient request IDs and capture-approval state", async () => {
const browser = await startFakeCdpBrowser();
browsers.push(browser);
@@ -11,6 +11,78 @@ import {
writeFixtureFiles,
} from "../../support/javascriptApplicationFixture.js";
cliTest(
"resolves emitted module imports without substituting Electron runtime paths",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-typescript-runtime-paths-");
await writeFixtureFiles(root, {
"package.json": JSON.stringify({ main: "main.ts" }),
"main.ts": `import { BrowserWindow, utilityProcess } from "electron";
import "./worker.js";
import "./config.mjs";
import "./legacy.cjs";
import "./view.js";
import "./runtime.js";
const win = new BrowserWindow({webPreferences:{preload:"./worker.js"}});
win.loadURL("./renderer.js");
utilityProcess.fork("./worker.js");
utilityProcess.fork("./runtime.js");
throw new Error("source must stay inert");`,
"worker.ts": "export const worker = 1;",
"config.mts": "export const config = 1;",
"legacy.cts": "export const legacy = 1;",
"view.tsx": "export const view = <div />;",
"renderer.ts": "export const renderer = 1;",
"runtime.ts": "export const source = 1;",
"runtime.js": "throw new Error('runtime must stay inert');",
});
const output = await cli.run({
arguments: ["analyze-javascript-application", root, "--json"],
});
expect(output.exitCode, output.stderr).toBe(0);
const result = javascriptApplicationAnalysisResultSchema.parse(
parseEvidence(output.json).normalized_result,
);
const { graph } = result;
const source = findSourceModule(graph, "main.ts");
for (const [specifier, target] of [
["./worker.js", "worker.ts"],
["./config.mjs", "config.mts"],
["./legacy.cjs", "legacy.cts"],
["./view.js", "view.tsx"],
["./runtime.js", "runtime.js"],
] as const)
expect(
findGraphEdge(graph, source, findSourceModule(graph, target), "imports")
?.properties,
).toMatchObject({ specifier, resolved_path: target });
expect(result.summary).toMatchObject({
utility_processes: 2,
resolved_utility_entrypoints: 1,
});
expect(
graph.edges.find(
(edge) =>
edge.evidence.extractor.operation ===
"associate-browser-window-preload",
)?.properties,
).toMatchObject({
declared_path: "./worker.js",
resolved_path: null,
resolution_status: "not-found",
});
expect(
graph.edges
.filter(
(edge) =>
edge.properties.declared_path === "./worker.js" ||
edge.properties.declared_path === "./renderer.js",
)
.some((edge) => edge.properties.resolved_path != null),
).toBe(false);
},
);
cliTest(
"returns literal self-import evidence while preserving sibling imports and self-re-exports",
async ({ cli }) => {
@@ -75,7 +147,7 @@ cliTest(
);
cliTest(
"discloses CommonJS and TypeScript self-imports while retaining unresolved extension rewrites",
"discloses CommonJS and TypeScript self-imports including emitted-name rewrites",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-self-require-");
await writeFixtureFiles(root, {
@@ -94,8 +166,10 @@ cliTest(
expect(
graph.edges.filter((edge) => edge.source_node_id === edge.target_node_id),
).toEqual([]);
// ./util.ts is a literal self-import and ./util.js resolves under NodeNext
// emitted-name semantics back to util.ts itself, as ./c.cjs does for CJS.
expect(graph.limitations).toContainEqual(
expect.stringMatching(/^2 import specifiers .*were omitted;/u),
expect.stringMatching(/^3 import specifiers .*were omitted;/u),
);
expect(result.limitations).toEqual(
expect.arrayContaining(graph.limitations),
@@ -128,12 +202,21 @@ cliTest(
).toBe(false);
}
expect(
graph.edges.find(
graph.edges.some(
(edge) =>
edge.source_node_id === findSourceModule(graph, "util.ts")?.node_id &&
edge.properties.specifier === "./util.js" &&
edge.properties.module_link_kind === "import",
)?.properties,
).toMatchObject({ resolved_path: null, resolution_status: "not-found" });
(edge.properties.module_link_kind === "import" ||
edge.properties.resolution_status === "not-found"),
),
).toBe(false);
expect(
graph.nodes.some((node) =>
node.observations.some(
({ properties }) =>
properties.semantic_role === "module-reference" &&
properties.declared_specifier === "./util.js",
),
),
).toBe(false);
},
);
@@ -1,86 +0,0 @@
import { describe, expect } from "vitest";
import { inspectBundleKeyedArchive } from "../../../src/artifacts/apple/KeyedArchiveReader.js";
import { keyedArchiveResultSchema } from "../../../src/domain/apple/keyedArchive.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import {
keyedArchiveIntegerFormats,
keyedArchiveIntegerCases,
keyedArchiveIntegerFixtures,
expectKeyedArchiveIntegerCase,
type KeyedArchiveIntegerFixtures,
} from "../../fixtures/keyedArchiveIntegers.js";
import { cliTest } from "../../support/cli/cliFixture.js";
import {
createTestWorkspace,
removeTestWorkspace,
} from "../../support/workspace/workspaceFixture.js";
const archiveTest = cliTest.extend<{
$worker: { keyedArchiveIntegerArchives: KeyedArchiveIntegerFixtures };
}>({
keyedArchiveIntegerArchives: [
// oxlint-disable-next-line no-empty-pattern -- Vitest parses fixture dependencies from object destructuring.
async ({}, use) => {
const workspace = await createTestWorkspace("rea-keyed-integers-");
try {
await use(await keyedArchiveIntegerFixtures(workspace.root));
} finally {
await removeTestWorkspace(workspace.root);
}
},
{ scope: "worker" },
],
});
const cases = keyedArchiveIntegerFormats.flatMap((format) =>
keyedArchiveIntegerCases.map((selectedCase) => ({ format, selectedCase })),
);
// Selected by the existing required native keyed-archive verifier, not Linux skips.
describe.skipIf(process.platform !== "darwin")(
"Foundation archive integer precision",
() => {
archiveTest.for(cases)(
"filesystem preserves $format $selectedCase numeric meaning",
async ({ format, selectedCase }, { keyedArchiveIntegerArchives }) => {
const fixture = keyedArchiveIntegerArchives[format];
const result = await inspectBundleKeyedArchive({
bundlePath: fixture.root,
targetSha256: fixture.digest,
parameters: { path: fixture.selected.filename, limit: 100 },
});
expectKeyedArchiveIntegerCase(
result,
selectedCase,
fixture.selected,
fixture.digest,
);
},
);
archiveTest.for(cases)(
"built CLI preserves $format $selectedCase numeric meaning",
async (
{ format, selectedCase },
{ cli, keyedArchiveIntegerArchives },
) => {
const fixture = keyedArchiveIntegerArchives[format];
const output = await cli.run({
arguments: ["inspect-keyed-archive", fixture.archivePath, "--json"],
environment: {
REA_LOG_LEVEL: "silent",
REA_ANALYSIS_PROVIDER: "auto",
},
});
expect(output.exitCode).toBe(0);
const result = keyedArchiveResultSchema.parse(
parseEvidence(output.json).normalized_result,
);
expectKeyedArchiveIntegerCase(
result,
selectedCase,
fixture.selected,
fixture.digest,
);
},
);
},
);
@@ -308,6 +308,8 @@ it.each(["depth", "dependency", "link"])(
expect(normalized.diagnostics).toEqual([
{
input_path: "$input",
stage: "gzip",
missing_dependencies: ["sasquatch"],
report: {
__typename__: "ExtractorDependencyNotFoundReport",
severity: "ERROR",
@@ -1,8 +1,11 @@
import { writeFile } from "node:fs/promises";
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it } from "vitest";
import { readFirmwareReport } from "../../../src/firmware/FirmwareFiles.js";
import {
inventoryFirmwareOutput,
readFirmwareReport,
} from "../../../src/firmware/FirmwareFiles.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
it.each([
@@ -41,3 +44,24 @@ it("preserves valid Unicode and a literal replacement character in producer JSON
report,
);
});
it("orders extracted firmware paths by code point independently of host locale", async () => {
const root = await createTestTempDirectory("rea-firmware-inventory-");
await mkdir(join(root, "Lib"));
for (const path of ["a.bin", "z.bin", "\u00e4.bin", "B.bin", "Lib/x.bin"])
await writeFile(join(root, path), "");
const entries = await inventoryFirmwareOutput(
root,
1024,
16,
"inspect_firmware_regions",
);
// Locale collation would interleave case and place "ä" by language rules.
expect(entries.map(({ relativePath }) => relativePath)).toEqual([
"B.bin",
"Lib/x.bin",
"a.bin",
"z.bin",
"\u00e4.bin",
]);
});
@@ -741,7 +741,76 @@ describe("nested and array package export targets", () => {
},
);
});
describe("package export target URL normalization compared with Node", () => {
it.each([
[["./.\t./outside.cjs", "./array.cjs"]],
[["./.%\n2e/outside.cjs", "./array.cjs"]],
[["./.\r./outside.cjs", "./array.cjs"]],
["./arr\tay.cjs"],
["./array.cjs \t"],
["./array.cjs?selected=one#fragment"],
["./.\t./example/array.cjs"],
] as const)(
"resolves normalized target %j through both loaders",
async (target) => {
for (const moduleKind of ["import", "require"] as const) {
const { node, outcome } = await compareWithNode(target, moduleKind);
expect(node).toBe("array.cjs");
expect(outcome).toMatchObject({
resolution_status: "resolved",
resolved_path: "node_modules/example/array.cjs",
});
}
},
);
it.each([
[["./arr%2fay.cjs", "./array.cjs"], "rejected"],
[["./miss\ting.cjs", "./array.cjs"], "not-found"],
] as const)(
"retains the first selected target failure in %j",
async (target, status) => {
for (const moduleKind of ["import", "require"] as const) {
const { node, node_error, outcome } = await compareWithNode(
target,
moduleKind,
);
expect(node).toBeNull();
expect(node_error).not.toBeNull();
expect(outcome).toMatchObject({
resolution_status: status,
resolved_path: null,
});
}
},
);
});
describe("unmatched package export conditions", () => {
it.each([
[[{ browser: "./default.cjs" }], "browser"],
[
[[{ browser: "./default.cjs" }, { "rea-inactive": "./node.cjs" }]],
"browser, rea-inactive",
],
[{ node: [{ browser: "./default.cjs" }] }, "node, browser"],
] as const)(
"preserves condition names in unmatched target %j",
async (target, declared) => {
for (const moduleKind of ["import", "require"] as const) {
const { node_error, outcome } = await compareWithNode(
target,
moduleKind,
);
expect(node_error).toBe("ERR_PACKAGE_PATH_NOT_EXPORTED");
expect(outcome).toMatchObject({
resolution_status: "external",
resolved_path: null,
});
expect(outcome.limitations[0]).toContain(`It declares ${declared}.`);
}
},
);
it.each(["import", "require"] as const)(
"names the declared conditions for %s",
async (moduleKind) => {
@@ -769,6 +838,31 @@ describe("unmatched package export conditions", () => {
});
});
describe("blocked package export provenance", () => {
it.each([
[[], "an empty exports target array"],
[{ node: [] }, "an empty exports target array"],
[[null, []], "an empty exports target array"],
[[[], null], "an explicit null exports target"],
] as const)(
"preserves the blocking source value in %j",
async (target, limitation) => {
for (const moduleKind of ["import", "require"] as const) {
const { node_error, outcome } = await compareWithNode(
target,
moduleKind,
);
expect(node_error).toBe("ERR_PACKAGE_PATH_NOT_EXPORTED");
expect(outcome).toMatchObject({
resolution_status: "external",
resolved_path: null,
});
expect(outcome.limitations[0]).toContain(limitation);
}
},
);
});
describe("package exports fallback refusal reasons", () => {
it.each([
[{ import: [42, 7] }, "ERR_INVALID_PACKAGE_TARGET", "rejected"],
@@ -0,0 +1,786 @@
import { execFile } from "node:child_process";
import { mkdir, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { dirname, join, relative } from "node:path";
import { promisify } from "node:util";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import {
resolveArtifactPathByContext,
type ArtifactPathResolution,
} from "../../../src/application/javascript/JavaScriptArtifactPathResolution.js";
import type { JavaScriptArtifactFile } from "../../../src/domain/javascript/javascriptArtifactFiles.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const execute = promisify(execFile);
const nodeOutcomeSchema = z.strictObject({
target: z.string().nullable(),
error_code: z.string().nullable(),
});
const posixRelative = (root: string, absolute: string): string =>
relative(root, absolute).replaceAll("\\", "/");
const inventory = (
contents: ReadonlyMap<string, string>,
): Map<string, JavaScriptArtifactFile> =>
new Map(
[...contents].map(([path, value]) => [
path,
{
path,
container_sha256: "a".repeat(64),
sha256: "b".repeat(64),
bytes: Buffer.byteLength(value),
inventory_artifact_id: path,
kind: path.endsWith("package.json") ? "package-json" : "javascript",
unpacked: false,
text: { included: true, value },
},
]),
);
const writeTree = async (
root: string,
files: Readonly<Record<string, string>>,
): Promise<Map<string, string>> => {
const contents = new Map<string, string>();
await Promise.all(
Object.entries(files).map(async ([path, value]) => {
const absolute = join(root, path);
await mkdir(dirname(absolute), { recursive: true });
await writeFile(absolute, value);
contents.set(path, value);
}),
);
return contents;
};
const nodeRequireTarget = async (
importer: string,
specifier: string,
): Promise<z.infer<typeof nodeOutcomeSchema>> => {
try {
return {
target: createRequire(importer).resolve(specifier),
error_code: null,
};
} catch (error) {
const code =
error instanceof Error && "code" in error
? z.string().parse(Reflect.get(error, "code"))
: null;
return { target: null, error_code: code };
}
};
const nodeImportTarget = async (
cwd: string,
specifier: string,
): Promise<z.infer<typeof nodeOutcomeSchema>> => {
const { stdout } = await execute(
process.execPath,
[
"--input-type=module",
"-e",
`
try {
const url = await import.meta.resolve(${JSON.stringify(specifier)});
console.log(JSON.stringify({ target: url, error_code: null }));
} catch (error) {
console.log(JSON.stringify({
target: null,
error_code: error.code ?? null,
}));
}
`,
],
{ cwd },
);
return nodeOutcomeSchema.parse(JSON.parse(stdout));
};
const resolveAlias = (
files: Map<string, JavaScriptArtifactFile>,
declaredPath: string,
sourcePath: string,
moduleKind: "import" | "require",
): ArtifactPathResolution =>
resolveArtifactPathByContext({
declaredPath,
sourcePath,
context: "module-specifier",
moduleKind,
files,
});
describe("literal package import keys compared with Node", () => {
it("matches literal imports keys containing path-like bytes in both Node loaders", async () => {
const root = await createTestTempDirectory("rea-import-alias-literal-");
const specifiers = ["#/x", "#x%2Fy", "#x%2Ey", "#x\\y", "#x\0y"];
const contents = await writeTree(root, {
"package.json": JSON.stringify({
imports: Object.fromEntries(
specifiers.map((specifier) => [specifier, "./target.cjs"]),
),
}),
"main.cjs": "module.exports = 1;",
"target.cjs": "module.exports = 1;",
});
const inventoried = inventory(contents);
for (const specifier of specifiers) {
const required = await nodeRequireTarget(
join(root, "main.cjs"),
specifier,
);
expect(required.error_code).toBeNull();
expect(posixRelative(root, required.target ?? "")).toBe("target.cjs");
const imported = await nodeImportTarget(root, specifier);
expect(imported.error_code).toBeNull();
expect(posixRelative(root, fileURLToPath(imported.target ?? ""))).toBe(
"target.cjs",
);
for (const moduleKind of ["require", "import"] as const)
expect(
resolveAlias(inventoried, specifier, "main.cjs", moduleKind),
JSON.stringify({ specifier, moduleKind }),
).toMatchObject({
declared_path: specifier,
resolution_status: "resolved",
resolved_path: "target.cjs",
});
}
});
it("still rejects unsafe selected targets for literal imports keys", async () => {
const root = await createTestTempDirectory("rea-import-alias-target-");
const contents = await writeTree(root, {
"package.json": JSON.stringify({
imports: { "#x%2Fy": "./nested%2Ftarget.cjs" },
}),
"main.cjs": "module.exports = 1;",
"nested/target.cjs": "module.exports = 1;",
});
const inventoried = inventory(contents);
const required = await nodeRequireTarget(join(root, "main.cjs"), "#x%2Fy");
expect(required.error_code).toBe("ERR_INVALID_MODULE_SPECIFIER");
const imported = await nodeImportTarget(root, "#x%2Fy");
expect(imported.error_code).toBe("ERR_INVALID_MODULE_SPECIFIER");
for (const moduleKind of ["require", "import"] as const)
expect(
resolveAlias(inventoried, "#x%2Fy", "main.cjs", moduleKind),
).toMatchObject({ resolution_status: "rejected", resolved_path: null });
});
});
describe("inactive package target arrays compared with Node", () => {
it("continues past inactive arrays in enclosing imports and exports conditions", async () => {
const root = await createTestTempDirectory("rea-inactive-package-array-");
const conditional = {
node: [{ browser: "./browser.cjs" }],
default: "./fallback.cjs",
};
const nested = {
node: [
[{ browser: "./browser.cjs" }],
{ "rea-inactive": "./inactive.cjs" },
],
default: "./fallback.cjs",
};
const contents = await writeTree(root, {
"package.json": JSON.stringify({
imports: { "#conditional": conditional, "#nested": nested },
}),
"main.cjs": "module.exports = 1;",
"fallback.cjs": "module.exports = 1;",
"node_modules/fixture/package.json": JSON.stringify({
name: "fixture",
exports: { ".": conditional, "./nested": nested },
}),
"node_modules/fixture/fallback.cjs": "module.exports = 2;",
});
const inventoried = inventory(contents);
for (const [specifier, expected] of [
["#conditional", "fallback.cjs"],
["#nested", "fallback.cjs"],
["fixture", "node_modules/fixture/fallback.cjs"],
["fixture/nested", "node_modules/fixture/fallback.cjs"],
] as const) {
const required = await nodeRequireTarget(
join(root, "main.cjs"),
specifier,
);
expect(required.error_code, specifier).toBeNull();
expect(posixRelative(root, required.target ?? "")).toBe(expected);
const imported = await nodeImportTarget(root, specifier);
expect(imported.error_code).toBeNull();
expect(posixRelative(root, fileURLToPath(imported.target ?? ""))).toBe(
expected,
);
for (const moduleKind of ["require", "import"] as const)
expect(
resolveAlias(inventoried, specifier, "main.cjs", moduleKind),
).toMatchObject({
declared_path: specifier,
resolution_status: "resolved",
resolved_path: expected,
});
}
});
});
describe("package target refusal evidence compared with Node", () => {
it("keeps empty, null, invalid, and unmatched array outcomes distinct", async () => {
const root = await createTestTempDirectory("rea-inactive-package-refusal-");
const inactive = { browser: "./browser.cjs" };
const contents = await writeTree(root, {
"package.json": JSON.stringify({
imports: {
"#empty-direct": [],
"#empty": { node: [], default: "./fallback.cjs" },
"#null": { node: [null, inactive], default: "./fallback.cjs" },
"#null-last": [[], null],
"#empty-last": [null, []],
"#invalid": {
node: ["../outside.cjs", inactive],
default: "./fallback.cjs",
},
"#unmatched": [inactive],
"#unmatched-nested": [
[inactive, { "rea-inactive": "./inactive.cjs" }],
],
"#unmatched-active": { node: [inactive] },
},
}),
"main.cjs": "module.exports = 1;",
"fallback.cjs": "module.exports = 1;",
});
const inventoried = inventory(contents);
for (const [specifier, errorCode, status, limitation] of [
[
"#empty-direct",
"ERR_PACKAGE_IMPORT_NOT_DEFINED",
"external",
"an empty imports target array",
],
[
"#empty",
"ERR_PACKAGE_IMPORT_NOT_DEFINED",
"external",
"an empty imports target array",
],
[
"#null",
"ERR_PACKAGE_IMPORT_NOT_DEFINED",
"external",
"an explicit null imports target",
],
[
"#null-last",
"ERR_PACKAGE_IMPORT_NOT_DEFINED",
"external",
"an explicit null imports target",
],
[
"#empty-last",
"ERR_PACKAGE_IMPORT_NOT_DEFINED",
"external",
"an empty imports target array",
],
["#invalid", "ERR_INVALID_PACKAGE_TARGET", "rejected", "../outside.cjs"],
[
"#unmatched",
"ERR_PACKAGE_IMPORT_NOT_DEFINED",
"external",
"it declares browser.",
],
[
"#unmatched-nested",
"ERR_PACKAGE_IMPORT_NOT_DEFINED",
"external",
"it declares browser, rea-inactive.",
],
[
"#unmatched-active",
"ERR_PACKAGE_IMPORT_NOT_DEFINED",
"external",
"it declares node, browser.",
],
] as const) {
expect(
(await nodeRequireTarget(join(root, "main.cjs"), specifier)).error_code,
).toBe(errorCode);
expect((await nodeImportTarget(root, specifier)).error_code).toBe(
errorCode,
);
for (const moduleKind of ["require", "import"] as const) {
const result = resolveAlias(
inventoried,
specifier,
"main.cjs",
moduleKind,
);
expect(result).toMatchObject({
resolution_status: status,
resolved_path: null,
});
expect(result.limitations.join(" "), specifier).toContain(limitation);
}
}
});
});
describe("package import target arrays compared with Node", () => {
it("skips invalid parent, absolute, and URL targets before an exact fallback", async () => {
const root = await createTestTempDirectory("rea-import-alias-fallback-");
const imports = {
"#parent": ["../outside.cjs", "./fallback.cjs"],
"#absolute": { node: [["/outside.cjs"], "./fallback.cjs"] },
"#url": {
import: ["https://example.invalid/outside.cjs", "./fallback.cjs"],
require: ["file:///outside.cjs", "./fallback.cjs"],
},
};
const contents = await writeTree(root, {
"package.json": JSON.stringify({ imports }),
"main.cjs": "module.exports = 1;",
"fallback.cjs": "module.exports = 1;",
});
const inventoried = inventory(contents);
for (const specifier of Object.keys(imports)) {
const required = await nodeRequireTarget(
join(root, "main.cjs"),
specifier,
);
expect(required.error_code).toBeNull();
expect(posixRelative(root, required.target ?? "")).toBe("fallback.cjs");
const imported = await nodeImportTarget(root, specifier);
expect(imported.error_code).toBeNull();
expect(posixRelative(root, fileURLToPath(imported.target ?? ""))).toBe(
"fallback.cjs",
);
for (const moduleKind of ["require", "import"] as const)
expect(
resolveAlias(inventoried, specifier, "main.cjs", moduleKind),
).toMatchObject({
declared_path: specifier,
resolution_status: "resolved",
resolved_path: "fallback.cjs",
});
}
});
it("preserves invalid, null, and unsupported-package outcomes in arrays", async () => {
const root = await createTestTempDirectory(
"rea-import-alias-fallback-refuse-",
);
const contents = await writeTree(root, {
"package.json": JSON.stringify({
imports: {
"#invalid": [null, "../outside.cjs"],
"#blocked": ["../outside.cjs", null],
"#package": ["fixture", "./fallback.cjs"],
},
}),
"main.cjs": "module.exports = 1;",
"fallback.cjs": "module.exports = 1;",
"node_modules/fixture/package.json": JSON.stringify({
name: "fixture",
main: "index.cjs",
}),
"node_modules/fixture/index.cjs": "module.exports = 2;",
});
const inventoried = inventory(contents);
for (const [specifier, errorCode, resolutionStatus, reason] of [
["#invalid", "ERR_INVALID_PACKAGE_TARGET", "rejected", "../outside.cjs"],
[
"#blocked",
"ERR_PACKAGE_IMPORT_NOT_DEFINED",
"external",
"explicit null",
],
] as const) {
const required = await nodeRequireTarget(
join(root, "main.cjs"),
specifier,
);
expect(required.error_code).toBe(errorCode);
expect((await nodeImportTarget(root, specifier)).error_code).toBe(
errorCode,
);
for (const moduleKind of ["require", "import"] as const) {
const result = resolveAlias(
inventoried,
specifier,
"main.cjs",
moduleKind,
);
expect(result).toMatchObject({
resolution_status: resolutionStatus,
resolved_path: null,
});
expect(result.limitations.join(" ")).toContain(reason);
}
}
const required = await nodeRequireTarget(
join(root, "main.cjs"),
"#package",
);
expect(posixRelative(root, required.target ?? "")).toBe(
"node_modules/fixture/index.cjs",
);
const imported = await nodeImportTarget(root, "#package");
expect(imported.error_code).toBeNull();
expect(posixRelative(root, fileURLToPath(imported.target ?? ""))).toBe(
"node_modules/fixture/index.cjs",
);
for (const moduleKind of ["require", "import"] as const) {
const result = resolveAlias(
inventoried,
"#package",
"main.cjs",
moduleKind,
);
expect(result).toMatchObject({
resolution_status: "external",
resolved_path: null,
});
expect(result.limitations.join(" ")).toContain(
"External-package import targets remain unresolved",
);
}
});
});
describe("package import target URL normalization compared with Node", () => {
it("normalizes targets before package-root validation and array selection", async () => {
const root = await createTestTempDirectory("rea-package-target-url-");
const directory = "app space#?%λ";
const imports = {
"#tab-escape": ["./.\t./outside.cjs", "./fallback.cjs"],
"#newline-escape": ["./.%\n2e/outside.cjs", "./fallback.cjs"],
"#cr-escape": ["./.\r./outside.cjs", "./fallback.cjs"],
"#normalized": "./fall\tback.cjs",
"#trimmed": "./fallback.cjs \t",
"#suffix": "./fallback.cjs?selected=one#fragment",
"#return": `./.\t./${encodeURIComponent(directory)}/fallback.cjs`,
};
const contents = await writeTree(root, {
[`${directory}/package.json`]: JSON.stringify({ imports }),
[`${directory}/main.cjs`]: "module.exports = 1;",
[`${directory}/fallback.cjs`]: "module.exports = 1;",
});
const inventoried = inventory(contents);
for (const specifier of Object.keys(imports)) {
const required = await nodeRequireTarget(
join(root, directory, "main.cjs"),
specifier,
);
expect(required.error_code, specifier).toBeNull();
expect(posixRelative(root, required.target ?? "")).toBe(
`${directory}/fallback.cjs`,
);
const imported = await nodeImportTarget(join(root, directory), specifier);
expect(imported.error_code, specifier).toBeNull();
expect(posixRelative(root, fileURLToPath(imported.target ?? ""))).toBe(
`${directory}/fallback.cjs`,
);
for (const moduleKind of ["require", "import"] as const)
expect(
resolveAlias(
inventoried,
specifier,
`${directory}/main.cjs`,
moduleKind,
),
specifier,
).toMatchObject({
declared_path: specifier,
resolution_status: "resolved",
resolved_path: `${directory}/fallback.cjs`,
});
}
});
it("keeps URL decoding and missing-file failures after array selection", async () => {
const root = await createTestTempDirectory(
"rea-package-target-url-refusal-",
);
const contents = await writeTree(root, {
"package.json": JSON.stringify({
imports: {
"#escape": "./.\t./outside.cjs",
"#separator": ["./fall%2fback.cjs", "./fallback.cjs"],
"#missing": ["./miss\ting.cjs", "./fallback.cjs"],
"#query-separator": ["./first.cjs?selected=%2f", "./fallback.cjs"],
},
}),
"main.cjs": "module.exports = 1;",
"fallback.cjs": "module.exports = 1;",
"first.cjs": "module.exports = 2;",
});
const inventoried = inventory(contents);
for (const [specifier, code] of [
["#escape", "ERR_INVALID_PACKAGE_TARGET"],
["#separator", "ERR_INVALID_MODULE_SPECIFIER"],
] as const) {
expect(
(await nodeRequireTarget(join(root, "main.cjs"), specifier)).error_code,
).toBe(code);
expect((await nodeImportTarget(root, specifier)).error_code).toBe(code);
for (const moduleKind of ["require", "import"] as const)
expect(
resolveAlias(inventoried, specifier, "main.cjs", moduleKind),
).toMatchObject({ resolution_status: "rejected", resolved_path: null });
}
expect(
(await nodeRequireTarget(join(root, "main.cjs"), "#missing")).error_code,
).toBe("MODULE_NOT_FOUND");
const imported = await nodeImportTarget(root, "#missing");
expect(posixRelative(root, fileURLToPath(imported.target ?? ""))).toBe(
"missing.cjs",
);
for (const moduleKind of ["require", "import"] as const)
expect(
resolveAlias(inventoried, "#missing", "main.cjs", moduleKind),
).toMatchObject({
resolution_status: "not-found",
resolved_path: null,
limitations: [expect.stringContaining("missing.cjs")],
});
expect(
resolveAlias(
inventoried,
"#escape",
"main.cjs",
"require",
).limitations.join(" "),
).toContain(JSON.stringify("./.\t./outside.cjs"));
expect(
(await nodeRequireTarget(join(root, "main.cjs"), "#query-separator"))
.error_code,
).toBe("ERR_INVALID_MODULE_SPECIFIER");
expect(
resolveAlias(inventoried, "#query-separator", "main.cjs", "require"),
).toMatchObject({ resolution_status: "rejected", resolved_path: null });
const withQuery = await nodeImportTarget(root, "#query-separator");
expect(posixRelative(root, fileURLToPath(withQuery.target ?? ""))).toBe(
"first.cjs",
);
expect(
resolveAlias(inventoried, "#query-separator", "main.cjs", "import"),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "first.cjs",
});
expect(
resolveAlias(
inventoried,
"#missing",
"main.cjs",
"require",
).limitations.join(" "),
).toContain(JSON.stringify("./miss\ting.cjs"));
});
});
describe("package import aliases compared with Node", () => {
it("matches Node require and import for an exact root alias", async () => {
const root = await createTestTempDirectory("rea-import-alias-root-");
const files = {
"package.json": JSON.stringify({
name: "app",
imports: { "#config": "./config.cjs" },
}),
"main.cjs": 'module.exports = require("#config");',
"config.cjs": "module.exports = 'config.cjs';",
};
const contents = await writeTree(root, files);
const inventoried = inventory(contents);
const required = await nodeRequireTarget(join(root, "main.cjs"), "#config");
expect(posixRelative(root, required.target ?? "")).toBe("config.cjs");
expect(
resolveAlias(inventoried, "#config", "main.cjs", "require"),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "config.cjs",
});
const imported = await nodeImportTarget(root, "#config");
expect(imported.error_code).toBeNull();
expect(
resolveAlias(inventoried, "#config", "main.cjs", "import"),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "config.cjs",
});
});
it("matches Node when a nested package has its own imports map", async () => {
const root = await createTestTempDirectory("rea-import-alias-nested-");
const files = {
"package.json": JSON.stringify({
name: "app",
imports: { "#config": "./root.cjs" },
}),
"root.cjs": "module.exports = 'root';",
"node_modules/fixture/package.json": JSON.stringify({
name: "fixture",
imports: { "#config": "./local.cjs" },
}),
"node_modules/fixture/index.cjs": 'module.exports = require("#config");',
"node_modules/fixture/local.cjs": "module.exports = 'local';",
};
const contents = await writeTree(root, files);
const inventoried = inventory(contents);
const nested = await nodeRequireTarget(
join(root, "node_modules/fixture/index.cjs"),
"#config",
);
expect(posixRelative(root, nested.target ?? "")).toBe(
"node_modules/fixture/local.cjs",
);
expect(
resolveAlias(
inventoried,
"#config",
"node_modules/fixture/index.cjs",
"require",
),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "node_modules/fixture/local.cjs",
});
const fromRoot = await nodeRequireTarget(join(root, "root.cjs"), "#config");
expect(posixRelative(root, fromRoot.target ?? "")).toBe("root.cjs");
expect(
resolveAlias(inventoried, "#config", "root.cjs", "require"),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "root.cjs",
});
});
it("matches Node when a nested package does not define the alias", async () => {
const root = await createTestTempDirectory("rea-import-alias-scope-");
const files = {
"package.json": JSON.stringify({
name: "app",
imports: { "#config": "./root.cjs" },
}),
"root.cjs": "module.exports = 'root';",
"node_modules/fixture/package.json": JSON.stringify({
name: "fixture",
}),
"node_modules/fixture/index.cjs": 'module.exports = require("#config");',
};
await writeTree(root, files);
const nested = await nodeRequireTarget(
join(root, "node_modules/fixture/index.cjs"),
"#config",
);
expect(nested.target).toBeNull();
// CJS reports MODULE_NOT_FOUND when the nested package.json has no
// `imports` field at all; it still does not inherit the ancestor map.
expect(nested.error_code).toBe("MODULE_NOT_FOUND");
const outcome = resolveAlias(
inventory(new Map(Object.entries(files))),
"#config",
"node_modules/fixture/index.cjs",
"require",
);
expect(outcome).toMatchObject({
resolution_status: "external",
resolved_path: null,
});
expect(outcome.limitations.join(" ")).toContain(
"node_modules/fixture/package.json",
);
});
});
describe("package import alias refusals compared with Node", () => {
it("matches Node refusal for a missing key, explicit null, and reserved specifier", async () => {
const root = await createTestTempDirectory("rea-import-alias-refuse-");
const files = {
"package.json": JSON.stringify({
name: "app",
imports: {
"#config": "./config.cjs",
"#blocked": null,
"#": "./config.cjs",
"#/": "./config.cjs",
"#config/": "./config.cjs",
},
}),
"main.cjs": "module.exports = 1;",
"config.cjs": "module.exports = 1;",
};
await writeTree(root, files);
const inventoried = inventory(new Map(Object.entries(files)));
const missing = await nodeRequireTarget(join(root, "main.cjs"), "#missing");
expect(missing.error_code).toBe("ERR_PACKAGE_IMPORT_NOT_DEFINED");
expect(
resolveAlias(inventoried, "#missing", "main.cjs", "require"),
).toMatchObject({ resolution_status: "external", resolved_path: null });
const blocked = await nodeRequireTarget(join(root, "main.cjs"), "#blocked");
expect(blocked.error_code).toBe("ERR_PACKAGE_IMPORT_NOT_DEFINED");
expect(
resolveAlias(inventoried, "#blocked", "main.cjs", "require"),
).toMatchObject({ resolution_status: "external", resolved_path: null });
for (const specifier of ["#", "#/", "#config/"]) {
const reserved = await nodeRequireTarget(
join(root, "main.cjs"),
specifier,
);
expect(reserved.error_code).toBe("ERR_INVALID_MODULE_SPECIFIER");
expect((await nodeImportTarget(root, specifier)).error_code).toBe(
"ERR_INVALID_MODULE_SPECIFIER",
);
for (const moduleKind of ["require", "import"] as const)
expect(
resolveAlias(inventoried, specifier, "main.cjs", moduleKind),
).toMatchObject({ resolution_status: "rejected", resolved_path: null });
}
});
it("matches Node when an import condition selects a different exact file", async () => {
const root = await createTestTempDirectory("rea-import-alias-cond-");
const files = {
"package.json": JSON.stringify({
name: "app",
type: "module",
imports: {
"#config": {
import: "./config.mjs",
require: "./config.cjs",
},
},
}),
"main.cjs": 'module.exports = require("#config");',
"config.cjs": "export default 'cjs'; module.exports = 'cjs';",
"config.mjs": "export default 'mjs';",
};
await writeTree(root, files);
const inventoried = inventory(new Map(Object.entries(files)));
const required = await nodeRequireTarget(join(root, "main.cjs"), "#config");
expect(posixRelative(root, required.target ?? "")).toBe("config.cjs");
expect(
resolveAlias(inventoried, "#config", "main.cjs", "require"),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "config.cjs",
});
const imported = await nodeImportTarget(root, "#config");
expect(imported.error_code).toBeNull();
expect(imported.target ?? "").toContain("config.mjs");
expect(
resolveAlias(inventoried, "#config", "main.cjs", "import"),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "config.mjs",
});
});
});
+18 -14
View File
@@ -50,6 +50,8 @@ const contract: ToolContract = {
accessesNetwork: false,
changesUiState: false,
mayDiscardData: false,
executesForeignCode: false,
mutatesDevice: false,
idempotent: true,
},
annotations: {
@@ -336,20 +338,22 @@ describe("tool result projection", () => {
const result = delivery.toCallToolResult(
err(
new HopperProcessError(80, {
component: "hopper_private_display",
operation: "launch",
status: "error",
failure_code: "x11_socket_directory_unusable",
reason: "socket_directory_read_only",
socket_directory: "/tmp/.X11-unix",
socket_directory_mode: "0777",
mount_read_only: true,
effective_socket_directory_mode: "1777",
effective_mount_read_only: false,
wsl: true,
strategy: "user-mount-namespace",
fallback_reason: null,
xvfb_stderr_bytes: 512,
diagnostic: {
component: "hopper_private_display",
operation: "launch",
status: "error",
failure_code: "x11_socket_directory_unusable",
reason: "socket_directory_read_only",
socket_directory: "/tmp/.X11-unix",
socket_directory_mode: "0777",
mount_read_only: true,
effective_socket_directory_mode: "1777",
effective_mount_read_only: false,
wsl: true,
strategy: "user-mount-namespace",
fallback_reason: null,
xvfb_stderr_bytes: 512,
},
}),
),
contract,
+15 -1
View File
@@ -73,7 +73,7 @@ function expectKnownAuthorityHints(tools: readonly ToolSchemas[]): void {
},
annotate_native_function: {
readOnlyHint: false,
destructiveHint: false,
destructiveHint: true,
idempotentHint: true,
openWorldHint: true,
},
@@ -102,8 +102,22 @@ function expectKnownAuthorityHints(tools: readonly ToolSchemas[]): void {
openWorldHint: false,
},
capture_process_scenario: {
readOnlyHint: false,
destructiveHint: true,
openWorldHint: true,
},
observe_native_calls: {
readOnlyHint: false,
destructiveHint: true,
},
uninstall_adb_package: {
readOnlyHint: false,
destructiveHint: true,
},
start_adb_app: {
readOnlyHint: false,
destructiveHint: true,
},
export_evidence_bundle: {
readOnlyHint: false,
destructiveHint: true,
@@ -0,0 +1,131 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it as test, onTestFinished } from "vitest";
import { androidResultSchemas } from "../../../src/domain/android/androidAnalysis.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import {
createJadxProtocolFixture,
verifyJadxFixtureCleanup,
} from "../../fixtures/android/jadx.js";
const INVENTORY_CLASS_COUNT = 7096;
/** Count inventoried names across raw call records: MCP pages ride in text content. */
const rawInventoryNames = (raw: unknown): number => {
const calls =
(
raw as {
calls?: {
operation: string;
response: { content?: { text?: string }[] };
}[];
}
).calls ?? [];
return calls
.flatMap((call) => call.response.content ?? [])
.map((entry) =>
entry.text === undefined ? {} : (JSON.parse(entry.text) as unknown),
)
.filter((page) => Array.isArray((page as { items?: unknown[] }).items))
.flatMap((page) => (page as { items: unknown[] }).items).length;
};
test("delivers bounded search_android_classes Evidence while retaining the complete inventory", async () => {
const { provider, apk, launches } = await createJadxProtocolFixture(
"normal",
undefined,
{ classCount: INVENTORY_CLASS_COUNT - 1 },
);
const session = createTestBinarySession(() => {
throw new Error("APK analysis must not acquire a deep binary provider");
});
const server = createServer(
{ kind: "session", session },
{ androidAnalysis: provider },
);
const client = new Client({
name: "android-search-inventory-budget",
version: "1",
});
onTestFinished(async () => {
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const search = async (query: string) =>
parseEvidence(
(
await client.callTool({
name: "search_android_classes",
arguments: { path: apk, query },
})
).structuredContent,
);
const single = await search("Target");
expect(
androidResultSchemas.search_android_classes.parse(single.normalized_result),
).toMatchObject({
query: "Target",
total_classes: INVENTORY_CLASS_COUNT,
matches: ["fixture.Target"],
coverage: "complete",
});
// The inline raw record keeps the pagination audit, not the class names.
const singleRaw = JSON.stringify(single.raw_result);
expect(singleRaw).not.toContain("fixture.Class");
expect(singleRaw).toContain("items_omitted");
expect(Buffer.byteLength(JSON.stringify(single))).toBeLessThan(32 * 1024);
// The complete inventory stays locally retrievable through the retained record.
const completeId = single.evidence_links[0];
expect(completeId).toBeDefined();
expect(completeId).toBe(
(single.raw_result as { complete_evidence_id: string })
.complete_evidence_id,
);
const complete = session.evidenceById(completeId as string);
expect(complete).toBeDefined();
expect(complete?.operation).toBe("search_android_classes");
expect(rawInventoryNames(complete?.raw_result)).toBe(INVENTORY_CLASS_COUNT);
expect(JSON.stringify(complete?.raw_result)).toContain("fixture.Class7094");
const empty = await search("fixture.Missing");
expect(
androidResultSchemas.search_android_classes.parse(empty.normalized_result),
).toMatchObject({
query: "fixture.Missing",
total_classes: INVENTORY_CLASS_COUNT,
matches: [],
coverage: "complete",
});
expect(JSON.stringify(empty.raw_result)).not.toContain("fixture.Class");
await client.close();
await server.close();
await verifyJadxFixtureCleanup(launches);
});
test("keeps the complete search inventory inline without a retaining session", async () => {
const { service, apk, launches, provider } = await createJadxProtocolFixture(
"normal",
undefined,
{ classCount: INVENTORY_CLASS_COUNT - 1 },
);
const result = await service.execute("search_android_classes", {
path: apk,
query: "Target",
});
if (!result.ok) throw result.error;
// Complete CLI JSON output keeps the full raw provider inventory.
expect(rawInventoryNames(result.value.raw_result)).toBe(
INVENTORY_CLASS_COUNT,
);
await provider.close();
await verifyJadxFixtureCleanup(launches);
});
+97 -1
View File
@@ -8,7 +8,10 @@ import {
runOwnedCommand,
} from "../../../src/process/OwnedCommand.js";
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js";
import {
cleanupOwnedProcessGroup,
type ProcessCleanupResult,
} from "../../../src/process/ProcessOwnership.js";
import { prepareProcessOwnershipInspection } from "../../../src/process/ProcessOwnershipObservation.js";
import { waitForProviderProcessReady } from "../../fixtures/providerProcess.js";
@@ -186,6 +189,99 @@ it("returns a timeout for a running process after independent cleanup", async ()
).rejects.toMatchObject({ reason: "timeout", cleanupFailure: null });
});
it.skipIf(process.platform === "win32").each(["cancelled", "timeout"] as const)(
"retains the real per-member cleanup ledger after %s and settles after cooperative exit",
async (reason) => {
const childScript =
'process.stdin.once("data", () => process.exit(0)); process.stdout.write("child-ready\\n")';
const request = {
...command(`
const { spawn } = require("node:child_process");
const child = spawn(process.execPath, ["-e", ${JSON.stringify(childScript)}], {
env: { ...process.env, REA_PROCESS_RUN_ID: "different-child-owner" },
stdio: ["pipe", "inherit", "inherit"],
});
const release = () => child.stdin.end("release");
process.stdin.once("data", release);
const failsafe = setTimeout(release, 10000);
child.once("exit", () => { clearTimeout(failsafe); process.stdin.destroy(); });
`),
stdin: "pipe" as const,
};
const controller = new AbortController();
let launched:
| Awaited<ReturnType<typeof spawnOwnedProviderProcess>>
| undefined;
let cleanup: ProcessCleanupResult | undefined;
let failure: OwnedCommandFailure | undefined;
try {
await runOwnedCommand(
request,
{ timeoutMs: 2000, diagnosticBytes: 1024 },
{
signal: controller.signal,
launcher: async (input) => {
const acquired = await spawnOwnedProviderProcess(input);
launched = acquired;
acquired.process.stdout?.on("data", (chunk: Buffer) => {
if (
reason === "cancelled" &&
chunk.toString().includes("child-ready")
)
controller.abort();
});
return {
...acquired,
cleanup: async () => {
const observed = await cleanupOwnedProcessGroup(
acquired.ownership,
);
cleanup ??= observed;
return observed;
},
};
},
},
).catch((cause: unknown) => {
if (!(cause instanceof OwnedCommandFailure)) throw cause;
failure = cause;
});
if (failure === undefined || launched === undefined)
throw new Error(
"The acquired command must retain its failed cleanup owner",
);
expect(failure.reason).toBe(reason);
expect(failure.snapshot?.stdout.text).toContain("child-ready");
expect(cleanup).toMatchObject({
cleaned: false,
failures: [expect.objectContaining({ reason: "run-token-mismatch" })],
});
expect(failure.cleanupResult).toEqual(cleanup);
expect(failure.resources).toEqual(
expect.arrayContaining([request.runId]),
);
// An unresolved member does not grant authority to signal the shared group.
const acquiredPid = launched.ownership.leaderPid;
expect(() => process.kill(acquiredPid, 0)).not.toThrow();
if (cleanup?.cleaned === false) {
for (const member of cleanup.failures ?? []) {
expect(() => process.kill(member.pid, 0)).not.toThrow();
expect(failure.cleanupFailure).toContain(String(member.pid));
}
}
} finally {
// Release through the fixture's acquired input channel, never by an unverified PID.
launched?.process.stdin?.end("release");
if (failure?.cleanupOwner !== undefined) {
expect(await failure.cleanupOwner.waitForOutputClose(5000)).toBe(true);
expect(await failure.cleanupOwner.stop()).toEqual({
status: "verified-cleanup",
});
}
}
},
);
it("honors cancellation during cleanup after a successful command", async () => {
const controller = new AbortController();
await expect(
@@ -358,6 +358,57 @@ describe("provider process output and cleanup primitives", () => {
});
});
it("retains member failures and sweep uncertainty from a failed cleanup recheck", async () => {
const child = spawnProviderProcessFixture("stubborn");
await waitForProviderProcessReady(child);
const pid = child.pid;
if (pid === undefined) {
await stopProviderProcessFixture(child);
throw new Error("The acquired ready fixture must have a process ID");
}
const failed = {
cleaned: false as const,
reason: "fixture identity unavailable during recheck",
failures: [
{
pid,
reason: "process-identity-unavailable" as const,
diagnostic: "fixture identity reader unavailable",
},
],
unverified: [
{ pid: 777, diagnostic: "fixture foreign process token unavailable" },
],
};
let attempts = 0;
let release = false;
const supervisor = new ProviderProcessSupervisor({
process: child,
ownsProcessLifetime: true,
cleanup: async () => {
if (release) child.kill("SIGKILL");
attempts += 1;
return release || attempts === 1
? { cleaned: true as const, signaled: release }
: failed;
},
});
try {
await expect(supervisor.stop({ killGraceMs: 20 })).resolves.toEqual({
status: "incomplete",
reason: failed.reason,
cleanupResult: failed,
});
expect(child.exitCode).toBeNull();
release = true;
await expect(supervisor.stop()).resolves.toEqual({
status: "verified-cleanup",
});
} finally {
await stopProviderProcessFixture(child);
}
});
describe("provider process host injection", () => {
it("uses injected host platform and environment when spawning", async () => {
const spawned = await spawnOwnedProviderProcess({
@@ -3,7 +3,6 @@ import { access } from "node:fs/promises";
import { afterEach, describe, expect, it } from "vitest";
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
import { ok } from "../../../../src/domain/result.js";
import type {
BridgeLauncher,
@@ -53,31 +52,6 @@ class OwnedFixtureLauncher implements BridgeLauncher {
}
}
class UnconfirmedFixtureLauncher implements BridgeLauncher {
constructor(readonly ownsProcessLifetime = false) {}
launch(session: BridgeSession) {
return Promise.resolve(
ok({
process: spawn(
process.execPath,
[
fixturePath,
session.socketPath,
session.token,
session.runId,
"unconfirmed",
],
{ stdio: ["ignore", "ignore", "pipe"] },
),
ownsProcessLifetime: this.ownsProcessLifetime,
providerLifetime: "external-application" as const,
shutdownMode: "bridge-request" as const,
}),
);
}
}
const clients: HopperClient[] = [];
afterEach(async () => {
@@ -137,42 +111,6 @@ describe("HopperClient cleanup", () => {
});
});
it.each([
["unowned", false],
["owned helper", true],
] as const)(
"reports unconfirmed external document cleanup for an %s process",
async (_description, ownsProcessLifetime) => {
const client = new HopperClient({
launcher: new UnconfirmedFixtureLauncher(ownsProcessLifetime),
startupTimeoutMs: 1_000,
});
clients.push(client);
expect((await client.start()).ok).toBe(true);
const closed = await client.close();
expect(closed).toMatchObject({
ok: false,
error: {
_tag: "ProviderAdapterError",
cleanupIncomplete: true,
cleanupResources: expect.arrayContaining(["hopper-document"]),
},
});
if (!closed.ok)
expect(projectAnalysisError(closed.error)).toMatchObject({
code: "cleanup_incomplete",
details: {
provider_id: "hopper",
operation: "close_binary",
cleanup: "incomplete",
resources: expect.arrayContaining(["hopper-document"]),
},
});
},
);
it("kills only its owned Hopper group and emits sanitized shutdown coordinates", async () => {
const unrelated = spawn(
process.execPath,
@@ -160,50 +160,71 @@ it("retains failed startup cleanup until an owned process and its backing image
});
});
it("keeps an unconfirmed external document visible across sequential closes", async () => {
const launcher = new RetryCleanupLauncher(true);
const runtimeRoot = await PrivateRuntimeRoot.create();
onTestFinished(() => runtimeRoot.close());
const launched = await launcher.launch({
directory: runtimeRoot.path,
socketPath: join(runtimeRoot.path, "bridge.sock"),
token: "fixture-token",
runId: "fixture-run",
});
if (!launched.ok) throw launched.error;
const child = launched.value.process;
const supervisor = new ProviderProcessSupervisor(launched.value);
onTestFinished(() => supervisor.dispose());
const resources: HopperOwnedResources = {
launch: launched.value,
processSupervisor: supervisor,
runtimeRoot,
shutdownConfirmed: false,
};
for (let attempt = 0; attempt < 2; attempt += 1) {
await expect(
cleanupHopperSession({
socket: undefined,
resources,
activeRequest: null,
retainDocument: false,
progress: undefined,
logger: silentLogger,
onDiagnostic: undefined,
request: () => Promise.resolve(ok(null)),
releaseTransport: (socket) => socket?.destroy(),
}),
).resolves.toMatchObject({
ok: false,
error: { cleanupResources: ["hopper-document", runtimeRoot.path] },
it.each([false, true])(
"keeps an unconfirmed external document across closes when helper ownership is %s",
async (ownsHelper) => {
const launcher = new RetryCleanupLauncher(true);
const runtimeRoot = await PrivateRuntimeRoot.create();
onTestFinished(() => runtimeRoot.close());
const launched = await launcher.launch({
directory: runtimeRoot.path,
socketPath: join(runtimeRoot.path, "bridge.sock"),
token: "fixture-token",
runId: "fixture-run",
});
}
expect(child.exitCode).toBeNull();
expect(child.signalCode).toBeNull();
await expect(
access(join(runtimeRoot.path, "image.macho")),
).resolves.toBeUndefined();
});
if (!launched.ok) throw launched.error;
const child = launched.value.process;
const launch: BridgeLaunch = ownsHelper
? { ...launched.value, ownsProcessLifetime: true }
: launched.value;
const supervisor = new ProviderProcessSupervisor(launch);
onTestFinished(() => supervisor.dispose());
const resources: HopperOwnedResources = {
launch,
processSupervisor: supervisor,
runtimeRoot,
shutdownConfirmed: false,
};
const socket = new Socket();
onTestFinished(() => {
socket.destroy();
});
for (let attempt = 0; attempt < 2; attempt += 1) {
await expect(
cleanupHopperSession({
socket: attempt === 0 ? socket : undefined,
resources,
activeRequest: null,
retainDocument: false,
progress: undefined,
logger: silentLogger,
onDiagnostic: undefined,
request: () =>
Promise.resolve(
ok({
shutdown: true,
analysis_stopped: true,
document_closed: false,
}),
),
releaseTransport: (socket) => socket?.destroy(),
}),
).resolves.toMatchObject({
ok: false,
error: { cleanupResources: ["hopper-document", runtimeRoot.path] },
});
}
if (ownsHelper)
expect(child.exitCode !== null || child.signalCode !== null).toBe(true);
else {
expect(child.exitCode).toBeNull();
expect(child.signalCode).toBeNull();
}
await expect(
access(join(runtimeRoot.path, "image.macho")),
).resolves.toBeUndefined();
},
);
it("blocks a fresh launch while cleanup remains unverified", async () => {
const launcher = new RetryCleanupLauncher();
@@ -1,4 +1,5 @@
import { EventEmitter } from "node:events";
import { PassThrough } from "node:stream";
import { describe, expect, it, onTestFinished, vi } from "vitest";
@@ -12,15 +13,18 @@ import { HopperClient } from "../../../../src/hopper/HopperClient.js";
import { HopperFixtureLauncher } from "./hopperClient.fixture.js";
class ObservedProcess extends EventEmitter {
readonly stdout = null;
readonly stderr = null;
readonly stdout = new PassThrough();
readonly stderr = new PassThrough();
exitCode: number | null = null;
readonly signalCode = null;
signalCode: NodeJS.Signals | null = null;
exit(code: number): void {
exit(code: number | null, signal: NodeJS.Signals | null = null): void {
this.exitCode = code;
this.emit("exit", code, null);
this.emit("close", code, null);
this.signalCode = signal;
this.emit("exit", code, signal);
this.stdout.end();
this.stderr.end();
this.emit("close", code, signal);
}
kill(): boolean {
@@ -66,7 +70,7 @@ describe("Hopper provider lifecycle health", () => {
launcher.observed.exit(0);
const pending = client.callTool("hang");
await launcher.fixture.waitForRequest("hang");
launcher.fixture.processes.at(-1)?.kill("SIGKILL");
launcher.fixture.processes.at(-1)?.send({ disconnect: true });
await vi.waitFor(() =>
expect(client.operationHealth().state).toBe("unreachable"),
);
@@ -92,6 +96,7 @@ describe("Hopper provider lifecycle health", () => {
operation: "procedure_pseudo_code",
},
});
expect((await client.close()).ok).toBe(true);
});
it("projects the exit code when the owned process exit is observed before disconnection", async () => {
@@ -120,6 +125,7 @@ describe("Hopper provider lifecycle health", () => {
stage: "analysis",
operation: "hang",
request_id: request.id,
launcher: { exit_code: 7, signal: null, output_closed: false },
},
});
});
@@ -166,3 +172,52 @@ describe("Hopper provider lifecycle health", () => {
expect(client.operationHealth().state).toBe("idle");
});
});
it("preserves an owned signal exit and diagnostics for active, queued and later callers", async () => {
const { client, launcher } = await start(true);
const active = client.callTool("hang");
const request = await launcher.fixture.waitForRequest("hang");
const queued = client.callTool("echo");
await vi.waitFor(() =>
expect(client.requestActivity()?.queuedRequests).toBe(1),
);
const token = launcher.fixture.tokens[0];
launcher.observed.stderr.write(`API_KEY=local-evidence-kept ${token}\n`);
launcher.observed.exit(null, "SIGTERM");
const results = await Promise.all([active, queued]);
for (const [index, result] of results.entries()) {
if (result.ok) throw new Error("Expected an observed provider exit");
const projected = projectAnalysisError(result.error);
expect(projected).toMatchObject({
code: "provider_unavailable",
message: expect.stringContaining("signal SIGTERM"),
details: {
provider_state: "exited",
operation: index === 0 ? "hang" : "echo",
request_id: request.id + index,
launcher: {
exit_code: null,
signal: "SIGTERM",
output_closed: false,
stderr: {
text: "API_KEY=local-evidence-kept [redacted transport credential]\n",
},
},
},
});
expect(JSON.stringify(projected)).not.toContain(token);
}
const later = await client.callTool("procedure_pseudo_code", {
procedure: "main",
});
if (later.ok) throw new Error("An exited provider must reject later queries");
expect(projectAnalysisError(later.error)).toMatchObject({
code: "provider_unavailable",
details: {
provider_state: "exited",
stage: "decompilation",
operation: "procedure_pseudo_code",
launcher: { signal: "SIGTERM", output_closed: true },
},
});
});
@@ -1,13 +1,68 @@
import { spawn } from "node:child_process";
import { access } from "node:fs/promises";
import { expect, it, onTestFinished } from "vitest";
import { AnalysisError } from "../../../../src/domain/analysisErrorBase.js";
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
import { ok } from "../../../../src/domain/result.js";
import type { BridgeLauncher } from "../../../../src/hopper/BridgeLauncher.js";
import type {
BridgeLauncher,
BridgeSession,
} from "../../../../src/hopper/BridgeLauncher.js";
import { HopperApplicationLauncher } from "../../../../src/hopper/BridgeLauncher.js";
import { HopperClient } from "../../../../src/hopper/HopperClient.js";
import { HopperFixtureLauncher } from "./hopperClient.fixture.js";
// Failure assertions keep the external document unknown. Teardown then publishes
// this run's authenticated bridge so normal cleanup can release its runtime/lease.
const trackFailedHelperClient = (
launcher: BridgeLauncher,
startupTimeoutMs = 10_000,
): HopperClient => {
let session: BridgeSession | undefined;
let external = false;
const client = new HopperClient({
launcher: {
async launch(input, options) {
session = input;
const launched = await launcher.launch(input, options);
external =
launched.ok &&
launched.value.providerLifetime === "external-application";
return launched;
},
},
startupTimeoutMs,
});
onTestFinished(async () => {
const fixture = new HopperFixtureLauncher();
const published =
external && session !== undefined
? await fixture.launch(session)
: undefined;
try {
const closed = await client.close();
if (!closed.ok) throw closed.error;
if (published !== undefined) {
expect(fixture.requests.map((request) => request.method)).toEqual([
"health",
"shutdown_document",
]);
}
if (session !== undefined)
await expect(access(session.directory)).rejects.toMatchObject({
code: "ENOENT",
});
} finally {
if (published?.ok) {
const cleaned = await published.value.cleanup();
expect(cleaned.cleaned).toBe(true);
}
}
});
return client;
};
const projectPrimaryStartupFailure = (error: AnalysisError) => {
if (!error.cleanupIncomplete) return projectAnalysisError(error);
@@ -32,10 +87,7 @@ it("does not equate an owned native helper exit with an external GUI exit", asyn
bridgeScriptPath: "/rea/hopper_bridge.py",
launchMode: "native",
});
const client = new HopperClient({ launcher, startupTimeoutMs: 10_000 });
onTestFinished(async () => {
await client.close();
}, 45_000);
const client = trackFailedHelperClient(launcher);
const result = await client.start();
expect(result).toMatchObject({
ok: false,
@@ -84,10 +136,7 @@ it.each(["exit", "signal", "exit75"] as const)(
);
},
};
const client = new HopperClient({ launcher, startupTimeoutMs: 10_000 });
onTestFinished(async () => {
await client.close();
}, 45_000);
const client = trackFailedHelperClient(launcher);
const result = await client.start();
expect(result).toMatchObject({
ok: false,
@@ -136,10 +185,7 @@ it.each([0, 1])(
);
},
};
const client = new HopperClient({ launcher, startupTimeoutMs: 10_000 });
onTestFinished(async () => {
await client.close();
}, 45_000);
const client = trackFailedHelperClient(launcher);
const result = await client.start();
expect(result).toMatchObject({
ok: false,
@@ -174,10 +220,7 @@ it("preserves a successful helper's diagnostics when bridge readiness is never o
);
},
};
const client = new HopperClient({ launcher, startupTimeoutMs: 1500 });
onTestFinished(async () => {
await client.close();
}, 45_000);
const client = trackFailedHelperClient(launcher, 1500);
const result = await client.start();
if (result.ok)
throw new Error("Expected missing bridge readiness to time out");
@@ -53,10 +53,7 @@ class CancelThenFixtureLauncher implements BridgeLauncher {
}
class ExitingLauncher implements BridgeLauncher {
constructor(
readonly code: number,
readonly ownsProcessLifetime = true,
) {}
constructor(readonly code: number) {}
launch() {
return Promise.resolve(
@@ -64,10 +61,8 @@ class ExitingLauncher implements BridgeLauncher {
process: spawn(process.execPath, ["-e", `process.exit(${this.code})`], {
stdio: ["ignore", "ignore", "pipe"],
}),
ownsProcessLifetime: this.ownsProcessLifetime,
providerLifetime: this.ownsProcessLifetime
? ("launcher-process" as const)
: ("external-application" as const),
ownsProcessLifetime: true as const,
providerLifetime: "launcher-process" as const,
shutdownMode: "bridge-request" as const,
}),
);
@@ -286,21 +281,4 @@ describe("HopperClient startup failures", () => {
},
});
});
it("allows a short-lived launcher to hand off bridge startup", async () => {
const client = new HopperClient({
launcher: new ExitingLauncher(0, false),
startupTimeoutMs: 100,
});
clients.push(client);
const result = await client.start();
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toMatchObject({
cleanupIncomplete: true,
cause: { _tag: "HopperTimeoutError" },
diagnostics: { primary_error: { code: "provider_timeout" } },
});
}
});
});
@@ -218,6 +218,8 @@ const lipoRunner = (stdout: string): NativeCommandRunner => ({
// the same slice `arm64e`, and its physical identity must still match.
describe("artifact Mach-O arm64e variant slices", () => {
const ARM64E_V1 = { type: 0x0100000c, subtype: 0x81000002 } as const;
// CPU_SUBTYPE_ARM64E_X1 (12) with the pointer-auth ABI bit, as in macOS 27 /bin/ls.
const ARM64E_X1 = { type: 0x0100000c, subtype: 0x8000000c } as const;
const variantSlices = async (
cpu: { readonly type: number; readonly subtype: number },
lipo: (size: number) => string,
@@ -249,24 +251,29 @@ describe("artifact Mach-O arm64e variant slices", () => {
it.each([
[
"arm64e.v1",
ARM64E_V1,
" cputype CPU_TYPE_ARM64\n cpusubtype CPU_SUBTYPE_ARM64E\n capabilities PTR_AUTH_VERSION USERSPACE 1",
],
[
"arm64e.x1",
ARM64E_X1,
" cputype CPU_TYPE_ARM64\n cpusubtype unknown arm64 cpusubtype",
],
])("accepts lipo's %s name for the FAT arm64e slice", async (name, cpu) => {
expect(
await variantSlices(
ARM64E_V1,
(size) =>
`architecture ${name}\n${cpu}\n offset 8192\n size ${String(size)}\n align 2^12 (4096)\n`,
),
).toEqual([
["slices/x86_64", 4096],
[`slices/${name}`, 8192],
]);
});
])(
"accepts lipo's %s name for the FAT arm64e slice",
async (name, fatCpu, cpu) => {
expect(
await variantSlices(
fatCpu,
(size) =>
`architecture ${name}\n${cpu}\n offset 8192\n size ${String(size)}\n align 2^12 (4096)\n`,
),
).toEqual([
["slices/x86_64", 4096],
[`slices/${name}`, 8192],
]);
},
);
it.each([
["a plain arm64 slice", CPU.arm64, "8192"],
+36 -27
View File
@@ -161,21 +161,17 @@ describe("incremental module import boundaries", () => {
["src/application/probe.ts", "../browser/CdpCaptureValues.js", true],
["src/ghidra/probe.ts", "../generatedPackageMetadata.js", true],
["src/hopper/probe.ts", "../contracts/officialToolContracts.js", true],
])("checks %s importing %s", async (file, dependency, allowed) => {
const temporary = await createTestTempDirectory("rea-module-boundary-");
const fixture = join(temporary, file);
await mkdir(dirname(fixture), { recursive: true });
await writeFile(
fixture,
])("checks %s importing %s", (file, dependency, allowed) => {
const violations = inspectModuleBoundaries(
file,
`import { value } from ${JSON.stringify(dependency)}; export { value };\n`,
process.cwd(),
);
const result = spawnSync(process.execPath, [verifier, file], {
cwd: temporary,
encoding: "utf8",
});
if (result.error !== undefined) throw result.error;
expect(result.status).toBe(allowed ? 0 : 1);
if (!allowed) expect(result.stderr).toContain("resolves to src/");
if (allowed) expect(violations).toEqual([]);
else
expect(violations).toMatchObject([
{ file, boundary: expect.any(String) },
]);
});
});
@@ -282,21 +278,25 @@ describe("module import syntax and source discovery", () => {
});
describe("test lane import boundaries", () => {
it.each([
const cases: Array<[string, string, boolean]> = [
["src/application/probe.test.ts", "../server/createServer.js", false],
["tests/composition/probe.test.ts", "node:child_process", false],
["tests/composition/probe.test.ts", "node:net", false],
["tests/composition/probe.test.ts", "playwright", false],
["tests/composition/probe.test.ts", "../../src/domain/result.js", true],
])("checks %s importing %s", async (file, dependency, allowed) => {
["tests/composition/process.test.ts", "node:child_process", false],
["tests/composition/net.test.ts", "node:net", false],
["tests/composition/browser.test.ts", "playwright", false],
["tests/composition/domain.test.ts", "../../src/domain/result.js", true],
];
it("checks the test-lane import matrix in one lint invocation", async () => {
const temporary = await createTestTempDirectory("rea-test-lane-");
const config = join(temporary, ".oxlintrc.json");
await copyFile(resolve(".oxlintrc.json"), config);
await mkdir(dirname(join(temporary, file)), { recursive: true });
await writeFile(
join(temporary, file),
`import { value } from ${JSON.stringify(dependency)}; export { value };\n`,
);
for (const [file, dependency] of cases) {
await mkdir(dirname(join(temporary, file)), { recursive: true });
await writeFile(
join(temporary, file),
`import { value } from ${JSON.stringify(dependency)}; export { value };\n`,
);
}
const result = spawnSync(
process.execPath,
[
@@ -305,13 +305,22 @@ describe("test lane import boundaries", () => {
config,
"--format",
"json",
file,
...cases.map(([file]) => file),
],
{ cwd: temporary, encoding: "utf8" },
);
if (result.error !== undefined) throw result.error;
expect(result.status).toBe(allowed ? 0 : 1);
if (!allowed) expect(result.stdout).toContain("no-restricted-imports");
const report = JSON.parse(result.stdout) as {
diagnostics: Array<{ filename: string; code: string }>;
};
const violations = new Set(
report.diagnostics
.filter(({ code }) => code === "eslint(no-restricted-imports)")
.map(({ filename }) => filename.replaceAll("\\", "/")),
);
for (const [file, , allowed] of cases)
expect(violations.has(file)).toBe(!allowed);
expect(result.status).toBe(cases.some(([, , allowed]) => !allowed) ? 1 : 0);
});
});
+11 -1
View File
@@ -10,10 +10,20 @@ const server = new McpServer({
version:
mode === "empty-server-identity" ? "" : mode === "version" ? "99.0.0" : "1",
});
const requestedCount = Number.parseInt(
process.env.REA_FAKE_JADX_CLASS_COUNT ?? "",
10,
);
const generatedCount =
Number.isInteger(requestedCount) && requestedCount >= 0
? requestedCount
: mode === "large-inventory"
? 9000
: 400;
const classes = [
"fixture.Target",
...Array.from(
{ length: mode === "large-inventory" ? 9000 : 400 },
{ length: generatedCount },
(_, index) => `fixture.Class${index}`,
),
];
+10 -1
View File
@@ -27,6 +27,7 @@ const fixture = fileURLToPath(new URL("./jadx-mcp.mjs", import.meta.url));
export const createJadxProtocolFixture = async (
mode = "normal",
cleanupFailure?: () => boolean,
inventory?: { readonly classCount?: number },
) => {
const root = await createTestTempDirectory("rea-android-boundary-");
const apk = join(root, "fixture.apk");
@@ -64,7 +65,15 @@ export const createJadxProtocolFixture = async (
command: process.execPath,
arguments: [fixture],
expectedCommand: process.execPath,
env: { ...options.env, REA_FAKE_JADX_MODE: mode },
env: {
...options.env,
REA_FAKE_JADX_MODE: mode,
...(inventory?.classCount === undefined
? {}
: {
REA_FAKE_JADX_CLASS_COUNT: String(inventory.classCount),
}),
},
});
launches.push({
runId: options.runId,
+7
View File
@@ -10,8 +10,13 @@ const [
] = process.argv.slice(2);
let diagnosticOutputEmitted = false;
const heldReplies = new Map();
const sockets = new Set();
if (process.send !== undefined)
process.on("message", (message) => {
if (message?.disconnect === true) {
for (const socket of sockets) socket.destroy();
return;
}
const reply = heldReplies.get(message?.release);
if (reply === undefined) return;
heldReplies.delete(message.release);
@@ -173,6 +178,8 @@ const sendEchoWithProgress = (send, request) => {
};
const server = createServer((socket) => {
sockets.add(socket);
socket.once("close", () => sockets.delete(socket));
socket.on("error", () => undefined);
socket.setEncoding("utf8");
let buffer = "";
-160
View File
@@ -1,160 +0,0 @@
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
import { expect } from "vitest";
import { z } from "zod";
import { keyedArchiveResultSchema } from "../../src/domain/apple/keyedArchive.js";
const rowSchema = z.object({
container: z.enum(["roots", "objects"]),
root: z.string(),
objectId: z.number().int().nonnegative().optional(),
path: z.array(z.union([z.string(), z.number().int().nonnegative()])),
kind: z.enum(["integer", "real"]),
literal: z.string(),
});
const archiveSchema = z.object({
filename: z.string(),
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
rows: z.array(rowSchema),
});
const oracleSchema = z.object({ xml: archiveSchema, binary: archiveSchema });
export const keyedArchiveIntegerFormats = ["xml", "binary"] as const;
export const keyedArchiveIntegerCases = ["controls", "unsafe"] as const;
type Case = (typeof keyedArchiveIntegerCases)[number];
type Row = z.infer<typeof rowSchema>;
type SelectedFixture = {
readonly root: string;
readonly selected: z.infer<typeof archiveSchema>;
readonly archivePath: string;
readonly digest: string;
};
export interface KeyedArchiveIntegerFixtures {
readonly xml: SelectedFixture;
readonly binary: SelectedFixture;
}
export const keyedArchiveIntegerFixtures = async (
root: string,
): Promise<KeyedArchiveIntegerFixtures> => {
await promisify(execFile)(
"/usr/bin/xcrun",
[
"swift",
"-module-cache-path",
join(root, "modules"),
"tests/conformance/native/keyed-archive-integers.swift",
root,
],
{ maxBuffer: 1024 * 1024 },
);
const oracle = oracleSchema.parse(
JSON.parse(await readFile(join(root, "oracle.json"), "utf8")),
);
for (const entry of [oracle.xml, oracle.binary]) {
expect(entry.rows).toContainEqual(
expect.objectContaining({
root: "unsafeSigned",
kind: "integer",
literal: "9007199254740993",
}),
);
expect(entry.rows).toContainEqual(
expect.objectContaining({
root: "unsafeNegative",
kind: "integer",
literal: "-9223372036854775808",
}),
);
expect(
entry.rows.some(
(row) =>
row.root === "boxedUnsigned" &&
row.kind === "integer" &&
row.literal === "9007199254740993",
),
).toBe(true);
expect(
entry.rows.some(
(row) =>
row.root === "boxedReal" &&
row.kind === "real" &&
Number(row.literal) === 9007199254740992,
),
).toBe(true);
}
const selectedFixture = async (
selected: z.infer<typeof archiveSchema>,
): Promise<SelectedFixture> => {
const archivePath = join(root, selected.filename);
const bytes = await readFile(archivePath);
const digest = createHash("sha256").update(bytes).digest("hex");
expect(digest).toBe(selected.sha256);
return { root, selected, archivePath, digest };
};
return {
xml: await selectedFixture(oracle.xml),
binary: await selectedFixture(oracle.binary),
};
};
const at = (value: unknown, path: Row["path"]): unknown => {
for (const key of path) {
if (value === null || typeof value !== "object") return undefined;
value = (value as Record<string | number, unknown>)[key];
}
return value;
};
export const expectKeyedArchiveIntegerCase = (
result: z.infer<typeof keyedArchiveResultSchema>,
selectedCase: Case,
selected: z.infer<typeof archiveSchema>,
digest: string,
) => {
expect(result.archive_sha256).toBe(digest);
const unsafe = (row: Row) =>
row.kind === "integer" &&
(BigInt(row.literal) > BigInt(Number.MAX_SAFE_INTEGER) ||
BigInt(row.literal) < BigInt(Number.MIN_SAFE_INTEGER));
const rows = selected.rows.filter((row) =>
selectedCase === "unsafe" ? unsafe(row) : !unsafe(row),
);
expect(rows.length).toBeGreaterThan(0);
for (const row of rows) {
const value = at(
row.container === "roots"
? result.roots
: result.objects.find((object) => object.id === row.objectId)?.value,
row.path,
);
expect(
value,
`${row.root} numeric slot remains present`,
).not.toBeUndefined();
if (unsafe(row)) {
const exact =
typeof value === "object" &&
value !== null &&
(value as Record<string, unknown>).$plist_type === "integer" &&
(value as Record<string, unknown>).decimal ===
BigInt(row.literal).toString();
// The accepted alternate contract must explicitly disclose numeric precision loss.
const disclosed = result.limitations.some(
(reason) =>
/integer|number/iu.test(reason) &&
/precision|exact range|rounded/iu.test(reason),
);
expect(
exact || disclosed,
`${row.root} ${row.literal} must be exact or disclose numeric loss`,
).toBe(true);
} else {
expect(typeof value, `${row.root} retains its numeric type`).toBe(
"number",
);
expect(value).toBe(Number(row.literal));
}
}
};