Merge commit '5100a1a1a56b810c8246b8c7ed19ff42c4d9dbe1' into fix/ci-duplicate-boundaries-1603

This commit is contained in:
N0zoM1z0
2026-10-11 03:50:21 +08:00
120 changed files with 5518 additions and 1142 deletions
@@ -0,0 +1,47 @@
import { stat, truncate, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it } from "vitest";
import { snapshotAndroidTarget } from "../../../src/android/AndroidTargetSnapshot.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
it.skipIf(process.platform === "win32")(
"cancels an in-flight APK snapshot and removes its partial output",
async () => {
const root = await createTestTempDirectory("rea-android-snapshot-cancel-");
const source = join(root, "large.apk");
const snapshot = join(root, "target.apk");
await writeFile(source, "");
// A sparse extent keeps fixture setup cheap while ensuring the copy cannot
// finish before the test observes its first output bytes and aborts it.
await truncate(source, 64 * 1024 * 1024 * 1024);
const controller = new AbortController();
const pending = snapshotAndroidTarget(
source,
"0".repeat(64),
root,
"inspect_android_package",
controller.signal,
);
try {
await expect
.poll(
() =>
stat(snapshot).then(
({ size }) => size > 0,
() => false,
),
{ timeout: 10_000, interval: 10 },
)
.toBe(true);
controller.abort();
await expect(pending).rejects.toMatchObject({ name: "AbortError" });
await expect(stat(snapshot)).rejects.toMatchObject({ code: "ENOENT" });
} finally {
controller.abort();
await pending.catch(() => undefined);
}
},
);
@@ -5,7 +5,8 @@ import { expect, it as test } from "vitest";
import {
inspectJadxAvailability,
resolveJadxConfiguration,
resolveJadxConfigurationInputs,
validateJadxConfiguration,
} from "../../../src/android/JadxConfiguration.js";
import { AnalysisCapabilityUnavailableError } from "../../../src/domain/analysisErrorCore.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
@@ -14,6 +15,18 @@ import { writeJadxJarInventory } from "../../fixtures/android/jadxJar.js";
const it = test.skipIf(process.platform === "win32");
const resolveConfiguration = async (
environment: Parameters<typeof resolveJadxConfigurationInputs>[0],
operation: Parameters<typeof resolveJadxConfigurationInputs>[1],
) => {
const configuration = await resolveJadxConfigurationInputs(
environment,
operation,
);
await validateJadxConfiguration(configuration, environment, operation);
return configuration;
};
it("rejects malformed or unrelated engine archives with JAR-specific recovery", async () => {
const root = await createTestTempDirectory("rea-jadx-invalid-jar-");
const javaHome = await createFakeJdk(root);
@@ -29,7 +42,7 @@ it("rejects malformed or unrelated engine archives with JAR-specific recovery",
diagnostics: { jar_path: await realpath(jar), phase: "jar-inspection" },
});
await expect(
resolveJadxConfiguration(environment, "inspect_android_package"),
resolveConfiguration(environment, "inspect_android_package"),
).rejects.toMatchObject({
_tag: "AnalysisCapabilityUnavailableError",
reason: expect.stringContaining("REA_JADX_MCP_JAR"),
@@ -45,7 +58,7 @@ it("rejects an explicit JAVA_HOME without an executable java binary", async () =
await writeJadxJarInventory(jar);
await expect(
resolveJadxConfiguration(
resolveConfiguration(
{ REA_JADX_MCP_JAR: jar, JAVA_HOME: javaHome },
"inspect_android_package",
),
@@ -62,7 +75,7 @@ it("accepts a full JDK and canonicalizes the selected JAR", async () => {
await writeJadxJarInventory(jar);
await expect(
resolveJadxConfiguration(
resolveConfiguration(
{ REA_JADX_MCP_JAR: jar, JAVA_HOME: javaHome },
"inspect_android_package",
),
@@ -78,7 +91,7 @@ it("configures heap and visible processors independently without forcing either"
const jar = join(root, "engine.jar");
const javaHome = await createFakeJdk(root);
await writeJadxJarInventory(jar);
const configuration = await resolveJadxConfiguration(
const configuration = await resolveConfiguration(
{
REA_JADX_MCP_JAR: jar,
JAVA_HOME: javaHome,
@@ -92,7 +105,7 @@ it("configures heap and visible processors independently without forcing either"
"-XX:ActiveProcessorCount=4",
]);
await expect(
resolveJadxConfiguration(
resolveConfiguration(
{
REA_JADX_MCP_JAR: jar,
JAVA_HOME: javaHome,
@@ -107,7 +120,7 @@ it("configures heap and visible processors independently without forcing either"
for (const name of ["REA_JADX_HEAP_MIB", "REA_JADX_ACTIVE_PROCESSOR_COUNT"])
for (const value of ["", "0", "-1", "1.5", "8g", " 4", "9007199254740992"])
await expect(
resolveJadxConfiguration(
resolveConfiguration(
{
REA_JADX_MCP_JAR: jar,
JAVA_HOME: javaHome,
@@ -127,7 +140,7 @@ it("distinguishes a runnable JRE from a missing Java executable", async () => {
await writeJadxJarInventory(jar);
const jreHome = await createFakeJdk(root, false);
await expect(
resolveJadxConfiguration(
resolveConfiguration(
{ REA_JADX_MCP_JAR: jar, JAVA_HOME: jreHome },
"inspect_android_package",
),
@@ -175,7 +188,7 @@ it("preserves exact Java probe output and marks max-buffer capture as truncated"
);
await chmod(java, 0o700);
const failure = await resolveJadxConfiguration(
const failure = await resolveConfiguration(
{ REA_JADX_MCP_JAR: jar, JAVA_HOME: javaHome },
"inspect_android_package",
).then(
@@ -241,7 +254,7 @@ it("distinguishes an unreported Java version from an unsupported old version", a
);
await chmod(join(oldHome, "bin", "java"), 0o700);
await expect(
resolveJadxConfiguration(
resolveConfiguration(
{ REA_JADX_MCP_JAR: jar, JAVA_HOME: oldHome },
"inspect_android_package",
),
@@ -294,6 +294,15 @@ describe("CdpBrowserProvider: WebMCP discovery and completeness", () => {
],
},
});
expect(result.value.completeness.excluded).toContainEqual(
expect.objectContaining({
section: "webmcp_tools",
reason: "out_of_target_scope",
}),
);
expect(result.value.completeness.unavailable_sections).not.toContain(
"webmcp_tools",
);
const serialized = JSON.stringify(result.value);
expect(serialized).toContain("tool-secret");
expect(serialized).toContain("tool-source-secret");
@@ -354,7 +363,9 @@ describe("CdpBrowserProvider: WebMCP discovery and completeness", () => {
"WebMCP.invokeTool",
);
});
});
describe("CdpBrowserProvider: WebMCP replay inventory", () => {
it("returns every WebMCP registration in the replay", async () => {
const browser = await startFakeCdpBrowser({
webMcpTools: true,
@@ -410,7 +421,98 @@ describe("CdpBrowserProvider: WebMCP discovery and completeness", () => {
});
});
describe("CdpBrowserProvider WebMCP inventory completeness", () => {
describe("CdpBrowserProvider WebMCP malformed replay completeness", () => {
it.each(["toolsAdded", "toolsRemoved"] as const)(
"keeps malformed %s replay entries from proving WebMCP equality",
async (malformedEvent) => {
let malformed = false;
const registration = {
name: "read_item",
frameId: "frame-main",
inputSchema: { type: "object" },
};
const browser = await startFakeCdpBrowser({
commandEvents: (command) => {
if (command.method !== "WebMCP.enable") return undefined;
const events: {
readonly method: string;
readonly params: unknown;
readonly sessionId?: string;
}[] = [
{
method: "WebMCP.toolsAdded",
...(command.sessionId === undefined
? {}
: { sessionId: command.sessionId }),
params: {
tools:
malformed && malformedEvent === "toolsAdded"
? [registration, null]
: [registration],
},
},
];
if (malformed && malformedEvent === "toolsRemoved")
events.push({
method: "WebMCP.toolsRemoved",
...(command.sessionId === undefined
? {}
: { sessionId: command.sessionId }),
params: { tools: [{ name: registration.name }, null] },
});
return events;
},
});
trackBrowser(browser);
const provider = new CdpBrowserProvider();
const input = {
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
observation_ms: 0,
};
const inspection = await provider.inspectPage(
inspectWebPageInputSchema.parse(input),
);
if (!inspection.ok) throw inspection.error;
const discover = async () => {
const result = await provider.discoverWebMcpTools(
discoverWebMcpToolsInputSchema.parse(input),
);
if (!result.ok) throw result.error;
return result.value;
};
const before = await discover();
expect(before.tools.items).toHaveLength(1);
expect(before.completeness.unavailable_sections).not.toContain(
"webmcp_tools",
);
malformed = true;
const after = await discover();
expect(after.tools.items).toHaveLength(1);
expect(after.completeness.unavailable_sections).toContain("webmcp_tools");
expect(after.completeness.excluded).toContainEqual(
expect.objectContaining({
section: "webmcp_tools",
reason: "invalid_protocol_value",
}),
);
const comparison = compareWebCaptures(
compareWebCapturesInputSchema.parse({
before: { inspection: inspection.value, webmcp: before },
after: { inspection: inspection.value, webmcp: after },
}),
);
expect(comparison.dimensions.webmcp).toMatchObject({
status: "unknown",
total_changes: 0,
});
},
);
});
describe("CdpBrowserProvider WebMCP schema comparison", () => {
it("compares full untrusted declarations independently of object-key order", async () => {
const declaration: JsonValue = {
type: "object",
@@ -47,6 +47,7 @@ it.each(["Page.disable", "Target.detachFromTarget"])(
expect(methods).toContain("Target.detachFromTarget");
expect(methods).not.toContain("Target.closeTarget");
expect(methods).not.toContain("Browser.close");
await vi.waitFor(() => expect(browser.activeConnectionCount()).toBe(0));
},
);
@@ -76,6 +77,11 @@ it("releases cleanup when cancellation arrives after capture completes", async (
expect(browser.commands.map(({ method }) => method)).toContain(
"Target.detachFromTarget",
);
await vi.waitFor(() => expect(browser.activeConnectionCount()).toBe(0));
const methods = browser.commands.map(({ method }) => method);
expect(methods).not.toContain("Target.closeTarget");
expect(methods).not.toContain("Browser.close");
expect((await fetch(`${browser.endpoint}/json/version`)).ok).toBe(true);
});
it("closes an Electron inspection session when cleanup is cancelled", async () => {
@@ -122,11 +128,11 @@ it("closes an Electron inspection session when cleanup is cancelled", async () =
operation: "inspect_electron_page",
},
});
expect(browser.commands.map(({ method }) => method)).toContain(
"Page.disable",
);
const methods = browser.commands.map(({ method }) => method);
expect(methods).not.toContain("Page.disable");
expect(methods).toContain("Target.detachFromTarget");
expect(methods).not.toContain("Target.closeTarget");
expect(methods).not.toContain("Browser.close");
await vi.waitFor(() => expect(browser.activeConnectionCount()).toBe(0));
expect((await fetch(`${browser.endpoint}/json/version`)).ok).toBe(true);
});
@@ -39,6 +39,68 @@ const equivalentBodies = [
},
];
it("captures all repeated array rows and empty arrays without retaining payload values", async () => {
const count = 6_000;
const body = JSON.stringify(
Array.from({ length: count }, (_, index) => ({
value: index % 2 === 0 ? index : "payload-value-excluded",
nested: index % 2 === 0 ? [] : [true, null],
empty: [],
"*": { "": "payload-value-excluded" },
})),
);
const before = captureBody("base64 response", body);
const shape = before.network.requests[0]?.body_shapes.response;
const element = { kind: "array-element" };
const property = (name: string) => ({ kind: "property", name });
expect(shape).toMatchObject({
root_type: "array",
node_count: count * 7 + 1,
max_depth_observed: 3,
properties: [
{ path: [element], types: ["object"], observations: count },
{
path: [element, property("*")],
types: ["object"],
observations: count,
},
{
path: [element, property("*"), property("")],
types: ["string"],
observations: count,
},
{
path: [element, property("empty")],
types: ["array"],
observations: count,
},
{
path: [element, property("nested")],
types: ["array"],
observations: count,
},
{
path: [element, property("nested"), element],
types: ["boolean", "null"],
observations: count,
},
{
path: [element, property("value")],
types: ["number", "string"],
observations: count,
},
],
});
expect(JSON.stringify(shape)).not.toContain("payload-value-excluded");
const after = captureBody("base64 response", body);
expect(
(await compareCaptures(before, after)).dimensions.network,
).toMatchObject({
status: "unknown",
total_changes: 0,
});
});
describe.each<BodySource>(["request", "response", "base64 response"])(
"CDP %s JSON shape comparison",
(source) => {
@@ -188,6 +188,107 @@ describe("runtime window and producer granularity", () => {
});
});
it("joins a reordered multi-script coverage sample by identity and preserves unavailable bounds", async () => {
const texts = new Map(
Array.from({ length: 256 }, (_, index) => [
`script-${index}`,
`// 🔥\r\n${" ".repeat(index)}function f(){return ${index};}`,
]),
);
const { browser, provider, execution } = await fixture({
commandEvents: (command, origin) =>
command.method === "Debugger.enable"
? [...texts.keys(), "foreign-script"].map((scriptId) => ({
...(command.sessionId === undefined
? {}
: { sessionId: command.sessionId }),
method: "Debugger.scriptParsed",
params: {
scriptId,
url: `${origin}/shared.js`,
executionContextId: scriptId === "foreign-script" ? 99 : 1,
startLine: 0,
startColumn: 0,
endLine: 1,
endColumn: 0,
},
}))
: undefined,
commandError: (command) =>
command.method === "Debugger.getScriptSource" &&
command.params.scriptId === "script-128"
? { code: -32000, message: "Selected source is unavailable" }
: undefined,
commandResult: (command, origin) => {
if (command.method === "Debugger.getScriptSource")
return { scriptSource: texts.get(String(command.params.scriptId)) };
if (command.method !== "Profiler.takePreciseCoverage") return undefined;
return {
timestamp: 13,
result: [...texts]
.reverse()
.map(([scriptId, text]) => ({
scriptId,
url: `${origin}/shared.js`,
functions: [
{
functionName: "f",
isBlockCoverage: true,
ranges: [
{ startOffset: 0, endOffset: text.length, count: 1 },
{ startOffset: 8, endOffset: 9, count: 0 },
],
},
],
}))
.concat([
{
scriptId: "foreign-script",
url: `${origin}/shared.js`,
functions: [],
},
]),
};
},
});
const result = await provider.observeExecution(execution);
if (!result.ok) throw result.error;
expect(result.value.coverage.excluded_scripts).toBe(1);
expect(
result.value.coverage.scripts.map(({ script_id }) => script_id),
).toEqual([...texts.keys()].reverse());
for (const script of result.value.coverage.scripts) {
expect(script.functions[0]?.ranges).toEqual([
{
start_offset: 0,
end_offset: texts.get(script.script_id)?.length,
count: 1,
source_bounds:
script.script_id === "script-128" ? "unknown" : "verified",
},
{
start_offset: 8,
end_offset: 9,
count: 0,
source_bounds:
script.script_id === "script-128" ? "unknown" : "verified",
},
]);
}
expect(
result.value.sources.find(({ script_id }) => script_id === "script-128")
?.source,
).toMatchObject({ state: "unavailable" });
expect(
browser.commands.some(
({ method }) => method === "Profiler.stopPreciseCoverage",
),
).toBe(true);
expect(
browser.commands.some(({ method }) => method === "Target.detachFromTarget"),
).toBe(true);
});
describe("runtime source and listener identity", () => {
it("retains same-URL script identities, UTF-16 bounds, nested zero counts and actual cleanup", async () => {
const { browser, provider, execution } = await fixture();
@@ -5,6 +5,59 @@ import { observeWebExecutionInputSchema } from "../../../src/domain/webExecution
import { inspectWebEventListenersInputSchema } from "../../../src/domain/webEventListeners.js";
import { startRuntimeBrowser } from "../../fixtures/webRuntime.js";
it("invalidates retained sources when their execution context is reused during another source read", async () => {
let emit: ((event: CdpEvent) => void) | undefined;
const browser = await startRuntimeBrowser({
commandResult: (command, origin) => {
if (
command.method === "Debugger.getScriptSource" &&
command.params.scriptId === "script-b"
)
emit?.({
sessionId: "session-1",
method: "Runtime.executionContextCreated",
params: {
context: {
id: 1,
uniqueId: "replacement-context",
origin,
name: "",
auxData: {
frameId: "runtime-main",
isDefault: true,
type: "default",
},
},
},
});
return undefined;
},
});
emit = browser.emitEvent;
onTestFinished(() => browser.close());
const result = await new CdpWebRuntimeProvider().observeExecution(
observeWebExecutionInputSchema.parse({
cdp_endpoint: browser.endpoint,
target_id: "allowed-page",
observation_ms: 5,
}),
);
if (!result.ok) throw result.error;
expect(result.value.coverage.scripts).toEqual([]);
expect(result.value.coverage.excluded_scripts).toBe(3);
expect(result.value.script_inventory.main_document_scripts).toBe(0);
for (const scriptId of ["script-a", "script-b"])
expect(
result.value.sources.find(({ script_id }) => script_id === scriptId),
).toMatchObject({ frame_id: null, source: { state: "excluded" } });
expect(browser.commands.map(({ method }) => method)).toEqual(
expect.arrayContaining([
"Profiler.stopPreciseCoverage",
"Target.detachFromTarget",
]),
);
});
it.each(
["listeners", "execution"].flatMap((operation) =>
["source_read", "other_source_read", "final_assertion"].map((phase) => ({
@@ -252,6 +252,65 @@ describe("trace-dylib-resolution CLI", () => {
);
});
cliTest(
"retains directory requirements when resolving dylib install names",
async ({ cli }) => {
const directory = await createTestTempDirectory("rea-dylib-path-cli-");
const names = [
"@loader_path/lib/libhelper.dylib/",
"@loader_path/lib/libhelper.dylib/.",
"@rpath/libhelper.dylib/",
"@rpath/libhelper.dylib/.",
"@rpath/",
"@loader_path/lib/./libhelper.dylib",
"@loader_path/lib//libhelper.dylib",
];
await writeFiles(directory, {
tool: machoImage({
commands: [
buildVersionCommand(1),
rpathCommand("@loader_path/lib/libhelper.dylib"),
rpathCommand("@loader_path/lib"),
...names.map((name) => dylibCommand(LC.LOAD_DYLIB, name)),
],
}),
"lib/libhelper.dylib": machoImage({
fileType: FILE_TYPE.dylib,
commands: [buildVersionCommand(1)],
}),
});
const result = await cli.run({
arguments: ["trace-dylib-resolution", join(directory, "tool"), "--json"],
environment: ENVIRONMENT,
});
expect(result.exitCode, JSON.stringify(result.json)).toBe(0);
const trace = dylibResolutionResultSchema.parse(
parseEvidence(result.json).normalized_result,
);
expect(
trace.edges.map(({ install_name, candidates, resolution }) => ({
install_name,
outcome: candidates[0]?.outcome,
resolution,
})),
).toEqual(
names.map((name, index) => ({
install_name: name,
outcome: index < 5 ? "absent" : "resolved",
resolution:
index < 5
? { status: "unresolved", image: null }
: { status: "resolved", image: "lib/libhelper.dylib" },
})),
);
expect(
trace.findings.map(({ kind, edge_index }) => [kind, edge_index]),
).toEqual(
[0, 1, 2, 3, 4].map((index) => ["required-load-unresolved", index]),
);
},
);
describe.skipIf(process.getuid?.() === 0)(
"trace-dylib-resolution permissions",
() => {
@@ -0,0 +1,96 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { createEvidence } from "../../../src/domain/evidence.js";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import {
createResidualUnknown,
updateResidualUnknown,
} from "../../../src/domain/residualUnknown.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
const revisionBundle = () => {
const records = ["open", "investigate"].map((operation) =>
createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
{ operation, parameters: {}, result: { observed: operation } },
),
);
const [opened, investigated] = records;
if (opened === undefined || investigated === undefined)
throw new Error("Missing mutation Evidence");
const details = {
severity: "high" as const,
supporting_evidence_ids: [],
contradicting_evidence_ids: [],
required_authority: null,
required_confidence: "observed" as const,
required_environment: null,
recommended_probes: [],
relationships: [],
};
const initial = createResidualUnknown(
{ question: "How is this input handled?", domain: "protocol", ...details },
opened.evidence_id,
null,
);
const revised = updateResidualUnknown(
initial,
{
unknown_id: initial.unknown_id,
expected_revision: initial.revision,
status: "investigating",
...details,
resolution: null,
},
investigated.evidence_id,
);
return createEvidenceBundle(records, [initial, revised]);
};
cliTest(
"reports standalone import counts for every unknown revision",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-evidence-import-");
const path = join(root, "bundle.json");
await writeFile(path, JSON.stringify(revisionBundle()));
const result = await cli.run({
arguments: ["evidence-import", path, "--json"],
});
expect(result.exitCode).toBe(0);
expect(result.json).toEqual({ imported: 2, unknowns_added: 2, total: 2 });
},
);
cliTest(
"rejects altered Evidence and incomplete unknown history before reporting counts",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-evidence-import-invalid-");
const path = join(root, "bundle.json");
const bundle = revisionBundle();
for (const invalid of [
{
...bundle,
records: bundle.records.map((record) => ({
...record,
normalized_result: "altered",
})),
},
{ ...bundle, unknowns: bundle.unknowns.slice(1) },
]) {
await writeFile(path, JSON.stringify(invalid));
const result = await cli.run({
arguments: ["evidence-import", path, "--json"],
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "evidence_integrity_mismatch",
});
expect(result.json).not.toHaveProperty("imported");
}
},
);
@@ -7,6 +7,7 @@ import { projectAnalysisError } from "../../../src/domain/analysisErrorProjectio
import { evmInterfaceSchema } from "../../../src/domain/evm/evmInterface.js";
import { EvmoleInterfaceProvider } from "../../../src/evm/EvmoleInterfaceProvider.js";
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js";
import { waitForProviderProcessReady } from "../../fixtures/providerProcess.js";
import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
import {
@@ -128,31 +129,75 @@ it.runIf(!unsupportedHost)(
async () => {
const { path } = await fixture();
let ownedPath = "";
let failCleanup = true;
let launches = 0;
const provider = new EvmoleInterfaceProvider({}, async (spawn) => {
launches += 1;
ownedPath = spawn.cwd ?? "";
const launched = await spawnOwnedProviderProcess({
...spawn,
command: process.execPath,
arguments: ["-e", 'process.stdout.write("x".repeat(1048577))'],
});
const cleanupOwned =
launched.cleanup ??
(() => cleanupOwnedProcessGroup(launched.ownership));
return {
...launched,
cleanup: async () => {
await launched.cleanup?.();
throw new Error("injected post-cleanup reporting failure");
const cleaned = await cleanupOwned();
if (failCleanup)
throw new Error("injected post-cleanup reporting failure");
return cleaned;
},
};
});
onTestFinished(async () => {
failCleanup = false;
await provider.close();
});
const result = await provider.inspect({ path, encoding: "hex" });
if (result.ok) throw new Error("Expected compounded lifecycle failure");
expect(result.error).toMatchObject({
cleanupIncomplete: true,
diagnostics: {
reason: "injected post-cleanup reporting failure",
previous_error: { failure_kind: "output-limit" },
captured_output: { truncated: true, stderr: "" },
expect(result.error.cleanupIncomplete).toBe(true);
// Inspect the retained error chain without diffing a megabyte of stdout.
const cleanup = z
.object({
reason: z.string(),
previous_error: z
.object({
failure_kind: z.string(),
stdout: z.unknown().optional(),
stderr: z.unknown().optional(),
})
.transform(({ failure_kind, stdout, stderr }) => ({
failure_kind,
output_repeated: stdout !== undefined || stderr !== undefined,
})),
captured_output: z.object({
truncated: z.boolean(),
stderr: z.literal(""),
stdout: z.string().transform((value) => Buffer.byteLength(value)),
}),
})
.parse(projectAnalysisError(result.error).details?.["diagnostics"]);
expect(cleanup).toEqual({
reason: "injected post-cleanup reporting failure",
previous_error: {
failure_kind: "output-limit",
output_repeated: false,
},
captured_output: { truncated: true, stderr: "", stdout: 1048576 },
});
expect(result.error.cleanupResources).toContain(ownedPath);
await access(ownedPath);
const blocked = await provider.inspect({ path, encoding: "hex" });
expect(blocked.ok).toBe(false);
expect(launches).toBe(1);
await expect(provider.close()).rejects.toMatchObject({
cleanupIncomplete: true,
});
failCleanup = false;
await provider.close();
await expect(access(ownedPath)).rejects.toMatchObject({ code: "ENOENT" });
},
);
@@ -69,6 +69,35 @@ describe("artifact inventory entry order", () => {
},
);
it("resolves deep ZIP members without inventing missing directories", async () => {
const root = await createTestTempDirectory("rea-deep-archive-parent-");
const archive = join(root, "deep.zip");
// Fits the ZIP filename field while exceeding the formerly expensive depth.
const members = ["data.txt", "second.txt", "third.bin"].map(
(name) => `observed/${"d/".repeat(30_000)}${name}`,
);
await writeOrderedZip(archive, [...members, "observed/", "unrelated/"]);
const inventory = await inventoryArtifact(archive);
expect(artifactParentPaths(inventory)).toEqual({
".": null,
observed: ".",
unrelated: ".",
...Object.fromEntries(members.map((member) => [member, "observed"])),
});
const observedParent = artifactOccurrenceAt(inventory, "observed");
for (const member of members) {
const occurrence = artifactOccurrenceAt(inventory, member);
expect(occurrence.hash_status).toBe("verified");
expect(inventory.edges).toContainEqual(
expect.objectContaining({
occurrence_id: occurrence.occurrence_id,
parent_artifact_id: observedParent.artifact_id,
relation: "contains",
}),
);
}
});
it.each([
{
entries: ["pkg/sub/data.txt"],
@@ -129,6 +158,61 @@ describe("entry-order validation and reader controls", () => {
}
});
it("retains high-cardinality case-folded directories and their descendants", async () => {
const root = await createTestTempDirectory(
"rea-entry-order-case-capacity-",
);
const archive = join(root, "case-capacity.zip");
const variants = Array.from({ length: 256 }, (_, mask) =>
[..."abcdefgh"]
.map((character, index) =>
(mask & (1 << index)) === 0 ? character : character.toUpperCase(),
)
.join(""),
);
await writeOrderedZip(
archive,
variants.flatMap((variant) => [variant + "/", variant + "/entry.txt"]),
);
const inventory = await inventoryArtifact(archive);
const directories = variants.map((variant) =>
artifactOccurrenceAt(inventory, variant),
);
const descendants = variants.map((variant) =>
artifactOccurrenceAt(inventory, `${variant}/entry.txt`),
);
const ordered = [...variants].sort();
const first = ordered[0];
const second = ordered[1];
expect(inventory.occurrences).toHaveLength(1 + variants.length * 2);
expect(
new Set(inventory.occurrences.map(({ logical_path }) => logical_path))
.size,
).toBe(1 + variants.length * 2);
expect(
new Set(
[...directories, ...descendants].map(
({ occurrence_id }) => occurrence_id,
),
).size,
).toBe(variants.length * 2);
expect(
directories.every(({ limitations }) => limitations.length === 1),
).toBe(true);
expect(
descendants.every(({ limitations }) => limitations.length === 1),
).toBe(true);
expect(
directories.find(({ logical_path }) => logical_path === first)
?.limitations[0],
).toContain(`with ${second} and 254 other spellings;`);
expect(descendants[0]?.limitations[0]).toContain(
`is under ${variants[0]}, which collides under English (en-US) Unicode case folding with ${first} and 254 other spellings;`,
);
});
it("preserves ordinary directory and ASAR structure", async () => {
const root = await createTestTempDirectory("rea-entry-order-readers-");
const directory = join(root, "source");
@@ -305,19 +305,22 @@ describe("ASAR read failures", () => {
errno: -5,
syscall: "fstat",
});
const closeError = Object.assign(new Error("device close failed"), {
code: "EIO",
errno: -5,
syscall: "close",
});
let closeCount = 0;
const reader = new AsarArtifactReader(archive, async (path, flags) => {
const handle = await openFile(path, flags);
expect(await matchingDescriptorCount(identity)).toBeGreaterThan(0);
let statCount = 0;
return {
async stat() {
statCount += 1;
if (statCount === 2) throw ioError;
return handle.stat();
throw ioError;
},
async close() {
closeCount += 1;
if (closeCount === 1) throw closeError;
await handle.close();
},
createReadStream: (options) => handle.createReadStream(options),
@@ -337,73 +340,320 @@ describe("ASAR read failures", () => {
message: expect.stringContaining(
`Could not read ${entry.path} ASAR at ${archive}: device stat failed`,
),
cause: { code: "EIO", errno: -5, syscall: "fstat" },
cause: {
reason: "io",
cause: { code: "EIO", errno: -5, syscall: "fstat" },
},
cleanup: {
resources: [unpackedPath],
reason: "device close failed",
},
});
expect(closeCount).toBe(1);
expect(await matchingDescriptorCount(identity)).toBeGreaterThan(0);
await reader.close();
expect(closeCount).toBe(2);
await waitForNoMatchingDescriptor(identity);
} finally {
await reader.close();
}
},
);
});
it.each(["missing", "replaced"] as const)(
"reads a captured zero-length member when the original container is %s",
async (change) => {
const root = await createTestTempDirectory("rea-asar-empty-member-");
const source = join(root, "source");
const archive = join(root, "fixture.asar");
await mkdir(source);
await writeFile(join(source, "empty.js"), "");
await createPackageWithOptions(source, archive, {});
const reader = new AsarArtifactReader(archive);
it.skipIf(process.platform === "win32")(
"retries cleanup when cancellation arrives immediately after unpacked stat",
async () => {
const root = await createTestTempDirectory("rea-asar-unpacked-abort-stat-");
const source = join(root, "source");
const archive = join(root, "fixture.asar");
await mkdir(source);
await writeFile(join(source, "small.js"), "module.exports = 1;\n");
await createPackageWithOptions(source, archive, { unpack: "small.js" });
const unpackedPath = join(`${archive}.unpacked`, "small.js");
const identity = await lstat(unpackedPath);
const controller = new AbortController();
let closeCount = 0;
const reader = new AsarArtifactReader(archive, async (path, flags) => {
const handle = await openFile(path, flags);
return {
async stat() {
const observed = await handle.stat();
controller.abort();
return observed;
},
async close() {
closeCount += 1;
if (closeCount === 1) throw new Error("first close failed");
await handle.close();
},
createReadStream: (options) => handle.createReadStream(options),
};
});
try {
const entries = [];
for await (const entry of reader.entries()) entries.push(entry);
const entry = entries.find(({ path }) => path === "empty.js");
if (entry === undefined) throw new Error("Expected empty ASAR member");
if (change === "missing") await rm(archive);
else await writeFile(archive, "replacement container");
try {
const entries = [];
for await (const entry of reader.entries()) entries.push(entry);
const entry = entries.find(({ path }) => path === "small.js");
if (entry === undefined) throw new Error("Expected unpacked ASAR member");
expect(await buffer(await reader.open(entry))).toHaveLength(0);
} finally {
await reader.close();
}
},
await expect(reader.open(entry, controller.signal)).rejects.toMatchObject(
{
reason: "cancelled",
cleanup: {
resources: [unpackedPath],
reason: "first close failed",
},
},
);
expect(closeCount).toBe(1);
expect(await matchingDescriptorCount(identity)).toBeGreaterThan(0);
await reader.close();
expect(closeCount).toBe(2);
await waitForNoMatchingDescriptor(identity);
} finally {
await reader.close();
}
},
);
it.skipIf(process.platform === "win32")(
"preserves an unpacked identity failure when closing its handle fails",
async () => {
const root = await createTestTempDirectory("rea-asar-unpacked-identity-");
const source = join(root, "source");
const archive = join(root, "fixture.asar");
await mkdir(source);
await writeFile(join(source, "small.js"), "module.exports = 1;\n");
await createPackageWithOptions(source, archive, { unpack: "small.js" });
const unpackedPath = join(`${archive}.unpacked`, "small.js");
const identity = await lstat(unpackedPath);
const closeError = new Error("first close failed");
let closeCount = 0;
const reader = new AsarArtifactReader(archive, async (path, flags) => {
const handle = await openFile(path, flags);
return {
async stat() {
const observed = await handle.stat();
return Object.assign(Object.create(observed), {
ino: observed.ino + 1,
});
},
async close() {
closeCount += 1;
if (closeCount === 1) throw closeError;
await handle.close();
},
createReadStream: (options) => handle.createReadStream(options),
};
});
try {
const entries = [];
for await (const entry of reader.entries()) entries.push(entry);
const entry = entries.find(({ path }) => path === "small.js");
if (entry === undefined) throw new Error("Expected unpacked ASAR member");
await expect(reader.open(entry)).rejects.toMatchObject({
name: "ArtifactReaderFailure",
reason: "integrity",
message: expect.stringContaining(
`ASAR unpacked entry changed before read: ${entry.path}`,
),
cleanup: {
resources: [unpackedPath],
reason: "first close failed",
},
});
expect(closeCount).toBe(1);
expect(await matchingDescriptorCount(identity)).toBeGreaterThan(0);
await reader.close();
expect(closeCount).toBe(2);
await waitForNoMatchingDescriptor(identity);
} finally {
await reader.close();
}
},
);
it.skipIf(process.platform === "win32")(
"retains unpacked handles and snapshots across combined cleanup failures",
async () => {
const root = await createTestTempDirectory("rea-asar-combined-cleanup-");
const source = join(root, "source");
const archive = join(root, "fixture.asar");
await mkdir(source);
await writeFile(join(source, "small.js"), "module.exports = 1;\n");
await createPackageWithOptions(source, archive, { unpack: "small.js" });
const unpackedPath = join(`${archive}.unpacked`, "small.js");
const identity = await lstat(unpackedPath);
const closeError = new Error("unpacked close denied");
const snapshotError = new Error("snapshot removal denied");
let closeCount = 0;
const snapshotPaths: string[] = [];
const reader = new AsarArtifactReader(
archive,
async (path, flags) => {
const handle = await openFile(path, flags);
return {
async stat() {
throw Object.assign(new Error("device stat failed"), {
code: "EIO",
errno: -5,
syscall: "fstat",
});
},
async close() {
closeCount += 1;
if (closeCount < 3) throw closeError;
await handle.close();
},
createReadStream: (options) => handle.createReadStream(options),
};
},
async (path) => {
snapshotPaths.push(path);
if (snapshotPaths.length === 1) throw snapshotError;
await rm(path, { recursive: true, force: true });
},
);
try {
const entries = [];
for await (const entry of reader.entries()) entries.push(entry);
const entry = entries.find(({ path }) => path === "small.js");
if (entry === undefined) throw new Error("Expected unpacked ASAR member");
await expect(reader.open(entry)).rejects.toMatchObject({
reason: "io",
cleanup: { resources: [unpackedPath] },
});
expect(closeCount).toBe(1);
const cleanupFailure = await reader.close().then(
() => undefined,
(cause: unknown) => cause,
);
expect(cleanupFailure).toMatchObject({
cleanup: {
resources: [unpackedPath, expect.any(String)],
reason: expect.stringContaining("unpacked close denied"),
},
});
const snapshotRoot = snapshotPaths[0];
if (snapshotRoot === undefined)
throw new Error("Expected owned ASAR snapshot root");
expect(snapshotPaths).toEqual([snapshotRoot]);
expect(cleanupFailure).toMatchObject({
cleanup: { resources: [unpackedPath, snapshotRoot] },
});
expect(closeCount).toBe(2);
expect(await matchingDescriptorCount(identity)).toBeGreaterThan(0);
expect((await lstat(snapshotRoot)).isDirectory()).toBe(true);
await reader.close();
expect(closeCount).toBe(3);
expect(snapshotPaths).toEqual([snapshotRoot, snapshotRoot]);
await waitForNoMatchingDescriptor(identity);
await expect(lstat(snapshotRoot)).rejects.toMatchObject({
code: "ENOENT",
});
} finally {
await reader.close();
}
},
);
it.skipIf(process.platform === "win32")(
"releases unpacked handles after stream completion and cancellation",
async () => {
const root = await createTestTempDirectory("rea-asar-unpacked-stream-");
const source = join(root, "source");
const archive = join(root, "fixture.asar");
await mkdir(source);
await writeFile(join(source, "small.js"), "module.exports = 1;\n");
await createPackageWithOptions(source, archive, { unpack: "small.js" });
const identity = await lstat(join(`${archive}.unpacked`, "small.js"));
const reader = new AsarArtifactReader(archive);
try {
const entries = [];
for await (const entry of reader.entries()) entries.push(entry);
const entry = entries.find(({ path }) => path === "small.js");
if (entry === undefined) throw new Error("Expected unpacked ASAR member");
expect((await buffer(await reader.open(entry))).toString()).toBe(
"module.exports = 1;\n",
);
await waitForNoMatchingDescriptor(identity);
const controller = new AbortController();
const output = await reader.open(entry, controller.signal);
const reading = buffer(output);
controller.abort();
await expect(reading).rejects.toMatchObject({ reason: "cancelled" });
await waitForNoMatchingDescriptor(identity);
} finally {
await reader.close();
}
},
);
it.each(["missing", "replaced"] as const)(
"reads a captured zero-length member when the original container is %s",
async (change) => {
const root = await createTestTempDirectory("rea-asar-empty-member-");
const source = join(root, "source");
const archive = join(root, "fixture.asar");
await mkdir(source);
await writeFile(join(source, "empty.js"), "");
await createPackageWithOptions(source, archive, {});
const reader = new AsarArtifactReader(archive);
try {
const entries = [];
for await (const entry of reader.entries()) entries.push(entry);
const entry = entries.find(({ path }) => path === "empty.js");
if (entry === undefined) throw new Error("Expected empty ASAR member");
if (change === "missing") await rm(archive);
else await writeFile(archive, "replacement container");
expect(await buffer(await reader.open(entry))).toHaveLength(0);
} finally {
await reader.close();
}
},
);
it("preserves filesystem errors raised while consuming a member stream", async () => {
const ioError = Object.assign(new Error("device read failed"), {
code: "EIO",
errno: -5,
syscall: "read",
});
const source = Readable.from(
(async function* () {
yield Buffer.from("partial");
throw ioError;
})(),
);
const output = readValidatedAsarEntry(
source,
undefined,
"nested/member.bin",
"/tmp/source.asar",
);
it("preserves filesystem errors raised while consuming a member stream", async () => {
const ioError = Object.assign(new Error("device read failed"), {
code: "EIO",
errno: -5,
syscall: "read",
});
const source = Readable.from(
(async function* () {
yield Buffer.from("partial");
throw ioError;
})(),
);
const output = readValidatedAsarEntry(
source,
undefined,
"nested/member.bin",
"/tmp/source.asar",
);
await expect(async () => {
for await (const _chunk of output) {
// Consume through the source failure.
}
}).rejects.toMatchObject({
name: "ArtifactReaderFailure",
reason: "io",
message: expect.stringContaining(
"Could not read nested/member.bin ASAR at /tmp/source.asar",
),
cause: { code: "EIO", errno: -5, syscall: "read" },
});
await expect(async () => {
for await (const _chunk of output) {
// Consume through the source failure.
}
}).rejects.toMatchObject({
name: "ArtifactReaderFailure",
reason: "io",
message: expect.stringContaining(
"Could not read nested/member.bin ASAR at /tmp/source.asar",
),
cause: { code: "EIO", errno: -5, syscall: "read" },
});
});
@@ -7,6 +7,7 @@ import { parse as parseJsonc } from "jsonc-parser";
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
import { systemSetupHost } from "../../../src/application/SetupHost.js";
import { MANAGED_SKILL_FILES } from "../../../src/application/SetupSkill.js";
import { supportedClients } from "../../../src/application/SupportedClients.js";
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
@@ -151,6 +152,7 @@ describe("Qwen Code profile setup", () => {
});
expect(await setup.installSkill([client.name])).toBe("installed");
const skill = join(home, ".agents", "skills", PRODUCT_IDENTITY.skillName);
await writeFile(join(skill, "user-notes.txt"), "user-authored");
expect(await readFile(join(skill, "SKILL.md"), "utf8")).toContain(
"reverse-engineer-anything",
);
@@ -173,7 +175,13 @@ describe("Qwen Code profile setup", () => {
expect(registered).toEqual(client);
expect((await uninstall.removeClient(client)).status).toBe("removed");
expect((await uninstall.removeSkill()).status).toBe("removed");
await expect(access(skill)).rejects.toMatchObject({ code: "ENOENT" });
for (const relativePath of MANAGED_SKILL_FILES)
await expect(access(join(skill, relativePath))).rejects.toMatchObject({
code: "ENOENT",
});
expect(await readFile(join(skill, "user-notes.txt"), "utf8")).toBe(
"user-authored",
);
if (customHome)
await expect(access(join(home, ".qwen"))).rejects.toMatchObject({
code: "ENOENT",
@@ -2,10 +2,14 @@ import { createHash } from "node:crypto";
import {
access,
chmod,
mkdir,
readFile,
readdir,
readlink,
rename,
rm,
symlink,
writeFile,
} from "node:fs/promises";
import { join } from "node:path";
import { Readable } from "node:stream";
@@ -17,7 +21,7 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { SafeOutputTree } from "../../../src/artifacts/SafeOutputTree.js";
import { ArtifactReaderFailure } from "../../../src/artifacts/ArtifactReader.js";
describe("safe artifact output tree", () => {
describe("safe artifact output cleanup", () => {
it.skipIf(process.platform !== "linux")(
"closes the parent descriptor when the output disappears before commit",
async () => {
@@ -32,12 +36,169 @@ describe("safe artifact output tree", () => {
),
);
expect(targets.filter((target) => target === parent)).toEqual([]);
const failure = await tree.rollback().catch((cause: unknown) => cause);
expect(failure).toBeInstanceOf(ArtifactReaderFailure);
expect(failure).toMatchObject({ cleanup: { resources: [output] } });
expect(tree.cleanup).toEqual({
status: "incomplete",
residualPaths: ["published"],
});
await rm(parent, { recursive: true, force: true });
},
);
});
describe("safe artifact output tree identity", () => {
it.skipIf(process.platform === "win32")(
"refuses a replaced root and retries cleanup when the owned root is restored",
async () => {
const parent = await createTestTempDirectory("rea-safe-output-root-");
const output = join(parent, "published");
const displaced = join(parent, "owned-original");
const outside = join(parent, "outside");
await mkdir(outside);
const tree = await SafeOutputTree.create(output);
await rename(output, displaced);
await symlink(outside, output, "dir");
const writeFailure = await tree
.write("escaped.txt", Readable.from(Buffer.from("outside")), {
sha256: createHash("sha256").update("outside").digest("hex"),
bytes: Buffer.byteLength("outside"),
})
.catch((cause: unknown) => cause);
expect(writeFailure).toBeInstanceOf(ArtifactReaderFailure);
await expect(access(join(outside, "escaped.txt"))).rejects.toThrow();
await expect(tree.commit()).rejects.toBeInstanceOf(ArtifactReaderFailure);
const cleanupFailure = await tree
.rollback()
.catch((cause: unknown) => cause);
expect(cleanupFailure).toBeInstanceOf(ArtifactReaderFailure);
expect(cleanupFailure).toMatchObject({
cleanup: { resources: [output] },
});
expect(await readlink(output)).toBe(outside);
await rm(output);
await rename(displaced, output);
expect(await tree.rollback()).toEqual({
status: "complete",
residualPaths: [],
});
expect(await readdir(parent)).toEqual(["outside"]);
},
);
it.skipIf(process.platform === "win32")(
"refuses a replaced nested parent without touching it and retries after restoration",
async () => {
const parent = await createTestTempDirectory("rea-safe-output-parent-");
const output = join(parent, "published");
const nested = join(output, "nested");
const displaced = join(parent, "owned-nested");
const outside = join(parent, "outside");
await mkdir(outside);
await writeFile(join(outside, "sentinel.txt"), "keep");
const tree = await SafeOutputTree.create(output);
const bytes = Buffer.from("owned");
await tree.write("nested/owned.txt", Readable.from(bytes), {
sha256: createHash("sha256").update(bytes).digest("hex"),
bytes: bytes.byteLength,
});
await rename(nested, displaced);
await symlink(outside, nested, "dir");
const writeFailure = await tree
.write("nested/escaped.txt", Readable.from(Buffer.from("outside")), {
sha256: createHash("sha256").update("outside").digest("hex"),
bytes: Buffer.byteLength("outside"),
})
.catch((cause: unknown) => cause);
expect(writeFailure).toBeInstanceOf(ArtifactReaderFailure);
await expect(access(join(outside, "escaped.txt"))).rejects.toThrow();
expect(await readFile(join(outside, "sentinel.txt"), "utf8")).toBe(
"keep",
);
const cleanupFailure = await tree
.rollback()
.catch((cause: unknown) => cause);
expect(cleanupFailure).toBeInstanceOf(ArtifactReaderFailure);
expect(await readlink(nested)).toBe(outside);
expect(await readFile(join(outside, "sentinel.txt"), "utf8")).toBe(
"keep",
);
await rm(nested);
await rename(displaced, nested);
expect(await tree.rollback()).toEqual({
status: "complete",
residualPaths: [],
});
expect(await readdir(parent)).toEqual(["outside"]);
},
);
it.skipIf(process.platform === "win32")(
"preserves an outside file when a tracked output file is replaced by a symlink",
async () => {
const parent = await createTestTempDirectory("rea-safe-output-file-");
const output = join(parent, "published");
const tracked = join(output, "nested", "file.txt");
const displaced = join(parent, "owned-file.txt");
const outside = join(parent, "outside.txt");
await writeFile(outside, "outside bytes");
const tree = await SafeOutputTree.create(output);
const bytes = Buffer.from("owned bytes");
await tree.write("nested/file.txt", Readable.from(bytes), {
sha256: createHash("sha256").update(bytes).digest("hex"),
bytes: bytes.byteLength,
});
await rename(tracked, displaced);
await symlink(outside, tracked, "file");
const failure = await tree.rollback().catch((cause: unknown) => cause);
expect(failure).toBeInstanceOf(ArtifactReaderFailure);
expect(tree.cleanup).toMatchObject({ status: "incomplete" });
expect(await readlink(tracked)).toBe(outside);
expect(await readFile(outside, "utf8")).toBe("outside bytes");
await rm(tracked);
await rename(displaced, tracked);
expect(await tree.rollback()).toEqual({
status: "complete",
residualPaths: [],
});
expect(await readFile(outside, "utf8")).toBe("outside bytes");
},
);
});
it("retains an untracked regular entry and retries after it is removed", async () => {
const parent = await createTestTempDirectory("rea-safe-output-untracked-");
const output = join(parent, "published");
const untracked = join(output, "untracked.txt");
const tree = await SafeOutputTree.create(output);
const bytes = Buffer.from("owned bytes");
await tree.write("owned.txt", Readable.from(bytes), {
sha256: createHash("sha256").update(bytes).digest("hex"),
bytes: bytes.byteLength,
});
await writeFile(untracked, "leave untouched");
const failure = await tree.rollback().catch((cause: unknown) => cause);
expect(failure).toBeInstanceOf(ArtifactReaderFailure);
expect(tree.cleanup).toMatchObject({ status: "incomplete" });
expect(await readdir(output)).toEqual(["untracked.txt"]);
expect(await readFile(untracked, "utf8")).toBe("leave untouched");
await rm(untracked);
expect(await tree.rollback()).toEqual({
status: "complete",
residualPaths: [],
});
expect(await readdir(parent)).toEqual([]);
});
describe("safe artifact output tree", () => {
it("removes only its owned tree after digest failure and proves absence", async () => {
const parent = await createTestTempDirectory("rea-safe-output-");
const output = join(parent, "published");
@@ -72,6 +233,7 @@ describe("safe artifact output tree", () => {
const failure = await tree.rollback().catch((cause: unknown) => cause);
expect(failure).toBeInstanceOf(ArtifactReaderFailure);
expect(failure).toMatchObject({
cause: { code: "EACCES" },
cleanup: { resources: [output] },
});
} finally {
@@ -81,6 +243,54 @@ describe("safe artifact output tree", () => {
},
);
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
"retains cleanup progress when one owned sibling is not writable",
async () => {
const parent = await createTestTempDirectory("rea-safe-output-siblings-");
const output = join(parent, "published");
const completed = join(output, "completed");
const blocked = join(output, "blocked");
const tree = await SafeOutputTree.create(output);
for (const directory of ["completed", "blocked"]) {
const bytes = Buffer.from(join(output, directory));
await tree.write(`${directory}/file.txt`, Readable.from(bytes), {
sha256: createHash("sha256").update(bytes).digest("hex"),
bytes: bytes.byteLength,
});
}
try {
await chmod(blocked, 0o500);
const failure = await tree.rollback().catch((cause: unknown) => cause);
expect(failure).toBeInstanceOf(ArtifactReaderFailure);
expect(failure).toMatchObject({
cause: { code: "EACCES" },
cleanup: { resources: [output] },
});
expect(await readdir(output)).toEqual(["blocked"]);
await expect(access(completed)).rejects.toThrow();
expect(await readFile(join(blocked, "file.txt"), "utf8")).toBe(blocked);
await expect(
tree.write("new/file.txt", Readable.from(Buffer.from("late")), {
sha256: createHash("sha256").update("late").digest("hex"),
bytes: Buffer.byteLength("late"),
}),
).rejects.toBeInstanceOf(ArtifactReaderFailure);
await expect(tree.commit()).rejects.toBeInstanceOf(
ArtifactReaderFailure,
);
} finally {
await chmod(blocked, 0o700);
}
expect(await tree.rollback()).toEqual({
status: "complete",
residualPaths: [],
});
expect(await readdir(parent)).toEqual([]);
},
);
it("publishes files while building and preserves them after sealing", async () => {
const parent = await createTestTempDirectory("rea-safe-output-");
const output = join(parent, "published");
@@ -115,6 +325,13 @@ describe("safe artifact output tree", () => {
status: "complete",
residualPaths: [],
});
await expect(
tree.write("late.txt", Readable.from(Buffer.from("late")), {
sha256: createHash("sha256").update("late").digest("hex"),
bytes: Buffer.byteLength("late"),
}),
).rejects.toBeInstanceOf(ArtifactReaderFailure);
await expect(tree.commit()).rejects.toBeInstanceOf(ArtifactReaderFailure);
});
it("publishes without POSIX-only directory chmod or fsync on Windows", async () => {
+2 -2
View File
@@ -187,12 +187,11 @@ describe("canonical skill transaction", () => {
expect(installedSkill).toContain(
`version: "${PRODUCT_IDENTITY.skillVersion}"`,
);
expect(installedSkill).toContain("call available analysis tools");
expect(installedSkill).toContain("obtain approval before setup writes");
expect(await readFile(`${nativeGuide}.rea.backup`, "utf8")).toBe(
"stale filesystem-write permission grant\n",
);
for (const reference of [
"connection-and-recovery.md",
"native-and-artifacts.md",
"javascript-applications.md",
"android-applications.md",
@@ -243,6 +242,7 @@ describe("canonical skill transaction", () => {
const paths = [
"SKILL.md",
"references/android-applications.md",
"references/connection-and-recovery.md",
"references/evidence-workflows.md",
"references/javascript-applications.md",
"references/native-and-artifacts.md",
@@ -324,7 +324,7 @@ it("cancels a waiting request promptly while keeping later launches behind the a
await assertFirmwareCleanup(fixture.launches);
});
it("retains an uncertain workspace and lets the next operation create a new root", async () => {
it("retains an uncertain worker's workspace and blocks later launches", async () => {
const fixture = await firmwareFixture("cleanup-failure");
const first = await fixture.service.execute("inspect_firmware_regions", {
path: fixture.path,
@@ -335,18 +335,22 @@ it("retains an uncertain workspace and lets the next operation create a new root
});
const workspace = fixture.launches[0]?.cwd;
expect(workspace).toBeDefined();
if (workspace === undefined) return;
if (workspace === undefined) throw new Error("Expected retained workspace");
await access(workspace);
const originalLaunches = [...fixture.launches];
const next = await fixture.service.execute("inspect_firmware_regions", {
path: fixture.path,
});
expect(next).toMatchObject({ ok: false, error: { cleanupIncomplete: true } });
expect(fixture.launches).toHaveLength(2);
const nextWorkspace = fixture.launches[1]?.cwd;
expect(nextWorkspace).toBeDefined();
expect(nextWorkspace).not.toBe(workspace);
expect(fixture.launches).toEqual(originalLaunches);
await access(workspace);
if (nextWorkspace !== undefined) await access(nextWorkspace);
fixture.restoreCleanup();
const resumed = await fixture.service.execute("inspect_firmware_regions", {
path: fixture.path,
});
if (!resumed.ok) throw resumed.error;
expect(resumed.value.subject?.local_path).toBe(fixture.path);
await assertFirmwareCleanup(fixture.launches);
});
it("accepts another build on the verified release line and reports it", async () => {
@@ -0,0 +1,164 @@
import { access, chmod, readFile } from "node:fs/promises";
import { join } from "node:path";
import { createHash } from "node:crypto";
import { expect, it } from "vitest";
import { STDIO_DEFAULT_MAX_BUFFER_SIZE } from "@modelcontextprotocol/server";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { firmwareResultSchemas } from "../../../src/domain/firmware/firmwareAnalysis.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { ToolResultDelivery } from "../../../src/server/toolResult.js";
import {
assertFirmwareCleanup,
firmwareFixture,
} from "../../fixtures/firmware/provider.js";
it.skipIf(process.platform !== "linux" || process.getuid?.() === 0)(
"retains completed extractions and retries all workspaces without blocking stopped-worker operations",
async () => {
const fixture = await firmwareFixture("workspace-cleanup-failure");
const sourceBytes = await readFile(fixture.path);
const sourceSha256 = createHash("sha256").update(sourceBytes).digest("hex");
const workspaces = new Set<string>();
try {
for (const output of [
fixture.output,
join(fixture.root, "second-output"),
]) {
const extracted = await fixture.service.execute("extract_firmware", {
path: fixture.path,
output_directory: output,
range: { offset: 2, length: 4 },
});
const workspace = fixture.launches.at(-1)?.cwd;
if (workspace === undefined)
throw new Error("Expected owned workspace");
expect(workspaces.has(workspace)).toBe(false);
workspaces.add(workspace);
if (extracted.ok) throw new Error("Expected workspace removal failure");
expect(extracted.error.cleanupIncomplete).toBe(true);
const partial = extracted.error.partialObservation;
if (
partial === undefined ||
!("kind" in partial) ||
partial.kind !== "firmware"
)
throw new Error("Expected completed firmware observation");
expect(partial.provenance).toMatchObject({
subject: {
format: "file",
path: fixture.path,
sha256: sourceSha256,
},
provider: { id: "unblob", version: "26.6.4" },
raw_result: {
report: expect.any(Array),
execution: { exit_code: 0 },
},
locations: [{ kind: "file-offset-range", start: 2, end: 6 }],
});
const result = firmwareResultSchemas.extract_firmware.parse(
partial.result,
);
expect(result.selection).toEqual({
offset: 2,
length: 4,
sha256: createHash("sha256")
.update(sourceBytes.subarray(2, 6))
.digest("hex"),
});
const file = result.files[0];
if (file === undefined)
throw new Error("Expected published extracted file");
expect(await readFile(file.path, "utf8")).toBe("firmware=true\n");
expect(extracted.error.cleanupResources).toContain(workspace);
await access(workspace);
const delivered = new ToolResultDelivery(
STDIO_DEFAULT_MAX_BUFFER_SIZE,
).toCallToolResult(extracted, toolContract("extract_firmware"));
expect(delivered.isError).toBe(true);
expect(delivered.structuredContent).toMatchObject({
error: {
details: {
partial_observation: {
kind: "firmware",
result,
provenance: partial.provenance,
},
},
},
});
const inspected = await fixture.service.execute(
"inspect_firmware_regions",
{
path: fixture.path,
},
);
if (!inspected.ok) throw inspected.error;
expect(inspected.value.subject?.local_path).toBe(fixture.path);
expect(
firmwareResultSchemas.inspect_firmware_regions.parse(
inspected.value.normalized_result,
).regions[0]?.signature,
).toBe("gzip");
}
await expect(fixture.close()).rejects.toMatchObject({
cleanupResources: expect.arrayContaining([...workspaces]),
});
for (const workspace of workspaces) await access(workspace);
} finally {
for (const workspace of workspaces)
await chmod(join(workspace, "cleanup-blocked"), 0o700);
await fixture.close();
}
await assertFirmwareCleanup(fixture.launches);
expect(await readFile(fixture.path)).toEqual(sourceBytes);
for (const output of [fixture.output, join(fixture.root, "second-output")])
expect(await readFile(join(output, "rootfs/config"), "utf8")).toBe(
"firmware=true\n",
);
},
);
it.skipIf(process.platform !== "linux" || process.getuid?.() === 0)(
"preserves the report failure alongside a workspace removal failure",
async () => {
const fixture = await firmwareFixture(
"workspace-cleanup-failure-malformed",
);
let workspace: string | undefined;
try {
const failed = await fixture.service.execute("extract_firmware", {
path: fixture.path,
output_directory: fixture.output,
});
workspace = fixture.launches.at(-1)?.cwd;
if (failed.ok || workspace === undefined)
throw new Error("Expected both report and cleanup failures");
expect(projectAnalysisError(failed.error)).toMatchObject({
code: "cleanup_incomplete",
details: {
diagnostics: {
primary_error: { code: "unreadable_output" },
cleanup_error: {
code: "cleanup_incomplete",
details: {
diagnostics: { reason: expect.stringContaining("EACCES") },
},
},
},
resources: expect.arrayContaining([workspace]),
},
});
await expect(access(fixture.output)).rejects.toMatchObject({
code: "ENOENT",
});
} finally {
if (workspace !== undefined)
await chmod(join(workspace, "cleanup-blocked"), 0o700);
await fixture.close();
}
await assertFirmwareCleanup(fixture.launches);
},
);
@@ -19,6 +19,7 @@ import {
analysisViewJavaScriptEvidence,
analysisViewJavaScriptAnalysisWithSource,
analysisViewBindJavaScriptGraphs,
analysisViewLayoutEvidence,
analysisViewLayoutFixture,
} from "../../fixtures/analysisView.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
@@ -111,6 +112,35 @@ it("advertises exact schemas and projects one layout section from retained Evide
);
});
it("reports a tampered inline Evidence ID at its full MCP source path", async () => {
const { client } = await connect();
const parent = analysisViewLayoutEvidence();
const response = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: {
kind: "inline",
evidence: { ...parent, evidence_id: `ev_${"0".repeat(64)}` },
},
view: { kind: "summary" },
},
});
expect(parseMcpToolError(response).error).toMatchObject({
code: "invalid_request",
category: "invalid_input",
details: {
issues: [
{
path: ["source", "evidence", "evidence_id"],
reason: "invalid_value",
message: "Evidence semantic identifier does not match its record",
},
],
},
});
});
it("delivers a bounded native dossier view over MCP without a Ghidra provider or lost connection", async () => {
const { client, session } = await connect();
const original = functionDossierSchema.parse(ghidraFunctionDossier());
@@ -36,8 +36,8 @@ const writeBlockingCompiler = async (directory: string) => {
const statePath = join(directory, "compile-state.json");
const releasePath = join(directory, "release-compiler");
const source = `#!/usr/bin/env node
const fs = require("node:fs");
const path = require("node:path");
const fs = process.getBuiltinModule("node:fs");
const path = process.getBuiltinModule("node:path");
const statePath = ${JSON.stringify(statePath)};
const releasePath = ${JSON.stringify(releasePath)};
const state = fs.existsSync(statePath)
@@ -69,14 +69,14 @@ const writeBlockingIdentityCompiler = async (directory: string) => {
const executable = join(directory, "fake-identity-xcrun");
const statePath = join(directory, "identity-helper-state.json");
const helperSource = `#!/usr/bin/env node
const fs = require("node:fs");
const fs = process.getBuiltinModule("node:fs");
fs.writeFileSync(${JSON.stringify(statePath)}, JSON.stringify({
root: __dirname,
root: process.getBuiltinModule("node:path").dirname(fs.realpathSync(process.argv[1])),
}));
setInterval(() => {}, 1000);
`;
const compilerSource = `#!/usr/bin/env node
const fs = require("node:fs");
const fs = process.getBuiltinModule("node:fs");
const outputIndex = process.argv.indexOf("-o");
const output = process.argv[outputIndex + 1];
fs.writeFileSync(output, ${JSON.stringify(helperSource)});
@@ -309,14 +309,14 @@ const writeTemporaryObjectCompiler = async (directory: string) => {
const executable = join(directory, "fake-temporary-xcrun");
const statePath = join(directory, "temporary-state.json");
const source = `#!/usr/bin/env node
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const { spawn } = require("node:child_process");
const fs = process.getBuiltinModule("node:fs");
const os = process.getBuiltinModule("node:os");
const path = process.getBuiltinModule("node:path");
const { spawn } = process.getBuiltinModule("node:child_process");
const temporary = fs.mkdtempSync(path.join(os.tmpdir(), "TemporaryDirectory."));
const object = path.join(temporary, "ProcessRunTokenReader-1.o");
const job = spawn(process.execPath, ["-e",
"setTimeout(() => { const fs = require('node:fs'); fs.mkdirSync(" + JSON.stringify(temporary) +
"setTimeout(() => { const fs = process.getBuiltinModule('node:fs'); fs.mkdirSync(" + JSON.stringify(temporary) +
", { recursive: true }); fs.writeFileSync(" + JSON.stringify(object) + ", 'object'); }, 300)"],
{ detached: true, stdio: "ignore" });
job.unref();
@@ -567,9 +567,9 @@ it.skipIf(process.platform === "win32")(
},
);
it.skipIf(process.platform === "win32")(
"preserves cancellation through system-host baseline identity inspection",
async () => {
it.skipIf(process.platform === "win32").each(["baseline", "tokens"] as const)(
"preserves cancellation through system-host %s inspection",
async (kind) => {
const directory = await mkdtemp(
join(tmpdir(), "rea-process-baseline-abort-test-"),
);
@@ -579,8 +579,23 @@ it.skipIf(process.platform === "win32")(
});
const controller = new AbortController();
let helperRoot: string | undefined;
const inspection =
kind === "baseline"
? host.captureBaseline?.(controller.signal)
: host.runTokens?.(
[
{
pid: process.pid,
parentPid: process.ppid,
processGroupId: process.pid,
state: "S",
command: process.execPath,
},
],
controller.signal,
);
const baseline =
host.captureBaseline?.(controller.signal).then(
inspection?.then(
() => ({ state: "fulfilled" as const }),
(cause: unknown) => ({ state: "rejected" as const, cause }),
) ?? Promise.resolve({ state: "missing" as const });
@@ -91,8 +91,9 @@ it("reuses immutable engine state while keeping each Evidence observation separa
await verifyCleanup(launches);
});
it("bounds output per operation across a retained session rather than accumulating earlier captures", async () => {
const { service, apk, launches, provider } = await setup("large-manifest");
it("bounds output per operation without repeating prerequisite probes for a retained session", async () => {
const { service, apk, launches, provider, javaProbeCount } =
await setup("large-manifest");
const expectedManifest = "x".repeat(1024 * 1024);
for (let index = 0; index < 34; index += 1) {
const result = await service.execute("inspect_android_package", {
@@ -106,12 +107,14 @@ it("bounds output per operation across a retained session rather than accumulati
).toBe(expectedManifest);
}
expect(launches).toHaveLength(1);
expect(await javaProbeCount()).toBe(1);
await provider.close();
await verifyCleanup(launches);
});
it("retire sessions when APK bytes, engine bytes or JVM options change", async () => {
const { service, apk, jar, launches, provider, environment } = await setup();
const { service, apk, jar, launches, provider, environment, javaProbeCount } =
await setup();
const inspect = async () => {
const result = await service.execute("inspect_android_package", {
path: apk,
@@ -133,6 +136,7 @@ it("retire sessions when APK bytes, engine bytes or JVM options change", async (
environment._JAVA_OPTIONS = "-XX:+UseG1GC";
await inspect();
expect(launches).toHaveLength(4);
expect(await javaProbeCount()).toBe(4);
expect(launches[3]).toMatchObject({
javaToolOptions: "-Xmx8g",
legacyJavaOptions: "-XX:+UseG1GC",
@@ -1,8 +1,10 @@
import { fileURLToPath } from "node:url";
import { access } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { Ajv2020 } from "ajv/dist/2020.js";
import { afterEach, expect } from "vitest";
import { afterEach, expect, it } from "vitest";
import { z } from "zod";
import { toolContract } from "../../../src/contracts/toolContracts.js";
@@ -13,6 +15,7 @@ import {
import { createServer } from "../../../src/server/createServer.js";
import { silentLogger } from "../../../src/logger.js";
import { itWithCaptureCapability } from "./processCaptureCapability.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const processFixture = fileURLToPath(
new URL("../../fixtures/processFidelity.mjs", import.meta.url),
@@ -23,6 +26,50 @@ afterEach(async () => {
await Promise.all(resources.splice(0).map((resource) => resource.close()));
});
it("rejects oversized initial and resize terminal buffers through MCP before launching", async () => {
const root = await createTestTempDirectory("rea-terminal-admission-");
const marker = join(root, "launched");
const session = createTestBinarySession(() => {
throw new Error("Terminal admission must not launch a binary provider");
});
const server = createServer(
{ kind: "session", session },
{ logger: silentLogger },
);
const client = new Client({ name: "terminal-admission", version: "1" });
resources.push(client, server, session);
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
for (const input of [
{ terminal: { columns: 1_000, rows: 1, scrollback: 1_000 } },
{ events: [{ type: "resize", at_ms: 10, columns: 1_000, rows: 1 }] },
] as const) {
const result = await client.callTool({
name: "capture_process_scenario",
arguments: {
executable: process.execPath,
arguments: [
"-e",
"require('node:fs').writeFileSync(process.argv[1], 'launched')",
marker,
],
...input,
},
});
expect(result.isError).toBe(true);
expect(result.content).toContainEqual(
expect.objectContaining({
type: "text",
text: expect.stringContaining("1000000"),
}),
);
await expect(access(marker)).rejects.toMatchObject({ code: "ENOENT" });
}
await client.ping();
});
itWithCaptureCapability(
"records process residuals linked to capture Evidence",
async () => {
@@ -202,9 +202,11 @@ describe("provider process output and cleanup primitives", () => {
expect(snapshot).toMatchObject({
stdout: {
bytes: outputBytes,
observedBytes: outputBytes,
},
stderr: {
bytes: outputBytes,
observedBytes: outputBytes,
},
exitCode: 23,
signal: null,
@@ -29,6 +29,12 @@ it("bounds capture before diagnostic callbacks while draining both output stream
expect(
diagnostics.some((event) => event.type === "output" && event.truncated),
).toBe(true);
const snapshot = supervisor.snapshot();
expect(snapshot.stdout.observedBytes).toBe(70_000);
expect(snapshot.stderr.observedBytes).toBe(70_000);
expect(snapshot.stdout.bytes + snapshot.stderr.bytes).toBeLessThanOrEqual(
1024,
);
for (const stream of ["stdout", "stderr"])
expect(
diagnostics
@@ -11,6 +11,7 @@ import type { Logger } from "pino";
import { ok } from "../../../../src/domain/result.js";
import { GhidraClient } from "../../../../src/ghidra/GhidraClient.js";
import { GHIDRA_PROCESS_DIAGNOSTIC_BYTES } from "../../../../src/ghidra/GhidraDiagnostics.js";
import { GhidraHeadlessLauncher } from "../../../../src/ghidra/GhidraLauncher.js";
import type { GhidraDiagnostic } from "../../../../src/ghidra/GhidraClientTypes.js";
import type {
@@ -49,7 +50,8 @@ type FixtureMode =
| "hang_tools"
| "exit_tools"
| "silent"
| "exit";
| "exit"
| "diagnostic_output";
class FixtureLauncher implements GhidraLauncher {
#notifyStarted: ((child: ChildProcess) => void) | undefined;
@@ -458,6 +460,53 @@ describe("GhidraClient cleanup and diagnostics", () => {
});
});
it("bounds long-lived launcher diagnostics without interrupting the session", async () => {
const launcher = new FixtureLauncher("diagnostic_output");
const client = clientFor(launcher);
await expect(client.start()).resolves.toMatchObject({ ok: true });
await expect(
client.callTool("list_strings", { document: null }),
).resolves.toMatchObject({ ok: true });
await vi.waitFor(() => {
expect(client.diagnostics()).toMatchObject({
diagnostic_truncated: true,
});
});
const diagnostics = client.diagnostics();
const stdout = diagnostics.stdout as {
bytes: number;
retained_bytes: number;
text: string;
};
const stderr = diagnostics.stderr as {
bytes: number;
retained_bytes: number;
text: string;
};
expect(stdout.bytes + stderr.bytes).toBeGreaterThan(
GHIDRA_PROCESS_DIAGNOSTIC_BYTES,
);
expect(stdout.retained_bytes + stderr.retained_bytes).toBeLessThanOrEqual(
GHIDRA_PROCESS_DIAGNOSTIC_BYTES,
);
expect(stdout.bytes).toBeGreaterThanOrEqual(stdout.retained_bytes);
expect(stderr.bytes).toBeGreaterThanOrEqual(stderr.retained_bytes);
expect(JSON.stringify(diagnostics)).not.toContain(launcher.tokens[0] ?? "");
expect(`${stdout.text}${stderr.text}`).toContain("[REDACTED]");
expect(
stderr.text.endsWith(
"source=/tmp/local-evidence.bin?cursor=keep&[REDACTED]",
),
).toBe(true);
await client.close();
expect(exited(launcher.processes[0])).toBe(true);
await expect(access(launcher.runtimeRoots[0] ?? "")).rejects.toMatchObject({
code: "ENOENT",
});
});
it("retains actionable diagnostics without retaining its token", async () => {
const launcher = new FixtureLauncher("exit");
const events: GhidraDiagnostic[] = [];
@@ -0,0 +1,88 @@
import { access } from "node:fs/promises";
import { expect, it, onTestFinished, vi } from "vitest";
import { HopperTimeoutError } from "../../../../src/domain/hopperErrors.js";
import {
HopperClient,
HOPPER_PROCESS_DIAGNOSTIC_BYTES,
} from "../../../../src/hopper/HopperClient.js";
import { HopperFixtureLauncher } from "./hopperClient.fixture.js";
it("bounds long-lived launcher output while keeping the bridge usable", async () => {
let observedStderrBytes = 0;
const diagnosticLauncher = new HopperFixtureLauncher(undefined, "noisy");
const client = new HopperClient({
launcher: diagnosticLauncher,
startupTimeoutMs: 10_000,
onDiagnostic(event) {
if (event.type === "launcher-stderr") observedStderrBytes += event.bytes;
},
});
onTestFinished(async () => {
await client.close();
});
await expect(client.start()).resolves.toMatchObject({ ok: true });
const session = await client.callTool("echo", { value: "still usable" });
expect(session).toEqual({ ok: true, value: { value: "still usable" } });
await vi.waitFor(() => {
expect(observedStderrBytes).toBeGreaterThan(
HOPPER_PROCESS_DIAGNOSTIC_BYTES,
);
});
await client.close();
const directory = diagnosticLauncher.directories[0] ?? "";
await expect(access(directory)).rejects.toMatchObject({ code: "ENOENT" });
expect(diagnosticLauncher.processes[0]?.exitCode).not.toBeNull();
});
it("reports observed and retained output when capture cuts a token", async () => {
const diagnosticLauncher = new HopperFixtureLauncher(
undefined,
"noisy_no_socket",
);
const client = new HopperClient({
launcher: diagnosticLauncher,
startupTimeoutMs: 1_000,
});
onTestFinished(async () => {
await client.close();
});
const started = await client.start();
if (started.ok || !(started.error instanceof HopperTimeoutError))
throw new Error("Expected the no-socket fixture to time out");
const outcome = started.error.launcherOutcome;
expect(outcome).toMatchObject({ diagnostic_truncated: true });
if (outcome === undefined) throw new Error("Launcher outcome was omitted");
expect(outcome.stdout.bytes + outcome.stderr.bytes).toBeGreaterThan(
HOPPER_PROCESS_DIAGNOSTIC_BYTES,
);
expect(
outcome.stdout.retained_bytes + outcome.stderr.retained_bytes,
).toBeLessThanOrEqual(HOPPER_PROCESS_DIAGNOSTIC_BYTES);
expect(outcome.stdout.bytes).toBeGreaterThanOrEqual(
outcome.stdout.retained_bytes,
);
expect(outcome.stderr.bytes).toBeGreaterThanOrEqual(
outcome.stderr.retained_bytes,
);
expect(outcome.stderr.retained_bytes).toBe(HOPPER_PROCESS_DIAGNOSTIC_BYTES);
const token = diagnosticLauncher.tokens[0] ?? "";
expect(JSON.stringify(outcome)).not.toContain(token);
expect(`${outcome.stdout.text}${outcome.stderr.text}`).toContain(
"[redacted transport credential]",
);
expect(
outcome.stderr.text.endsWith(
"source=/tmp/local-evidence.bin?cursor=keep&[redacted transport credential]",
),
).toBe(true);
await client.close();
const directory = diagnosticLauncher.directories[0] ?? "";
await expect(access(directory)).rejects.toMatchObject({ code: "ENOENT" });
expect(diagnosticLauncher.processes[0]?.exitCode).not.toBeNull();
});
@@ -28,15 +28,20 @@ export class HopperFixtureLauncher implements BridgeLauncher {
readonly socketPaths: string[] = [];
readonly directories: string[] = [];
readonly runIds: string[] = [];
readonly tokens: string[] = [];
readonly processes: ChildProcess[] = [];
readonly requests: FixtureRequest[] = [];
constructor(readonly tokenOverride?: string) {}
constructor(
readonly tokenOverride?: string,
readonly diagnosticMode: "quiet" | "noisy" | "noisy_no_socket" = "quiet",
) {}
launch(session: BridgeSession) {
this.socketPaths.push(session.socketPath);
this.directories.push(session.directory);
this.runIds.push(session.runId);
this.tokens.push(session.token);
const child = spawn(
process.execPath,
[
@@ -44,8 +49,10 @@ export class HopperFixtureLauncher implements BridgeLauncher {
session.socketPath,
this.tokenOverride ?? session.token,
session.runId,
"acknowledge",
this.diagnosticMode,
],
{ stdio: ["ignore", "ignore", "pipe", "ipc"] },
{ stdio: ["ignore", "pipe", "pipe", "ipc"] },
);
child.on("message", (value: unknown) => {
const request = requestSchema.safeParse(value);
@@ -1,7 +1,7 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { describe, expect, it, onTestFinished } from "vitest";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
@@ -40,6 +40,7 @@ describe("artifact Mach-O slices", () => {
),
};
const reader = new MachOSliceArtifactReader(binary, {}, runner);
onTestFinished(() => reader.close());
const enumerate = async (): Promise<void> => {
for await (const _entry of reader.entries()) {
// Enumeration must reject out-of-bounds lipo metadata before yielding.
@@ -78,6 +79,7 @@ describe("artifact Mach-O slices", () => {
),
};
const reader = new MachOSliceArtifactReader(binary, {}, runner);
onTestFinished(() => reader.close());
const entries = [];
for await (const entry of reader.entries()) entries.push(entry);
expect(entries).toHaveLength(2);
@@ -105,7 +107,9 @@ describe("artifact Mach-O slices", () => {
Reflect.set(provenance[0], "tool", "forged");
expect(reader.provenance()[0]?.tool).toBe("lipo");
});
});
describe("artifact Mach-O slice integrity", () => {
it.each([
["CPU type", "cputype 16777223"],
["CPU subtype", "cpusubtype 2"],
@@ -139,6 +143,7 @@ describe("artifact Mach-O slices", () => {
{},
lipoRunner(`${details.join("\n")}\n`),
);
onTestFinished(() => reader.close());
await expect(async () => {
for await (const _entry of reader.entries()) {
// The structural comparison runs before the reader yields a slice.
@@ -161,6 +166,7 @@ describe("artifact Mach-O slices", () => {
`architecture arm64\n cputype 16777228\n cpusubtype 0\n offset 4096\n size ${thin.length}\n align 2^12 (4096)\n`,
),
);
onTestFinished(() => reader.close());
await expect(async () => {
for await (const _entry of reader.entries()) {
// Malformed structural facts must fail before any slice is yielded.
@@ -215,6 +221,7 @@ describe("artifact Mach-O arm64e variant slices", () => {
`architecture x86_64\n cputype CPU_TYPE_X86_64\n cpusubtype CPU_SUBTYPE_X86_64_ALL\n offset 4096\n size ${String(x86.length)}\n align 2^12 (4096)\n${lipo(arm.length)}`,
),
);
onTestFinished(() => reader.close());
const entries = [];
for await (const entry of reader.entries()) entries.push(entry);
return entries.map(({ path, byteOffset }) => [path, byteOffset]);
@@ -9,6 +9,7 @@ import {
rename,
rm,
symlink,
utimes,
writeFile,
} from "node:fs/promises";
import { dirname, join } from "node:path";
@@ -102,8 +103,13 @@ describe("native signature target identity", () => {
const runner = new Captures(async (args) => {
if (!args.includes("--entitlements")) return;
if (change === "remove") await rm(path);
else if (change === "rewrite") await writeFile(path, CONTENT);
else {
else if (change === "rewrite") {
const before = await lstat(path);
await writeFile(path, CONTENT);
// Identical writes may share a filesystem clock tick. Make the
// metadata change observed by the target guard explicit.
await utimes(path, before.atimeMs / 1000, before.mtimeMs / 1000 + 1);
} else {
const replacement = `${path}.replacement`;
await writeFile(replacement, CONTENT);
await rename(replacement, path);
@@ -8,6 +8,10 @@ import { MANAGED_STATIC_PROVIDER } from "../../../src/application/InvestigationP
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import { parseJavaScriptApplicationGraph } from "../../../src/domain/javascript/javascriptApplicationGraph.js";
import { managedApplicationGraphResultSchema } from "../../../src/domain/managed/managedApplicationGraph.js";
import {
managedMemberInspectionSchema,
managedNativeBoundaryInspectionSchema,
} from "../../../src/domain/managed/managedArtifact.js";
import { inspectManagedArtifactBytes } from "../../../src/dotnet/ManagedArtifactInspector.js";
import { inspectManagedMembersBytes } from "../../../src/dotnet/ManagedMemberInspector.js";
import { inspectManagedNativeBoundariesBytes } from "../../../src/dotnet/ManagedNativeBoundaryInspector.js";
@@ -299,6 +303,282 @@ describe("managed application graph identity facts", () => {
});
});
it("normalizes MVID casing for node identity while preserving observed values", () => {
const { memberEvidence, boundaryEvidence } = createManagedInteropEvidence();
const members = managedMemberInspectionSchema.parse(
parseEvidence(memberEvidence).normalized_result,
);
if (members.module === null)
throw new Error("Expected fixture module identity");
const uppercaseMvid = members.module.mvid?.toUpperCase();
if (uppercaseMvid === undefined || uppercaseMvid === null)
throw new Error("Expected fixture module MVID");
const uppercaseMembers = createEvidence(undefined, MANAGED_STATIC_PROVIDER, {
operation: "inspect_managed_members",
parameters: {},
result: {
...members,
module: {
...members.module,
mvid: uppercaseMvid,
enc_id: null,
enc_base_id: null,
},
identity_scope: {
...members.identity_scope,
requires_mvid: uppercaseMvid,
},
},
rawResult: null,
limitations: members.limitations,
});
const baseline = projectManagedApplicationGraphEvidence({
managed_members: memberEvidence,
managed_native_boundaries: boundaryEvidence,
});
const uppercase = projectManagedApplicationGraphEvidence({
managed_members: uppercaseMembers,
managed_native_boundaries: boundaryEvidence,
});
if (!baseline.ok) throw baseline.error;
if (!uppercase.ok) throw uppercase.error;
const baselineResult = managedApplicationGraphResultSchema.parse(
parseEvidence(baseline.value).normalized_result,
);
const uppercaseResult = managedApplicationGraphResultSchema.parse(
parseEvidence(uppercase.value).normalized_result,
);
const baselineModule = parseJavaScriptApplicationGraph(
baselineResult.graph,
).nodes.find(({ kind }) => kind === "managed-module");
const uppercaseGraph = parseJavaScriptApplicationGraph(uppercaseResult.graph);
const uppercaseModule = uppercaseGraph.nodes.find(
({ kind }) => kind === "managed-module",
);
expect(uppercaseGraph.edges).toContainEqual(
expect.objectContaining({
relation: "imports",
source_node_id: uppercaseGraph.nodes.find(
({ kind }) => kind === "managed-method",
)?.node_id,
}),
);
expect(uppercaseModule?.node_id).toBe(baselineModule?.node_id);
expect(uppercaseModule?.observations[0]?.properties.mvid).toBe(uppercaseMvid);
});
describe("managed application graph module identity consistency", () => {
it("rejects contradictory known module MVIDs across same-artifact inputs", () => {
const { artifactEvidence, memberEvidence, boundaryEvidence } =
createManagedInteropEvidence();
const boundaries = managedNativeBoundaryInspectionSchema.parse(
parseEvidence(boundaryEvidence).normalized_result,
);
const conflictingMvid = "ffffffff-ffff-ffff-ffff-ffffffffffff";
const conflictingBoundaries = createEvidence(
undefined,
MANAGED_STATIC_PROVIDER,
{
operation: "inspect_managed_native_boundaries",
parameters: {},
result: {
...boundaries,
module:
boundaries.module === null
? null
: { ...boundaries.module, mvid: conflictingMvid },
identity_scope: {
...boundaries.identity_scope,
requires_mvid: conflictingMvid,
},
},
rawResult: null,
limitations: boundaries.limitations,
},
);
const projected = projectManagedApplicationGraphEvidence({
managed_artifact: artifactEvidence,
managed_members: memberEvidence,
managed_native_boundaries: conflictingBoundaries,
});
expect(projected.ok).toBe(false);
if (projected.ok) throw new Error("conflicting MVIDs were accepted");
expect(JSON.stringify(projected.error)).toContain(
"conflicting known module MVIDs or token scopes",
);
});
it("rejects contradictory known module declaration fields", () => {
const { artifactEvidence, memberEvidence } = createManagedInteropEvidence();
const members = managedMemberInspectionSchema.parse(
parseEvidence(memberEvidence).normalized_result,
);
if (members.module === null)
throw new Error("Expected fixture module identity");
const conflictingMembers = createEvidence(
undefined,
MANAGED_STATIC_PROVIDER,
{
operation: "inspect_managed_members",
parameters: {},
result: {
...members,
module: {
...members.module,
generation: members.module.generation + 1,
},
},
rawResult: null,
limitations: members.limitations,
},
);
const projected = projectManagedApplicationGraphEvidence({
managed_artifact: artifactEvidence,
managed_members: conflictingMembers,
});
expect(projected.ok).toBe(false);
if (projected.ok)
throw new Error("conflicting module declaration was accepted");
expect(JSON.stringify(projected.error)).toContain(
"conflicting module generation values",
);
});
});
describe("managed application graph token scope", () => {
it("checks declared token artifact and MVID scopes without a subject digest", () => {
const { memberEvidence } = createManagedInteropEvidence();
const members = managedMemberInspectionSchema.parse(
parseEvidence(memberEvidence).normalized_result,
);
const wrongMvidValue = "ffffffff-ffff-ffff-ffff-ffffffffffff";
const wrongMvidEvidence = createEvidence(
undefined,
MANAGED_STATIC_PROVIDER,
{
operation: "inspect_managed_members",
parameters: {},
result: {
...members,
identity_scope: {
...members.identity_scope,
requires_mvid: wrongMvidValue,
},
},
rawResult: null,
limitations: members.limitations,
},
);
const wrongArtifactEvidence = createEvidence(
undefined,
MANAGED_STATIC_PROVIDER,
{
operation: "inspect_managed_members",
parameters: {},
result: {
...members,
identity_scope: {
...members.identity_scope,
requires_artifact_sha256: "b".repeat(64),
},
},
rawResult: null,
limitations: members.limitations,
},
);
const wrongMvidResult = projectManagedApplicationGraphEvidence({
managed_members: wrongMvidEvidence,
});
expect(wrongMvidResult.ok).toBe(false);
if (wrongMvidResult.ok)
throw new Error("mismatched token MVID was accepted");
expect(JSON.stringify(wrongMvidResult.error)).toContain("token scope MVID");
const wrongArtifact = projectManagedApplicationGraphEvidence({
managed_members: wrongArtifactEvidence,
});
expect(wrongArtifact.ok).toBe(false);
if (wrongArtifact.ok)
throw new Error("mismatched token artifact digest was accepted");
expect(JSON.stringify(wrongArtifact.error)).toContain(
"token scope SHA-256",
);
});
});
describe("unknown managed application graph token scope", () => {
it("keeps absent MVID scope unknown and marks cross-source token joins partial", () => {
const { memberEvidence, boundaryEvidence } = createManagedInteropEvidence();
const members = managedMemberInspectionSchema.parse(
parseEvidence(memberEvidence).normalized_result,
);
const boundaries = managedNativeBoundaryInspectionSchema.parse(
parseEvidence(boundaryEvidence).normalized_result,
);
const unknownMembers = createEvidence(undefined, MANAGED_STATIC_PROVIDER, {
operation: "inspect_managed_members",
parameters: {},
result: {
...members,
module:
members.module === null
? null
: {
...members.module,
mvid: null,
enc_id: null,
enc_base_id: null,
},
identity_scope: { ...members.identity_scope, requires_mvid: null },
},
rawResult: null,
limitations: members.limitations,
});
const projected = projectManagedApplicationGraphEvidence({
managed_members: unknownMembers,
managed_native_boundaries: boundaryEvidence,
});
if (!projected.ok) throw projected.error;
const result = managedApplicationGraphResultSchema.parse(
parseEvidence(projected.value).normalized_result,
);
const graph = parseJavaScriptApplicationGraph(result.graph);
expect(result.summary.modules).toBe(1);
expect(result.coverage.status).toBe("partial");
expect(result.limitations).toContain(
"Managed boundary tokens were not linked to member nodes because matching module MVID scope was not established.",
);
const moduleObservation = graph.nodes.find(
({ kind }) => kind === "managed-module",
)?.observations[0];
expect(moduleObservation?.properties.mvid).toBe(boundaries.module?.mvid);
expect(moduleObservation?.evidence.extractor.operation).toBe(
"inspect_managed_native_boundaries",
);
const method = graph.nodes.find(
({ kind, observations }) =>
kind === "managed-method" &&
observations[0]?.label === "Fixture.Program.Main",
);
expect(method).toBeDefined();
const importEdge = graph.edges.find(
({ relation, target_node_id }) =>
relation === "imports" &&
graph.nodes.find(({ node_id }) => node_id === target_node_id)?.kind ===
"managed-pinvoke-import",
);
expect(importEdge).toBeDefined();
expect(
graph.nodes.find(({ node_id }) => node_id === importEdge?.source_node_id)
?.kind,
).toBe("artifact");
});
});
describe("managed application graph coverage", () => {
it("preserves partial parser coverage in graph and per-fact coverage", () => {
const bytes = buildManagedPeFixture();
@@ -186,6 +186,40 @@ it("matches renderer, frame, script bytes, and worker without claiming execution
);
});
it("keeps static load states unknown when one scoped capture omits scripts", async () => {
const fixture = await applicationFixture();
const staticEvidence = await analyzeFixture(fixture);
const result = reconcileInput({
static_layers: [{ role: "application", analysis: staticEvidence }],
runtime_observations: [
electronRuntimeEvidence(fixture, SOURCE, {
includeWorker: false,
targetId: "target-complete",
}),
electronRuntimeEvidence(fixture, SOURCE, {
includeWorker: false,
scriptsUnavailable: true,
targetId: "target-incomplete",
}),
],
});
expect(
result.runtime_captures.map(
({ scripts_complete_within_scope }) => scripts_complete_within_scope,
),
).toEqual(expect.arrayContaining([false, true]));
expect(result.summary.static_not_observed).toBe(0);
expect(result.static_load_states).toEqual(
expect.arrayContaining([
expect.objectContaining({
status: "unknown",
reason: "static-or-runtime-coverage-incomplete",
}),
]),
);
});
it("reports a captured digest disagreement instead of accepting a path match", async () => {
const fixture = await applicationFixture();
const staticEvidence = await analyzeFixture(fixture);
@@ -316,7 +350,7 @@ it("imports an operator-provided cache layer through an explicit file mapping",
const application = await applicationFixture();
const cache = await createTestTempDirectory("rea-runtime-cache-static-");
const runtimeCache = await createTestTempDirectory("rea-runtime-cache-live-");
const cacheSource = "export const cachedFeature = 'fixture';\n";
const cacheSource = SOURCE;
await mkdir(join(cache, "mapped"));
await Promise.all([
writeFile(join(cache, "mapped", "chunk.js"), cacheSource),
@@ -373,6 +407,16 @@ it("imports an operator-provided cache layer through an explicit file mapping",
status: "unknown",
reason: "layer-outside-runtime-scope",
});
const sharedFile = result.graph.nodes.find(
({ observations }) =>
observations.some(({ properties }) => properties.path === "app.js") &&
observations.some(
({ properties }) => properties.path === "mapped/chunk.js",
),
);
expect(
sharedFile?.observations.map(({ properties }) => properties.path),
).toEqual(expect.arrayContaining(["app.js", "mapped/chunk.js"]));
});
const applicationFixture = async (): Promise<string> => {
@@ -410,6 +454,7 @@ const electronRuntimeEvidence = (
readonly targetId?: string;
readonly sourceIncluded?: boolean;
readonly workersUnavailable?: boolean;
readonly scriptsUnavailable?: boolean;
} = {},
) => {
const scriptFile = options.scriptFile ?? "app.js";
@@ -445,15 +490,7 @@ const electronRuntimeEvidence = (
ended_at: "2026-07-15T00:00:00.100Z",
observation_ms: 100,
},
completeness: options.workersUnavailable
? {
...completeCapture(),
status: "attach_limited" as const,
conditions: ["attach_limited" as const],
attach_limited_sections: ["workers" as const],
unavailable_sections: ["workers" as const],
}
: completeCapture(),
completeness: captureCompleteness(options),
frames: [
{
frame_id: "frame-main",
@@ -522,3 +559,21 @@ const completeCapture = () => ({
total: 0,
},
});
const captureCompleteness = (options: {
readonly workersUnavailable?: boolean;
readonly scriptsUnavailable?: boolean;
}) => {
const unavailableSections = [
...(options.scriptsUnavailable ? (["scripts"] as const) : []),
...(options.workersUnavailable ? (["workers"] as const) : []),
];
if (unavailableSections.length === 0) return completeCapture();
return {
...completeCapture(),
status: "attach_limited" as const,
conditions: ["attach_limited" as const],
attach_limited_sections: unavailableSections,
unavailable_sections: unavailableSections,
};
};
@@ -77,6 +77,29 @@ async function runnerFailurePredicate(): Promise<(item: unknown) => unknown> {
}
describe("scoped factual report", () => {
it("requires a validated target clarification and zero REA calls for the negative route", () => {
const clarification = {
...routingSuccess,
expectedFirstTool: null,
naturalUse: false,
factualCorrectness: "not_assessed" as const,
answerHeuristicsMet: false,
epistemicCuePresent: false,
targetClarificationPassed: true,
};
expect(agentEvaluationPassed(clarification)).toBe(true);
for (const change of [
{ naturalUse: true },
{ correctFirstTool: false },
{ targetClarificationPassed: false },
{ exitCode: 1 },
{ inputTokens: 0 },
])
expect(agentEvaluationPassed({ ...clarification, ...change })).toBe(
false,
);
});
it("accepts correct structured facts without superficial prose cues", () => {
expect(
agentEvaluationPassed({
@@ -101,6 +101,35 @@ describe("Codex agent release evaluation", () => {
).toBe(1);
});
it("distinguishes session verification after a successful close from an unchanged retry", () => {
const call = (id: string, tool: string, status = "completed") => ({
type: "item.completed",
item: {
id,
type: "mcp_tool_call",
server: "rea",
tool,
arguments: {},
status,
},
});
for (const [status, repeats] of [
["completed", 0],
["failed", 1],
] as const) {
expect(
evaluateCodexEvents(
[
call("before", "binary_session"),
call("close", "close_binary", status),
call("after", "binary_session"),
],
"binary_session",
).repeatedCallCount,
).toBe(repeats);
}
});
it("counts identical arguments with reversed Unicode key insertion order", () => {
const call = (id: string, arguments_: Record<string, number>) => ({
type: "item.completed",
@@ -125,6 +154,119 @@ describe("Codex agent release evaluation", () => {
});
});
describe("Codex agent routing and error evaluation", () => {
it("preserves an unrecognized structured failure without inventing its code", () => {
const metrics = evaluateCodexEvents(
[
{
type: "item.completed",
item: {
type: "mcp_tool_call",
server: "rea",
tool: "close_binary",
arguments: {},
result: { structured_content: { error: "unrecognized failure" } },
},
},
],
"close_binary",
{ requiredToolSubsequence: ["close_binary"] },
);
expect(metrics.reaCalls[0]).toMatchObject({ error: true, errorCode: null });
expect(metrics.requiredToolSubsequenceMet).toBe(false);
});
it("requires no REA call when target selection is missing", () => {
const events = [
{
type: "item.completed",
item: { type: "agent_message", text: "Which app should I inspect?" },
},
];
expect(evaluateCodexEvents(events, null)).toMatchObject({
naturalUse: false,
correctFirstTool: true,
firstTool: null,
});
expect(
evaluateCodexEvents(
[
...events,
{
type: "item.completed",
item: {
type: "mcp_tool_call",
server: "rea",
tool: "analyze_javascript_application",
arguments: { input_path: "/nearby/test-fixture" },
},
},
],
null,
).correctFirstTool,
).toBe(false);
});
it("counts actual text-only REA errors and SDK-rejected schema inputs once per call", () => {
const source = {
kind: "retained-evidence",
evidence_id: `ev_${"a".repeat(64)}`,
};
const failed = (id: string, arguments_: unknown, text: string) => ({
type: "item.completed",
item: {
id,
type: "mcp_tool_call",
server: "rea",
tool: "inspect_analysis_view",
arguments: arguments_,
status: "failed",
error: null,
result: { content: [{ type: "text", text }], structured_content: null },
},
});
const metrics = evaluateCodexEvents(
[
failed(
"sdk",
{ source, view: { kind: "module", path: "main.js" } },
"Input validation error: Invalid arguments for tool inspect_analysis_view: view.kind: Invalid discriminator value.",
),
failed(
"ambiguous",
{
source,
view: {
kind: "item",
collection: "modules",
selector: { path: "main.js" },
},
},
JSON.stringify({
error: {
code: "invalid_request",
message:
"Multiple modules have this path; select one by node_id.",
},
}),
),
failed(
"incomplete-preview",
{ source, view: { kind: "summary" } },
'{"error":{"code":"invalid_request"',
),
],
"inspect_analysis_view",
);
expect(metrics.inputValidationFailureCount).toBe(2);
expect(metrics.reaCalls.map(({ errorCode }) => errorCode)).toEqual([
null,
"invalid_request",
null,
]);
});
});
describe("Codex agent completion evaluation", () => {
it("does not present matching answer terms as factual correctness or honesty", () => {
const evidenceId = `ev_${"a".repeat(64)}`;
+14 -2
View File
@@ -1,4 +1,11 @@
import { access, chmod, mkdir, rm, writeFile } from "node:fs/promises";
import {
access,
chmod,
mkdir,
readFile,
rm,
writeFile,
} from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { expect, onTestFinished } from "vitest";
@@ -27,10 +34,11 @@ export const createJadxProtocolFixture = async (
const javaHome = join(root, "jdk");
const javaBin = join(javaHome, "bin");
const java = join(javaBin, "java");
const javaProbeLog = join(root, "java-probes.log");
await mkdir(javaBin, { recursive: true });
await writeFile(
java,
`#!/usr/bin/env node\nif (process.argv[2] === "--list-modules") console.log("java.base@21.0.0\\njdk.compiler@21.0.0");\n`,
`#!/usr/bin/env node\nif (process.argv[2] === "--list-modules") { require("node:fs").appendFileSync(${JSON.stringify(javaProbeLog)}, "probe\\n"); console.log("java.base@21.0.0\\njdk.compiler@21.0.0"); }\n`,
);
await chmod(java, 0o755);
await writeOrderedZip(apk, ["AndroidManifest.xml", "classes.dex"]);
@@ -115,6 +123,10 @@ export const createJadxProtocolFixture = async (
jar,
environment,
launches,
javaProbeCount: async () => {
const contents = await readFile(javaProbeLog, "utf8");
return contents.split("\n").filter(Boolean).length;
},
};
};
+1
View File
@@ -143,6 +143,7 @@ export const startFakeCdpBrowser = async (
browserWebSocketUrl: `ws://127.0.0.1:${String(port)}/devtools/browser/fake`,
allowedOrigin: endpoint,
commands,
activeConnectionCount: () => sockets.size,
emitRawMessage(message) {
for (const socket of sockets) socket.send(message);
},
+2
View File
@@ -11,6 +11,8 @@ export interface FakeCdpBrowser {
readonly browserWebSocketUrl: string;
readonly allowedOrigin: string;
readonly commands: readonly FakeCdpCommand[];
/** Actual WebSocket connections still held by the wire fixture. */
activeConnectionCount(): number;
/** Deliver actual malformed wire data without bypassing the production transport parser. */
emitRawMessage(message: string): void;
emitEvent(event: {
+10
View File
@@ -153,6 +153,16 @@ const handleRequest = (socket, server, request, state) => {
const handlePing = (socket, request, state) => {
state.pings.value += 1;
if (state.mode === "diagnostic_output" && state.pings.value === 1) {
const retainedTokenPrefixBytes = Math.floor(state.token.length / 2);
const preservedMarker = "source=/tmp/local-evidence.bin?cursor=keep&";
const fillLength = 8 * 1024 * 1024 - retainedTokenPrefixBytes;
const fill = "x".repeat(fillLength - Buffer.byteLength(preservedMarker));
process.stderr.write(`${fill}${preservedMarker}`);
setImmediate(() => {
process.stderr.write(state.token);
});
}
if (state.mode === "malformed") {
socket.write("{invalid\n");
return;
+23 -3
View File
@@ -1,7 +1,13 @@
import { createServer } from "node:net";
const [socketPath, token, runId, shutdownMode = "acknowledge"] =
process.argv.slice(2);
const [
socketPath,
token,
runId,
shutdownMode = "acknowledge",
diagnosticMode = "quiet",
] = process.argv.slice(2);
let diagnosticOutputEmitted = false;
const heldReplies = new Map();
if (process.send !== undefined)
process.on("message", (message) => {
@@ -16,6 +22,18 @@ const shutdownResult = () => ({
document_closed: shutdownMode !== "unconfirmed",
...(shutdownMode === "cleanup-required" ? { cleanup_required: true } : {}),
});
const emitDiagnosticOutput = () => {
if (diagnosticMode === "quiet" || diagnosticOutputEmitted) return;
diagnosticOutputEmitted = true;
const retainedTokenPrefixBytes = Math.floor(token.length / 2);
const preservedMarker = "source=/tmp/local-evidence.bin?cursor=keep&";
const fillLength = 8 * 1024 * 1024 - retainedTokenPrefixBytes;
const fill = "x".repeat(fillLength - Buffer.byteLength(preservedMarker));
process.stderr.write(`${fill}${preservedMarker}`);
setImmediate(() => {
process.stderr.write(token);
});
};
const capabilityUnavailableResult = (id) => ({
id,
error: {
@@ -182,6 +200,7 @@ const server = createServer((socket) => {
if (request.token !== token) {
send({ id: request.id, error: { code: -32001, message: "bad token" } });
} else if (request.method === "health") {
emitDiagnosticOutput();
send(
{
id: request.id,
@@ -249,5 +268,6 @@ const closeServer = () =>
if (process.connected) process.disconnect();
});
server.listen(socketPath);
if (diagnosticMode === "noisy_no_socket") emitDiagnosticOutput();
else server.listen(socketPath);
process.on("SIGTERM", closeServer);
+13 -2
View File
@@ -1,5 +1,5 @@
import { createHash } from "node:crypto";
import { mkdir, readFile, writeFile, symlink } from "node:fs/promises";
import { chmod, mkdir, readFile, writeFile, symlink } from "node:fs/promises";
import { join } from "node:path";
const args = process.argv.slice(2);
const mode = process.env.REA_FIRMWARE_FIXTURE_MODE;
@@ -125,8 +125,19 @@ if (args.includes("--version")) {
];
await writeFile(
reportPath,
mode === "malformed" ? "[" : JSON.stringify(records),
mode === "malformed" || mode === "workspace-cleanup-failure-malformed"
? "["
: JSON.stringify(records),
);
if (mode === "dependency") process.exitCode = 1;
if (
mode === "workspace-cleanup-failure" ||
mode === "workspace-cleanup-failure-malformed"
) {
const blocked = join(process.cwd(), "cleanup-blocked");
await mkdir(blocked);
await writeFile(join(blocked, "retained"), "owned workspace bytes");
await chmod(blocked, 0);
}
}
}
+22 -8
View File
@@ -5,6 +5,7 @@ import { expect, onTestFinished } from "vitest";
import { createFirmwareAnalysisProvider } from "../../../src/composition/firmware.js";
import { FirmwareAnalysisService } from "../../../src/application/firmware/FirmwareAnalysisService.js";
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js";
import { createTestTempDirectory } from "../temporaryDirectory.js";
/** Exercise real subprocess ownership with synthetic pinned producer representations. */
@@ -18,6 +19,7 @@ export const firmwareFixture = async (mode = "normal", banner?: string) => {
pid: number | undefined;
args: readonly string[];
}[] = [];
let cleanupUnverified = mode === "cleanup-failure";
const provider = createFirmwareAnalysisProvider(
{
...process.env,
@@ -54,21 +56,29 @@ export const firmwareFixture = async (mode = "normal", banner?: string) => {
args: options.arguments,
});
if (mode === "cleanup-failure") {
onTestFinished(async () => {
if (options.cwd !== undefined)
await rm(options.cwd, { recursive: true, force: true });
});
return {
...spawned,
cleanup: async () => ({
cleaned: false,
reason: "injected ownership failure",
}),
cleanup: () =>
cleanupUnverified
? Promise.resolve({
cleaned: false,
reason: "injected ownership failure",
})
: cleanupOwnedProcessGroup(spawned.ownership),
};
}
return spawned;
},
);
const close = async () => {
if (provider.close === undefined)
throw new Error("Expected firmware provider cleanup capability");
await provider.close();
};
onTestFinished(async () => {
cleanupUnverified = false;
await close();
});
return {
provider,
service: new FirmwareAnalysisService(provider),
@@ -76,6 +86,10 @@ export const firmwareFixture = async (mode = "normal", banner?: string) => {
output: join(root, "output"),
root,
launches,
close,
restoreCleanup: () => {
cleanupUnverified = false;
},
};
};