docs: preserve relative guide links through README relocation

This commit is contained in:
morluto
2026-10-13 22:59:54 +08:00
234 changed files with 12178 additions and 1977 deletions
+86
View File
@@ -7,6 +7,7 @@ import {
aotFixtureImage,
engineFixtureImage,
REFERENCE_HASH,
appendElfRanges,
} from "../../src/flutter/FlutterBuild.fixture.js";
import {
createFlutterApk,
@@ -159,3 +160,88 @@ cliTest(
).toEqual([4, 4]);
},
);
cliTest(
"CLI and MCP qualify conflicting load mappings and bounded ELF notes",
async ({ cli }) => {
const note = Buffer.from(
"040000000800000003000000474e55000123456789abcdef",
"hex",
);
const engine = engineFixtureImage({
notes: Buffer.concat([note, Buffer.alloc(2000)]),
});
const denseEngine = appendElfRanges(
engine,
"program",
Array.from({ length: 2000 }, (_, index) => ({
type: 4,
offset: 0x400 + note.length + index,
size: 1,
})),
);
const { call } = await connectLocalToolsMcp();
for (const conflict of [false, true]) {
const image = appendElfRanges(aotFixtureImage(), "program", [
{
type: 1,
address: 0x2010,
offset: conflict ? 0x1010 : 0x2010,
size: 4,
},
]);
const path = await createFlutterApk(`load-${String(conflict)}.apk`, [
{ path: "lib/x86_64/libapp.so", bytes: image },
{
path: "lib/x86_64/libflutter.so",
bytes: conflict ? denseEngine : engine,
},
]);
for (const name of [
"inspect_dart_aot",
"identify_flutter_build",
] as const) {
const result = await cli.run({
arguments: [name.replaceAll("_", "-"), path, "--json"],
});
expect(result.exitCode, result.stderr).toBe(0);
const evidence = toolContract(name).outputSchema.parse(result.json);
const response = await call(name, { path });
expect(response.isError, JSON.stringify(response)).not.toBe(true);
const mcp = parseEvidence(response.structuredContent);
expect(mcp.normalized_result).toEqual(evidence.normalized_result);
expect(mcp.evidence_id).toBe(evidence.evidence_id);
expect(mcp.subject).toEqual(evidence.subject);
expect(mcp.limitations).toEqual(evidence.limitations);
expect(evidence.normalized_result.coverage).toBe(
conflict ? "partial" : "complete",
);
if (name === "inspect_dart_aot") {
const facts = flutterResultSchemas[name].parse(
evidence.normalized_result,
);
expect(facts.libapp.sections).toHaveLength(conflict ? 3 : 4);
expect(facts.string_pool.coverage).toBe(
conflict ? "partial" : "complete",
);
if (conflict) {
expect(facts.string_pool.package_uris).toEqual([]);
expect(evidence.limitations.join("\n")).toContain(
"conflicting PT_LOAD",
);
}
} else {
const facts = flutterResultSchemas[name].parse(
evidence.normalized_result,
);
expect(facts.abis[0]?.libflutter).toMatchObject({
build_id: conflict ? null : "0123456789abcdef",
build_id_candidates: ["0123456789abcdef"],
});
if (conflict)
expect(evidence.limitations.join("\n")).toContain("note-range");
}
}
}
},
);
+304
View File
@@ -0,0 +1,304 @@
import { expect, it } from "vitest";
import {
analyzeJadxRequest,
type JadxToolPort,
} from "../../../src/android/JadxAnalysis.js";
import { androidInputSchemas } from "../../../src/domain/android/androidAnalysis.js";
const summary = {
full_name: "fixture.Target",
name: "Target",
method_count: 2,
field_count: 0,
inner_class_count: 0,
methods: [
{
name: "choose",
signature: "choose(String): void",
dex_descriptor: "(Ljava/lang/String;)V",
is_constructor: false,
def_pos: 0,
},
{
name: "choose",
signature: "choose(int): void",
dex_descriptor: "(I)V",
is_constructor: false,
def_pos: 0,
},
],
fields: [],
inner_classes: [],
};
const engine = {
name: "jadx",
version: "0.7.1",
artifact_sha256: "a".repeat(64),
source_revision: null,
worker_count: 1,
heap_limit_mib: null,
};
it("publishes exact DEX prototypes instead of discarding bridge metadata", async () => {
const tools: JadxToolPort = {
json: () => Promise.resolve(summary),
text: () => Promise.reject(new Error("unexpected text call")),
};
const result = await analyzeJadxRequest(
tools,
{
operation: "inspect_android_class",
input: androidInputSchemas.inspect_android_class.parse({
path: "/fixture.apk",
class_name: "fixture.Target",
}),
},
{} as never,
engine,
);
expect(result).toMatchObject({
methods: [
{ name: "choose", dex_descriptor: "(Ljava/lang/String;)V" },
{ name: "choose", dex_descriptor: "(I)V" },
],
});
});
it("traces only the selected overloaded method and checks the producer identity", async () => {
const calls: Record<string, unknown>[] = [];
const tools: JadxToolPort = {
json: (name, input) => {
calls.push({ name, ...input });
if (name === "get_class_summary") return Promise.resolve(summary);
return Promise.resolve({
target: "fixture.Target.choose",
overload_index: 1,
reported_signature: "choose(int): void",
total: 1,
count: 1,
resolve_line: false,
items: [
{
kind: "method",
name: "caller",
full_name: "fixture.Other.caller",
containing_class: "fixture.Other",
top_class: "fixture.Other",
def_pos: 0,
direct_invokes: [
{
dex_entry: "classes.dex",
source_raw_method_id: "fixture.Other.caller()V",
dex_code_unit_offset: 0,
dex_method_index: 1,
opcode: "INVOKE_STATIC",
},
{
dex_entry: "classes.dex",
source_raw_method_id: "fixture.Other.caller()V",
dex_code_unit_offset: 3,
dex_method_index: 1,
opcode: "INVOKE_STATIC",
},
],
},
],
});
},
text: () => Promise.reject(new Error("unexpected text call")),
};
const request = {
operation: "trace_android_references",
input: androidInputSchemas.trace_android_references.parse({
path: "/fixture.apk",
class_name: "fixture.Target",
method_name: "choose",
overload_index: 1,
}),
} as const;
const result = await analyzeJadxRequest(tools, request, {} as never, engine);
expect(result).toMatchObject({
method_name: "choose",
overload_index: 1,
reported_signature: "choose(int): void",
dex_descriptor: "(I)V",
total: 1,
reference_unit: "using_node",
references: [
{
direct_invokes: [
{ dex_code_unit_offset: 0 },
{ dex_code_unit_offset: 3 },
],
},
],
});
expect(calls[1]).toMatchObject({
name: "get_xrefs_to_method",
overload_index: 1,
});
});
it("rejects an ambiguous method and a producer response for a different overload", async () => {
const xrefs = {
target: "fixture.Target.choose",
overload_index: 0,
reported_signature: "choose(String): void",
total: 0,
count: 0,
resolve_line: false,
items: [],
};
const tools: JadxToolPort = {
json: (name) =>
Promise.resolve(name === "get_class_summary" ? summary : xrefs),
text: () => Promise.reject(new Error("unexpected text call")),
};
const input = {
path: "/fixture.apk",
class_name: "fixture.Target",
method_name: "choose",
};
await expect(
analyzeJadxRequest(
tools,
{
operation: "trace_android_references",
input,
},
{} as never,
engine,
),
).rejects.toMatchObject({
_tag: "AnalysisInputError",
});
await expect(
analyzeJadxRequest(
tools,
{
operation: "trace_android_references",
input: { ...input, overload_index: 1 },
},
{} as never,
engine,
),
).rejects.toMatchObject({
_tag: "AnalysisOutputError",
});
});
const invokeSite = {
dex_entry: "classes.dex",
source_raw_method_id: "fixture.Other.caller()V",
dex_code_unit_offset: 0,
dex_method_index: 1,
opcode: "INVOKE_STATIC",
};
const traceWithReference = (fields: Record<string, unknown>) =>
analyzeJadxRequest(
{
json: (name) =>
Promise.resolve(
name === "get_class_summary"
? summary
: {
target: "fixture.Target.choose",
overload_index: 0,
reported_signature: "choose(String): void",
total: 1,
count: 1,
resolve_line: false,
items: [
{
kind: "method",
name: "caller",
full_name: "fixture.Other.caller",
containing_class: "fixture.Other",
top_class: "fixture.Other",
def_pos: 0,
...fields,
},
],
},
),
text: () => Promise.reject(new Error("unexpected text call")),
},
{
operation: "trace_android_references",
input: {
path: "/fixture.apk",
class_name: "fixture.Target",
method_name: "choose",
overload_index: 0,
},
},
{} as never,
engine,
);
it.each([
[{}, null],
[{ direct_invokes: [] }, []],
])(
"preserves unavailable versus observed-empty invoke sites: %j",
async (fields, expected) => {
const result = await traceWithReference(fields as Record<string, unknown>);
expect(result).toMatchObject({
references: [{ direct_invokes: expected }],
});
},
);
it.each([
{ ...invokeSite, dex_code_unit_offset: -1 },
{
dex_entry: "classes.dex",
source_raw_method_id: "fixture.Other.caller()V",
dex_code_unit_offset: 0,
dex_method_index: 1,
},
])("rejects malformed direct invoke producer evidence: %j", async (site) => {
await expect(
traceWithReference({ direct_invokes: [site] }),
).rejects.toThrow();
});
it("preserves bounded instruction coverage separately from using-node coverage", async () => {
const result = await traceWithReference({
direct_invokes: [invokeSite],
direct_invokes_exhaustive: false,
});
expect(result).toMatchObject({
coverage: "complete",
reference_unit: "using_node",
references: [
{ direct_invokes: [invokeSite], direct_invokes_exhaustive: false },
],
});
});
it("rejects malformed method descriptors at the Android adapter boundary", async () => {
const invalidSummary = {
...summary,
methods: summary.methods.map((method) => ({
...method,
dex_descriptor: "not-a-dex-descriptor",
})),
};
await expect(
analyzeJadxRequest(
{
json: () => Promise.resolve(invalidSummary),
text: () => Promise.reject(new Error("unexpected text call")),
},
{
operation: "inspect_android_class",
input: { path: "/fixture.apk", class_name: "fixture.Target" },
},
{} as never,
engine,
),
).rejects.toThrow();
});
@@ -0,0 +1,60 @@
import { spawn } from "node:child_process";
import { readFile } from "node:fs/promises";
import { expect, it } from "vitest";
it.skipIf(process.platform !== "win32")(
"retains guardian cleanup ownership through more than 100 transient failures",
async () => {
const guardian = await readFile(
new URL(
"../../../scripts/rea-android-workspace-guardian.mjs",
import.meta.url,
),
"utf8",
);
const withoutTimer = guardian
.replace(/^#!.*\r?\n/u, "")
.replace(
'import { setTimeout as delay } from "node:timers/promises";',
"const delay = async () => {};",
);
const injected = withoutTimer.replace(
'import { WindowsPrivateRuntime } from "../dist/windows/WindowsPrivateRuntime.js";',
`let attempts = 0;
const WindowsPrivateRuntime = {
create: () => ({
observation: { path: "synthetic-root", volumeSerial: "0", fileId: "0", privateDacl: true },
close: async () => { if (++attempts <= 101) throw new Error("transient cleanup failure"); },
}),
};`,
);
expect(withoutTimer).not.toBe(guardian);
expect(injected).not.toBe(withoutTimer);
const child = spawn(
process.execPath,
[
"--input-type=module",
"-e",
'process.argv.splice(1, 0, "guardian.mjs");\n' + injected,
"synthetic-parent",
],
{ signal: AbortSignal.timeout(3000) },
);
let stdout = "";
let stderr = "";
child.stdout.on("data", (chunk: Buffer) => {
stdout += chunk.toString();
});
child.stderr.on("data", (chunk: Buffer) => {
stderr += chunk.toString();
});
child.stdin.end();
const code = await new Promise<number | null>((resolve, reject) => {
child.once("close", resolve);
child.once("error", reject);
});
expect(code, stderr).toBe(0);
expect(JSON.parse(stdout.trim())).toMatchObject({ path: "synthetic-root" });
},
);
@@ -1,3 +1,4 @@
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect } from "vitest";
@@ -9,6 +10,7 @@ import {
} from "../../support/process/processFixture.js";
import {
BROWSER_DEVTOOLS_STARTUP_TIMEOUT_MS,
BrowserStartupError,
waitForBrowserDevtoolsPort,
} from "../../../src/browser/BrowserProcessStartup.js";
@@ -86,15 +88,68 @@ describe("browser process startup", () => {
failure: "timeout",
exitCode: null,
signalCode: null,
startupTimeoutMs: 20,
});
expect(String(failure)).toContain("stderr=<empty>");
expect(String(failure)).toContain("startup_timeout_ms=20");
} finally {
child.kill("SIGKILL");
expect(await waitForExit(child, 5_000)).toBe(true);
}
});
it("names the owner's deadline when a caller omits one", async ({
processes,
}) => {
const root = await temporaryRoot();
const child = processes.spawn(process.execPath, [
"-e",
"setTimeout(() => process.exit(3), 10)",
]);
const failure = await waitForBrowserDevtoolsPort({
child,
executable: process.execPath,
activePortPath: join(root, "DevToolsActivePort"),
stderr: () => "owner default fixture",
pollIntervalMs: 5,
}).catch((cause: unknown) => cause);
expect(failure).toBeInstanceOf(BrowserStartupError);
expect(failure).toMatchObject({
failure: "exited",
startupTimeoutMs: BROWSER_DEVTOOLS_STARTUP_TIMEOUT_MS,
});
expect(String(failure)).toContain(
`startup_timeout_ms=${String(BROWSER_DEVTOOLS_STARTUP_TIMEOUT_MS)}`,
);
});
it("keeps one owner for the DevToolsActivePort deadline", async () => {
expect(BROWSER_DEVTOOLS_STARTUP_TIMEOUT_MS).toBe(60_000);
const callers = [
"../../../scripts/verify-real-browser.mjs",
"../../../scripts/lib/browser-runtime-fixture-lifecycle.mjs",
];
for (const caller of callers) {
const source = await readFile(new URL(caller, import.meta.url), "utf8");
expect(devtoolsPortDeadlines(source)).toEqual([
["BROWSER_DEVTOOLS_STARTUP_TIMEOUT_MS"],
]);
}
});
});
const temporaryRoot = async (): Promise<string> => {
return createTestTempDirectory("rea-browser-startup-");
};
const devtoolsPortDeadlines = (source: string): string[][] => {
const calls = /waitForBrowserDevtoolsPort\(\{(?<body>[\s\S]*?)\}\)/gu;
const deadlines = /\btimeoutMs:\s*(?<value>[^\n,]+)/gu;
return [...source.matchAll(calls)].map((call) =>
[...String(call.groups?.body).matchAll(deadlines)].map((deadline) =>
String(deadline.groups?.value).trim(),
),
);
};
@@ -0,0 +1,255 @@
import { describe, expect, it } from "vitest";
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js";
import type { WebPageInspection } from "../../../src/domain/browserObservationSchemas.js";
import { compareWebCaptures } from "../../../src/domain/webCaptureDiff.js";
import { compareWebCapturesInputSchema } from "../../../src/domain/webCaptureDiffSchemas.js";
import type { FakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
import {
startHttpComparisonBrowser,
type HttpRequestObservation,
} from "../../fixtures/httpComparisonBrowser.js";
import { trackBrowser } from "./cdpBrowserProvider.support.js";
const inspect = async (browser: FakeCdpBrowser): Promise<WebPageInspection> => {
const result = await new CdpBrowserProvider().inspectPage(
inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
observation_ms: 0,
}),
);
if (!result.ok) throw result.error;
return result.value;
};
const capturePair = async (
before: readonly HttpRequestObservation[],
after: readonly HttpRequestObservation[],
): Promise<readonly [WebPageInspection, WebPageInspection]> => {
const fixture = await startHttpComparisonBrowser(before);
trackBrowser(fixture.browser);
const left = await inspect(fixture.browser);
fixture.setRequests(after);
return [left, await inspect(fixture.browser)];
};
const compareNetwork = (before: WebPageInspection, after: WebPageInspection) =>
compareWebCaptures(
compareWebCapturesInputSchema.parse({
before: { inspection: before },
after: { inspection: after },
}),
).dimensions.network;
const response = {
requestId: "request-before",
status: 200,
mimeType: "application/json",
} as const;
describe("HTTP comparison response coverage", () => {
it("does not compare an unavailable byte count with a completed response", async () => {
const [before, after] = await capturePair(
[response],
[{ ...response, requestId: "request-after", encodedDataLength: 100 }],
);
expect(before.network.requests[0]?.encoded_data_length).toBeNull();
expect(after.network.requests[0]?.encoded_data_length).toBe(100);
for (const [left, right] of [
[before, after],
[after, before],
] as const)
expect(compareNetwork(left, right)).toMatchObject({
status: "unknown",
total_changes: 0,
changes: [],
});
});
it("does not treat an unobserved response as a changed response", async () => {
const [before, after] = await capturePair(
[{ requestId: "request-before" }],
[{ ...response, encodedDataLength: 100 }],
);
expect(before.network.requests).toEqual([
expect.objectContaining({
status: null,
mime_type: null,
encoded_data_length: null,
}),
]);
for (const [left, right] of [
[before, after],
[after, before],
] as const)
expect(compareNetwork(left, right)).toMatchObject({
status: "unknown",
total_changes: 0,
});
});
it("retains observed status changes when response bytes are unavailable", async () => {
const [before, after] = await capturePair(
[response],
[{ ...response, status: 500 }],
);
expect(compareNetwork(before, after)).toMatchObject({
status: "changed",
changes: [expect.objectContaining({ change: "modified" })],
});
});
it.each([
{ mimeType: "text/plain", encodedDataLength: 100 },
{ mimeType: "application/json", encodedDataLength: 200 },
])("retains observed response changes: %j", async (change) => {
const [before, after] = await capturePair(
[{ ...response, encodedDataLength: 100 }],
[{ ...response, ...change }],
);
expect(compareNetwork(before, after).status).toBe("changed");
});
});
describe("HTTP comparison repeated request coverage", () => {
it("does not assign missing evidence by request order or transient ID", async () => {
const [before, after] = await capturePair(
[
{ ...response, encodedDataLength: 100 },
{ ...response, requestId: "second-before" },
],
[
{ ...response, requestId: "second-after", encodedDataLength: 200 },
{ ...response, requestId: "first-after", encodedDataLength: 100 },
],
);
expect(before.network.requests).toHaveLength(2);
expect(after.network.requests).toHaveLength(2);
expect(compareNetwork(before, after)).toMatchObject({
status: "unknown",
total_changes: 0,
});
});
it("compares complete byte counts even when another field is incomplete", async () => {
const [before, after] = await capturePair(
[
{ ...response, encodedDataLength: 100 },
{ requestId: "second-before", encodedDataLength: 200 },
],
[
{ requestId: "second-after", encodedDataLength: 300 },
{ ...response, requestId: "first-after", encodedDataLength: 100 },
],
);
expect(compareNetwork(before, after).status).toBe("changed");
});
it("preserves the association between complete response fields", async () => {
const [before, after] = await capturePair(
[
{ ...response, encodedDataLength: 100 },
{
...response,
requestId: "second-before",
status: 201,
encodedDataLength: 200,
},
],
[
{ ...response, requestId: "first-after", encodedDataLength: 200 },
{
...response,
requestId: "second-after",
status: 201,
encodedDataLength: 100,
},
],
);
expect(compareNetwork(before, after).status).toBe("changed");
});
});
it.each([
{
name: "a pending request in an empty inventory",
before: [],
after: [{ requestId: "pending" }],
},
{
name: "a known request beside an existing pending request",
before: [{ requestId: "pending" }],
after: [
{ requestId: "pending" },
{
...response,
requestId: "new",
path: "/api/new",
encodedDataLength: 100,
},
],
},
])("preserves additions and removals of $name", async (observations) => {
const [before, after] = await capturePair(
observations.before,
observations.after,
);
// Live CDP observations have attach-limited inventories. Their absence
// remains unknown even when a request is seen in the other capture.
for (const [left, right] of [
[before, after],
[after, before],
] as const)
expect(compareNetwork(left, right)).toMatchObject({
status: "unknown",
total_changes: 0,
changes: [],
});
// Project explicitly complete inventory coverage without changing the
// producer's request facts; response fields remain independently unknown.
markNetworkInventoriesComplete(before, after);
for (const [left, right, change] of [
[before, after, "added"],
[after, before, "removed"],
] as const)
expect(compareNetwork(left, right)).toMatchObject({
status: "changed",
total_changes: 1,
changes: [expect.objectContaining({ change })],
});
});
it("requires response field coverage even when capture sections are complete", async () => {
const [before, after] = await capturePair(
[response],
[{ ...response, encodedDataLength: 100 }],
);
markNetworkInventoriesComplete(before, after);
expect(compareNetwork(before, before).status).toBe("unknown");
expect(compareNetwork(before, after).status).toBe("unknown");
expect(compareNetwork(after, after).status).toBe("unchanged");
});
const markNetworkInventoriesComplete = (
...inspections: WebPageInspection[]
): void => {
const sections = new Set([
"network_requests",
"websocket_connections",
"websocket_frames",
]);
for (const inspection of inspections)
for (const key of [
"policy_filtered_sections",
"attach_limited_sections",
"truncated_sections",
"unavailable_sections",
] as const)
inspection.completeness[key] = inspection.completeness[key].filter(
(section) => !sections.has(section),
);
};
+42 -83
View File
@@ -446,91 +446,50 @@ 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";
it.each(["status", "mime_type"] as const)(
"keeps an independently unavailable HTTP %s unknown",
async (field) => {
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 observed = structuredClone(captured.value);
const request = observed.network.requests[0];
if (request === undefined) throw new Error("Missing network request");
request.status = 200;
request.mime_type = "application/json";
request.encoded_data_length = 100;
markSectionsComplete(observed, [
"network_requests",
"websocket_connections",
"websocket_frames",
"json_body_shapes",
]);
for (const item of observed.network.requests)
item.body_shapes.status = "not_approved";
expect(compareNetwork(observed, observed).status).toBe("unchanged");
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);
const partial = structuredClone(observed);
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");
});
for (const [left, right] of [
[partial, observed],
[observed, partial],
[partial, partial],
] as const)
expect(compareNetwork(left, right)).toMatchObject({
status: "unknown",
total_changes: 0,
changes: [],
});
},
);
it("ignores transient request IDs and capture-approval state", async () => {
const browser = await startFakeCdpBrowser();
@@ -29,6 +29,104 @@ const expectInvalidIncludedSourceMaps = (result: WebSourceMaps): void => {
expectInvalidSourceMaps({ ...result, status: "unavailable" });
};
it.each(["regular", "indexed"])(
"collects an HTTP %s source map with omitted names without accepting invalid names",
async (format) => {
const leaf = {
version: 3,
sources: ["src/main.ts"],
sourcesContent: ["import './dependency.ts';"],
mappings: "AAAA",
};
const texts = [
leaf,
{ ...leaf, names: [] },
{ ...leaf, names: null },
{ ...leaf, names: 42 },
{ ...leaf, names: [42] },
{ ...leaf, mappings: "AAAAA" },
].map((map) =>
JSON.stringify(
format === "indexed"
? {
version: 3,
sections: [{ offset: { line: 2, column: 5 }, map }],
}
: map,
),
);
const server = createServer((incoming, response) => {
response.setHeader("content-type", "application/source-map+json");
response.end(texts[Number(incoming.url?.slice(1))]);
});
try {
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", resolve);
});
const address = server.address();
if (address === null || typeof address === "string")
throw new TypeError("Expected a TCP listener address");
const localOrigin = `http://127.0.0.1:${String(address.port)}`;
const result = await fetchWebSourceMaps(
texts.map((_, index) => ({
...request,
fetchUrl: `${localOrigin}/${index}`,
declaredUrl: `${localOrigin}/${index}`,
})),
input({ allowed_origins: [localOrigin] }),
);
expect(result.items.map(({ status }) => status)).toEqual([
"included",
"included",
"invalid",
"invalid",
"invalid",
"invalid",
]);
for (const [index, text] of texts.slice(0, 2).entries())
expect(result.items[index]).toMatchObject({
artifact: {
text,
bytes: Buffer.byteLength(text),
sha256: createHash("sha256").update(text).digest("hex"),
},
original_sources: [{ source: `${localOrigin}/src/main.ts` }],
mappings: [
{
generated_line: format === "indexed" ? 3 : 1,
generated_column: format === "indexed" ? 5 : 0,
source: `${localOrigin}/src/main.ts`,
original_line: 1,
original_column: 0,
name: null,
},
],
original_module_edges: [
{
from_source: `${localOrigin}/src/main.ts`,
resolved_source: `${localOrigin}/src/dependency.ts`,
},
],
});
for (const item of result.items.slice(2))
expect(item).toMatchObject({
artifact: null,
mappings: [],
original_sources: [],
});
} finally {
server.closeAllConnections();
if (server.listening)
await new Promise<void>((resolve, reject) => {
server.close((error) =>
error === undefined ? resolve() : reject(error),
);
});
}
},
);
it("parses ECMA-426 HTTP source-map prefixes while retaining exact response evidence", async () => {
const map = JSON.stringify({
version: 3,
@@ -1,3 +1,7 @@
import {
descriptorFailurePath,
expectRetainedDescriptor,
} from "../../fixtures/descriptorCloseFailure.js";
import { expect, it, onTestFinished, vi } from "vitest";
import { writeFile } from "node:fs/promises";
import type { FileHandle } from "node:fs/promises";
@@ -15,27 +19,22 @@ const cleanup = vi.hoisted(() => ({
}));
vi.mock("node:fs/promises", async (importOriginal) => {
const filesystem = await importOriginal<typeof import("node:fs/promises")>();
return {
...filesystem,
open: async (...args: Parameters<typeof filesystem.open>) => {
const handle = await filesystem.open(...args);
if (args[0] === cleanup.path) {
cleanup.handles.push(handle);
const close = handle.close.bind(handle);
handle.close = async () => {
if (cleanup.denied && handle.fd >= 0)
throw new Error("Descriptor close deliberately denied");
await close();
};
}
return handle;
},
};
const { withDescriptorCloseFailure } =
await import("../../fixtures/descriptorCloseFailure.js");
return withDescriptorCloseFailure(filesystem, cleanup);
});
it
.runIf(process.platform === "linux")
.each(["capture", "tool", "limiter", "kernel"])(
.each([
"capture",
"tool",
"limiter",
"kernel",
"field-tool",
"field-limiter",
"field-kernel",
])(
"retains failed %s descriptors and retries them before further acquisition and shutdown",
async (member) => {
const directory = await createTestTempDirectory("rea-capture-descriptor-");
@@ -67,14 +66,16 @@ it
},
() => PrivateRuntimeRoot.create({ parent: directory }),
);
cleanup.path =
member === "capture"
? path
: member === "tool"
? command
: member === "limiter"
? limiter
: "/proc/self/limits";
const discovery = member.startsWith("field-");
const resource = discovery ? member.slice(6) : member;
const operation = discovery
? "inspect_packet_fields"
: "inspect_packet_capture";
cleanup.path = descriptorFailurePath(resource, {
capture: path,
tool: command,
limiter,
});
cleanup.denied = true;
cleanup.handles = [];
onTestFinished(async () => {
@@ -84,24 +85,45 @@ it
cleanup.path = "";
});
const service = new PacketCaptureService(provider);
const first = await service.inspect({ path, fields: ["frame.number"] });
expect(first).toMatchObject({
ok: false,
error: { cleanupIncomplete: true, cleanupResources: [cleanup.path] },
});
expect(cleanup.handles).toHaveLength(1);
expect(cleanup.handles[0]?.fd).toBeGreaterThanOrEqual(0);
const first = discovery
? await service.inspectFields({ query: "usb" })
: await service.inspect({ path, fields: ["frame.number"] });
expectRetainedDescriptor(first, cleanup, operation);
const launchCount = launches;
expect(
await service.inspect({ path, fields: ["frame.number"] }),
).toMatchObject({ ok: false, error: { cleanupIncomplete: true } });
).toMatchObject({
ok: false,
error: { cleanupIncomplete: true, operation },
});
expect(cleanup.handles).toHaveLength(1);
expect(launches).toBe(launchCount);
let closingOperation = operation;
if (discovery) {
cleanup.denied = false;
const recovered = await service.inspect({
path,
fields: ["frame.number"],
});
expect(recovered.ok).toBe(true);
expect(cleanup.handles.every((handle) => handle.fd === -1)).toBe(true);
expect(launches).toBeGreaterThan(launchCount);
cleanup.denied = true;
expect(
await service.inspect({ path, fields: ["frame.number"] }),
).toMatchObject({
ok: false,
error: { cleanupIncomplete: true, operation: "inspect_packet_capture" },
});
expect(cleanup.handles.at(-1)?.fd).toBeGreaterThanOrEqual(0);
closingOperation = "inspect_packet_capture";
}
await expect(provider.close()).rejects.toMatchObject({
cleanupIncomplete: true,
operation: closingOperation,
});
cleanup.denied = false;
await provider.close();
expect(cleanup.handles[0]?.fd).toBe(-1);
expect(cleanup.handles.every((handle) => handle.fd === -1)).toBe(true);
},
);
@@ -11,6 +11,9 @@ import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { createDeferred } from "../../fixtures/binarySession.js";
import { Cli } from "incur";
import { registerCaptureCommands } from "../../../src/cli/captureCommands.js";
import { silentLogger } from "../../../src/logger.js";
// A command-boundary simulator: real process ownership/filesystem, not real TShark coverage.
const fixture = async (mode = "ok", failCleanup = false) => {
@@ -625,3 +628,34 @@ it("retains completed discovery on late cancellation and cleanup failure", async
await f.service.close();
}
});
it("preserves discovery resource ownership through CLI shutdown retries", async () => {
const f = await fixture("cleanup", true);
const cli = Cli.create("discovery-cleanup", { sync: false });
registerCaptureCommands(cli, silentLogger, {}, f.service);
let stdout = "";
try {
await cli.serve(
["inspect-packet-fields", "--query", "usb", "--format", "json"],
{
stdout: (text) => {
stdout += text;
},
exit: () => {},
},
);
expect(JSON.parse(stdout)).toMatchObject({
code: "cleanup_incomplete",
details: {
diagnostics: {
cleanup_error: {
details: { operation: "inspect_packet_fields" },
},
},
},
});
} finally {
f.allowCleanup();
await f.service.close();
}
});
@@ -23,7 +23,7 @@ const analyze = async (cli: TestCli, extra = "") => {
const output = await cli.run({
arguments: ["analyze-javascript-application", root, "--json"],
});
expect(output.exitCode).toBe(0);
expect(output.exitCode, output.stderr).toBe(0);
const { normalized_result: result } = z
.object({
normalized_result: javascriptApplicationAnalysisResultSchema,
@@ -122,6 +122,190 @@ cliTest(
},
);
cliTest(
"traces a nested contextBridge member through a unique IPC channel",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-electron-nested-bridge-");
await writeFixtureFiles(root, {
"preload.js": `const { contextBridge, ipcRenderer } = require("electron");
contextBridge.exposeInMainWorld("api", {
nested: { write: (value) => ipcRenderer.invoke("nested:write", value) }
});`,
"main.js": `const { ipcMain, clipboard } = require("electron");
ipcMain.handle("nested:write", (event, value) => clipboard.writeText(value));`,
});
const output = await cli.run({
arguments: ["analyze-javascript-application", root, "--json"],
});
expect(output.exitCode, output.stderr).toBe(0);
const { normalized_result: application } = z
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
.parse(output.json);
const { graph } = application;
const paths = graph.nodes
.flatMap((node) => node.observations)
.filter(
(observation) =>
observation.properties.entry === "api.nested.write" &&
observation.properties.entry_kind === "bridge-member",
);
expect(
paths.some(
(observation) => observation.properties.step_kind === "exposure",
),
).toBe(true);
expect(
paths.some(
(observation) => observation.properties.step_kind === "terminal",
),
).toBe(true);
const joins = graph.edges.filter(
(edge) =>
edge.evidence.extractor.operation === "join-electron-wrapper-paths",
);
expect(joins.map((edge) => edge.properties.channel)).toEqual([
"nested:write",
]);
const traceInput = join(root, "trace-nested-input.json");
await writeFile(
traceInput,
JSON.stringify({
application: output.json,
seed: { kind: "api", value: "api.nested.write", match: "exact" },
direction: "outgoing",
}),
);
const traced = await cli.run({
arguments: ["trace-application-feature", traceInput, "--json"],
});
expect(traced.exitCode).toBe(0);
const { normalized_result: trace } = z
.object({ normalized_result: applicationFeatureTraceResultSchema })
.parse(traced.json);
expect(trace.seed_matches).toHaveLength(1);
expect(trace.paths.some((path) => path.contains_inference)).toBe(true);
},
);
cliTest(
"preserves exact bridge member segments through the public CLI",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-electron-bridge-segments-");
await writeFixtureFiles(root, {
"preload.js": `const { contextBridge, ipcRenderer } = require("electron");
const write = () => ipcRenderer.send("write");
contextBridge.exposeInMainWorld("desktop", {
"nested.write": write,
nested: { write },
__proto__: { inherited: write },
["__proto__"]: { own: write },
});`,
"main.js": `const { ipcMain } = require("electron");
ipcMain.on("write", (event) => event.sender.copy());`,
});
const output = await cli.run({
arguments: ["analyze-javascript-application", root, "--json"],
});
expect(output.exitCode).toBe(0);
const { normalized_result: application } = z
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
.parse(output.json);
const observations = application.graph.nodes.flatMap((node) =>
node.observations.filter(
(observation) =>
observation.properties.entry_kind === "bridge-member" &&
observation.properties.step_kind === "exposure",
),
);
const bridge = application.graph.nodes
.filter((node) => node.kind === "context-bridge-api")
.flatMap((node) => node.observations)
.find((observation) => observation.properties.api_key === "desktop");
expect(bridge?.properties.members).not.toContain("__proto__.inherited");
expect(bridge?.properties.members).toContain("__proto__.own");
const paths = observations.map(
(observation) => observation.properties.entry_path,
);
expect(paths).toEqual(
expect.arrayContaining([
["desktop", "nested.write"],
["desktop", "nested", "write"],
["desktop", "__proto__", "own"],
]),
);
expect(paths).not.toContainEqual(["desktop", "__proto__", "inherited"]);
const handlerPaths = application.graph.nodes
.flatMap((node) => node.observations)
.filter(
(observation) => observation.properties.entry_kind === "ipc-handler",
);
expect(handlerPaths.length).toBeGreaterThan(0);
expect(
handlerPaths.every(
(observation) => !("entry_path" in observation.properties),
),
).toBe(true);
},
);
cliTest(
"retains a nested bridge path when its IPC handler has no external terminal",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-electron-nested-return-");
await writeFixtureFiles(root, {
"preload.js": `const { contextBridge, ipcRenderer } = require("electron");
contextBridge.exposeInMainWorld("api", {
nested: { write: (value) => ipcRenderer.invoke("nested:write", value) }
});`,
"main.js": `const { ipcMain } = require("electron");
ipcMain.handle("nested:write", (event, value) => value);`,
});
const output = await cli.run({
arguments: ["analyze-javascript-application", root, "--json"],
});
expect(output.exitCode).toBe(0);
const { normalized_result: application } = z
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
.parse(output.json);
const { graph } = application;
expect(
graph.nodes.some((node) =>
node.observations.some(
(observation) =>
observation.properties.entry === "api.nested.write" &&
observation.properties.step_kind === "exposure",
),
),
).toBe(true);
expect(
graph.edges.some(
(edge) =>
edge.evidence.extractor.operation === "join-electron-wrapper-paths",
),
).toBe(false);
const traceInput = join(root, "trace-nested-input.json");
await writeFile(
traceInput,
JSON.stringify({
application: output.json,
seed: { kind: "api", value: "api.nested.write", match: "exact" },
direction: "outgoing",
}),
);
const traced = await cli.run({
arguments: ["trace-application-feature", traceInput, "--json"],
});
expect(traced.exitCode).toBe(0);
const { normalized_result: trace } = z
.object({ normalized_result: applicationFeatureTraceResultSchema })
.parse(traced.json);
expect(trace.seed_matches).toHaveLength(1);
expect(trace.graph?.nodes.length).toBeGreaterThan(1);
},
);
for (const surface of ["CLI", "stdio MCP"] as const) {
cliTest(
`preserves handler ambiguity and short-circuit factory paths through ${surface}`,
@@ -225,3 +409,89 @@ cliTest(
expect(joins.map((e) => e.properties.channel)).toEqual(["test:cut"]);
},
);
cliTest(
"keeps shallow bridge members when a sibling exceeds the nesting limit",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-electron-deep-bridge-");
let deepMember = '() => e.ipcRenderer.send("deep:run")';
for (let index = 0; index < 129; index += 1)
deepMember = `{ level${index}: ${deepMember} }`;
await writeFixtureFiles(root, {
"preload.js": `const e=require("electron");
e.contextBridge.exposeInMainWorld("desktop", {
deep: ${deepMember},
shallow: () => e.ipcRenderer.send("shallow:run")
});`,
"main.js": `const e=require("electron");
e.ipcMain.on("shallow:run", event => event.sender.copy());
e.ipcMain.on("deep:run", event => event.sender.copy());`,
});
const output = await cli.run({
arguments: ["analyze-javascript-application", root, "--json"],
});
expect(output.exitCode).toBe(0);
const { normalized_result: application } = z
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
.parse(output.json);
const { graph } = application;
const joins = graph.edges.filter(
(edge) =>
edge.evidence.extractor.operation === "join-electron-wrapper-paths",
);
expect(joins.map((edge) => edge.properties.channel)).toEqual([
"shallow:run",
]);
expect(
graph.nodes
.flatMap((node) => node.observations)
.some(
(observation) =>
observation.properties.entry === "desktop.shallow" &&
observation.properties.step_kind === "exposure",
),
).toBe(true);
},
);
cliTest(
"preserves empty bridge member segments in nested paths",
async ({ cli }) => {
const root = await createTestTempDirectory(
"rea-electron-empty-bridge-key-",
);
await writeFixtureFiles(root, {
"preload.js": `const { contextBridge, ipcRenderer } = require("electron");
contextBridge.exposeInMainWorld("desktop", {
"": { nested: { call: () => ipcRenderer.send("empty:key") } }
});`,
"main.js": `const { ipcMain } = require("electron");
ipcMain.on("empty:key", event => event.sender.copy());`,
});
const output = await cli.run({
arguments: ["analyze-javascript-application", root, "--json"],
});
expect(output.exitCode).toBe(0);
const { normalized_result: application } = z
.object({ normalized_result: javascriptApplicationAnalysisResultSchema })
.parse(output.json);
const observations = application.graph.nodes.flatMap(
(node) => node.observations,
);
expect(
observations.some(
(observation) =>
observation.properties.entry === "desktop..nested.call" &&
observation.properties.step_kind === "exposure",
),
).toBe(true);
expect(
application.graph.edges
.filter(
(edge) =>
edge.evidence.extractor.operation === "join-electron-wrapper-paths",
)
.map((edge) => edge.properties.channel),
).toEqual(["empty:key"]);
},
);
@@ -0,0 +1,77 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it } from "vitest";
import { webPageInspectionSchema } from "../../../src/domain/browserObservationSchemas.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { runCliJson } from "../../fixtures/cliJsonProcess.js";
import { startHttpComparisonBrowser } from "../../fixtures/httpComparisonBrowser.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
it("CLI compares incomplete HTTP responses without inventing changes", async () => {
const root = await createTestTempDirectory("rea-http-comparison-");
const response = {
requestId: "request-1",
status: 200,
mimeType: "application/json",
};
const fixture = await startHttpComparisonBrowser([response]);
try {
const inspect = async () =>
webPageInspectionSchema.parse(
parseEvidence(
await runCliJson([
"inspect-web-page",
fixture.browser.endpoint,
"allowed-page",
"--observation-ms",
"0",
"--json",
]),
).normalized_result,
);
const pending = await inspect();
fixture.setRequests([{ ...response, encodedDataLength: 100 }]);
const finished = await inspect();
fixture.setRequests([{ ...response, status: 500, encodedDataLength: 100 }]);
const changed = await inspect();
expect(pending.network.requests).toMatchObject([
{ status: 200, mime_type: "application/json", encoded_data_length: null },
]);
expect(finished.network.requests).toMatchObject([
{ status: 200, mime_type: "application/json", encoded_data_length: 100 },
]);
const paths = [pending, finished, changed].map((_, index) =>
join(root, `capture-${String(index)}.json`),
);
await Promise.all(
[pending, finished, changed].map((inspection, index) =>
writeFile(paths[index]!, JSON.stringify({ inspection })),
),
);
for (const [left, right, status, count] of [
[0, 1, "unknown", 0],
[1, 0, "unknown", 0],
[0, 2, "changed", 1],
] as const) {
const compared = await runCliJson([
"compare-web-captures",
paths[left]!,
paths[right]!,
"--json",
]);
expect(compared).toMatchObject({
operation: "compare_web_captures",
normalized_result: {
overall_status: status,
dimensions: {
network: { status, total_changes: count },
},
},
});
}
} finally {
await fixture.browser.close();
}
}, 60_000);
@@ -79,6 +79,7 @@ describe("headless IDA timeout through the one-shot CLI", () => {
backend: "worker",
owned: null,
input_path: null,
is_active: null,
},
],
},
@@ -71,4 +71,27 @@ describe("native UI scenario CLI input", () => {
});
},
);
cliTest(
"refuses scenario steps on passive observation instead of dropping them",
async ({ cli }) => {
const result = await cli.run({
arguments: [
"observe-native-ui",
"/provider-must-not-be-invoked",
"--pid",
"1",
"--window-id",
"1",
"--steps",
'[{"kind":"wait","milliseconds":0}]',
"--json",
],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(result.exitCode).not.toBe(0);
expect(result.stdout).toContain("Unknown flag: --steps");
},
);
});
@@ -0,0 +1,75 @@
import { execFile } from "node:child_process";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
import { expect, it } from "vitest";
import { solidityMetadataSchema } from "../../../src/domain/evm/solidityMetadata.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
/** Real compiled worker and unchanged WASM engine; no Linux provider-admission claim. */
it.each([
["compiler", "00a164736f6c634300081e000a", "decoded"],
["integer", "00a1011bffffffffffffffff000b", "decoded"],
["BOM text", "00a1617864efbbbf610008", "decoded"],
["nested value", "00a1617881000005", "partial"],
["unavailable trailer", "00", "unavailable"],
["unsupported tag", "00a16178c0000005", "not-decoded"],
["floating point", "00a16178fa3f8000000008", "not-decoded"],
["invalid UTF-8", "00a1617861ff0005", "not-decoded"],
])(
"retains independent %s metadata through the actual worker",
async (kind, hex, status) => {
const directory = await createTestTempDirectory("rea-solidity-worker-");
const snapshot = join(directory, "selected.hex");
const reply = join(directory, "reply.json");
const request = join(directory, "request.json");
await writeFile(snapshot, hex);
await writeFile(
request,
JSON.stringify({
snapshot_path: snapshot,
reply_path: reply,
failure_marker_path: join(directory, "resource.failure"),
encoding: "hex",
}),
);
await promisify(execFile)(
process.execPath,
[
"--max-old-space-size=256",
"--disable-wasm-trap-handler",
new URL("../../../dist/evm/EvmoleInterfaceWorker.js", import.meta.url)
.pathname,
request,
],
{ timeout: 30_000, maxBuffer: 1024 * 1024 },
);
const value = JSON.parse(await readFile(reply, "utf8"));
expect(value.ok, JSON.stringify(value)).toBe(true);
expect(value.bytecode.hex).toBe(hex);
const metadata = solidityMetadataSchema.parse(value.bytecode.metadata);
expect(metadata.status).toBe(status);
if (kind === "integer")
expect(metadata.entries[0]?.value).toEqual({
kind: "integer",
value: "18446744073709551615",
});
if (kind === "compiler")
expect(metadata.compiler_version?.value).toBe("0.8.30");
if (kind === "BOM text")
expect(metadata.entries[0]?.value).toEqual({
kind: "text",
value: "\ufeffa",
});
if (kind === "nested value")
expect(metadata.entries[0]?.value).toEqual({
kind: "uninterpreted",
container: "array",
});
if (kind === "unavailable trailer") {
expect(metadata.bytecode_offset).toBeNull();
expect(metadata.entries).toEqual([]);
expect(metadata.compiler_version).toBeNull();
}
},
);
@@ -118,14 +118,21 @@ it("reuses only scheduled qualification and preserves every explicit full reques
).toBe("fast");
});
it("keeps every translated root README and authored guide on the documentation lane", async () => {
it("keeps every translated README and authored guide on the documentation lane", async () => {
const { directory, base } = await fixture();
const readmes = (await readdir(new URL("../../../", import.meta.url))).filter(
(name) => /^README(?:_.*)?\.md$/u.test(name),
);
const translated = (
await readdir(new URL("../../../docs/readme/", import.meta.url))
)
.filter((name) => /^README_.*\.md$/u.test(name))
.map((name) => `docs/readme/${name}`);
expect(readmes).toContain("README.md");
expect(translated.length).toBeGreaterThan(0);
const head = await change(directory, [
...readmes,
...translated,
"docs/guide.md",
"AGENTS.md",
"CONTRIBUTING.md",
@@ -198,7 +205,7 @@ it("emits an observational owner proposal without changing ordinary or full port
it("does not charge a documentation PR for unrelated implementation updates on main", async () => {
const { directory, base } = await fixture();
await git(directory, ["switch", "-c", "docs/change"]);
const head = await change(directory, ["README_zh-TW.md"]);
const head = await change(directory, ["docs/readme/README_zh-TW.md"]);
await git(directory, ["switch", "main"]);
const advancedBase = await change(directory, ["src/anotherProvider.ts"]);
expect(advancedBase).not.toBe(base);
@@ -240,7 +247,7 @@ it("retains complete checks when implementation is renamed into documentation",
it("keeps main pushes scoped when a successful ancestor baseline is available", async () => {
const { directory, base } = await fixture();
const head = await change(directory, ["README_ja.md"]);
const head = await change(directory, ["docs/readme/README_ja.md"]);
expect(await classify(directory, base, head, "push")).toMatchObject({
tier: "fast",
code: false,
@@ -449,6 +456,10 @@ it.each([
sqlite: false,
},
],
[
"scripts/verify-solidity-metadata.mjs",
{ code: true, evm: true, browser: false, package: false },
],
[
"src/browser/execution/evaluate.ts",
{
@@ -470,7 +481,10 @@ it.each([
{ code: false, website: true, package: false },
],
["scripts/website_i18n.py", { code: false, website: true, package: false }],
["README_ja.md", { code: false, docs: true, website: true, package: false }],
[
"docs/readme/README_ja.md",
{ code: false, docs: true, website: true, package: false },
],
[
".github/workflows/website-pages.yml",
{ code: false, website: true, package: false },
@@ -924,7 +938,7 @@ it.each(["workflow_dispatch", "schedule"])(
it("honors ci:full for successive PR revisions", async () => {
const { directory, base } = await fixture();
const first = await change(directory, ["README.md"]);
const second = await change(directory, ["README_ja.md"]);
const second = await change(directory, ["docs/readme/README_ja.md"]);
for (const head of [first, second]) {
expect(
await classify(directory, base, head, "pull_request", true),
@@ -0,0 +1,412 @@
import {
access,
mkdir,
readFile,
rm,
symlink,
writeFile,
} from "node:fs/promises";
import { dirname, join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { CLAUDE_DESKTOP_PACKAGE_FAMILY } from "../../../src/application/ClaudeDesktopConfigLocation.js";
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
import { npxRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js";
import {
configureClientConfiguration,
inspectClientConfiguration,
} from "../../../src/application/SetupClientConfiguration.js";
import { detectClients } from "../../../src/application/SetupHost.js";
import {
supportedClients,
type SetupClient,
} from "../../../src/application/SupportedClients.js";
import {
runUninstall,
systemUninstallHost,
} from "../../../src/application/Uninstall.js";
import { clearClientLocationEnvironment } from "../../fixtures/clientEnvironment.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
/** The Windows registration setup writes, independent of the test host. */
const command = npxRegistrationCommand("win32");
const CONFIG = "claude_desktop_config.json";
const roots: string[] = [];
beforeEach(clearClientLocationEnvironment);
afterEach(async () => {
vi.unstubAllEnvs();
await Promise.all(
roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
);
});
/** A Windows profile with separate roaming and local AppData roots. */
const windowsProfile = async () => {
const home = await createTestTempDirectory("rea-claude-desktop-");
roots.push(home);
const env = {
APPDATA: join(home, "AppData", "Roaming"),
LOCALAPPDATA: join(home, "AppData", "Local"),
};
const appDataConfig = join(env.APPDATA, "Claude", CONFIG);
const container = join(
env.LOCALAPPDATA,
"Packages",
CLAUDE_DESKTOP_PACKAGE_FAMILY,
);
const privateConfig = join(
container,
"LocalCache",
"Roaming",
"Claude",
CONFIG,
);
return { home, env, appDataConfig, container, privateConfig };
};
const claudeDesktop = (
home: string,
env: Readonly<Record<string, string>>,
): SetupClient => {
const client = supportedClients(home, "win32", env).find(
({ name }) => name === "claude_desktop",
);
if (client === undefined) throw new Error("claude_desktop is not supported");
return client;
};
const writeJson = async (path: string, value: unknown): Promise<void> => {
await mkdir(dirname(path), { recursive: true });
await writeFile(path, `${JSON.stringify(value, null, 2)}\n`);
};
const readJson = async (path: string): Promise<Record<string, unknown>> =>
JSON.parse(await readFile(path, "utf8")) as Record<string, unknown>;
const reaEntry = { command: command[0], args: command.slice(1) };
describe("Windows Claude Desktop configuration location", () => {
it("uses AppData when no MSIX package storage exists", async () => {
const { home, env, appDataConfig } = await windowsProfile();
await mkdir(
join(env.LOCALAPPDATA, "Packages", "Contoso.App_8wekyb3d8bbwe"),
{
recursive: true,
},
);
const client = claudeDesktop(home, env);
expect(client.configPath).toBe(appDataConfig);
expect(client.markerPath).toBe(dirname(appDataConfig));
expect(client.msixPackage).toBeUndefined();
expect(client.quitBeforeSetup).toBe(true);
});
it("uses the package-private copy that the MSIX package reads", async () => {
const { home, env, appDataConfig, container, privateConfig } =
await windowsProfile();
await writeJson(privateConfig, { preferences: { theme: "dark" } });
await writeJson(appDataConfig, { mcpServers: {} });
const client = claudeDesktop(home, env);
expect(client.configPath).toBe(privateConfig);
expect(client.markerPath).toBe(container);
expect(client.msixPackage).toEqual({
packageFamilyName: CLAUDE_DESKTOP_PACKAGE_FAMILY,
privateConfigPath: privateConfig,
appDataConfigPath: appDataConfig,
virtualizedRoots: [env.APPDATA, env.LOCALAPPDATA],
processView: "direct",
});
expect(
(await detectClients(home, "win32", env)).map(({ name }) => name),
).toContain("claude_desktop");
});
it("uses AppData while the MSIX package has no private copy", async () => {
const { home, env, appDataConfig, container, privateConfig } =
await windowsProfile();
await mkdir(container, { recursive: true });
await writeJson(appDataConfig, { preferences: {} });
const client = claudeDesktop(home, env);
expect(client.configPath).toBe(appDataConfig);
expect(client.msixPackage).toMatchObject({
privateConfigPath: privateConfig,
processView: "unknown",
});
// No private file shows whether the running package started this process.
const inspection = await inspectClientConfiguration(client, {}, command);
expect(inspection.status).toBe("invalid");
expect(inspection.status === "invalid" && inspection.remediation).toContain(
"Open Claude Desktop once if it has never run, quit it fully, then rerun setup",
);
});
it("creates the private copy when the MSIX package has no configuration", async () => {
const { home, env, privateConfig } = await windowsProfile();
await writeJson(join(dirname(privateConfig), "Local State"), {});
const client = claudeDesktop(home, env);
expect(client.configPath).toBe(privateConfig);
expect(client.msixPackage?.processView).toBe("direct");
await expect(
inspectClientConfiguration(client, {}, command),
).resolves.toEqual({ status: "create" });
await expect(
configureClientConfiguration(client, {}, command),
).resolves.toEqual({ status: "configured" });
expect(await readJson(privateConfig)).toEqual({
mcpServers: { rea: reaEntry },
});
});
it("reports an unrecognized Claude package instead of falling back to AppData", async () => {
const { home, env, appDataConfig } = await windowsProfile();
const foreign = join(env.LOCALAPPDATA, "Packages", "Claude_abcdefghjkmnp");
await mkdir(foreign, { recursive: true });
await writeJson(appDataConfig, { mcpServers: {} });
const client = claudeDesktop(home, env);
expect(client.configPath).toBe(foreign);
expect(client.configPathError).toContain("unrecognized publisher");
expect(client.configPathError).toContain(CLAUDE_DESKTOP_PACKAGE_FAMILY);
expect(
(await detectClients(home, "win32", env)).map(({ name }) => name),
).not.toContain("claude_desktop");
const status = (
await readClientRegistrationStatuses(home, "unused", {
platform: "win32",
environment: env,
})
).find(({ client: name }) => name === "claude_desktop");
expect(status).toMatchObject({ state: "invalid", config_path: foreign });
await expect(
inspectClientConfiguration(client, {}, command),
).resolves.toMatchObject({ status: "invalid" });
});
});
describe("MSIX Claude Desktop registration lifecycle", () => {
it("registers in the private copy and reports an AppData-only entry as missing", async () => {
const { home, env, appDataConfig, privateConfig } = await windowsProfile();
const privateOriginal = {
coworkUserFilesPath: "C:\\Users\\a\\Claude",
preferences: { menuBarEnabled: false },
mcpServers: { other: { command: "other", args: ["serve"] } },
};
await writeJson(privateConfig, privateOriginal);
// Earlier setups wrote AppData, which the package never reads.
await writeJson(appDataConfig, { mcpServers: { rea: reaEntry } });
const appDataOriginal = await readFile(appDataConfig, "utf8");
const status = async () =>
(
await readClientRegistrationStatuses(home, "unused", {
platform: "win32",
environment: env,
})
).find(({ client }) => client === "claude_desktop");
expect(await status()).toMatchObject({
state: "missing",
config_path: privateConfig,
});
expect((await status())?.remediation).toContain(
"Quit Claude Desktop fully",
);
const client = claudeDesktop(home, env);
await expect(
inspectClientConfiguration(client, {}, command),
).resolves.toEqual({
status: "update",
backupPath: `${privateConfig}.rea.backup`,
});
await expect(
configureClientConfiguration(client, {}, command),
).resolves.toEqual({
status: "configured",
backupPath: `${privateConfig}.rea.backup`,
});
expect(await readJson(privateConfig)).toEqual({
...privateOriginal,
mcpServers: {
...privateOriginal.mcpServers,
rea: reaEntry,
},
});
expect(await readJson(`${privateConfig}.rea.backup`)).toEqual(
privateOriginal,
);
expect(await readFile(appDataConfig, "utf8")).toBe(appDataOriginal);
expect(await status()).toMatchObject({
state: "aligned",
config_path: privateConfig,
});
await expect(
configureClientConfiguration(client, {}, command),
).resolves.toEqual({ status: "unchanged" });
});
it("refuses to write from a process the running package started", async () => {
const { home, env, privateConfig } = await windowsProfile();
await writeJson(privateConfig, { preferences: {} });
const resolved = claudeDesktop(home, env);
if (resolved.msixPackage === undefined)
throw new Error("expected MSIX package storage");
// Only a packaged process sees AppData redirected; model that observation.
const client: SetupClient = {
...resolved,
msixPackage: { ...resolved.msixPackage, processView: "redirected" },
};
const inspection = await inspectClientConfiguration(client, {}, command);
expect(inspection.status).toBe("invalid");
expect(inspection.status === "invalid" && inspection.remediation).toContain(
"Quit Claude Desktop fully, then rerun setup from a terminal that Claude Desktop did not start",
);
expect(await readJson(privateConfig)).toEqual({ preferences: {} });
await configureClientConfiguration(resolved, {}, command);
await expect(
inspectClientConfiguration(client, {}, command),
).resolves.toEqual({ status: "already_current" });
});
it("refuses a write once the package reads a newer private copy", async () => {
const { home, env, appDataConfig, privateConfig } = await windowsProfile();
await writeJson(join(dirname(privateConfig), "Preferences"), {});
await writeJson(appDataConfig, { preferences: {} });
const client = claudeDesktop(home, env);
expect(client.configPath).toBe(appDataConfig);
// Quitting the app after the plan was shown can save its private copy.
await writeJson(privateConfig, { preferences: {} });
await expect(
configureClientConfiguration(client, {}, command),
).resolves.toEqual({ status: "failed", reason: "target_changed" });
expect(await readJson(appDataConfig)).toEqual({ preferences: {} });
expect(await readJson(privateConfig)).toEqual({ preferences: {} });
});
it("registers in AppData while the package has no private copy", async () => {
const { home, env, appDataConfig, privateConfig } = await windowsProfile();
await writeJson(join(dirname(privateConfig), "Preferences"), {});
await writeJson(appDataConfig, { preferences: { theme: "light" } });
const client = claudeDesktop(home, env);
expect(client.configPath).toBe(appDataConfig);
expect(client.msixPackage?.processView).toBe("direct");
await expect(
configureClientConfiguration(client, {}, command),
).resolves.toMatchObject({ status: "configured" });
expect(await readJson(appDataConfig)).toEqual({
preferences: { theme: "light" },
mcpServers: { rea: reaEntry },
});
await expect(access(privateConfig)).rejects.toMatchObject({
code: "ENOENT",
});
});
});
describe("MSIX Claude Desktop uninstall", () => {
it("refuses uninstall when the package view is unknown", async () => {
const { home, env, appDataConfig, container } = await windowsProfile();
await mkdir(container, { recursive: true });
await writeJson(appDataConfig, { mcpServers: { rea: reaEntry } });
const result = await runUninstall(
false,
systemUninstallHost(home, undefined, env, "win32"),
);
expect(result.status).toBe("failed");
expect(result.items).toContainEqual(
expect.objectContaining({
name: "claude_desktop",
status: "failed",
detail: expect.stringContaining("rerun uninstall"),
}),
);
expect(await readJson(appDataConfig)).toEqual({
mcpServers: { rea: reaEntry },
});
});
it("retains an unrelated rea-named entry when the package view is unknown", async () => {
const { home, env, appDataConfig, container } = await windowsProfile();
await mkdir(container, { recursive: true });
const unrelated = { mcpServers: { rea: { command: "unrelated-server" } } };
await writeJson(appDataConfig, unrelated);
const result = await runUninstall(
false,
systemUninstallHost(home, undefined, env, "win32"),
);
expect(result.status).toBe("complete");
expect(await readJson(appDataConfig)).toEqual(unrelated);
});
it("blocks managed skill removal through redirected AppData before any removal", async () => {
const { home, env, appDataConfig, privateConfig } = await windowsProfile();
await writeJson(join(dirname(privateConfig), "Preferences"), {});
await mkdir(dirname(dirname(appDataConfig)), { recursive: true });
await symlink(dirname(privateConfig), dirname(appDataConfig), "dir");
const agents = join(env.APPDATA, "dsh", "agents");
const manifest = join(
agents,
"skills",
"reverse-engineer-anything",
"SKILL.md",
);
await mkdir(dirname(manifest), { recursive: true });
await writeFile(
manifest,
"---\nname: reverse-engineer-anything\n---\nmanaged fixture\n",
);
const environment = { ...env, DSH_AGENTS_HOME: agents };
const result = await runUninstall(
false,
systemUninstallHost(home, undefined, environment, "win32"),
);
expect(result.status).toBe("failed");
expect(result.items).toContainEqual(
expect.objectContaining({
name: "skill",
status: "failed",
detail: expect.stringContaining("redirects its writes"),
}),
);
expect(await readFile(manifest, "utf8")).toContain("managed fixture");
});
it("removes REA from both the private copy and AppData on uninstall", async () => {
const { home, env, appDataConfig, privateConfig } = await windowsProfile();
await writeJson(privateConfig, {
preferences: {},
mcpServers: { other: { command: "other" }, rea: reaEntry },
});
await writeJson(appDataConfig, { mcpServers: { rea: reaEntry } });
const result = await runUninstall(
false,
systemUninstallHost(home, undefined, env, "win32"),
);
expect(result.status).toBe("complete");
expect(await readJson(privateConfig)).toEqual({
preferences: {},
mcpServers: { other: { command: "other" } },
});
expect(await readJson(appDataConfig)).toEqual({ mcpServers: {} });
});
});
@@ -1,5 +1,6 @@
import { createReadStream } from "node:fs";
import { open, readFile, rm, stat, utimes, writeFile } from "node:fs/promises";
import { createServer } from "node:net";
import { join } from "node:path";
import { Readable } from "node:stream";
import { Uint8ArrayReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
@@ -1122,11 +1123,16 @@ it.each(["identify_flutter_build", "inspect_dart_aot"] as const)(
if (result.ok) throw new Error("Duplicate libraries must be refused");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "invalid_request",
details: {
issues: [
{
message: expect.stringContaining(
`duplicate Flutter library members: ${path}:`,
),
},
],
},
});
expect(JSON.stringify(projectAnalysisError(result.error))).toContain(
"duplicate Flutter library members",
);
expect(JSON.stringify(projectAnalysisError(result.error))).toContain(path);
expect(extract).not.toHaveBeenCalled();
},
);
@@ -1171,6 +1177,69 @@ it.each(["identify_flutter_build", "inspect_dart_aot"] as const)(
},
);
const expectSelectionIssue = async (
provider: FlutterBuildProvider,
path: string,
message: string,
): Promise<void> => {
for (const operation of [
"identify_flutter_build",
"inspect_dart_aot",
] as const) {
const result = await provider.execute({ operation, input: { path } });
if (result.ok) throw new Error("A non-file APK selection must fail");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "invalid_request",
details: {
issues: [
{
path: ["path"],
reason: "invalid_format",
message: `${message}: ${path}`,
},
],
},
});
}
};
it("names a missing or non-file APK selection instead of blaming package bytes", async () => {
const root = await createTestTempDirectory("rea-flutter-selection-");
const provider = new FlutterBuildProvider();
onTestFinished(() => provider.close());
await expectSelectionIssue(
provider,
join(root, "absent.apk"),
"Selected APK does not exist",
);
await expectSelectionIssue(
provider,
root,
"Selected APK is not a regular file",
);
});
// Windows listens on named pipes rather than filesystem sockets.
it.skipIf(process.platform === "win32")(
"names an unopenable Unix socket APK selection as a non-file",
async () => {
const root = await createTestTempDirectory("rea-flutter-socket-");
const socketPath = join(root, "s.sock");
const socket = createServer();
await new Promise<void>((resolve) => socket.listen(socketPath, resolve));
onTestFinished(
() => new Promise<void>((resolve) => socket.close(() => resolve())),
);
const provider = new FlutterBuildProvider();
onTestFinished(() => provider.close());
await expectSelectionIssue(
provider,
socketPath,
"Selected APK is not a regular file",
);
},
);
it.each(["EACCES", "EPERM"] as const)(
"preserves %s at the shared source admission boundary",
async (code) => {
@@ -0,0 +1,79 @@
import { open, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it, vi } from "vitest";
import { readElfBuildIds } from "../../../src/flutter/ElfBuildId.js";
import {
appendElfRanges,
engineFixtureImage,
} from "../../../src/flutter/FlutterBuild.fixture.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const note = Buffer.from(
"040000000800000003000000474e55000123456789abcdef",
"hex",
);
it.each([
{ bits: 32, table: "program" },
{ bits: 64, table: "section" },
] as const)(
"bounds dense $bits-bit $table note ranges while retaining examined IDs",
async ({ bits, table }) => {
const count = 30_000;
const image = appendElfRanges(
engineFixtureImage({
bits,
notes: Buffer.concat([note, Buffer.alloc(count)]),
ownership: "both",
}),
table,
Array.from({ length: count }, (_, index) => ({
type: table === "program" ? 4 : 7,
offset: 0x400 + note.length + index,
size: 1,
})),
);
const root = await createTestTempDirectory("rea-flutter-notes-");
const path = join(root, "engine.so");
await writeFile(path, image);
const file = await open(path, "r");
const read = vi.spyOn(file, "read");
try {
const result = await readElfBuildIds(file, image.length, undefined);
expect(result.candidates).toEqual(["0123456789abcdef"]);
expect(result.failures).toContainEqual({
reason: expect.stringContaining("note-range"),
});
expect(read.mock.calls.length).toBeLessThanOrEqual(1027);
} finally {
await file.close();
}
},
);
it("deduplicates shared program/section notes and skips empty ranges before charging inventory", async () => {
const ranges = Array.from({ length: 2000 }, (_, index) => ({
type: 7,
offset: index % 2 === 0 ? 0x400 : index,
size: index % 2 === 0 ? note.length : 0,
}));
const image = appendElfRanges(
engineFixtureImage({ notes: note, ownership: "both" }),
"section",
ranges,
);
const root = await createTestTempDirectory("rea-flutter-notes-");
const path = join(root, "engine.so");
await writeFile(path, image);
const file = await open(path, "r");
const read = vi.spyOn(file, "read");
try {
expect(await readElfBuildIds(file, image.length, undefined)).toEqual({
candidates: ["0123456789abcdef"],
failures: [],
});
expect(read.mock.calls.length).toBe(4);
} finally {
await file.close();
}
});
@@ -696,6 +696,49 @@ describe("NIB projection byte amplification", () => {
});
});
cliTest(
"compiled CLI preserves distinct NIB keys and class identity",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-nib-name-identity-");
const bundle = join(root, "Example.app");
const resources = join(bundle, "Contents", "Resources");
await mkdir(resources, { recursive: true });
await mkdir(join(bundle, "Contents", "MacOS"), { recursive: true });
await writeFile(
join(bundle, "Contents", "MacOS", "App"),
thinMach(0xfeedfacf, 0x0100000c),
);
await writeFile(
join(bundle, "Contents", "Info.plist"),
"<plist><dict><key>CFBundleExecutable</key><string>App</string></dict></plist>",
);
await writeFile(
join(resources, "Identity.nib"),
encodeNibArchiveFixture({
classes: ["\uFEFFWidget"],
objects: [{ classIndex: 0, values: { count: 1, "\uFEFFcount": 2 } }],
}),
);
const output = await cli.run({
arguments: ["decode-interface-builder", bundle, "--json"],
environment: { REA_LOG_LEVEL: "silent", REA_ANALYSIS_PROVIDER: "auto" },
});
expect(output.exitCode, output.stderr).toBe(0);
const result = interfaceBuilderAnalysisSchema.parse(
parseEvidence(output.json).normalized_result,
);
expect(result.graph.nodes).toContainEqual(
expect.objectContaining({
attributes: expect.objectContaining({
class_name: "\uFEFFWidget",
nibValues: { count: 1, "\uFEFFcount": 2 },
}),
}),
);
expect(JSON.stringify(result)).toContain("\uFEFFWidget");
},
);
cliTest(
"compiled CLI preserves a good archive and reports repeated key and data omissions",
async ({ cli }) => {
@@ -9,7 +9,10 @@ import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js
import { javascriptApplicationAnalysisResultSchema } from "../../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import { matchJavaScriptApplicationVersions } from "../../../../src/domain/javascript/javascriptApplicationVersionKeys.js";
import { findApplicationFeatureSeeds } from "../../../../src/domain/javascript/javascriptFeatureSeed.js";
import { traceApplicationFeatureInputSchema } from "../../../../src/domain/javascript/javascriptFeatureTraceSchemas.js";
import {
applicationFeatureSeedSchema,
traceApplicationFeatureInputSchema,
} from "../../../../src/domain/javascript/javascriptFeatureTraceSchemas.js";
import { analyzeJavaScriptApplication } from "../../../support/javascriptApplicationScope.js";
const analyzeSource = async (
@@ -76,6 +79,59 @@ it("retains empty literal evidence across the application boundary surfaces", as
);
});
it("keeps bridge entry paths stable through worker validation and API seed matching", async () => {
const output = await analyzeSource(`
const { contextBridge, ipcRenderer } = require("electron");
const literal = () => ipcRenderer.send("literal");
const nested = () => ipcRenderer.send("nested");
contextBridge.exposeInMainWorld("desktop", {
"nested.write": literal,
nested: { write: nested },
});
`);
const semanticPathIds = new Set(
(output.semantic_graph?.nodes ?? [])
.map(({ properties }) => properties.path_id)
.filter((pathId): pathId is string => typeof pathId === "string"),
);
const applicationPathIds = new Set(
output.graph.nodes.flatMap(({ observations }) =>
observations
.map(({ properties }) => properties.path_id)
.filter((pathId): pathId is string => typeof pathId === "string"),
),
);
expect(semanticPathIds).toEqual(applicationPathIds);
const matches = findApplicationFeatureSeeds(
output.graph.nodes,
applicationFeatureSeedSchema.parse({
kind: "api",
value: "desktop.nested.write",
entry_path: ["desktop", "nested.write"],
}),
);
expect(matches).toHaveLength(1);
expect(
output.graph.nodes
.find(({ node_id: nodeId }) => nodeId === matches[0]?.node_id)
?.observations.some(
({ properties }) =>
Array.isArray(properties.entry_path) &&
properties.entry_path.join("\0") === "desktop\0nested.write",
),
).toBe(true);
expect(
findApplicationFeatureSeeds(
output.graph.nodes,
applicationFeatureSeedSchema.parse({
kind: "api",
value: "desktop.nested.write",
}),
),
).toHaveLength(2);
});
it("analyzes a plain long-line loader without package metadata", async () => {
const output = await analyzeSource(
`var Module = {}; fetch(""); new Worker(""); var payload = "${"x".repeat(65_536)}";`,
@@ -240,8 +296,18 @@ it.each([
[{ kind: "channel", value: "" }, false],
[{ kind: "channel", value: "", match: "contains" }, false],
[{ kind: "node-id", value: "", match: "exact" }, false],
[{ kind: "api", value: "desktop.nested.write" }, true],
[
{
kind: "api",
value: "desktop.nested.write",
entry_path: ["desktop", "nested.write"],
},
true,
],
[{ kind: "channel", value: "channel", entry_path: ["channel"] }, false],
] as const)(
"validates empty seed %j at runtime and in the advertised schema",
"validates seed %j at runtime and in the advertised schema",
(seed, accepted) => {
expect(seedSchema.safeParse(seed).success).toBe(accepted);
expect(validateAdvertisedSeed(seed)).toBe(accepted);
@@ -37,6 +37,48 @@ import {
const root = fileURLToPath(new URL("../../..", import.meta.url));
const temporaryRoots: string[] = [];
const README_FACT_FIXTURE_PATHS = [
"README.md",
"docs/readme/README_zh.md",
"docs/readme/README_ja.md",
"docs/readme/README_ko.md",
"docs/readme/README_ar.md",
"website/locales/languages.json",
"docs/installation.md",
"AGENTS.md",
".github/pull_request_template.md",
] as const;
const README_LINK_DRIFT_MUTATIONS = [
["(../native-investigation.md)", "(../native-investigation.md?other=1)"],
[
"(../installation.md#supported-agents)",
"(../installation.md#missing-agents)",
],
["(../native-investigation.md)", "(../missing-native.md)"],
["https://rea.tools/zh-CN/guides/", "https://rea.tools/zh-TW/guides/"],
[
"https://rea.tools/zh-CN/guides/",
"https://rea.tools/zh-CN/guides/?other=1",
],
[
'src="../assets/rea-hopper-analysis.png"',
'src="../assets/missing-hopper.png"',
],
['href="https://discord.gg/GkcryMnJDM"', 'href="https://discord.gg/missing"'],
] as const;
const seedReadmeFactFixture = async (directory: string) => {
for (const path of README_FACT_FIXTURE_PATHS) {
const destination = join(directory, path);
await mkdir(dirname(destination), { recursive: true });
await copyFile(join(root, path), destination);
}
await mkdir(join(directory, "skills/reverse-engineer-anything"), {
recursive: true,
});
};
afterEach(async () => {
await Promise.all(
temporaryRoots
@@ -176,47 +218,14 @@ describe("canonical product catalog drift", () => {
it("keeps translated readmes linked to canonical setup and tool details", async () => {
const directory = await createTestTempDirectory("rea-readme-facts-");
temporaryRoots.push(directory);
const paths = [
"README.md",
"README_zh.md",
"README_ja.md",
"README_ko.md",
"README_ar.md",
"website/locales/languages.json",
"docs/installation.md",
"AGENTS.md",
".github/pull_request_template.md",
];
for (const path of paths) {
const destination = join(directory, path);
await mkdir(dirname(destination), { recursive: true });
await copyFile(join(root, path), destination);
}
await mkdir(join(directory, "skills/reverse-engineer-anything"), {
recursive: true,
});
const translatedPath = join(directory, "README_zh.md");
await seedReadmeFactFixture(directory);
const translatedPath = join(directory, "docs/readme/README_zh.md");
const translated = await readFile(translatedPath, "utf8");
const catalog = await createProductCatalog(root);
await expect(documentationFactIssues(directory, catalog)).resolves.toEqual(
[],
);
for (const [original, changed] of [
[
"(docs/installation.md#supported-agents)",
"(docs/installation.md#missing-agents)",
],
["(docs/native-investigation.md)", "(docs/missing-native.md)"],
[
"(docs/native-investigation.md)",
"(docs/native-investigation.md?other=1)",
],
["https://rea.tools/zh-CN/guides/", "https://rea.tools/zh-TW/guides/"],
[
"https://rea.tools/zh-CN/guides/",
"https://rea.tools/zh-CN/guides/?other=1",
],
] as const) {
for (const [original, changed] of README_LINK_DRIFT_MUTATIONS) {
expect(translated).toContain(original);
await writeFile(
translatedPath,
@@ -226,11 +235,10 @@ describe("canonical product catalog drift", () => {
await expect(
documentationFactIssues(directory, catalog),
).resolves.toEqual([
"README_zh.md: documentation links differ from README.md",
"docs/readme/README_zh.md: documentation links differ from README.md",
]);
}
});
it("fails check mode without rewriting a stale generated artifact", async () => {
const directory = await createTestTempDirectory("rea-generated-check-");
temporaryRoots.push(directory);
@@ -0,0 +1,111 @@
import { describe, expect, it } from "vitest";
import { createIdaMcpConnection } from "../../src/ida/IdaMcpConnection.js";
describe("IDA startup diagnostics", () => {
it("preserves the failing launcher's stderr instead of reporting only a closed transport", async () => {
const connection = createIdaMcpConnection(
{
command: process.execPath,
args: [
"-e",
'process.stderr.write("FATAL: IDA runtime initialization failed\\n", () => process.exit(2));',
],
env: {},
mode: "headless",
timeoutMs: 1000,
},
{},
);
try {
await expect(connection.connect()).rejects.toMatchObject({
_tag: "ProviderAdapterError",
capturedOutput: {
stderr: expect.stringContaining("IDA runtime initialization failed"),
truncated: false,
},
});
} finally {
await connection.close();
}
});
it("retains only the bounded stderr tail and reports the original byte count", async () => {
const connection = createIdaMcpConnection(
{
command: process.execPath,
args: [
"-e",
'process.stderr.write("x".repeat(20000) + "FATAL-END", () => process.exit(2));',
],
env: {},
mode: "headless",
timeoutMs: 1000,
},
{},
);
try {
await expect(connection.connect()).rejects.toMatchObject({
_tag: "ProviderAdapterError",
capturedOutput: {
stderr: "x".repeat(16384 - "FATAL-END".length) + "FATAL-END",
stderr_bytes: 20000 + "FATAL-END".length,
truncated: true,
},
});
} finally {
await connection.close();
}
});
});
it("drops a leading partial UTF-8 character from the bounded stderr tail", async () => {
const connection = createIdaMcpConnection(
{
command: process.execPath,
args: [
"-e",
'process.stderr.write("€".repeat(6000), () => process.exit(2));',
],
env: {},
mode: "headless",
timeoutMs: 1000,
},
{},
);
try {
await expect(connection.connect()).rejects.toMatchObject({
capturedOutput: {
stderr: "€".repeat(Math.floor(16384 / 3)),
stderr_bytes: 18000,
truncated: true,
},
});
} finally {
await connection.close();
}
});
it("retains an in-budget undecodable leading byte without claiming tail truncation", async () => {
const connection = createIdaMcpConnection(
{
command: process.execPath,
args: [
"-e",
"process.stderr.write(Buffer.from([0x80, 0x61, 0x62]), () => process.exit(2));",
],
env: {},
mode: "headless",
timeoutMs: 1000,
},
{},
);
try {
const failure = await connection.connect().catch((cause: unknown) => cause);
expect(failure).toMatchObject({
capturedOutput: { stderr: "�ab", stderr_bytes: 3, truncated: false },
});
expect(failure).not.toHaveProperty("diagnostics.upstream_stderr");
} finally {
await connection.close();
}
});
@@ -1,7 +1,13 @@
import { createHash } from "node:crypto";
import { execFile } from "node:child_process";
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
import { expect, it } from "vitest";
import { JavaScriptAnalysisWorker } from "../../../src/javascript/analysis/JavaScriptAnalysisWorker.js";
import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js";
import type { OwnedProcessGroup } from "../../../src/process/ProcessOwnership.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
@@ -151,6 +157,121 @@ it("preserves a failed owned cleanup retry when the next caller cancels before a
}
});
it("ends worker stdin and unreferences process handles when cleanup reports inspection uncertainty", async () => {
let stdinEnded = false;
let unreferenced = false;
let permitCleanup = false;
let childStdin: typeof process.stdin | undefined;
const worker = new JavaScriptAnalysisWorker(
{ heapMb: 128, timeoutMs: 30_000 },
async (request) => {
const launched = await spawnOwnedProviderProcess(request);
const originalUnref = launched.process.unref;
launched.process.unref = () => {
unreferenced = true;
originalUnref?.call(launched.process);
};
childStdin = launched.process.stdin as unknown as typeof process.stdin;
launched.process.stdin?.once("finish", () => {
stdinEnded = true;
});
return {
...launched,
cleanup: async () =>
permitCleanup
? launched.cleanup === undefined
? cleanupOwnedProcessGroup(launched.ownership)
: launched.cleanup()
: {
cleaned: false,
reason: "process table could not be inspected: spawn EPERM",
},
};
},
);
try {
const file = source("app.mjs", "export const observed = 7;");
const result = await worker.analyze(file, 100);
if (!result.ok) throw result.error.error;
const closing = worker.close();
await expect(closing).rejects.toBeInstanceOf(ProviderCleanupError);
await expect(closing).rejects.toMatchObject({
cause: {
message: "process table could not be inspected: spawn EPERM",
},
});
expect(childStdin?.writableEnded || stdinEnded).toBe(true);
expect(unreferenced).toBe(true);
const errorListeners = childStdin?.listenerCount("error");
for (let retry = 0; retry < 3; retry++)
await expect(worker.close()).rejects.toBeInstanceOf(ProviderCleanupError);
expect(childStdin?.listenerCount("error")).toBeLessThanOrEqual(
errorListeners ?? 0,
);
permitCleanup = true;
await worker.close();
} finally {
permitCleanup = true;
await worker.close().catch(() => {});
}
});
it("lets a separate host exit while its live worker cleanup remains incomplete", async () => {
const root = await createTestTempDirectory("rea-worker-incomplete-host-");
const ownershipPath = join(root, "ownership.json");
const workerUrl = new URL(
"../../../dist/javascript/analysis/JavaScriptAnalysisWorker.js",
import.meta.url,
).href;
const launcherUrl = new URL(
"../../../dist/process/ProviderProcess.js",
import.meta.url,
).href;
const script = `
import { writeFile } from "node:fs/promises";
import { pathToFileURL } from "node:url";
import { JavaScriptAnalysisWorker } from ${JSON.stringify(workerUrl)};
import { spawnOwnedProviderProcess } from ${JSON.stringify(launcherUrl)};
const worker = new JavaScriptAnalysisWorker({ heapMb: 128, timeoutMs: 10000 }, async request => {
const entry = pathToFileURL(request.arguments.at(-1)).href;
const launched = await spawnOwnedProviderProcess({ ...request, arguments: [
...request.arguments.slice(0, -1), "--input-type=module", "-e",
"const interval = setInterval(() => {}, 1000); setTimeout(() => clearInterval(interval), 60000); await import(" + JSON.stringify(entry) + ");"
] });
// The launcher is deliberately orphaned when this host exits; cleanup still
// requires its run token and executable identity, rather than its old parent.
const { expectedParentPid, ...ownership } = launched.ownership;
await writeFile(${JSON.stringify(ownershipPath)}, JSON.stringify(ownership));
return { ...launched, cleanup: async () => ({ cleaned: false, reason: "fixture inspection unavailable" }) };
});
const analyzed = await worker.analyze(${JSON.stringify(source("app.mjs", "export const value = 1;"))}, 100);
if (!analyzed.ok) throw analyzed.error.error;
try { await worker.close(); throw new Error("cleanup unexpectedly completed"); }
catch (error) {
if (error.cleanupIncomplete !== true) throw error;
process.stdout.write(JSON.stringify({ code: "cleanup_incomplete", reason: error.cause.message }) + "\\n");
}
`;
try {
const result = await promisify(execFile)(
process.execPath,
["--input-type=module", "-e", script],
{ timeout: 10_000 },
);
expect(JSON.parse(result.stdout)).toMatchObject({
code: "cleanup_incomplete",
reason: "fixture inspection unavailable",
});
} finally {
const ownership = JSON.parse(
await readFile(ownershipPath, "utf8"),
) as OwnedProcessGroup;
expect(await cleanupOwnedProcessGroup(ownership)).toMatchObject({
cleaned: true,
});
}
});
// The handshake mirrors the real server: only Node.js reports an enforced V8 heap limit.
const resourceFailureWorker = (heapLimit: string) =>
new JavaScriptAnalysisWorker({ heapMb: 128, timeoutMs: 30_000 }, (request) =>
@@ -0,0 +1,86 @@
import { describe, expect, it } from "vitest";
import type {
CallToolResult,
ServerContext,
} from "@modelcontextprotocol/server";
import { STDIO_DEFAULT_MAX_BUFFER_SIZE } from "@modelcontextprotocol/server";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { AnalysisCancelledError } from "../../../src/domain/analysisErrorCore.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import type { Evidence } from "../../../src/domain/evidence.js";
import { err, ok } from "../../../src/domain/result.js";
import { silentLogger } from "../../../src/logger.js";
import { createEvidenceToolHandler } from "../../../src/server/contractToolHandler.js";
import { EvidenceMcpServer } from "../../../src/server/EvidenceMcpServer.js";
import { ToolResultDelivery } from "../../../src/server/toolResult.js";
const UNTRUSTED_TARGET_CONTENT = {
provenance: { untrusted_content: true, source: "analysis_target" },
};
const context = {
mcpReq: { signal: new AbortController().signal },
} as ServerContext;
/**
* Deliver one retained partial-observation failure through the shared Evidence
* handler. The handler is the producer of the result: `EvidenceMcpServer` only
* adds the marker later for results that bypass `ToolResultDelivery`, so a
* missing marker here also undercounts the wire budget by the marker's bytes.
*/
const deliverPartialFailure = async (): Promise<{
readonly result: CallToolResult;
readonly evidence: Evidence;
}> => {
const evidence = createEvidence(
undefined,
{ id: "fixture", name: "Completed capture fixture", version: "1" },
{
operation: "inspect_packet_capture",
parameters: { path: "recording.pcap" },
result: { packets: [{ "frame.number": ["1"] }] },
confidence: "observed",
},
);
const failure = new AnalysisCancelledError("inspect_packet_capture", {
partialObservation: evidence,
});
const writer = { recordEvidence: () => ok("added" as const) };
const server = new EvidenceMcpServer(
{ name: "partial-error-framing-test", version: "1" },
{ capabilities: {} },
writer.recordEvidence,
new ToolResultDelivery(STDIO_DEFAULT_MAX_BUFFER_SIZE),
);
const contract = toolContract("inspect_packet_capture");
const handler = createEvidenceToolHandler(
server,
async () => err(failure),
silentLogger,
writer.recordEvidence,
);
return {
result: await handler(contract)({ path: "recording.pcap" }, context),
evidence,
};
};
describe("shared Evidence handler target-content framing", () => {
it("marks a retained partial-observation error as untrusted target content", async () => {
const { result, evidence } = await deliverPartialFailure();
expect(result.isError).toBe(true);
expect(result.structuredContent).toMatchObject({
error: {
details: {
partial_observation: {
kind: "retained-evidence",
evidence_id: evidence.evidence_id,
},
},
},
});
expect(result._meta).toEqual(UNTRUSTED_TARGET_CONTENT);
});
});
+21 -3
View File
@@ -1,4 +1,5 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { createHash } from "node:crypto";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it, onTestFinished, vi } from "vitest";
import { EvmInterfaceService } from "../../../src/application/evm/EvmInterfaceService.js";
@@ -10,6 +11,7 @@ import {
} from "../../../src/domain/analysisErrorCore.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import { evmInterfaceSummaryViewResultSchema } from "../../../src/domain/analysisView/analysisView.js";
import { inspectSolidityMetadata } from "../../../src/evm/SolidityMetadata.js";
import { err, ok } from "../../../src/domain/result.js";
import { silentLogger } from "../../../src/logger.js";
import { createServer } from "../../../src/server/createServer.js";
@@ -26,8 +28,21 @@ import {
evmInterfaceExecution,
} from "../../fixtures/evm/interface.js";
it("advertises exact valid schemas and records inline EVM interface evidence without a binary target", async () => {
const decodedMetadataFixture = () => {
const bytes = Buffer.from("00a1011bffffffffffffffff000b", "hex");
const value = evmInterfaceFixture();
value.bytecode = {
...value.bytecode,
hex: bytes.toString("hex"),
bytes: bytes.length,
sha256: createHash("sha256").update(bytes).digest("hex"),
metadata: inspectSolidityMetadata(bytes),
};
return value;
};
it("advertises exact valid schemas and records inline EVM interface evidence without a binary target", async () => {
const value = decodedMetadataFixture();
const inspect = vi.fn(() =>
Promise.resolve(ok(evmInterfaceExecution(value))),
);
@@ -280,7 +295,8 @@ it("settles the admitted EVM operation after SDK cancellation and accepts a subs
});
it("returns the exact inferred interface summary while preserving complete defaults and retained source", async () => {
const value = evmInterfaceFixture();
const value = decodedMetadataFixture();
expect(value.bytecode.metadata?.status).toBe("decoded");
value.functions = [
{
selector: "0x11223344",
@@ -419,6 +435,7 @@ it.each(["valid", "wrong-subject", "no-subject"])(
"preserves historical portable EVM Evidence and rejects incompatible identity: %s",
async (scenario) => {
const value = evmInterfaceFixture();
const { metadata: _metadata, ...historicalBytecode } = value.bytecode;
const source = createEvidence(
scenario === "no-subject"
? undefined
@@ -434,7 +451,7 @@ it.each(["valid", "wrong-subject", "no-subject"])(
{
operation: "inspect_evm_interface",
parameters: { path: value.artifact.path, encoding: "hex" },
result: value,
result: { ...value, bytecode: historicalBytecode },
confidence: "inferred",
rawResult: { original: true },
},
@@ -463,6 +480,7 @@ it.each(["valid", "wrong-subject", "no-subject"])(
expect(view.parent_evidence_id).toBe(source.evidence_id);
expect(view.summary.functions).toEqual([]);
expect(view.summary.discovery_completeness).toBe("unknown");
expect(view.summary.bytecode.metadata).toBeNull();
expect(view.coverage).toMatchObject({
total: 0,
examined: 0,
@@ -1,6 +1,14 @@
import { ok as resultOk } from "../../../src/domain/result.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
import { describe, expect, it, onTestFinished } from "vitest";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import { compareFunctions } from "../../../src/domain/functionComparison.js";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { FUNCTION_COMPARISON_EXAMPLE } from "../../../src/contracts/functionComparisonExample.js";
@@ -271,3 +279,130 @@ describe("function comparison MCP integration", () => {
}
});
});
it.each([
{ status: "changed", expected: "fail" },
{ status: "unknown", expected: "unknown" },
{ status: "unchanged", expected: "pass" },
] as const)(
"checks the aggregate status of imported $status function comparisons",
async ({ status, expected }) => {
const left = FUNCTION_COMPARISON_EXAMPLE.left;
const right =
status === "changed"
? FUNCTION_COMPARISON_EXAMPLE.right
: createEvidence(
{
path: "/fixture/function-right",
sha256: "3".repeat(64),
format: "mach-o",
},
status === "unknown"
? { ...left.provider, id: "other-provider" }
: left.provider,
{
operation: left.operation,
parameters: left.parameters,
result: left.normalized_result,
confidence: left.confidence,
authority: left.authority,
relationshipCoverage: { status: "complete" },
},
);
const result = compareFunctions(left, right);
expect(result.status).toBe(status);
const provider = {
id: "rea-function-comparison",
name: "REA function comparison",
version: "1",
};
const observation = {
operation: "compare_functions",
predicateType: "rea.function-comparison",
parameters: {
left_evidence_id: left.evidence_id,
right_evidence_id: right.evidence_id,
},
confidence: "derived" as const,
authority: "analyst-inference" as const,
evidenceLinks: [left.evidence_id, right.evidence_id],
};
const consistent = createEvidence(undefined, provider, {
...observation,
result: jsonValueSchema.parse(result),
});
const inconsistent =
status === "unchanged"
? null
: createEvidence(undefined, provider, {
...observation,
result: jsonValueSchema.parse({ ...result, status: "unchanged" }),
});
const directory = await createTestTempDirectory("rea-function-status-");
const path = join(directory, "bundle.json");
await writeFile(
path,
JSON.stringify(
createEvidenceBundle([
left,
right,
consistent,
...(inconsistent === null ? [] : [inconsistent]),
]),
),
);
const session = createTestBinarySession(() => {
throw new Error("Imported comparison must not launch a provider");
});
const harness = await createApplicationMcpHarness({ session });
onTestFinished(harness.close);
const imported = await harness.client.callTool({
name: "import_evidence_bundle",
arguments: { path },
});
expect(imported.isError).not.toBe(true);
const verification = (evidence_id: string) =>
harness.client.callTool({
name: "verify_reconstruction",
arguments: {
specification: {
name: "Function aggregate",
claims: [
{
kind: "structural-function",
claim_id: "overall",
title: "Function agrees",
comparison_evidence_id: evidence_id,
dimension: "overall",
},
],
},
},
});
if (inconsistent !== null) {
const rejected = await verification(inconsistent.evidence_id);
expect(parseMcpToolError(rejected).error).toMatchObject({
code: "invalid_request",
details: {
issues: [
{
reason: "invalid_value",
message: expect.stringContaining(
"Function comparison status contradicts its dimensions or function match",
),
},
],
},
});
expect(harness.session.evidenceById(inconsistent.evidence_id)).toEqual(
inconsistent,
);
}
const verified = await verification(consistent.evidence_id);
expect(verified.isError).not.toBe(true);
expect(
parseEvidence(verified.structuredContent).normalized_result,
).toMatchObject({ status: expected });
await harness.client.ping();
},
);
@@ -1,10 +1,86 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { expect, it } from "vitest";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { nativeAotPeFixture } from "../../fixtures/nativeaotPe.js";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
import { ok } from "../../../src/domain/result.js";
import { ghidraFunctionIdentity } from "../../../src/domain/ghidraValues.fixture.js";
import { connectGhidraMcp, sessionEvidence } from "./ghidraMcpHarness.js";
it("retains missing PDB coverage in empty PE name-search Evidence and snapshot replay", async () => {
const root = await createTestTempDirectory("rea-pdb-evidence-");
const targetPath = join(root, "fixture.exe");
await writeFile(targetPath, nativeAotPeFixture());
// Synthetic post-analysis facts at the real provider boundary; no engine is simulated as verified.
const pdb = {
file: "C:\\build\\fixture.pdb",
guid: "01234567-89AB-CDEF-0123-456789ABCDEF",
age: "a",
signature: null,
version: "RSDS",
loaded: false,
};
const harness = await connectGhidraMcp(
"ghidra-pdb-coverage",
(operation) =>
Promise.resolve(
ok(
operation === "procedure_pseudo_code"
? {
value: "int FUN_140001000(void) { return 0; }",
limitations: [],
}
: [],
),
),
{
targetPath,
pdb,
},
);
try {
const reply = await harness.mcp.callTool({
name: "search_procedures",
arguments: { pattern: "add_numbers" },
});
expect(reply.isError).not.toBe(true);
const evidence = sessionEvidence(harness.session, reply.structuredContent);
expect(evidence.normalized_result).toEqual([]);
expect(evidence.analysis_profile?.parameters.pdb_observations).toBe(
"program-info-v1",
);
const limitation = evidence.limitations.find((value) =>
value.includes(pdb.file),
);
expect(limitation).toContain(pdb.guid);
expect(limitation).toContain("age (hex) a");
expect(limitation).toContain("not loaded");
const decompiled = await harness.mcp.callTool({
name: "procedure_pseudo_code",
arguments: { procedure: "0x140001000", document: "fixture" },
});
expect(decompiled.isError).not.toBe(true);
const functionEvidence = sessionEvidence(
harness.session,
decompiled.structuredContent,
);
expect(functionEvidence.limitations).toContain(limitation);
const replay = await harness.session.execute(
"procedure_pseudo_code",
functionEvidence.parameters,
);
if (!replay.ok) throw replay.error;
expect(replay.value.limitations).toContain(limitation);
expect(replay.value.limitations).toContainEqual(
expect.stringContaining("Loaded from a local REA analysis snapshot"),
);
} finally {
await harness.close();
}
});
it("retains defined-string coverage in empty and matching search Evidence", async () => {
let output = jsonValueSchema.parse([]);
const harness = await connectGhidraMcp("ghidra-string-coverage", () =>
+10 -2
View File
@@ -12,6 +12,7 @@ import type { GhidraOperation } from "../../../src/ghidra/GhidraClient.js";
import { GhidraProvider } from "../../../src/ghidra/GhidraProvider.js";
import type { GhidraProviderClientFactory } from "../../../src/ghidra/GhidraProviderClient.js";
import { GHIDRA_SESSION_CAPABILITIES } from "../../../src/ghidra/GhidraSessionValues.js";
import type { GhidraSessionInfo } from "../../../src/ghidra/GhidraSessionValues.js";
import { silentLogger } from "../../../src/logger.js";
import { createServer } from "../../../src/server/createServer.js";
import {
@@ -26,12 +27,19 @@ const INSTALL = "/opt/ghidra_12.1.4_PUBLIC";
export const connectGhidraMcp = async (
name: string,
execute?: ReturnType<GhidraProviderClientFactory>["callTool"],
observations: {
readonly targetPath?: string;
readonly pdb?: GhidraSessionInfo["pdb"];
} = {},
) => {
const calls: GhidraOperation[] = [];
const factory: GhidraProviderClientFactory = (options) => ({
start: () =>
Promise.resolve(
ok(sessionInfo(options.profileDigest, options.targetSha256)),
ok({
...sessionInfo(options.profileDigest, options.targetSha256),
...(observations.pdb === undefined ? {} : { pdb: observations.pdb }),
}),
),
callTool: (operation, input, options) => {
calls.push(operation);
@@ -68,7 +76,7 @@ export const connectGhidraMcp = async (
await mcp.connect(clientTransport);
const opened = await mcp.callTool({
name: "open_binary",
arguments: { path: process.execPath },
arguments: { path: observations.targetPath ?? process.execPath },
});
if (opened.isError === true)
throw new Error(
+16 -3
View File
@@ -342,17 +342,30 @@ it("exposes overload candidates and executes only an explicitly selected ambiguo
expect(result.method).toMatchObject({
overload_index: 1,
reported_signature: "choose(int): void",
dex_descriptor: null,
dex_descriptor: "(I)V",
});
expect(result.source.text).toContain("overload 1");
const references = await service.execute("trace_android_references", input);
expect(references).toMatchObject({
ok: false,
error: {
_tag: "AnalysisCapabilityUnavailableError",
reason: expect.stringContaining("unique method name"),
_tag: "AnalysisInputError",
issues: [expect.objectContaining({ path: ["overload_index"] })],
},
});
const selectedReferences = await service.execute("trace_android_references", {
...input,
overload_index: 1,
});
if (!selectedReferences.ok) throw selectedReferences.error;
expect(
androidResultSchemas.trace_android_references.parse(
selectedReferences.value.normalized_result,
),
).toMatchObject({
overload_index: 1,
reported_signature: "choose(int): void",
});
await provider.close();
await verifyCleanup(launches);
});
@@ -486,7 +486,9 @@ describe("Ghidra Windows launcher", () => {
}),
).toThrow(/metacharacters/u);
});
});
describe("Ghidra Windows launcher runtime", () => {
it.skipIf(process.platform !== "win32").each([
{
properties:
@@ -208,6 +208,22 @@ it("preserves missing callgraph coverage through direct, graph, and trace workfl
]),
);
const dossier = await client.execute("analyze_function", {
procedure: "main",
});
if (!dossier.ok) throw dossier.error;
expect(dossier.value.result).toMatchObject({
callers: [],
callees: [],
facet_availability: {
callers: { available: false },
callees: {
available: false,
reason: expect.stringContaining("callgraph was unavailable"),
},
},
});
const application = new EnhancedTools(client);
const graph = await application.execute("get_call_graph", {
address: "main",
@@ -12,6 +12,7 @@ import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js
import { NativeMacOSProvider } from "../../../../src/native/NativeMacOSProvider.js";
import {
NATIVE_COMMAND_OUTPUT_BUDGET_BYTES,
NATIVE_FAILURE_DIAGNOSTIC_BYTES,
NativeCommandFailure,
XcrunCommandRunner,
type NativeCommandRunner,
@@ -381,6 +382,36 @@ describe("native command failure capture and limits", () => {
});
});
it("bounds both failure streams at a UTF-8 boundary while keeping their totals", async () => {
const runner = new XcrunCommandRunner({}, () =>
Promise.resolve(ok({ path: process.execPath, sha256: "a".repeat(64) })),
);
// "é" is two bytes and straddles the excerpt boundary, so it is dropped whole.
const stdout = `${"x".repeat(NATIVE_FAILURE_DIAGNOSTIC_BYTES - 1)}é${"y".repeat(1024)}`;
const stderr = "z".repeat(NATIVE_FAILURE_DIAGNOSTIC_BYTES + 1024);
// Build the output in the child: one Linux argument is limited to 128 KiB.
const result = await runner.run(
"file",
[
"-e",
`const stdout = "x".repeat(${String(NATIVE_FAILURE_DIAGNOSTIC_BYTES - 1)}) + "\u00e9" + "y".repeat(1024); const stderr = "z".repeat(${String(NATIVE_FAILURE_DIAGNOSTIC_BYTES + 1024)}); process.stdout.write(stdout, () => process.stderr.write(stderr, () => process.exit(3)));`,
],
{},
);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error.reason).toBe("nonzero-exit");
expect(result.error.capture).toMatchObject({
stdout: "x".repeat(NATIVE_FAILURE_DIAGNOSTIC_BYTES - 1),
stderr: "z".repeat(NATIVE_FAILURE_DIAGNOSTIC_BYTES),
stdoutBytes: Buffer.byteLength(stdout),
stderrBytes: Buffer.byteLength(stderr),
exitCode: 3,
truncated: true,
});
});
it("rejects output beyond the complete native-command budget", async () => {
const runner = new XcrunCommandRunner({}, () =>
Promise.resolve(ok({ path: process.execPath, sha256: "a".repeat(64) })),
@@ -404,6 +435,13 @@ describe("native command failure capture and limits", () => {
(result.error.capture?.stdoutBytes ?? 0) +
(result.error.capture?.stderrBytes ?? 0),
).toBeLessThanOrEqual(NATIVE_COMMAND_OUTPUT_BUDGET_BYTES);
// The failure carries an excerpt, not the whole retained output budget.
expect(result.error.capture?.stdout.length).toBe(
NATIVE_FAILURE_DIAGNOSTIC_BYTES,
);
expect(result.error.capture?.stdoutBytes).toBeGreaterThan(
NATIVE_FAILURE_DIAGNOSTIC_BYTES,
);
});
});
@@ -834,6 +872,43 @@ describe("native signature entitlements", () => {
});
});
/** Fail every codesign call nonzero after writing more than one excerpt. */
class VerboseCodeSignFailureRunner extends FixtureRunner {
override async run(tool: string, arguments_: readonly string[]) {
const result = await super.run(tool, arguments_);
if (!result.ok || tool !== "codesign") return result;
const stderr = "e".repeat(NATIVE_FAILURE_DIAGNOSTIC_BYTES * 2);
return ok({
...result.value,
stderr,
stderrBytes: Buffer.byteLength(stderr),
exitCode: 1,
});
}
}
describe("native signature failure diagnostics", () => {
it("bounds accepted nonzero codesign output once it becomes a failure", async () => {
directory = await createTestTempDirectory("rea-signature-failure-");
const executable = join(directory, "fixture");
await writeFile(executable, "fixture");
const client = new NativeMacOSProvider(
{},
new VerboseCodeSignFailureRunner(),
"darwin",
).createClient(await nativeMachoTargetForFile(executable));
const signature = await client.execute("inspect_signature", {});
if (signature.ok) throw new Error("A failed codesign run must fail");
expect(signature.error.capturedOutput).toMatchObject({
stderr: "e".repeat(NATIVE_FAILURE_DIAGNOSTIC_BYTES),
stderr_bytes: NATIVE_FAILURE_DIAGNOSTIC_BYTES * 2,
truncated: true,
});
});
});
describe("native dispatch metadata error results", () => {
it("preserves tagged cancellation and integrity failures", async () => {
directory = await createTestTempDirectory("rea-dispatch-errors-");
@@ -1,3 +1,7 @@
import {
descriptorFailurePath,
expectRetainedDescriptor,
} from "../../fixtures/descriptorCloseFailure.js";
import { expect, it, onTestFinished, vi } from "vitest";
import { writeFile } from "node:fs/promises";
import type { FileHandle } from "node:fs/promises";
@@ -15,27 +19,22 @@ const cleanup = vi.hoisted(() => ({
}));
vi.mock("node:fs/promises", async (importOriginal) => {
const filesystem = await importOriginal<typeof import("node:fs/promises")>();
return {
...filesystem,
open: async (...args: Parameters<typeof filesystem.open>) => {
const handle = await filesystem.open(...args);
if (args[0] === cleanup.path) {
cleanup.handles.push(handle);
const close = handle.close.bind(handle);
handle.close = async () => {
if (cleanup.denied && handle.fd >= 0)
throw new Error("Descriptor close deliberately denied");
await close();
};
}
return handle;
},
};
const { withDescriptorCloseFailure } =
await import("../../fixtures/descriptorCloseFailure.js");
return withDescriptorCloseFailure(filesystem, cleanup);
});
it
.runIf(process.platform === "linux")
.each(["capture", "tool", "limiter", "kernel"])(
.each([
"capture",
"tool",
"limiter",
"kernel",
"field-tool",
"field-limiter",
"field-kernel",
])(
"retains failed %s descriptors and retries them before further acquisition and shutdown",
async (member) => {
const directory = await createTestTempDirectory("rea-signal-descriptor-");
@@ -67,14 +66,16 @@ it
},
() => PrivateRuntimeRoot.create({ parent: directory }),
);
cleanup.path =
member === "capture"
? path
: member === "tool"
? command
: member === "limiter"
? limiter
: "/proc/self/limits";
const discovery = member.startsWith("field-");
const resource = discovery ? member.slice(6) : member;
const operation = discovery
? "inspect_signal_decoders"
: "decode_signal_recording";
cleanup.path = descriptorFailurePath(resource, {
capture: path,
tool: command,
limiter,
});
cleanup.denied = true;
cleanup.handles = [];
onTestFinished(async () => {
@@ -84,22 +85,20 @@ it
cleanup.path = "";
});
const service = new SignalRecordingService(provider);
const first = await service.decode({ path, decoders: "uart" });
expect(first).toMatchObject({
ok: false,
error: { cleanupIncomplete: true, cleanupResources: [cleanup.path] },
});
expect(cleanup.handles).toHaveLength(1);
expect(cleanup.handles[0]?.fd).toBeGreaterThanOrEqual(0);
const first = discovery
? await service.inspectDecoders({ query: "uart" })
: await service.decode({ path, decoders: "uart" });
expectRetainedDescriptor(first, cleanup, operation);
const launchCount = launches;
expect(await service.decode({ path, decoders: "uart" })).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
error: { cleanupIncomplete: true, operation },
});
expect(cleanup.handles).toHaveLength(1);
expect(launches).toBe(launchCount);
await expect(provider.close()).rejects.toMatchObject({
cleanupIncomplete: true,
operation,
});
cleanup.denied = false;
await provider.close();
@@ -130,6 +130,71 @@ it("accounts for JSON escape expansion of a stored declaration in the reply limi
]);
});
it("attributes triggers declared with another ASCII case to the stored table name", async () => {
const path = await createDatabase(`
CREATE TABLE Users(id INTEGER PRIMARY KEY, email TEXT);
CREATE INDEX users_email ON users(email);
CREATE TRIGGER audit_insert AFTER INSERT ON users BEGIN SELECT 1; END;
CREATE TRIGGER audit_delete AFTER DELETE ON USERS BEGIN SELECT 1; END;
CREATE VIEW recent AS SELECT 1;
CREATE TRIGGER recent_insert INSTEAD OF INSERT ON Recent BEGIN SELECT 1; END;
`);
const selected = inspectSqliteDatabaseSnapshot(path, {
path,
table: "Users",
});
expect(selected.schema).toMatchObject({
scope: "selected_table",
completeness: "complete",
tables: [{ name: "Users" }],
indexes: [{ name: "users_email", table: "Users" }],
views: [],
});
expect(
selected.schema.triggers.map(({ name, table }) => ({ name, table })),
).toEqual([
{ name: "audit_insert", table: "Users" },
{ name: "audit_delete", table: "Users" },
]);
const inventory = inspectSqliteDatabaseSnapshot(path, { path });
expect(inventory.schema.triggers).toEqual([
{ name: "audit_insert", table: "Users" },
{ name: "audit_delete", table: "Users" },
{ name: "recent_insert", table: "recent" },
]);
});
it.each([
{
selection: "a differently cased table",
schema: "CREATE TABLE Users(id INTEGER PRIMARY KEY)",
trigger: "AFTER INSERT ON Users",
table: "users",
},
{
selection: "an exact view",
schema: "CREATE VIEW Recent AS SELECT 1 AS id",
trigger: "INSTEAD OF INSERT ON recent",
table: "Recent",
},
])(
"refuses $selection before expanding declarations under another spelling",
async ({ schema, trigger, table }) => {
const path = await createDatabase(`
${schema};
CREATE TRIGGER expanded ${trigger} BEGIN /*${"\u0001".repeat(3 * 1024 * 1024)}*/ SELECT 1; END;
`);
expect(() =>
inspectSqliteDatabaseSnapshot(path, { path, table }),
).toThrowError(
expect.objectContaining({
reason: "selection",
message: `Selected ordinary table does not exist with that exact name: ${table}`,
}),
);
},
);
it.each(["UTF-8", "UTF-16le", "UTF-16be"])(
"preserves exact %s schema text when decoding native bytes",
async (encoding) => {
@@ -357,6 +357,30 @@ it("does not execute views when selecting rows", async () => {
});
});
nativeTest.each(["absent.db", "absent-parent/absent.db"])(
"classifies a missing %s as an invalid value",
async (name) => {
const workspace = await createTestWorkspace("rea-sqlite-missing-");
onTestFinished(() => removeTestWorkspace(workspace.root));
const path = workspace.path(name);
const provider = createProvider();
onTestFinished(() => provider.close());
const result = await provider.inspect({ path });
if (result.ok) throw new Error("Expected a missing database rejection");
expect(projectAnalysisError(result.error)).toMatchObject({
details: {
issues: [
{
path: ["path"],
reason: "invalid_value",
message: `Selected SQLite database does not exist: ${path}`,
},
],
},
});
},
);
it("attributes table and column selection failures to their own arguments", async () => {
const { database } = await createFixture();
const provider = createProvider();
+83 -68
View File
@@ -1,6 +1,7 @@
import { rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { projectAnalysisError } from "../../src/domain/analysisErrorProjection.js";
import { IdaProvider } from "../../src/ida/IdaProvider.js";
import { createIdaTarget, RecordingIdaMcp } from "../fixtures/idaMcp.js";
import { createTestBinarySession } from "../fixtures/binarySession.js";
@@ -21,6 +22,73 @@ afterEach(async () => {
await rm(root, { recursive: true, force: true });
});
const reobservesExternallyMutableState = async (): Promise<void> => {
const { root, target } = await createIdaTarget();
roots.push(root);
const path = join(root, "registration.json");
await writeFile(path, JSON.stringify({ command: "fixture" }));
const config = parseConfig({ REA_IDA_MCP_CONFIG: path });
if (!config.ok) throw config.error;
const producer = new RecordingIdaMcp(target);
const session = createTestBinarySession(
new IdaProvider(config.value, {}, () => producer),
);
expect((await session.open(target.path)).ok).toBe(true);
const query = { procedure: "main", document: target.path };
const first = await session.execute("procedure_pseudo_code", query);
expect(first.ok && first.value.result).toContain("42");
const snapshot = session.exportAnalysisSnapshot();
if (!snapshot.ok) throw snapshot.error;
expect(snapshot.value.entries).toEqual([]);
const profile = session.analysisProfile();
if (profile === undefined) throw new Error("Missing profile");
const cached = createAnalysisExecution(
"stale output",
IDA_PROVIDER_IDENTITY,
{
analysisProfile: profile,
subject: {
path: target.path,
sha256: target.sha256,
format: target.format,
...(target.architecture === undefined
? {}
: { architecture: target.architecture }),
},
},
);
snapshot.value.entries.push(
createAnalysisSnapshotEntry({
target: snapshotTarget(target),
binding: snapshotBinding(profile),
operation: "procedure_pseudo_code",
parameters: query,
execution: cached,
}),
);
snapshot.value.evidence_bundle = createEvidenceBundle([
...snapshot.value.evidence_bundle.records,
createEvidence(target, IDA_PROVIDER_IDENTITY, {
operation: "procedure_pseudo_code",
parameters: query,
result: cached.result,
rawResult: cached.rawResult,
analysisProfile: profile,
}),
]);
expect(session.importAnalysisSnapshot(snapshot.value).ok).toBe(true);
expect(session.allowsSnapshotReplay("procedure_pseudo_code")).toBe(false);
expect(session.allowsSnapshotReplay("binary_overview")).toBe(false);
producer.pseudocode = "int main(void) { return 99; }";
const second = await session.execute("procedure_pseudo_code", query);
expect(second.ok && second.value.result).toContain("99");
expect(
producer.calls.filter(({ name }) => name === "decompile_function"),
).toHaveLength(2);
await session.close();
expect(producer.closes).toBe(1);
};
describe("IDA provider composition", () => {
it("discovers without launching and commits adapter semantics without persisting credentials", async () => {
const { root, target } = await createIdaTarget();
@@ -58,72 +126,10 @@ describe("IDA provider composition", () => {
.find(({ operation }) => operation === "procedure_callers")?.available,
).toBe(false);
});
it("re-observes externally mutable state even when a document is explicit and a snapshot is imported", async () => {
const { root, target } = await createIdaTarget();
roots.push(root);
const path = join(root, "registration.json");
await writeFile(path, JSON.stringify({ command: "fixture" }));
const config = parseConfig({ REA_IDA_MCP_CONFIG: path });
if (!config.ok) throw config.error;
const producer = new RecordingIdaMcp(target);
const session = createTestBinarySession(
new IdaProvider(config.value, {}, () => producer),
);
expect((await session.open(target.path)).ok).toBe(true);
const query = { procedure: "main", document: target.path };
const first = await session.execute("procedure_pseudo_code", query);
expect(first.ok && first.value.result).toContain("42");
const snapshot = session.exportAnalysisSnapshot();
if (!snapshot.ok) throw snapshot.error;
expect(snapshot.value.entries).toEqual([]);
const profile = session.analysisProfile();
if (profile === undefined) throw new Error("Missing profile");
const cached = createAnalysisExecution(
"stale output",
IDA_PROVIDER_IDENTITY,
{
analysisProfile: profile,
subject: {
path: target.path,
sha256: target.sha256,
format: target.format,
...(target.architecture === undefined
? {}
: { architecture: target.architecture }),
},
},
);
snapshot.value.entries.push(
createAnalysisSnapshotEntry({
target: snapshotTarget(target),
binding: snapshotBinding(profile),
operation: "procedure_pseudo_code",
parameters: query,
execution: cached,
}),
);
snapshot.value.evidence_bundle = createEvidenceBundle([
...snapshot.value.evidence_bundle.records,
createEvidence(target, IDA_PROVIDER_IDENTITY, {
operation: "procedure_pseudo_code",
parameters: query,
result: cached.result,
rawResult: cached.rawResult,
analysisProfile: profile,
}),
]);
expect(session.importAnalysisSnapshot(snapshot.value).ok).toBe(true);
expect(session.allowsSnapshotReplay("procedure_pseudo_code")).toBe(false);
expect(session.allowsSnapshotReplay("binary_overview")).toBe(false);
producer.pseudocode = "int main(void) { return 99; }";
const second = await session.execute("procedure_pseudo_code", query);
expect(second.ok && second.value.result).toContain("99");
expect(
producer.calls.filter(({ name }) => name === "decompile_function"),
).toHaveLength(2);
await session.close();
expect(producer.closes).toBe(1);
});
it(
"re-observes externally mutable state even when a document is explicit and a snapshot is imported",
reobservesExternallyMutableState,
);
it("rejects unsupported target kinds and reports incomplete upstream profiles on first analysis", async () => {
const { root, target } = await createIdaTarget();
roots.push(root);
@@ -157,12 +163,21 @@ describe("IDA provider composition", () => {
expect(analyzed).toMatchObject({
ok: false,
error: {
_tag: "AnalysisProtocolError",
message: expect.stringContaining(
_tag: "ProviderAdapterError",
userMessage: expect.stringContaining(
"headless compatibility profile is missing tools: idb_open",
),
},
});
if (analyzed.ok) throw new Error("Expected incompatible IDA profile");
expect(projectAnalysisError(analyzed.error).details).toMatchObject({
provider_id: "ida",
diagnostics: {
mode: "headless",
expected_profile: "database-supervisor",
missing_tools: expect.arrayContaining(["idb_open"]),
},
});
expect(producer.connects).toBe(1);
expect((await session.close()).ok).toBe(true);
expect(producer.closes).toBe(1);
@@ -60,6 +60,78 @@ public class ReaJadxMetadataRegression {
return apk;
}
private static void verifyDirectInvokes(SessionHolder holder, SessionConfig config,
Constructor<?> constructor, Method handle, Path sources, Path output) throws Exception {
SmaliOptions options = new SmaliOptions();
options.apiLevel = 28;
options.jobs = 1;
options.outputDexFile = output.resolve("direct-invokes.dex").toString();
require(Smali.assemble(options, List.of(
sources.resolve("Caller.smali").toString(), sources.resolve("Target.smali").toString())),
"Direct-invoke fixture assembly failed");
Path apk = output.resolve("direct-invokes.apk");
try (ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(apk))) {
zip.putNextEntry(new ZipEntry("classes.dex"));
Files.copy(Path.of(options.outputDexFile), zip);
zip.closeEntry();
}
BuildersKt.runBlocking(EmptyCoroutineContext.INSTANCE,
(scope, continuation) -> holder.unload(continuation));
BuildersKt.runBlocking(EmptyCoroutineContext.INSTANCE,
(scope, continuation) -> holder.load(apk.toString(), config, continuation));
JsonObject refs = call(handle, constructor.newInstance(holder), "get_xrefs_to_method",
methodArguments("fixture.Target", "mark"));
checkDirectInvokes(refs, "classes.dex");
SmaliOptions targetOptions = new SmaliOptions();
targetOptions.apiLevel = 28;
targetOptions.jobs = 1;
targetOptions.outputDexFile = output.resolve("direct-target.dex").toString();
SmaliOptions callerOptions = new SmaliOptions();
callerOptions.apiLevel = 28;
callerOptions.jobs = 1;
callerOptions.outputDexFile = output.resolve("direct-caller.dex").toString();
require(Smali.assemble(targetOptions, List.of(sources.resolve("Target.smali").toString())),
"Target DEX assembly failed");
require(Smali.assemble(callerOptions, List.of(sources.resolve("Caller.smali").toString())),
"Caller DEX assembly failed");
Path splitApk = output.resolve("direct-invokes-multidex.apk");
try (ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(splitApk))) {
zip.putNextEntry(new ZipEntry("classes.dex"));
Files.copy(Path.of(targetOptions.outputDexFile), zip);
zip.closeEntry();
zip.putNextEntry(new ZipEntry("classes2.dex"));
Files.copy(Path.of(callerOptions.outputDexFile), zip);
zip.closeEntry();
}
BuildersKt.runBlocking(EmptyCoroutineContext.INSTANCE,
(scope, continuation) -> holder.unload(continuation));
BuildersKt.runBlocking(EmptyCoroutineContext.INSTANCE,
(scope, continuation) -> holder.load(splitApk.toString(), config, continuation));
JsonObject crossDex = call(handle, constructor.newInstance(holder), "get_xrefs_to_method",
methodArguments("fixture.Target", "mark"));
checkDirectInvokes(crossDex, "classes2.dex");
System.out.println("DIRECT_INVOKE_REGRESSION_PASS nodes=1 offsets=0,3 cross_dex=true");
}
private static void checkDirectInvokes(JsonObject refs, String dexEntry) {
require(refs.get("total").getAsInt() == 1, "JADX using-node count changed");
JsonArray sites = refs.getAsJsonArray("items").get(0).getAsJsonObject()
.getAsJsonArray("direct_invokes");
require(sites.size() == 2, "Raw DEX invoke count differs from the fixture: " + sites);
for (int i = 0; i < sites.size(); i++) {
JsonObject site = sites.get(i).getAsJsonObject();
require(site.get("dex_entry").getAsString().equals(dexEntry), "Wrong DEX entry");
require(site.get("source_raw_method_id").getAsString().equals("fixture.Caller.twice()V"),
"Wrong raw source method");
require(site.get("dex_code_unit_offset").getAsInt() == i * 3, "Wrong DEX offset");
require(site.get("opcode").getAsString().equals("INVOKE_STATIC"), "Wrong opcode");
}
require(sites.get(0).getAsJsonObject().get("dex_method_index").getAsInt()
== sites.get(1).getAsJsonObject().get("dex_method_index").getAsInt(),
"Two invokes did not reference the same DEX method ID");
}
private static JsonObject methodArguments(String className, String methodName) {
JsonObject value = arguments(className);
value.addProperty("method_name", methodName);
@@ -152,13 +224,20 @@ public class ReaJadxMetadataRegression {
JsonObject componentArgs = arguments("androidx.activity.ComponentActivity");
JsonObject componentSummary = call(handle, bridge, "get_class_summary", componentArgs);
List<String> signatures = new ArrayList<>();
List<String> descriptors = new ArrayList<>();
for (JsonElement entry : componentSummary.getAsJsonArray("methods")) {
JsonObject method = entry.getAsJsonObject();
if (method.get("name").getAsString().equals("setContentView"))
if (method.get("name").getAsString().equals("setContentView")) {
signatures.add(method.get("signature").getAsString());
descriptors.add(method.get("dex_descriptor").getAsString());
}
}
require(signatures.size() == 3, "Fixture must contain three setContentView overloads");
require(descriptors.equals(List.of("(I)V", "(Landroid/view/View;)V",
"(Landroid/view/View;Landroid/view/ViewGroup$LayoutParams;)V")),
"Frozen DEX prototypes did not identify the three overloads: " + descriptors);
String[] declarations = { "setContentView(int ", "setContentView(View ", "setContentView(View view, ViewGroup.LayoutParams " };
List<Integer> referenceCounts = new ArrayList<>();
for (int index = 0; index < signatures.size(); index++) {
JsonObject methodArgs = arguments("androidx.activity.ComponentActivity");
methodArgs.addProperty("method_name", "setContentView");
@@ -169,12 +248,35 @@ public class ReaJadxMetadataRegression {
"Overload envelope mismatch");
require(first.get("mode").getAsString().equals("java"), "Fixture did not produce Java");
require(first.get("body").getAsString().contains(declarations[index]), "Wrong overload: " + signatures.get(index));
JsonObject references = call(handle, bridge, "get_xrefs_to_method", methodArgs);
require(references.get("overload_index").getAsInt() == index,
"Reference result did not preserve selected overload index");
require(references.get("reported_signature").getAsString().equals(signatures.get(index)),
"Reference result did not preserve selected overload signature");
if (index == 0) {
JsonArray invokes = references.getAsJsonArray("items").get(0).getAsJsonObject()
.getAsJsonArray("direct_invokes");
require(invokes.size() == 1, "Selected overload must have one raw direct invoke");
JsonObject invoke = invokes.get(0).getAsJsonObject();
require(invoke.get("source_raw_method_id").getAsString()
.equals("androidx.activity.ComponentActivity.onCreate(Landroid/os/Bundle;)V"),
"Wrong source method for overloaded target");
require(invoke.get("dex_code_unit_offset").getAsInt() == 37
&& invoke.get("opcode").getAsString().equals("INVOKE_VIRTUAL"),
"Wrong direct invoke for selected overloaded target");
}
referenceCounts.add(references.get("count").getAsInt());
}
require(referenceCounts.equals(List.of(1, 0, 0)),
"Incoming references were not isolated to the selected overload: " + referenceCounts);
require(componentSummary.equals(call(handle, bridge, "get_class_summary", componentArgs)),
"Frozen summary changed after code generation");
require(apiSummary.equals(call(handle, bridge, "get_class_summary", apiArgs)), "Unrelated frozen summary changed");
System.out.println("METADATA_REGRESSION_PASS classes=" + states.size() + " overloads=" + signatures.size());
System.out.println("METADATA_REGRESSION_PASS classes=" + states.size() + " overloads=" + signatures.size()
+ " reference_counts=" + referenceCounts);
verifyInitializers(holder, config, constructor, handle, initializerFixture(args[1], args[2]));
verifyDirectInvokes(holder, config, constructor, handle,
Path.of(args[3]), Path.of(args[2]));
} finally {
BuildersKt.runBlocking(EmptyCoroutineContext.INSTANCE,
(scope, continuation) -> holder.unload(continuation));
+83 -1
View File
@@ -160,7 +160,89 @@ export async function inspectMipsReadelf(path, byteOrder, floatAbi = "hard") {
};
}
/** Check effective Ghidra observations, not the requested analysis profile. */
/** Independent GNU readelf interpretation for the recordless legacy fixture. */
export async function inspectLegacyMipsReadelf(path, byteOrder) {
const command = process.env.REA_MIPS_READELF ?? "readelf";
const options = {
env: { ...process.env, LC_ALL: "C" },
timeout: 10000,
maxBuffer: 1024 * 1024,
};
const version = await execute(command, ["--version"], options);
assert.match(
version.stdout,
/^GNU readelf\b/u,
"This lane requires GNU readelf",
);
const header = await execute(command, ["-h", "-W", path], options);
assert.equal(
header.stderr.trim(),
"",
`readelf diagnostics: ${header.stderr}`,
);
const field = (expression, label) => {
const matches = [...header.stdout.matchAll(expression)];
assert.equal(matches.length, 1, `Missing or ambiguous readelf ${label}`);
return matches[0][1].trim();
};
assert.equal(field(/^\s*Class:\s*(.+)$/gmu, "class"), "ELF32");
assert.equal(
field(/^\s*Data:.*?,\s*(little|big) endian\s*$/gmu, "byte order"),
byteOrder,
);
assert.match(field(/^\s*Type:\s*(.+)$/gmu, "type"), /^EXEC\b/u);
assert.match(field(/^\s*Machine:\s*(.+)$/gmu, "machine"), /^MIPS\b/u);
const flags = field(/^\s*Flags:\s*(0x[\da-f]+)\b.*$/gmu, "flags");
assert.equal(
Number(flags),
0x50000001,
"Legacy fixture must carry EF_MIPS_ARCH_32 with an unspecified ABI field",
);
const abi = await execute(command, ["-A", path], options);
assert.equal(abi.stderr.trim(), "", `readelf diagnostics: ${abi.stderr}`);
// -A also prints unrelated MIPS facts such as the static GOT; only the ABI
// flags declaration itself must be gone from the recordless fixture.
assert.doesNotMatch(
abi.stdout,
/MIPS ABI Flags Version/u,
"GNU readelf still observes an ABI flags declaration in the legacy fixture",
);
const symbols = await execute(command, ["-s", "-W", path], options);
assert.equal(
symbols.stderr.trim(),
"",
`readelf diagnostics: ${symbols.stderr}`,
);
const parsed = {};
for (const name of ["rea_mips_entry", "rea_mips_probe"]) {
const matches = [
...symbols.stdout.matchAll(
new RegExp(
`^\\s*\\d+:\\s+([\\da-f]+)\\s+\\d+\\s+FUNC\\s+GLOBAL\\s+\\S+\\s+\\d+\\s+${name}\\s*$`,
"gmu",
),
),
];
assert.equal(
matches.length,
1,
`Missing or ambiguous readelf symbol ${name}`,
);
parsed[name] = `0x${BigInt(`0x${matches[0][1]}`).toString(16)}`;
}
return {
flags: Number(flags),
limitations: [],
symbols: parsed,
command,
version: version.stdout.split("\n")[0],
raw: {
header: header.stdout,
abi: abi.stdout,
symbols: symbols.stdout,
},
};
}
export function assertMipsLoadedImage(observations, byteOrder, sha256) {
assert.equal(observations.language_id, language(byteOrder));
assert.equal(observations.compiler_spec_id, "default");
+97 -6
View File
@@ -1,6 +1,6 @@
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
@@ -12,11 +12,13 @@ export async function buildMipsFixture(
directory,
byteOrder,
floatAbi = "hard",
options = {},
) {
if (byteOrder !== "little" && byteOrder !== "big")
throw new Error("MIPS fixture byte order must be little or big");
if (floatAbi !== "hard" && floatAbi !== "soft")
throw new Error("MIPS fixture float ABI must be hard or soft");
const legacy = options.legacy === true;
const soft = floatAbi === "soft";
const target = byteOrder === "little" ? "mipsel-linux-gnu" : "mips-linux-gnu";
const source = fileURLToPath(new URL("../c/mips.c", import.meta.url));
@@ -24,10 +26,13 @@ export async function buildMipsFixture(
new URL("../c/mips-soft-float.c", import.meta.url),
);
const probe = fileURLToPath(new URL("./mips-probe.S", import.meta.url));
const path = join(directory, `${target}${soft ? "-soft-float" : ""}.elf`);
const path = join(
directory,
`${target}${soft ? "-soft-float" : ""}${legacy ? "-legacy" : ""}.elf`,
);
const args = [
`--target=${target}`,
"-march=mips32r2",
`-march=${legacy ? "mips32" : "mips32r2"}`,
"-mabi=32",
...(soft ? ["-msoft-float"] : []),
"-mno-abicalls",
@@ -45,8 +50,88 @@ export async function buildMipsFixture(
"-o",
path,
];
const compiled = await compileMipsFixture(path, byteOrder, 2, args, {
expectedFlags: legacy ? 0x50001001 : 0x70001001,
});
// Legacy variant: retype the ABI record declarations out of the image and
// zero the header ABI field, matching pre-ABI-flags 2000s firmware toolchains
// (their compilers predate the record; the header leaves the ABI unspecified).
let attested = compiled;
if (legacy) {
const raw = await readFile(path);
const write16 = (offset, value) =>
byteOrder === "little"
? raw.writeUInt16LE(value, offset)
: raw.writeUInt16BE(value, offset);
const write32 = (offset, value) =>
byteOrder === "little"
? raw.writeUInt32LE(value, offset)
: raw.writeUInt32BE(value, offset);
const read16 = (offset) =>
byteOrder === "little"
? raw.readUInt16LE(offset)
: raw.readUInt16BE(offset);
const read32 = (offset) =>
byteOrder === "little"
? raw.readUInt32LE(offset)
: raw.readUInt32BE(offset);
const flags = read32(36);
if ((flags & 0xf0000000) !== 0x50000000)
throw new Error("Legacy fixture did not build as EF_MIPS_ARCH_32");
write32(36, flags & ~0x0000f000);
const programOffset = read32(28);
const programCount = read16(44);
if (read16(42) !== 32)
throw new Error("Legacy fixture has non-standard program headers");
for (let index = 0; index < programCount; index += 1) {
const offset = programOffset + index * 32;
if (read32(offset) === 0x70000003) write32(offset, 0);
}
const sectionOffset = read32(32);
const sectionCount = read16(48);
if (read16(46) !== 40)
throw new Error("Legacy fixture has non-standard section headers");
for (let index = 0; index < sectionCount; index += 1) {
const offset = sectionOffset + index * 40;
if (read32(offset + 4) === 0x7000002a) write32(offset + 4, 1);
}
// GNU readelf resolves the record by section name, not type, so a retyped
// header alone keeps a named declaration. Replace the name in the string
// table in place, preserving every remaining name and offset.
const stringTableIndex = read16(50);
const stringTableOffset =
stringTableIndex < sectionCount
? read32(sectionOffset + stringTableIndex * 40 + 16)
: -1;
const named =
stringTableOffset === -1
? -1
: raw.indexOf(
Buffer.from(".MIPS.abiflags", "ascii"),
stringTableOffset,
);
if (named === -1)
throw new Error("Legacy fixture lacks the expected ABI section name");
raw.write("x.rea.no.flags", named, "ascii");
await writeFile(path, raw);
const patched = await readFile(path);
const patchedFlags =
byteOrder === "little"
? patched.readUInt32LE(36)
: patched.readUInt32BE(36);
if (patchedFlags !== 0x50000001)
throw new Error(
"Legacy fixture did not end with the recordless o32 declaration",
);
attested = {
...compiled,
flags: patchedFlags,
sha256: createHash("sha256").update(patched).digest("hex"),
};
}
return {
...(await compileMipsFixture(path, byteOrder, 2, args)),
...attested,
legacy,
float_abi: floatAbi,
source_sha256: createHash("sha256")
.update(await readFile(source))
@@ -108,7 +193,13 @@ export async function buildMipsRelocatableFixture(
}
/** Compile and attest the shared ELF32/o32/MIPS32r2 fixture boundary. */
async function compileMipsFixture(path, byteOrder, objectType, args) {
async function compileMipsFixture(
path,
byteOrder,
objectType,
args,
options = {},
) {
const compiler = process.env.REA_MIPS_CLANG ?? "clang";
const version = await execute(compiler, ["--version"], { timeout: 10000 });
await execute(compiler, args, { timeout: 60000 });
@@ -128,7 +219,7 @@ async function compileMipsFixture(path, byteOrder, objectType, args) {
bytes[5] !== (byteOrder === "little" ? 1 : 2) ||
read16(16) !== objectType ||
read16(18) !== 8 ||
read32(36) !== 0x70001001
read32(36) !== (options.expectedFlags ?? 0x70001001)
)
throw new Error(
"Compiler did not produce the declared ELF32/o32/MIPS32r2 fixture",
+25 -20
View File
@@ -4,26 +4,6 @@ import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
import { PRODUCT_IDENTITY } from "../../src/identity.js";
const translatedReadmes = [
"README_zh.md",
"README_zh-TW.md",
"README_ja.md",
"README_ko.md",
"README_tr.md",
"README_ru.md",
"README_vi.md",
"README_th.md",
"README_de.md",
"README_es.md",
"README_fr.md",
"README_uk.md",
"README_pl.md",
"README_pt-BR.md",
"README_ar.md",
"README_fa.md",
"README_id.md",
] as const;
const jsonExamples = (content: string): unknown[] =>
[...content.matchAll(/```json\s*([\s\S]*?)```/gu)].map((match): unknown =>
JSON.parse(match[1] ?? ""),
@@ -64,6 +44,14 @@ describe("onboarding documentation product facts", () => {
});
it("keeps translated onboarding commands aligned with the English examples", async () => {
const inventory = JSON.parse(
await readFile(resolve("website/locales/languages.json"), "utf8"),
) as { code: string; readme: string }[];
const translatedReadmes = inventory
.filter((language) => language.code !== "en")
.map((language) => language.readme);
expect(translatedReadmes).toContain("docs/readme/README_it.md");
expect(translatedReadmes).toHaveLength(18);
const english = shellExamples(await readFile(resolve("README.md"), "utf8"));
for (const path of translatedReadmes)
expect(
@@ -71,4 +59,21 @@ describe("onboarding documentation product facts", () => {
path,
).toEqual(english);
});
it("preserves Persian joiners in links to GitHub-rendered headings", async () => {
const persian = await readFile(resolve("docs/readme/README_fa.md"), "utf8");
// Confirmed against GitHub's rendered README, which retains U+200C.
for (const heading of [
"REA چگونه کار می‌کند",
"چه چیزهایی را می‌توان تحلیل کرد",
"نمونه‌های عملی",
"پرسش‌های متداول",
"به‌روزرسانی REA",
]) {
expect(persian).toContain(`## ${heading}`);
expect(persian).toContain(
`](#${heading.toLowerCase().replaceAll(" ", "-")})`,
);
}
});
});
+9
View File
@@ -0,0 +1,9 @@
.class public Lfixture/Caller;
.super Ljava/lang/Object;
.method public static twice()V
.registers 0
invoke-static {}, Lfixture/Target;->mark()V
invoke-static {}, Lfixture/Target;->mark()V
return-void
.end method
+7
View File
@@ -0,0 +1,7 @@
.class public Lfixture/Target;
.super Ljava/lang/Object;
.method public static mark()V
.registers 0
return-void
.end method
+12 -1
View File
@@ -32,18 +32,21 @@ const methods = [
{
name: "onCreate",
signature: "onCreate(Bundle): void",
dex_descriptor: "(Landroid/os/Bundle;)V",
is_constructor: false,
def_pos: 0,
},
{
name: "choose",
signature: "choose(String): void",
dex_descriptor: "(Ljava/lang/String;)V",
is_constructor: false,
def_pos: 0,
},
{
name: "choose",
signature: "choose(int): void",
dex_descriptor: "(I)V",
is_constructor: false,
def_pos: 0,
},
@@ -139,10 +142,18 @@ register("get_method_body", ({ method_name, overload_index }) =>
}),
);
for (const name of ["get_xrefs_to_class", "get_xrefs_to_method"])
register(name, ({ class_name, method_name }) =>
register(name, ({ class_name, method_name, overload_index }) =>
json({
target:
method_name === undefined ? class_name : `${class_name}.${method_name}`,
...(method_name === undefined
? {}
: {
overload_index,
reported_signature: methods.filter(
(method) => method.name === method_name,
)[overload_index]?.signature,
}),
total: mode === "partial-xrefs" ? 2 : 1,
count: 1,
resolve_line: false,
+65
View File
@@ -0,0 +1,65 @@
import type { FileHandle } from "node:fs/promises";
import { expect } from "vitest";
import type { Result } from "../../src/domain/result.js";
import type { AnalysisError } from "../../src/domain/analysisErrorBase.js";
export interface DescriptorCloseFailure {
path: string;
denied: boolean;
handles: FileHandle[];
}
/** Public failure attribution and a still-live OS handle establish retained ownership. */
export const expectRetainedDescriptor = (
result: Result<unknown, AnalysisError>,
cleanup: DescriptorCloseFailure,
operation: string,
): void => {
expect(result).toMatchObject({
ok: false,
error: {
cleanupIncomplete: true,
cleanupResources: [cleanup.path],
operation,
},
});
expect(cleanup.handles).toHaveLength(1);
expect(cleanup.handles[0]?.fd).toBeGreaterThanOrEqual(0);
};
export const descriptorFailurePath = (
resource: string,
paths: Readonly<Record<"capture" | "tool" | "limiter", string>>,
): string => {
switch (resource) {
case "capture":
case "tool":
case "limiter":
return paths[resource];
case "kernel":
return "/proc/self/limits";
default:
throw new Error(`Unknown descriptor failure resource: ${resource}`);
}
};
/** Inject a retryable close failure while retaining the actual OS descriptor. */
export const withDescriptorCloseFailure = (
filesystem: typeof import("node:fs/promises"),
cleanup: DescriptorCloseFailure,
) => ({
...filesystem,
open: async (...args: Parameters<typeof filesystem.open>) => {
const handle = await filesystem.open(...args);
if (args[0] === cleanup.path) {
cleanup.handles.push(handle);
const close = handle.close.bind(handle);
handle.close = async () => {
if (cleanup.denied && handle.fd >= 0)
throw new Error("Descriptor close deliberately denied");
await close();
};
}
return handle;
},
});
+1
View File
@@ -18,6 +18,7 @@ export const evmInterfaceFixture = (
kind: "unknown",
deployment_authenticity: "unknown",
hardfork: "unknown",
metadata: null,
},
evidence_kind: "inferred",
functions: [],
+83
View File
@@ -0,0 +1,83 @@
import { startFakeCdpBrowser, type FakeCdpBrowser } from "./fakeCdpBrowser.js";
export type HttpRequestObservation = {
readonly requestId: string;
readonly path?: string;
readonly status?: number;
readonly mimeType?: string;
readonly encodedDataLength?: number;
};
type CdpEvent = Parameters<FakeCdpBrowser["emitEvent"]>[0];
const requestEvents = (
observation: HttpRequestObservation,
origin: string,
sessionId: string | undefined,
): CdpEvent[] => {
const session = sessionId === undefined ? {} : { sessionId };
const url = `${origin}${observation.path ?? "/api/items"}`;
const { requestId, status, mimeType, encodedDataLength } = observation;
const events: CdpEvent[] = [
{
...session,
method: "Network.requestWillBeSent",
params: {
requestId,
timestamp: 1,
type: "Fetch",
request: { url, method: "GET", headers: {} },
initiator: { type: "other" },
},
},
];
if (status !== undefined || mimeType !== undefined)
events.push({
...session,
method: "Network.responseReceived",
params: {
requestId,
timestamp: 2,
type: "Fetch",
response: {
url,
headers: {},
...(status === undefined ? {} : { status }),
...(mimeType === undefined ? {} : { mimeType }),
},
},
});
if (encodedDataLength !== undefined)
events.push({
...session,
method: "Network.loadingFinished",
params: { requestId, timestamp: 3, encodedDataLength },
});
return events;
};
/** Capture changing response coverage through the real CDP wire boundary. */
export const startHttpComparisonBrowser = async (
initial: readonly HttpRequestObservation[],
): Promise<{
readonly browser: FakeCdpBrowser;
setRequests(next: readonly HttpRequestObservation[]): void;
}> => {
let requests = initial;
const browser = await startFakeCdpBrowser({
eventsBeforeReply: ["Network.enable"],
commandEvents(command, origin) {
return command.method === "Network.enable"
? requests.flatMap((request) =>
requestEvents(request, origin, command.sessionId),
)
: undefined;
},
});
return {
browser,
setRequests(next) {
requests = next;
},
};
};
+4 -1
View File
@@ -1,5 +1,8 @@
/** Build a valid minimal JVM class file, optionally with an unused UTF-8 constant. */
export const javaClassFile = (extraUtf8Bytes = 0, fatCpuLookalike = false): Buffer => {
export const javaClassFile = (
extraUtf8Bytes = 0,
fatCpuLookalike = false,
): Buffer => {
const utf8 = (value: string): Buffer => {
const bytes = Buffer.from(value, "utf8");
const entry = Buffer.alloc(3 + bytes.length);
@@ -0,0 +1,53 @@
import { afterEach, expect, it, onTestFinished, vi } from "vitest";
import { ApktoolProvider } from "../../src/apktool/ApktoolProvider.js";
import { execFileOutput } from "../../src/process/ExecFileOutput.js";
vi.mock("../../src/process/ExecFileOutput.js", async (importOriginal) => ({
...(await importOriginal<
typeof import("../../src/process/ExecFileOutput.js")
>()),
execFileOutput: vi.fn(async () => ({ stdout: "2.7.0-stub\n", stderr: "" })),
}));
afterEach(() => {
vi.unstubAllEnvs();
vi.mocked(execFileOutput).mockClear();
});
it.skipIf(process.platform === "win32")(
"keeps an explicit environment's PATH choice and samples ambient inheritance per operation",
async () => {
vi.stubEnv("REA_APKTOOL_COMMAND", "/ambient/initial-apktool");
vi.stubEnv("REA_APKTOOL_TEST_INHERITED_VALUE", "initial");
const provider = new ApktoolProvider({ environment: {} });
onTestFinished(() => provider.close());
vi.stubEnv("REA_APKTOOL_COMMAND", "/ambient/changed-apktool");
vi.stubEnv("REA_APKTOOL_TEST_INHERITED_VALUE", "changed");
await provider.inspectAvailability();
expect(vi.mocked(execFileOutput).mock.lastCall?.[0]).toBe("apktool");
expect(vi.mocked(execFileOutput).mock.lastCall?.[2]?.env).toMatchObject({
REA_APKTOOL_COMMAND: undefined,
REA_APKTOOL_TEST_INHERITED_VALUE: "changed",
});
vi.stubEnv("REA_APKTOOL_TEST_INHERITED_VALUE", undefined);
await provider.inspectAvailability();
expect(
vi.mocked(execFileOutput).mock.lastCall?.[2]?.env
?.REA_APKTOOL_TEST_INHERITED_VALUE,
).toBeUndefined();
},
);
it.skipIf(process.platform === "win32")(
"inherits the current default launcher when no environment was selected",
async () => {
vi.stubEnv("REA_APKTOOL_COMMAND", "/ambient/initial-apktool");
const provider = new ApktoolProvider();
onTestFinished(() => provider.close());
vi.stubEnv("REA_APKTOOL_COMMAND", "/ambient/later-apktool");
await provider.inspectAvailability();
expect(vi.mocked(execFileOutput).mock.lastCall?.[0]).toBe(
"/ambient/later-apktool",
);
},
);
@@ -1,4 +1,5 @@
import { Cli } from "incur";
import { resolve } from "node:path";
import { expect, it, vi } from "vitest";
import type { BrowserScenarioCapturePort } from "../../src/application/BrowserScenarioCapturePort.js";
@@ -32,7 +33,7 @@ vi.mock("../../src/composition/browserScenario.js", () => ({
}));
const scenario = browserScenarioSchema.parse({
browser: { mode: "launch", executable_path: "/fixture/chromium" },
browser: { mode: "launch", executable_path: resolve("/fixture/chromium") },
start_url: { url: "https://app.example.test/" },
actions: [{ step_id: "wait", action: "wait_for_timeout", duration_ms: 1 }],
storage: {},
@@ -111,6 +112,22 @@ class RetrySession implements BrowserScenarioSessionPort {
}
}
it("waits for a slow but successful browser close before removing its profile", async () => {
const stages: string[] = [];
const cleanup = new PlaywrightScenarioBrowserCleanupOwner({
closeBrowser: async () => {
await new Promise((resolve) => setTimeout(resolve, 1_250));
stages.push("browser-closed");
},
removeProfile: async () => {
stages.push("profile-removed");
},
});
await cleanup.close();
expect(stages).toEqual(["browser-closed", "profile-removed"]);
});
const serveScenario = async () => {
const cli = Cli.create("browser-cleanup-test", { sync: false });
registerBrowserScenarioCommands(cli, silentLogger, {});
@@ -25,6 +25,7 @@ beforeEach(async () => {
HOME: home,
USERPROFILE: home,
APPDATA: join(home, "AppData", "Roaming"),
LOCALAPPDATA: join(home, "AppData", "Local"),
CLAUDE_CONFIG_DIR: home,
CODEX_HOME: join(home, ".codex"),
COPILOT_HOME: join(home, ".copilot"),