Merge remote-tracking branch 'origin/main' into HEAD

This commit is contained in:
Kaoru0822
2026-10-14 00:31:27 +00:00
559 changed files with 102122 additions and 35266 deletions
@@ -0,0 +1,98 @@
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import { applicationVersionComparisonResultSchema } from "../../../src/domain/javascript/javascriptApplicationVersionComparisonSchemas.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
cliTest(
"pairs repeated factory bodies by identity when application versions retain a shared bundle",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-version-matching-");
const factoryCount = 32;
const factories = Array.from(
{ length: factoryCount },
(_, index) => `${index}: function() {}`,
).join(",");
const bundle = `globalThis.webpackChunkApp.push([[1], {${factories}}]);`;
const versions = await Promise.all(
[1, 2].map(async (version) => {
const application = join(root, String(version));
await mkdir(application);
await writeFile(
join(application, "package.json"),
JSON.stringify({ name: "shared-bundle", version: `${version}.0.0` }),
);
await writeFile(join(application, "chunk.js"), bundle);
const response = await cli.run({
arguments: ["analyze-javascript-application", application, "--json"],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(response.exitCode, response.stderr).toBe(0);
return parseEvidence(response.json);
}),
);
const [left, right] = versions;
if (left === undefined || right === undefined)
throw new Error("Missing application version Evidence");
const analyses = versions.map(({ normalized_result }) =>
javascriptApplicationAnalysisResultSchema.parse(normalized_result),
);
const factoryNodes = analyses.map(({ graph }) => {
expect(graph.coverage.status).toBe("complete");
const nodes = graph.nodes.filter(
({ kind, observations }) =>
kind === "javascript-module" &&
observations.some(
({ properties }) => properties.module_key !== undefined,
),
);
expect(nodes).toHaveLength(factoryCount);
const sourceDigests = nodes.flatMap(({ observations }) =>
observations.map(({ properties }) => properties.source_sha256),
);
expect(sourceDigests.every((digest) => typeof digest === "string")).toBe(
true,
);
expect(new Set(sourceDigests).size).toBe(1);
return nodes;
});
const inputPath = join(root, "comparison.json");
await writeFile(inputPath, JSON.stringify({ left, right }));
const response = await cli.run({
arguments: ["compare-application-versions", inputPath, "--json"],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(response.exitCode, response.stderr).toBe(0);
const result = applicationVersionComparisonResultSchema.parse(
parseEvidence(response.json).normalized_result,
);
expect(result.left.root_artifact_sha256).not.toBe(
result.right.root_artifact_sha256,
);
expect(result.matching.ambiguous).toBe(0);
expect(result.coverage.status).toBe("complete-within-inputs");
expect(factoryNodes[0]?.map(({ node_id }) => node_id)).toEqual(
factoryNodes[1]?.map(({ node_id }) => node_id),
);
for (const node of factoryNodes[0] ?? []) {
expect(
result.items.find(({ left_node_id }) => left_node_id === node.node_id),
).toMatchObject({
status: "unchanged",
right_node_id: node.node_id,
match: {
status: "matched",
basis: "exact-node-identity",
candidate_left_node_ids: [],
candidate_right_node_ids: [],
},
});
}
},
);
@@ -0,0 +1,432 @@
import { chmod, mkdir, writeFile } from "node:fs/promises";
import { createServer } from "node:net";
import { join } from "node:path";
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { expect } from "vitest";
import {
artifactInventoryResultSchema,
type ArtifactInventoryResult,
} from "../../../src/domain/artifactGraph.js";
import { artifactInspectionResultSchema } from "../../../src/domain/artifactInspection.js";
import {
createEvidence,
parseEvidence,
type Evidence,
} from "../../../src/domain/evidence.js";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest, type TestCli } from "../../support/cli/cliFixture.js";
const plist = (message: string) =>
`<?xml version="1.0" encoding="UTF-8"?>\n<plist version="1.0"><dict><key>message</key><string>${message}</string></dict></plist>\n`;
const inventoryEvidence = (input: unknown): Evidence => {
const inspection = parseEvidence(input);
const inventory = artifactInspectionResultSchema
.parse(inspection.normalized_result)
.substeps.find(
({ evidence }) => evidence.operation === "inventory_artifact",
)?.evidence;
if (inventory === undefined) throw new Error("Expected inventory Evidence");
return parseEvidence(inventory);
};
const inspectPair = async (
cli: TestCli,
leftPath: string,
rightPath: string,
) => {
const result = await cli.run({
arguments: ["inspect-artifact", leftPath, "--json"],
});
expect(result.exitCode, `${result.stderr}\n${result.stdout}`).toBe(0);
const left = inventoryEvidence(result.json);
const { call } = await connectLocalToolsMcp();
const opened = await call("open_binary", { path: rightPath });
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
const inspected = await call("inspect_artifact", {});
expect(inspected.isError, JSON.stringify(inspected)).not.toBe(true);
return { left, right: inventoryEvidence(inspected.structuredContent), call };
};
const assertCoverageControls = async ({
left,
right,
inventory,
compare,
}: {
left: Evidence;
right: Evidence;
inventory: ArtifactInventoryResult;
compare: (left: Evidence, right: Evidence) => Promise<Evidence>;
}) => {
// Authenticated derived controls isolate missing members and genuine coverage
// gaps; they do not claim that the complete plist producer omitted children.
const derive = (result: unknown) =>
createEvidence(
{
path: right.subject?.local_path ?? "",
sha256: inventory.manifest.root_sha256,
format: "plist",
},
right.provider,
{
operation: "inventory_artifact",
parameters: {},
result: jsonValueSchema.parse(result),
confidence: "derived",
authority: "shipped-artifact",
},
);
const partial = await compare(left, derive({ ...inventory, nodes: [] }));
expect(partial.normalized_result).toMatchObject({
status: "truncated",
summary: { unchanged: 0, unknown: 1 },
});
const reworded = await compare(
left,
derive({
...inventory,
coverage: { scope: "root", status: "complete" },
limitations: ["Root bytes observed; no container children are modeled."],
}),
);
expect(reworded.normalized_result).toMatchObject({
status: "unchanged",
summary: { unchanged: 1, unknown: 0 },
limitations: expect.arrayContaining([
"Right: Root bytes observed; no container children are modeled.",
]),
});
const gap = await compare(
left,
derive({
...inventory,
coverage: { scope: "root", status: "unknown" },
coverage_status: "partial",
limitations: [],
}),
);
expect(gap.normalized_result).toMatchObject({
status: "unknown",
summary: { unchanged: 0, unknown: 1 },
});
const differentScope = await compare(
left,
derive({
...inventory,
coverage: { scope: "container-entries", status: "complete" },
}),
);
expect(differentScope.normalized_result).toMatchObject({
status: "unknown",
limitations: expect.arrayContaining(["Artifact inventory scopes differ."]),
});
const { coverage, coverage_status: _coverageStatus, ...legacy } = inventory;
expect(coverage).toBeDefined();
const retained = await compare(left, derive(legacy));
expect(retained.normalized_result).toMatchObject({
status: "unchanged",
summary: { unchanged: 1, unknown: 0 },
});
for (const limitation of [
"Child inventory is unavailable.",
"Missing child observations; 1 integrity contradiction(s) were recorded.",
]) {
const unfamiliarLegacy = await compare(
left,
derive({ ...legacy, limitations: [limitation] }),
);
expect(unfamiliarLegacy.normalized_result).toMatchObject({
status: "unknown",
summary: { unchanged: 0, unknown: 1 },
});
}
};
cliTest(
"compares fully observed roots without inventing coverage gaps through CLI and MCP",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-artifact-coverage-");
const leftPath = join(root, "left.plist");
const rightPath = join(root, "right.plist");
await Promise.all([
writeFile(leftPath, plist("hello")),
writeFile(rightPath, plist("hello")),
]);
const leftResult = await cli.run({
arguments: ["inspect-artifact", leftPath, "--json"],
});
expect(leftResult.exitCode, leftResult.stderr).toBe(0);
const left = inventoryEvidence(leftResult.json);
const { call } = await connectLocalToolsMcp();
const inspect = async (path: string) => {
const opened = await call("open_binary", { path });
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
const result = await call("inspect_artifact", {});
expect(result.isError, JSON.stringify(result)).not.toBe(true);
return inventoryEvidence(result.structuredContent);
};
const compare = async (left: Evidence, right: Evidence) => {
const result = await call("compare_artifacts", { left, right });
expect(result.isError, JSON.stringify(result)).not.toBe(true);
return parseEvidence(result.structuredContent);
};
const right = await inspect(rightPath);
const inventory = artifactInventoryResultSchema.parse(
right.normalized_result,
);
expect(inventory.coverage).toEqual({ scope: "root", status: "complete" });
expect(inventory.manifest).toMatchObject({
root_format: "plist",
node_count: 1,
occurrence_count: 1,
edge_count: 0,
});
expect(inventory.limitations).toEqual([
"Artifact has no child container entries.",
]);
const equal = await compare(left, right);
expect(equal.normalized_result).toMatchObject({
status: "unchanged",
summary: { unchanged: 1, unknown: 0 },
changes: [],
limitations: [
"Left: Artifact has no child container entries.",
"Right: Artifact has no child container entries.",
],
});
const behavior = await call("find_changed_behavior", {
comparisons: [equal],
});
expect(behavior.isError, JSON.stringify(behavior)).not.toBe(true);
expect(behavior.structuredContent).toMatchObject({
normalized_result: {
behavior_status: "unknown",
summary: { unresolved: 0 },
findings: { items: [] },
limitations: expect.arrayContaining([
"No process comparison Evidence was supplied.",
]),
},
});
const unknowns = await call("list_unknowns", {
domain: "artifact-comparison",
});
expect(unknowns.isError, JSON.stringify(unknowns)).not.toBe(true);
expect(unknowns.structuredContent).toMatchObject({
result: { items: [], total: 0 },
});
await writeFile(rightPath, plist("world"));
const changed = await compare(left, await inspect(rightPath));
expect(changed.normalized_result).toMatchObject({
status: "changed",
summary: { unchanged: 0, changed: 1, unknown: 0 },
changes: [
expect.objectContaining({ logical_path: ".", dimensions: ["content"] }),
],
});
const zipPaths = [join(root, "left.zip"), join(root, "right.zip")] as const;
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("same.txt", new TextReader("same"));
const bytes = await writer.close();
await Promise.all(zipPaths.map((path) => writeFile(path, bytes)));
const zip = await compare(
await inspect(zipPaths[0]),
await inspect(zipPaths[1]),
);
expect(zip.normalized_result).toMatchObject({
status: "unchanged",
summary: { unchanged: 2, unknown: 0 },
changes: [],
});
await assertCoverageControls({ left, right, inventory, compare });
},
30_000,
);
cliTest.skipIf(process.platform === "win32")(
"preserves executable metadata changes for fully observed plist roots",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-artifact-mode-");
const leftPath = join(root, "left.plist");
const rightPath = join(root, "right.plist");
await Promise.all([
writeFile(leftPath, plist("hello")),
writeFile(rightPath, plist("hello")),
]);
await Promise.all([chmod(leftPath, 0o644), chmod(rightPath, 0o755)]);
const result = await cli.run({
arguments: ["inspect-artifact", leftPath, "--json"],
});
expect(result.exitCode, result.stderr).toBe(0);
const left = inventoryEvidence(result.json);
const { call } = await connectLocalToolsMcp();
const opened = await call("open_binary", { path: rightPath });
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
const inspected = await call("inspect_artifact", {});
expect(inspected.isError, JSON.stringify(inspected)).not.toBe(true);
const right = inventoryEvidence(inspected.structuredContent);
expect(right.subject?.digest.sha256).toBe(left.subject?.digest.sha256);
const comparison = await call("compare_artifacts", { left, right });
expect(comparison.isError, JSON.stringify(comparison)).not.toBe(true);
expect(
parseEvidence(comparison.structuredContent).normalized_result,
).toMatchObject({
status: "changed",
summary: { unchanged: 0, changed: 1, unknown: 0 },
changes: [
expect.objectContaining({
logical_path: ".",
dimensions: ["executable"],
}),
],
});
},
30_000,
);
cliTest.skipIf(process.platform === "win32")(
"retains traversal uncertainty when a directory omits special filesystem entries",
async ({ cli, processes }) => {
const root = await createTestTempDirectory("rea-gap-");
const leftPath = join(root, "l.app"),
rightPath = join(root, "r.app");
await Promise.all([mkdir(leftPath), mkdir(rightPath)]);
await Promise.all([
writeFile(join(leftPath, "same.txt"), "same"),
writeFile(join(rightPath, "same.txt"), "same"),
]);
await Promise.all(
[leftPath, rightPath].flatMap((path) => [
writeFile(
join(path, "Info.plist"),
"<plist><dict><key>CFBundleExecutable</key><string>main.js</string></dict></plist>",
),
writeFile(join(path, "main.js"), "export const value = 1;"),
]),
);
const fifo = await processes.run("mkfifo", [join(leftPath, "p")]);
expect(fifo.exitCode, fifo.stderr).toBe(0);
const socket = createServer();
await new Promise<void>((resolve, reject) => {
socket.once("error", reject);
socket.listen(join(leftPath, "s"), resolve);
});
try {
const { left, right, call } = await inspectPair(cli, leftPath, rightPath);
const inventory = artifactInventoryResultSchema.parse(
left.normalized_result,
);
expect(inventory.coverage).toEqual({
scope: "container-entries",
status: "unknown",
});
expect(inventory.limitations).toEqual(
expect.arrayContaining([
'Artifact traversal omitted fifo at "p".',
'Artifact traversal omitted socket at "s".',
]),
);
const compared = await call("compare_artifacts", { left, right });
expect(compared.isError, JSON.stringify(compared)).not.toBe(true);
expect(
parseEvidence(compared.structuredContent).normalized_result,
).toMatchObject({ status: "unknown", summary: { unchanged: 0 } });
} finally {
await new Promise<void>((resolve, reject) =>
socket.close((cause) =>
cause === undefined ? resolve() : reject(cause),
),
);
}
},
30_000,
);
cliTest(
"compares fully traversed case-distinct ZIP entries while retaining materialization limits",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-case-coverage-");
const leftPath = join(root, "left.zip"),
rightPath = join(root, "right.zip");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("A", new TextReader("upper"));
await writer.add("a", new TextReader("lower"));
const bytes = await writer.close();
await Promise.all([
writeFile(leftPath, bytes),
writeFile(rightPath, bytes),
]);
const { left, right, call } = await inspectPair(cli, leftPath, rightPath);
const inventory = artifactInventoryResultSchema.parse(
left.normalized_result,
);
expect(inventory.coverage).toEqual({
scope: "container-entries",
status: "complete",
});
expect(
inventory.occurrences.map(({ logical_path }) => logical_path).sort(),
).toEqual([".", "A", "a"]);
const compared = await call("compare_artifacts", { left, right });
expect(compared.isError, JSON.stringify(compared)).not.toBe(true);
expect(
parseEvidence(compared.structuredContent).normalized_result,
).toMatchObject({
status: "unchanged",
summary: { unchanged: 3, unknown: 0 },
changes: [],
limitations: expect.arrayContaining([
expect.stringContaining("case-insensitive destination"),
]),
});
},
30_000,
);
cliTest(
"keeps unreadable encrypted ZIP content unknown with complete traversal",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-encrypted-comparison-");
const leftPath = join(root, "left.zip");
const rightPath = join(root, "right.zip");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("secret.txt", new TextReader("secret bytes"), {
password: "fixture-password",
});
const bytes = await writer.close();
await Promise.all([
writeFile(leftPath, bytes),
writeFile(rightPath, bytes),
]);
const { left, right, call } = await inspectPair(cli, leftPath, rightPath);
for (const evidence of [left, right])
expect(
artifactInventoryResultSchema.parse(evidence.normalized_result),
).toMatchObject({
coverage: { scope: "container-entries", status: "complete" },
occurrences: expect.arrayContaining([
expect.objectContaining({
logical_path: "secret.txt",
hash_status: "unavailable",
encrypted: true,
}),
]),
});
const compared = await call("compare_artifacts", { left, right });
expect(compared.isError, JSON.stringify(compared)).not.toBe(true);
const result = parseEvidence(compared.structuredContent).normalized_result;
expect(result).toMatchObject({
status: "unknown",
summary: { unknown: expect.any(Number) },
});
expect(result).toHaveProperty("summary.unknown", 1);
},
);
@@ -1,4 +1,4 @@
import { writeFile } from "node:fs/promises";
import { chmod, mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
@@ -68,6 +68,130 @@ cliTest(
},
);
const isWindows = process.platform === "win32";
const errorBody = (result: {
readonly content: readonly { readonly type: string }[];
}) => {
const content = result.content.find((item) => item.type === "text");
if (content?.type !== "text" || !("text" in content))
throw new Error("Missing error response");
return JSON.parse(String(content.text));
};
const createElectronApplication = async (root: string) => {
const application = join(root, "app");
await mkdir(application);
await writeFile(
join(application, "package.json"),
JSON.stringify({ name: "fixture", main: "main.js" }),
);
await writeFile(join(application, "main.js"), "");
return application;
};
cliTest.skipIf(isWindows)(
"rejects a non-executable Electron executable_path before launch through CLI and MCP",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-electron-not-executable-");
const application = await createElectronApplication(root);
const executable = join(root, "not-an-executable.txt");
await writeFile(executable, "plain text");
await chmod(executable, 0o644);
const request = {
executable_path: executable,
application_path: application,
actions: [],
};
const requestPath = join(root, "input.json");
await writeFile(requestPath, JSON.stringify(request));
const response = await cli.run({
arguments: ["capture-electron-scenario", requestPath, "--format", "json"],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(response.exitCode).toBe(1);
expect(response.json).toMatchObject({
code: "invalid_request",
details: {
issues: [{ path: ["executable_path"], reason: "invalid_value" }],
},
});
const { call } = await connectLocalToolsMcp();
const result = await call("capture_electron_scenario", request);
expect(result.isError).toBe(true);
expect(errorBody(result)).toMatchObject({
error: {
code: "invalid_request",
details: {
issues: [{ path: ["executable_path"], reason: "invalid_value" }],
},
},
});
const session = await call("binary_session", {});
expect(session.isError, JSON.stringify(session)).not.toBe(true);
},
);
cliTest.skipIf(isWindows)(
"returns a typed failure when an executable exits before Electron starts and keeps the MCP server and its Evidence",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-electron-early-exit-");
const application = await createElectronApplication(root);
const executable = join(root, "exits-immediately");
await writeFile(executable, "#!/bin/sh\nexit 0\n");
await chmod(executable, 0o755);
const request = {
executable_path: executable,
application_path: application,
actions: [],
};
const requestPath = join(root, "input.json");
await writeFile(requestPath, JSON.stringify(request));
const response = await cli.run({
arguments: ["capture-electron-scenario", requestPath, "--format", "json"],
environment: { REA_LOG_LEVEL: "silent" },
});
expect(response.exitCode).toBe(1);
expect(response.json).toMatchObject({
code: "execution_failure",
details: { operation: "capture_electron_scenario" },
});
expect(response.stdout).toContain("Process failed to launch");
const { call } = await connectLocalToolsMcp();
const analysis = await call("analyze_javascript_application", {
input_path: application,
});
expect(analysis.isError, JSON.stringify(analysis)).not.toBe(true);
const retained = async () => {
const bundle = await call("get_evidence_bundle", {});
expect(bundle.isError, JSON.stringify(bundle)).not.toBe(true);
const structured = bundle.structuredContent as {
result: { records: { evidence_id: string }[] };
};
return structured.result.records.map((record) => record.evidence_id);
};
const before = await retained();
expect(before).toHaveLength(1);
const result = await call("capture_electron_scenario", request);
expect(result.isError).toBe(true);
expect(errorBody(result)).toMatchObject({
error: {
code: "execution_failure",
details: { operation: "capture_electron_scenario" },
},
});
const session = await call("binary_session", {});
expect(session.isError, JSON.stringify(session)).not.toBe(true);
expect(await retained()).toEqual(before);
},
180_000,
);
cliTest(
"rejects a file URL path field without resolving an invented local path",
async ({ cli }) => {
@@ -0,0 +1,70 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js";
cliTest.for(["CLI", "stdio MCP"] as const)(
"preserves empty ESM import names on local re-export origins through %s",
async (surface, { cli, processes }) => {
const root = await createTestTempDirectory("rea-empty-import-name-");
const modulePath = join(root, "module.mjs");
const appPath = join(root, "app.mjs");
await writeFile(
modulePath,
'const value = 1; export { value as "", value as "a", value as "0" };',
);
await writeFile(
appPath,
[
'import { "" as empty, "a" as letter, "0" as zero } from "./module.mjs";',
"export { empty, letter, zero };",
'export { "" as direct } from "./module.mjs";',
].join("\n"),
);
for (const path of [modulePath, appPath]) {
const checked = await processes.run(process.execPath, ["--check", path]);
expect(checked.exitCode, checked.stderr).toBe(0);
}
const result = await analyzeJavaScriptDirectory(surface, cli, root);
expect(result.statistics.parse_failures).toBe(0);
const imports = result.graph.edges.filter(
({ relation, properties }) =>
relation === "imports" && properties.specifier === "./module.mjs",
);
for (const [name, local] of [
["", "empty"],
["a", "letter"],
["0", "zero"],
]) {
for (const kind of ["import", "export"]) {
expect(imports).toContainEqual(
expect.objectContaining({
properties: expect.objectContaining({
module_link_kind: kind,
...(kind === "export"
? { exported_name: local }
: { local_name: local }),
imported_name: name,
imported_path: [name],
resolved_path: "module.mjs",
resolution_status: "resolved",
}),
}),
);
}
}
expect(imports).toContainEqual(
expect.objectContaining({
properties: expect.objectContaining({
exported_name: "direct",
imported_name: "",
imported_path: [""],
resolution_status: "resolved",
}),
}),
);
},
);
@@ -0,0 +1,136 @@
import { expect } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js";
import { writeFixtureFiles } from "../../support/javascriptApplicationFixture.js";
cliTest.for(["CLI", "stdio MCP"] as const)(
"admits HTML script pathnames without treating URL suffixes as paths through %s",
async (surface, { cli }) => {
const root = await createTestTempDirectory("rea-html-url-suffixes-");
const cases = [
{
source: "query.html",
script: "./app.js?redirect=%2Ffoo",
resolved: "app.js",
},
{
source: "fragment.html",
script: "./app.js#route=%2Ffoo",
resolved: "app.js",
},
{
source: "suffix-bytes.html",
script: "./app.js?value=%2e%5c%00%ff\\tail",
resolved: "app.js",
},
{
source: "url-text.html",
script: " \n./a\tpp.js?redirect=%2\nfassets ",
resolved: "app.js",
},
{
source: "self.html",
script: "?redirect=%2Ffoo",
resolved: "self.html",
},
{
source: "self-fragment.html",
script: "#route=%5Cfoo",
resolved: "self-fragment.html",
},
{
source: "base.html",
base: "assets/?redirect=%2Froot",
script: "app.js#route=%2Ffoo",
resolved: "assets/app.js",
},
{
source: "base-self.html",
base: "assets/app.js?redirect=%5Croot",
script: "?redirect=%2Ffoo",
resolved: "assets/app.js",
},
{
source: "path-separator.html",
script: "./assets%2Fapp.js?valid=1",
resolved: null,
},
{ source: "path-dot.html", script: "./%2e/app.js#valid", resolved: null },
{
source: "path-backslash.html",
script: "./assets\\app.js?valid=1",
resolved: null,
},
{
source: "path-nul.html",
script: "./app%00.js?valid=1",
resolved: null,
},
{
source: "split-separator.html",
script: "./assets%2\nfapp.js?valid=1",
resolved: null,
},
{
source: "base-separator.html",
base: "assets%2F?valid=1",
script: "app.js?redirect=%2Ffoo",
resolved: null,
},
];
await writeFixtureFiles(root, {
...Object.fromEntries(
cases.map(({ source, base, script }) => [
source,
`${base === undefined ? "" : `<base href="${base}">`}<script src="${script}"></script>`,
]),
),
"app.js": "globalThis.rootApp = true;",
"assets/app.js": "globalThis.nestedApp = true;",
});
const result = await analyzeJavaScriptDirectory(surface, cli, root);
const loads = result.graph.edges.filter(
({ relation }) => relation === "loads",
);
const unresolved = result.graph.nodes
.flatMap(({ observations }) => observations)
.filter(
({ properties }) => properties.mechanism === "html-script-reference",
);
for (const { source, base, script, resolved } of cases) {
const load = loads.find(
({ evidence }) =>
evidence.location.available &&
evidence.location.value.kind === "source-range" &&
evidence.location.value.source === source,
);
if (resolved === null) {
expect(
unresolved.find(
({ properties }) => properties.script_path === script,
),
).toMatchObject({
properties: {
script_path: script,
resolved_path: null,
resolution_status: "rejected",
},
});
expect(load).toBeUndefined();
continue;
}
expect(load).toMatchObject({
properties: {
script_path: script,
base_href: base ?? null,
resolved_path: resolved,
resolution_context: "html-reference",
resolution_status: "resolved",
},
});
}
},
);
@@ -390,6 +390,9 @@ cliTest(
]),
),
"dynamic-base.mjs": 'new Worker(new URL("./worker.js", base));',
"empty-worker-url.mjs": 'new Worker("");',
"query-only-worker-url.mjs": 'new Worker("?cache=1");',
"fragment-only-worker-url.mjs": 'new Worker("#worker");',
"shadowed.mjs":
'function start(URL) { return new Worker(new URL("./worker.js", import.meta.url)); }',
"typed-shadowed.ts":
@@ -428,6 +431,9 @@ cliTest(
"directory-dot.mjs": "./worker.js/.",
"directory-parent.mjs": "./worker.js/child/..",
"empty-segment.mjs": "./child//../worker.js",
"empty-worker-url.mjs": "",
"query-only-worker-url.mjs": "?cache=1",
"fragment-only-worker-url.mjs": "#worker",
"package.mjs": "./package-worker",
"external.mjs": "https://example.test/worker.js",
};
@@ -0,0 +1,140 @@
import { join } from "node:path";
import { expect } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
import { analyzeJavaScriptDirectory } from "../../support/cli/javascriptApplication.js";
import { writeFixtureFiles } from "../../support/javascriptApplicationFixture.js";
cliTest.for(["CLI", "stdio MCP"] as const)(
"maps arguments to runtime TypeScript parameters through %s",
async (surface, { cli, processes }) => {
const root = await createTestTempDirectory("rea-this-parameters-");
await writeFixtureFiles(root, {
"bundle.mts": [
"self.webpackChunkApp.push([[1], { 7: function(this: void, module: unknown, exports: Record<string, unknown>, require: (id: number) => unknown) { exports.answer = 42; } }, function(this: void, require: (id: number) => unknown) { require(7); }]);",
].join("\n"),
"interop.cts": [
"function identity<T>(this: void, value: T) { return value; }",
'const electron = identity(require("electron"));',
'electron.ipcRenderer.send("typed-identity");',
].join("\n"),
"ipc-wrapper.cts": [
'const { ipcRenderer } = require("electron");',
"function send(this: void, channel: string) { ipcRenderer.send(channel); }",
"function sendRest(this: void, ...channels: string[]) { ipcRenderer.send(...channels); }",
'send("typed-channel");',
'sendRest("typed-rest");',
].join("\n"),
"entry.mts": [
"function first(this: void, value: number) { return value; }",
"function rest(this: void, ...values: number[]) { return values; }",
"function destructured({ left }: { left: number }, right: number) { return left + right; }",
"function mixed(this: void, head: number, ...tail: number[]) { return [head, ...tail]; }",
"const a = first(7);",
"const b = rest(1, 2);",
"const c = destructured({ left: 3 }, 4);",
"const d = mixed(9, 10, 11);",
"console.log(JSON.stringify([a, b, c, d, first.length, rest.length, mixed.length]));",
].join("\n"),
});
const control = await processes.run(
process.execPath,
[join(root, "entry.mts")],
{ timeoutMs: 15_000 },
);
expect(control.exitCode, control.stderr).toBe(0);
expect(JSON.parse(control.stdout)).toEqual([
7,
[1, 2],
7,
[9, 10, 11],
1,
0,
1,
]);
const analysis = await analyzeJavaScriptDirectory(surface, cli, root);
const graph = analysis.semantic_graph;
const parameters = graph.nodes.filter(
(node) =>
node.kind === "parameter" && node.identity.module_path === "entry.mts",
);
expect(parameters.map((node) => node.label).sort()).toEqual([
"head",
"left",
"right",
"tail",
"value",
"values",
]);
const parameterIds = new Set(parameters.map((node) => node.node_id));
const flows = graph.relations.filter(
(relation) =>
relation.relation === "argument-to-parameter" &&
parameterIds.has(relation.target_node_id),
);
expect(
flows
.map((flow) => {
const source = graph.nodes.find(
(node) => node.node_id === flow.source_node_id,
);
const target = parameters.find(
(node) => node.node_id === flow.target_node_id,
);
const owner = graph.nodes.find(
(node) => node.node_id === target?.function_node_id,
);
return [
source?.identity.source_range?.start.line,
source?.label,
owner?.label,
target?.label,
];
})
.sort(),
).toEqual([
[5, "argument 0", "first", "value"],
[6, "argument 0", "rest", "values"],
[6, "argument 1", "rest", "values"],
[7, "argument 0", "destructured", "left"],
[7, "argument 1", "destructured", "right"],
[8, "argument 0", "mixed", "head"],
[8, "argument 1", "mixed", "tail"],
[8, "argument 2", "mixed", "tail"],
]);
expect(
analysis.graph.nodes
.flatMap((node) => node.observations)
.some(
(observation) =>
Array.isArray(observation.properties.exports) &&
observation.properties.exports.includes("answer"),
),
).toBe(true);
const channels = analysis.graph.nodes
.filter((node) => node.kind === "ipc-channel")
.flatMap((node) =>
node.observations.map((observation) => observation.properties.channel),
);
expect(channels).toEqual(
expect.arrayContaining(["typed-channel", "typed-rest", "typed-identity"]),
);
for (const [name, arity] of [
["first", 1],
["rest", 1],
["destructured", 2],
["mixed", 2],
] as const) {
const callable = graph.nodes.find(
(node) => node.kind === "function" && node.label === name,
);
expect(callable, name).toBeDefined();
const fingerprint = graph.fingerprints.find(
(value) => value.function_node_id === callable?.node_id,
);
expect(fingerprint?.components.parameter_arity, name).toBe(arity);
}
},
);
@@ -50,7 +50,42 @@ test(
});
const mcp = new Client({ name: "hopper-literal-boundary", version: "1" });
let runtime: string | undefined;
onTestFinished(async () => {
try {
await mcp.connect(transport);
const call = (name: string, arguments_: Record<string, string> = {}) =>
mcp.callTool({ name, arguments: arguments_ });
expect((await call("open_binary", { path: target })).isError).not.toBe(
true,
);
const first = parseMcpToolError(await call("current_document"));
runtime = dirname(await readFile(receipt, "utf8"));
expect(first.error).toMatchObject({
code: "cleanup_incomplete",
details: {
diagnostics: {
primary_error: {
code: "provider_unavailable",
details: {
launcher: {
exit_code: 2,
stderr: {
text: expect.stringContaining(
"Not authorized to send Apple events",
),
},
},
},
},
},
},
});
await access(`${receipt}.document-created`);
await access(runtime);
expect(parseMcpToolError(await call("list_procedures"))).toEqual(first);
expect(parseMcpToolError(await call("close_binary")).error.code).toBe(
"cleanup_incomplete",
);
} finally {
// SDK close can return immediately after SIGKILL. Wait for its actual
// child-close event before recovering this process's retained lease.
let serverExited: Promise<void> | undefined;
@@ -77,41 +112,7 @@ test(
});
if (!acquired.acquired) throw new Error("Fixture lease remained live");
await acquired.lease.release();
});
await mcp.connect(transport);
const call = (name: string, arguments_: Record<string, string> = {}) =>
mcp.callTool({ name, arguments: arguments_ });
expect((await call("open_binary", { path: target })).isError).not.toBe(
true,
);
const first = parseMcpToolError(await call("current_document"));
runtime = dirname(await readFile(receipt, "utf8"));
expect(first.error).toMatchObject({
code: "cleanup_incomplete",
details: {
diagnostics: {
primary_error: {
code: "provider_unavailable",
details: {
launcher: {
exit_code: 2,
stderr: {
text: expect.stringContaining(
"Not authorized to send Apple events",
),
},
},
},
},
},
},
});
await access(`${receipt}.document-created`);
await access(runtime);
expect(parseMcpToolError(await call("list_procedures"))).toEqual(first);
expect(parseMcpToolError(await call("close_binary")).error.code).toBe(
"cleanup_incomplete",
);
}
}
},
);
@@ -201,13 +202,13 @@ test("recovers a denied Hopper launch through the same stdio MCP session and CLI
).toBe(false);
});
test(
"preserves a timed-out handoff and closes only a late bridge with matching run identity",
test.for(["handoff", "not-found"] as const)(
"preserves an unconfirmed %s handoff and closes only a late bridge with matching run identity",
{ timeout: 60_000 },
async ({ workspace }) => {
async (launchMode, { workspace }) => {
const target = workspace.path("target");
await copyFile("/usr/bin/true", target);
const mode = await workspace.write("mode", "handoff");
const mode = await workspace.write("mode", launchMode);
const receipt = workspace.path("bootstrap-path");
const transport = new StdioClientTransport({
command: process.execPath,
@@ -257,17 +258,35 @@ test(
details: {
diagnostics: {
primary_error: {
code: "provider_timeout",
details: { timeout_ms: 2000, launcher: { exit_code: 0 } },
code:
launchMode === "handoff"
? "provider_timeout"
: "provider_unavailable",
details:
launchMode === "handoff"
? { timeout_ms: 2000, launcher: { exit_code: 0 } }
: { stage: "launch", launcher: { exit_code: 3 } },
},
},
},
});
if (launchMode === "not-found") {
await access(`${receipt}.document-created`);
expect(initial.error.details).toMatchObject({
diagnostics: {
primary_error: { message: expect.stringContaining("Spotlight") },
},
});
}
expect(parseMcpToolError(await call("list_procedures"))).toEqual(initial);
const status = z.object({
result: z.object({
provider_operation_health: z.object({
state: z.literal("not_started"),
// A timeout observes incomplete startup; a failed launcher without
// confirmed ownership leaves the provider's state unknown.
state: z.literal(
launchMode === "handoff" ? "not_started" : "unknown",
),
stage: z.literal("launch"),
}),
}),
@@ -289,7 +308,7 @@ test(
const token = setting("REA_TOKEN");
const runId = setting("REA_RUN_ID");
runtime = dirname(socket);
const lateBridge = async (identity: string, credential = token) => {
const lateBridge = (identity: string, credential = token) => {
const child = spawn(
process.execPath,
[
@@ -301,14 +320,14 @@ test(
{ stdio: "ignore" },
);
children.push(child);
await vi.waitFor(() => access(socket));
return child;
};
for (const [identity, credential] of [
["different-run", token],
[runId, "different-token"],
] as const) {
const wrong = await lateBridge(identity, credential);
const wrong = lateBridge(identity, credential);
await vi.waitFor(() => access(socket));
expect(parseMcpToolError(await call("close_binary")).error.code).toBe(
"cleanup_incomplete",
);
@@ -319,7 +338,9 @@ test(
}
const closing = call("close_binary");
await delay(150);
const owned = await lateBridge(runId);
// A verified close may remove the socket before the fixture can poll it.
// The successful close and child exit establish the owned bridge outcome.
const owned = lateBridge(runId);
expect((await closing).isError).not.toBe(true);
await vi.waitFor(() => expect(owned.exitCode).toBe(0));
await expect(access(runtime)).rejects.toMatchObject({ code: "ENOENT" });
+71
View File
@@ -0,0 +1,71 @@
import { deflateSync } from "node:zlib";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { toolContract } from "../../src/contracts/toolContracts.js";
import { createRustImage } from "../fixtures/rust/image.js";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
import { cliTest } from "../support/cli/cliFixture.js";
cliTest(
"reports cargo-auditable packages through the public CLI",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-rust-cli-");
const path = join(root, "sample");
await writeFile(path, createRustImage({ format: "macho" }));
const result = await cli.run({
arguments: ["inspect-rust-binary", path, "--json"],
});
expect(result.exitCode, result.stderr).toBe(0);
const evidence = toolContract("inspect_rust_binary").outputSchema.parse(
result.json,
);
expect(evidence.normalized_result.auditable_metadata).toMatchObject({
section_name: "__DATA,.dep-v0",
format_version: 1,
root_package_index: 1,
packages: [
{ name: "itoa", version: "1.0.18" },
{ name: "sample", version: "0.1.0", root: true },
],
});
},
);
cliTest("returns null metadata when .dep-v0 is absent", async ({ cli }) => {
const root = await createTestTempDirectory("rea-rust-cli-missing-");
const path = join(root, "plain");
await writeFile(path, createRustImage({ format: "elf", omitSection: true }));
const result = await cli.run({
arguments: ["inspect-rust-binary", path, "--json"],
});
expect(result.exitCode, result.stderr).toBe(0);
const evidence = toolContract("inspect_rust_binary").outputSchema.parse(
result.json,
);
expect(evidence.normalized_result.auditable_metadata).toBeNull();
expect(evidence.normalized_result.limitations.join("\n")).toContain(
"does not mean the binary has no dependencies",
);
});
cliTest("reports malformed zlib as invalid input", async ({ cli }) => {
const root = await createTestTempDirectory("rea-rust-cli-zlib-");
const path = join(root, "broken.elf");
await writeFile(
path,
createRustImage({
format: "elf",
payload: deflateSync(Buffer.from("{")),
includeRustc: false,
}),
);
const result = await cli.run({
arguments: ["inspect-rust-binary", path, "--json"],
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "invalid_request",
details: { operation: "inspect_rust_binary" },
});
});
+40 -22
View File
@@ -279,26 +279,44 @@ it("preserves bounded instruction coverage separately from using-node coverage",
});
});
it("rejects malformed method descriptors at the Android adapter boundary", async () => {
const invalidSummary = {
...summary,
methods: summary.methods.map((method) => ({
...method,
dex_descriptor: "not-a-dex-descriptor",
})),
};
await expect(
analyzeJadxRequest(
{
json: () => Promise.resolve(invalidSummary),
text: () => Promise.reject(new Error("unexpected text call")),
it.each([
"not-a-dex-descriptor",
"(Lbad(name;)V",
"(Lbad)name;)V",
"()Lbad(name;",
"()Lbad)name;",
])(
"rejects malformed DEX prototype %s at the adapter boundary",
async (descriptor) => {
const invalidSummary = {
...summary,
methods: summary.methods.map((method) => ({
...method,
dex_descriptor: descriptor,
})),
};
await expect(
analyzeJadxRequest(
{
json: () => Promise.resolve(invalidSummary),
text: () => Promise.reject(new Error("unexpected text call")),
},
{
operation: "inspect_android_class",
input: { path: "/fixture.apk", class_name: "fixture.Target" },
},
{} as never,
engine,
),
).rejects.toMatchObject({
_tag: "AnalysisOutputError",
cause: {
issues: expect.arrayContaining([
expect.objectContaining({
path: ["methods", 0, "dex_descriptor"],
}),
]),
},
{
operation: "inspect_android_class",
input: { path: "/fixture.apk", class_name: "fixture.Target" },
},
{} as never,
engine,
),
).rejects.toThrow();
});
});
},
);
@@ -0,0 +1,355 @@
import { expect, it } from "vitest";
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js";
import type { WebPageInspection } from "../../../src/domain/browserObservationSchemas.js";
import { compareWebCaptures } from "../../../src/domain/webCaptureDiff.js";
import { compareWebCapturesInputSchema } from "../../../src/domain/webCaptureDiffSchemas.js";
import {
startFakeCdpBrowser,
type FakeOptions,
} from "../../fixtures/fakeCdpBrowser.js";
import { trackBrowser } from "./cdpBrowserProvider.support.js";
const inspect = async (options: FakeOptions, includeFingerprints = true) => {
const browser = await startFakeCdpBrowser(options);
trackBrowser(browser);
const input = inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
observation_ms: 0,
include_storage_keys: true,
include_storage_fingerprints: includeFingerprints,
});
const capture = async () => {
const result = await new CdpBrowserProvider().inspectPage(input);
if (!result.ok) throw result.error;
return result.value;
};
return { capture };
};
const compareStorage = (before: WebPageInspection, after: WebPageInspection) =>
compareWebCaptures(
compareWebCapturesInputSchema.parse({
before: { inspection: before },
after: { inspection: after },
}),
).dimensions.storage;
it.each([
["CacheStorage.requestCacheNames", {}],
["CacheStorage.requestCacheNames", { caches: null }],
["CacheStorage.requestCacheNames", { caches: [null] }],
[
"CacheStorage.requestCacheNames",
{ caches: [{ cacheName: "assets-v1", cacheId: "secret-id" }, null] },
],
["CacheStorage.requestCacheNames", { caches: [{ cacheName: "assets-v1" }] }],
["IndexedDB.requestDatabaseNames", { databaseNames: [null] }],
["DOMStorage.getDOMStorageItems", { entries: [null] }],
] as const)(
"preserves unknown inventory coverage from %s: %j",
async (method, reply) => {
let malformed = false;
const { capture } = await inspect({
commandResult: (command) =>
malformed && command.method === method ? reply : undefined,
});
const before = await capture();
malformed = true;
const after = await capture();
expect(after.storage.fingerprints_complete).toBe(false);
expect(after.completeness.unavailable_sections).toContain("storage_keys");
expect(after.completeness.excluded).toContainEqual({
section: "storage_keys",
reason: "invalid_protocol_value",
count: null,
});
expect(compareStorage(before, after)).toMatchObject({
status: "unknown",
total_changes: 0,
});
},
);
it("preserves unavailable storage-key coverage without requesting fingerprints", async () => {
const { capture } = await inspect(
{ unsupportedMethods: ["CacheStorage.requestCacheNames"] },
false,
);
const captured = await capture();
expect(captured.completeness.excluded).toContainEqual({
section: "storage_keys",
reason: "provider_unavailable",
count: null,
});
expect(captured.storage.local_storage_keys).toEqual(["public-key"]);
});
const validKey = { type: "string", value: "row-1" };
it.each(["unavailable", "malformed"] as const)(
"compares shared complete values with %s cache inventory",
async (inventory) => {
let entries: unknown[][] = [["shared-key", "before"]];
const { capture } = await inspect({
...(inventory === "unavailable"
? { unsupportedMethods: ["CacheStorage.requestCacheNames"] }
: {}),
commandResult: (command) => {
if (command.method === "CacheStorage.requestCacheNames")
return { caches: [null] };
if (command.method === "DOMStorage.getDOMStorageItems")
return { entries };
return undefined;
},
});
const before = await capture();
expect(before.completeness.unavailable_sections).toContain("storage_keys");
expect(before.storage.fingerprints_complete).toBe(false);
expect(compareStorage(before, await capture())).toMatchObject({
status: "unknown",
total_changes: 0,
});
entries = [["shared-key", "after"]];
const changed = await capture();
expect(changed.storage.usage_bytes).toBe(before.storage.usage_bytes);
expect(changed.storage.quota_bytes).toBe(before.storage.quota_bytes);
for (const [left, right] of [
[before, changed],
[changed, before],
] as const)
expect(compareStorage(left, right)).toMatchObject({
status: "changed",
total_changes: 2,
changes: [
expect.objectContaining({ change: "modified" }),
expect.objectContaining({ change: "modified" }),
],
});
const incompleteValues = structuredClone(changed);
for (const fingerprint of incompleteValues.storage.content_fingerprints)
if (["local_storage", "session_storage"].includes(fingerprint.scope))
fingerprint.complete = false;
expect(compareStorage(before, incompleteValues)).toMatchObject({
status: "unknown",
total_changes: 0,
});
// Missing or invalid peer values establish neither removal nor addition.
for (const partial of [[], [["shared-key", null]]]) {
entries = partial;
const incomplete = await capture();
for (const [left, right] of [
[before, incomplete],
[incomplete, before],
] as const)
expect(compareStorage(left, right)).toMatchObject({
status: "unknown",
total_changes: 0,
changes: [],
});
}
},
);
it.each(["key", "primaryKey"])(
"requires IndexedDB %s identity evidence",
async (field) => {
const { capture } = await inspect({
commandResult: (command) =>
command.method === "IndexedDB.requestData"
? {
objectStoreDataEntries: [
{
key: validKey,
primaryKey: validKey,
value: validKey,
[field]: {},
},
],
hasMore: false,
}
: undefined,
});
const captured = await capture();
expect(captured.storage.fingerprints_complete).toBe(false);
expect(
captured.storage.content_fingerprints.find(
({ scope }) => scope === "indexed_db_record",
)?.complete,
).toBe(false);
},
);
it("does not fingerprint a filtered partial object-store schema as complete", async () => {
let malformed = false;
const store = {
name: "records",
keyPath: { type: "string", string: "id" },
autoIncrement: false,
indexes: [],
};
const { capture } = await inspect({
commandResult: (command) =>
command.method === "IndexedDB.requestDatabase"
? {
databaseWithObjectStores: {
name: "app-db",
version: 1,
objectStores: [
store,
malformed ? null : { ...store, name: "other" },
],
},
}
: undefined,
});
const before = await capture();
malformed = true;
const after = await capture();
expect(
after.storage.content_fingerprints.find(
({ scope }) => scope === "indexed_db_schema",
)?.complete,
).toBe(false);
expect(compareStorage(before, after)).toMatchObject({
status: "unknown",
total_changes: 0,
});
});
const incompleteRemoteObjects = [
undefined,
null,
"raw",
{},
{ type: "string" },
{ type: "string", value: 1 },
{ type: "boolean", value: "false" },
{ type: "number" },
{ type: "number", unserializableValue: "invalid" },
{ type: "number", unserializableValue: ["NaN"] },
{ type: "function", description: "function f() {}" },
{ type: "symbol", description: "Symbol(x)" },
{ type: "object", subtype: "null" },
{ type: "bigint", unserializableValue: "broken" },
] as const;
const completeRemoteObjects = [
{ type: "string", value: "" },
{ type: "boolean", value: false },
{ type: "number", value: 0 },
{ type: "undefined" },
{ type: "number", unserializableValue: "NaN" },
{ type: "number", unserializableValue: "-0" },
{ type: "bigint", unserializableValue: "-42n" },
{ type: "object", subtype: "null", value: null },
{ type: "object", value: { nested: [false, null, 0] } },
] as const;
it.each([
...incompleteRemoteObjects.map((value) => [value, false] as const),
...completeRemoteObjects.map((value) => [value, true] as const),
])(
"validates IndexedDB RemoteObject completeness: %j => %s",
async (value, complete) => {
const { capture } = await inspect({
commandResult: (command) =>
command.method === "IndexedDB.requestData"
? {
objectStoreDataEntries: [
{ key: validKey, primaryKey: validKey, value },
],
hasMore: false,
}
: undefined,
});
const before = await capture();
const after = await capture();
const records = before.storage.content_fingerprints.filter(
({ scope }) => scope === "indexed_db_record",
);
expect(records).toHaveLength(1);
expect(records[0]?.complete).toBe(complete);
expect(before.storage.fingerprints_complete).toBe(complete);
expect(compareStorage(before, after)).toMatchObject({
status: complete ? "unchanged" : "unknown",
total_changes: 0,
});
},
);
it.each([
[undefined, false],
[{}, false],
[{ type: "string" }, false],
[{ type: "array", array: [null] }, false],
[{ type: "null" }, true],
[{ type: "string", string: "id" }, true],
[{ type: "array", array: ["id", "name"] }, true],
] as const)(
"requires complete IndexedDB key paths: %j",
async (keyPath, complete) => {
const { capture } = await inspect({
commandResult: (command) =>
command.method === "IndexedDB.requestDatabase"
? {
databaseWithObjectStores: {
name: "app-db",
version: 1,
objectStores: [
{
name: "records",
keyPath,
autoIncrement: false,
indexes: [
{
name: "by-id",
keyPath,
unique: false,
multiEntry: false,
},
],
},
],
},
}
: undefined,
});
const captured = await capture();
expect(
captured.storage.content_fingerprints.find(
({ scope }) => scope === "indexed_db_schema",
)?.complete,
).toBe(complete);
expect(captured.storage.fingerprints_complete).toBe(complete);
},
);
it("accepts genuinely empty inventories as complete", async () => {
const { capture } = await inspect({
commandResult: (command) => {
switch (command.method) {
case "CacheStorage.requestCacheNames":
return { caches: [] };
case "IndexedDB.requestDatabaseNames":
return { databaseNames: [] };
case "DOMStorage.getDOMStorageItems":
return { entries: [] };
case "Network.getCookies":
return { cookies: [] };
default:
return undefined;
}
},
});
const before = await capture();
const after = await capture();
expect(before.storage.fingerprints_complete).toBe(true);
expect(compareStorage(before, after).status).toBe("unchanged");
});
@@ -14,6 +14,185 @@ import {
} from "../../fixtures/fakeCdpBrowser.js";
const browsers: FakeCdpBrowser[] = [];
const inspectStorage = async (
browser: FakeCdpBrowser,
fingerprints = false,
) => {
const captured = await new CdpBrowserProvider().inspectPage(
inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
observation_ms: 0,
include_storage_keys: true,
include_storage_fingerprints: fingerprints,
}),
);
if (!captured.ok) throw captured.error;
return captured.value;
};
const compareStorage = (left: WebPageInspection, right: WebPageInspection) =>
compareWebCaptures(
compareWebCapturesInputSchema.parse({
before: { inspection: left },
after: { inspection: right },
}),
).dimensions.storage;
it.each([
["local", "DOMStorage.getDOMStorageItems", { entries: [null] }],
[
"session",
"DOMStorage.getDOMStorageItems",
{ entries: [["known", "value"], null] },
],
["indexed", "IndexedDB.requestDatabaseNames", { databaseNames: [null] }],
["cache", "CacheStorage.requestCacheNames", { caches: [null] }],
] as const)(
"does not invent membership changes after an incomplete %s inventory",
async (kind, method, malformed) => {
let failure: "unsupported" | "malformed" | undefined;
const matches = (command: {
method: string;
params: Record<string, unknown>;
}) => {
if (command.method !== method) return false;
if (kind !== "local" && kind !== "session") return true;
return (
(command.params.storageId as { isLocalStorage: boolean })
.isLocalStorage ===
(kind === "local")
);
};
const browser = await startFakeCdpBrowser({
commandError: (command) =>
failure === "unsupported" && matches(command)
? { code: -32601, message: "Method not found" }
: undefined,
commandResult: (command) =>
failure === "malformed" && matches(command) ? malformed : undefined,
});
browsers.push(browser);
const before = await inspectStorage(browser);
expect(before.completeness.unavailable_sections).not.toContain(
"storage_keys",
);
for (const [mode, reason] of [
["unsupported", "provider_unavailable"],
["malformed", "invalid_protocol_value"],
] as const) {
failure = mode;
const after = await inspectStorage(browser);
expect(after.completeness.excluded).toContainEqual({
section: "storage_keys",
reason,
count: null,
});
expect(after.completeness.unavailable_sections).toContain("storage_keys");
for (const [left, right] of [
[before, after],
[after, before],
] as const)
expect(compareStorage(left, right)).toMatchObject({
status: "unknown",
total_changes: 0,
changes: [],
});
if (kind === "session" && mode === "malformed")
expect(after.storage.session_storage_keys).toEqual(["known"]);
}
},
);
it("preserves shared content changes when a peer inventory is unavailable", async () => {
let value = "before";
const browser = await startFakeCdpBrowser({
unsupportedMethods: ["CacheStorage.requestCacheNames"],
commandResult: (command) =>
command.method === "DOMStorage.getDOMStorageItems"
? { entries: [["shared-key", value]] }
: undefined,
});
browsers.push(browser);
const before = await inspectStorage(browser, true);
expect(before.completeness.unavailable_sections).toContain("storage_keys");
expect(compareStorage(before, before)).toMatchObject({
status: "unknown",
total_changes: 0,
});
value = "after";
const after = await inspectStorage(browser, true);
for (const [left, right] of [
[before, after],
[after, before],
] as const)
expect(compareStorage(left, right)).toMatchObject({
status: "changed",
total_changes: 2,
changes: [
expect.objectContaining({ change: "modified" }),
expect.objectContaining({ change: "modified" }),
],
});
for (const fingerprint of after.storage.content_fingerprints)
if (["local_storage", "session_storage"].includes(fingerprint.scope))
fingerprint.complete = false;
expect(compareStorage(before, after)).toMatchObject({
status: "unknown",
total_changes: 0,
});
});
it("reports complete storage key additions and removals without content fingerprints", async () => {
const browser = await startFakeCdpBrowser();
browsers.push(browser);
const before = await inspectStorage(browser);
expect(before.storage.fingerprints_complete).toBe(false);
const after = structuredClone(before);
after.storage.local_storage_keys.push("new-local");
after.storage.session_storage_keys.push("new-session");
after.storage.indexed_db_names.push("new-db");
after.storage.cache_names.push("new-cache");
const identities = [
"storage:cache:new-cache",
"storage:indexed_db:new-db",
"storage:local_storage:new-local",
"storage:session_storage:new-session",
];
for (const [left, right, change] of [
[before, after, "added"],
[after, before, "removed"],
] as const) {
expect(compareStorage(left, right)).toMatchObject({
status: "changed",
total_changes: 4,
changes: identities.map((identity) => ({ identity, change })),
});
}
expect(compareStorage(after, after)).toMatchObject({
status: "unknown",
total_changes: 0,
});
const missingQuota = structuredClone(after);
missingQuota.storage.quota_bytes = null;
expect(compareStorage(before, missingQuota)).toMatchObject({
status: "changed",
total_changes: 4,
});
const partialInventory = structuredClone(after);
partialInventory.completeness.unavailable_sections.push("storage_keys");
expect(compareStorage(before, partialInventory)).toMatchObject({
status: "unknown",
total_changes: 0,
});
expect(compareStorage(partialInventory, before)).toMatchObject({
status: "unknown",
total_changes: 0,
});
});
const expectInvalidDiff = (input: unknown): void => {
expect(webCaptureDiffSchema.safeParse(input).success).toBe(false);
};
@@ -988,6 +988,41 @@ describe("source-map original dependency syntax", () => {
result.items[0]?.original_module_edges.map(({ specifier }) => specifier),
).toEqual(["./real.js", "./dynamic.js", "./common.cjs"]);
});
it("reads expression-free template module specifiers as literals", async () => {
const text = [
"import(`./dep.js`);",
"import(`./dep.${name}.js`);",
"require(`./common.cjs`);",
"require(`./${name}.cjs`);",
].join("\n");
const result = await fetchWebSourceMaps([request], input(), undefined, {
fetch: () =>
Promise.resolve(
new Response(
JSON.stringify({
version: 3,
names: [],
sources: ["main.ts"],
sourcesContent: [text],
mappings: "AAAA",
}),
),
),
});
const item = result.items[0];
if (item?.status !== "included") throw new Error("map not included");
expect(item.original_module_edges).toEqual([
expect.objectContaining({
kind: "dynamic_import",
specifier: "./dep.js",
resolved_source: `${origin}/assets/dep.js`,
}),
expect.objectContaining({ kind: "require", specifier: "./common.cjs" }),
]);
expect(item.original_sources[0]?.artifact?.text).toBe(text);
expect(item.mappings).toHaveLength(1);
});
});
describe("source-map original syntax boundaries", () => {
@@ -20,6 +20,56 @@ import { ghidraFunctionDossier } from "../../../src/domain/ghidraValues.fixture.
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import { inspectEvidenceBundle } from "../../../src/application/investigation/InspectEvidenceBundle.js";
cliTest(
"projects opted-in query names through compiled CLI without query values",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-query-names-cli-");
const path = join(root, "view.json");
const capture = analysisViewCaptureFixture();
capture.records = capture.records.slice(0, 2);
capture.total_records = 2;
capture.records.forEach((record, index) => {
record.reported = {
request: {
method: "GET",
url:
index === 0
? "https://api.test/products?category=books&page=1&category=repeat"
: "https://api.test/products?category=games&sort=price#ignored",
},
};
});
await writeFile(
path,
JSON.stringify({
source: {
kind: "inline",
evidence: analysisViewCaptureEvidence(capture),
},
view: { kind: "api-surface", include_query_parameter_names: true },
}),
);
const result = await cli.run({
arguments: ["inspect-analysis-view", path, "--json"],
});
expect(result.exitCode).toBe(0);
const evidence = parseEvidence(result.json);
expect(evidence.normalized_result).toMatchObject({
groups: [
{
query_parameter_names: [
{ name: "category", record_ordinals: [0, 1] },
{ name: "page", record_ordinals: [0] },
{ name: "sort", record_ordinals: [1] },
],
},
],
});
for (const value of ["books", "games", "repeat", "price", "ignored"])
expect(result.stdout).not.toContain(value);
},
);
cliTest(
"projects portable artifact inventory after the original ZIP is removed",
async ({ cli }) => {
+85
View File
@@ -262,6 +262,91 @@ cliTest(
},
);
cliTest(
"Gemini matches allowlist spellings independently of their policy order",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-gemini-case-");
const system = join(home, "system.json");
const defaults = join(home, "defaults.json");
await writeFile(system, JSON.stringify({ mcp: { allowed: ["REA"] } }));
const environment = {
HOME: home,
USERPROFILE: home,
GEMINI_CLI_SYSTEM_SETTINGS_PATH: system,
GEMINI_CLI_SYSTEM_DEFAULTS_PATH: defaults,
};
const run = () =>
cli.run({
arguments: ["setup", "--client", "gemini_cli", "--yes", "--json"],
cwd: home,
environment,
});
// The intersection compares names case-insensitively, so the spelling that
// survives must not decide the outcome: the same pair of policies in
// either arrangement has to consolidate to the same decision.
for (const [systemSpelling, defaultSpelling] of [
["REA", "rea"],
["rea", "REA"],
]) {
await writeFile(
system,
JSON.stringify({ mcp: { allowed: [systemSpelling] } }),
);
await writeFile(
defaults,
JSON.stringify({ mcp: { allowed: [defaultSpelling] } }),
);
const result = await run();
expect(result.exitCode, `${systemSpelling}+${defaultSpelling}`).toBe(0);
expect(result.json, `${systemSpelling}+${defaultSpelling}`).toMatchObject(
{
status: "ready",
},
);
}
},
);
cliTest(
"Gemini compares exclusions and padded allowlist entries through one normalization",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-gemini-normalized-");
const system = join(home, "system.json");
const defaults = join(home, "defaults.json");
const environment = {
HOME: home,
USERPROFILE: home,
GEMINI_CLI_SYSTEM_SETTINGS_PATH: system,
GEMINI_CLI_SYSTEM_DEFAULTS_PATH: defaults,
};
const run = () =>
cli.run({
arguments: ["setup", "--client", "gemini_cli", "--yes", "--json"],
cwd: home,
environment,
});
await writeFile(defaults, JSON.stringify({ mcp: {} }));
// An exclusion is a membership test over the same names the intersection
// compares, so a differently spelled and padded entry blocks setup rather
// than slipping past the raw comparison.
await writeFile(system, JSON.stringify({ mcp: { excluded: [" REA "] } }));
const blocked = await run();
expect(blocked.exitCode).toBe(1);
expect(blocked.json).toMatchObject({
status: "needs_human",
plannedActions: [],
appliedActions: [],
remediation: expect.stringContaining("mcp.excluded"),
});
// Padding is presentation, not identity: a padded allowlist entry permits
// the same server its exact spelling permits.
await writeFile(system, JSON.stringify({ mcp: { allowed: [" REA "] } }));
const allowed = await run();
expect(allowed.exitCode).toBe(0);
expect(allowed.json).toMatchObject({ status: "ready" });
},
);
cliTest(
"OpenCode doctor sees a global registration when the custom directory is absent",
async ({ cli }) => {
+183
View File
@@ -0,0 +1,183 @@
import { createServer } from "node:net";
import { createHmac } from "node:crypto";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { Cli } from "incur";
import { afterEach, describe, expect, it } from "vitest";
import { createCli } from "../../../src/cli.js";
import { serveCli } from "./cliServeHarness.js";
const SESSION_ID = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a";
const registeredCommands = Cli.toCommands as WeakMap<
object,
Map<string, unknown>
>;
const cutterCommand = async (
environment: Record<string, string | undefined>,
args: {
readonly sessionId: string;
readonly expectedGeneration: number;
readonly command: string;
},
): Promise<unknown> => {
const cli = createCli(environment);
const entry = registeredCommands.get(cli)?.get("cutter-command") ?? {};
const run = Reflect.get(entry, "run") as (...args: unknown[]) => unknown;
return Reflect.apply(run, undefined, [{ args, options: { json: false } }]);
};
const listen = async (
server: ReturnType<typeof createServer>,
): Promise<number> => {
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
if (address === null || typeof address === "string")
throw new Error("Expected an ephemeral TCP listener");
return address.port;
};
describe("Cutter CLI commands", () => {
let directory: string | undefined;
let server: ReturnType<typeof createServer> | undefined;
afterEach(async () => {
if (server !== undefined)
await new Promise<void>((resolve) => server?.close(() => resolve()));
if (directory !== undefined)
await rm(directory, { recursive: true, force: true });
directory = undefined;
server = undefined;
});
it("lists sessions from the selected bridge directory", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-cutter-cli-test-"));
const result = await serveCli(["list-cutter-sessions", "--json"], {
REA_CUTTER_BRIDGE_DIR: directory,
});
expect(result.exitCode).toBe(0);
expect(JSON.parse(result.stdout)).toMatchObject({
sessions: [],
discovery_status: "no_live_bridge_found",
bridge_directory: directory,
});
});
it("reports an unavailable selected session for a command", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-cutter-cli-test-"));
const result = await serveCli(
["cutter-command", SESSION_ID, "0", "pdi", "--json"],
{ REA_CUTTER_BRIDGE_DIR: directory },
);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain("invalid_request");
});
it("returns Evidence when the selected Cutter session completes a command", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-cutter-cli-test-"));
const token = "synthetic-cutter-cli-token-for-test";
let nextConnectionOrdinal = 0;
server = createServer((connection) => {
const ordinal = ++nextConnectionOrdinal;
connection.setEncoding("utf8");
let input = "";
let clientNonce = "";
let serverNonce = "";
connection.on("data", (chunk: string) => {
input += chunk;
const newline = input.indexOf("\n");
if (newline < 0) return;
const frame = JSON.parse(input.slice(0, newline)) as Record<
string,
unknown
>;
input = input.slice(newline + 1);
if (frame.kind === "rea-auth-v2") {
clientNonce = String(frame.nonce);
serverNonce = `${ordinal.toString(16).padStart(16, "0")}${"b".repeat(48)}`;
connection.write(
`${JSON.stringify({ session_id: SESSION_ID, nonce: serverNonce, proof: createHmac("sha256", token).update(`rea-cutter-server-v2:${SESSION_ID}:${clientNonce}:${serverNonce}`).digest("hex") })}\n`,
);
return;
}
const requestBytes = String(frame.request);
const request = JSON.parse(requestBytes) as Record<string, unknown>;
if (
frame.proof !==
createHmac("sha256", token)
.update(
`rea-cutter-client-v2:${SESSION_ID}:${clientNonce}:${serverNonce}:${requestBytes}`,
)
.digest("hex")
) {
connection.destroy();
return;
}
const status = request.kind === "status";
const response = JSON.stringify({
ok: true,
session_id: request.session_id,
...(status
? {
current_file: null,
document_generation: 0,
cutter_version: "Cutter fixture",
identity_status: "partial",
completed_connection: (ordinal - 1)
.toString(16)
.padStart(16, "0"),
completed_commands: [],
}
: request.kind === "ack"
? { acknowledged: false }
: {
output: { answer: 42 },
current_file: null,
document_generation: 0,
cutter_version: "Cutter fixture",
identity_status: "partial",
execution_state: "complete",
output_truncated: false,
}),
});
const proof = createHmac("sha256", token)
.update(
`rea-cutter-response-v2:${SESSION_ID}:${clientNonce}:${serverNonce}:${response}`,
)
.digest("hex");
connection.end(`${JSON.stringify({ response, proof })}\n`);
});
});
const port = await listen(server);
await writeFile(
join(directory, `cutter-${process.pid}-${SESSION_ID}.json`),
JSON.stringify({
session_id: SESSION_ID,
pid: process.pid,
host: "127.0.0.1",
port,
token,
document_generation: 0,
current_file: null,
cutter_version: "Cutter fixture",
identity_status: "partial",
}),
{ mode: 0o600 },
);
const result = await cutterCommand(
{ REA_CUTTER_BRIDGE_DIR: directory },
{ sessionId: SESSION_ID, expectedGeneration: 0, command: "pdi" },
);
expect(JSON.stringify(result)).toContain("rea.cutter.command-observation");
expect(JSON.stringify(result)).toContain('"answer":42');
});
});
@@ -45,6 +45,7 @@ const fixture = async () => {
for (const path of [
"scripts/run-development-tests.mjs",
"scripts/lib/development-tests.mjs",
"scripts/lib/test-projects.mjs",
])
await copyFile(join(process.cwd(), path), join(root, path));
await symlink(
@@ -106,6 +106,57 @@ const withBrokenHelper = async (app: string): Promise<void> => {
await writeFiles(app, { "Contents/Helpers/broken": broken });
};
cliTest(
"does not turn U+FEFF-prefixed strings into dyld path tokens",
async ({ cli }) => {
const app = await fixtureApp();
await writeFiles(app, {
"Contents/MacOS/App": machoImage({
commands: [
buildVersionCommand(1),
rpathCommand("@executable_path/../Frameworks"),
dylibCommand(LC.LOAD_DYLIB, "@rpath/libcore.dylib"),
dylibCommand(LC.LOAD_DYLIB, "\uFEFF@rpath/libcore.dylib"),
],
}),
"Contents/Helpers/tool": machoImage({
commands: [
buildVersionCommand(1),
rpathCommand("\uFEFF@loader_path/../Frameworks"),
dylibCommand(LC.LOAD_DYLIB, "@rpath/libcore.dylib"),
],
}),
});
const output = await cli.run({
arguments: ["trace-dylib-resolution", app, "--json"],
environment: ENVIRONMENT,
});
expect(output.exitCode, output.stderr).toBe(0);
const trace = dylibResolutionResultSchema.parse(
parseEvidence(output.json).normalized_result,
);
const ordinary = trace.edges.find(
({ loader, install_name }) =>
loader === "Contents/MacOS/App" &&
install_name === "@rpath/libcore.dylib",
);
expect(ordinary?.resolution).toMatchObject({
status: "resolved",
image: "Contents/Frameworks/libcore.dylib",
});
const marked = trace.edges.find(
({ install_name }) => install_name === "\uFEFF@rpath/libcore.dylib",
);
expect(marked).toBeDefined();
expect(marked?.resolution.image).toBeNull();
const helper = trace.edges.find(
({ loader }) => loader === "Contents/Helpers/tool",
);
expect(helper).toBeDefined();
expect(helper?.resolution.image).toBeNull();
},
);
describe("trace-dylib-resolution CLI", () => {
cliTest("traces every executable root of an app bundle", async ({ cli }) => {
const app = await fixtureApp();
@@ -55,7 +55,8 @@ cliTest(
expect(
byId.get(edge.target_node_id)?.observations[0]?.properties.channel,
).toBe(edge.properties.channel);
expect(edge.properties.conditions).toEqual([
expect(edge.properties.bridge_conditions).toEqual([]);
expect(edge.properties.handler_conditions).toEqual([
expect.objectContaining({ expression: "allowed(event)" }),
]);
}
@@ -495,3 +496,44 @@ cliTest(
).toEqual(["empty:key"]);
},
);
cliTest(
"retains bridge and handler conditions on Electron IPC join edges",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-electron-join-conditions-");
await writeFixtureFiles(root, {
"preload.js": `const e=require("electron");
e.contextBridge.exposeInMainWorld("desktop", {
choose: flag
? () => e.ipcRenderer.send("test:copy")
: () => e.ipcRenderer.send("test:cut")
});`,
"main.js": `const e=require("electron");
if(!flag)e.ipcMain.on("test:copy",event=>allowed(event)&&event.sender.copy());
if(flag)e.ipcMain.on("test:cut",event=>allowed(event)&&event.sender.cut());`,
});
const { graph } = await analyzeJavaScriptDirectory("CLI", cli, root);
const joins = graph.edges.filter(
(edge) =>
edge.evidence.extractor.operation === "join-electron-wrapper-paths",
);
expect(joins).toHaveLength(2);
for (const [channel, bridgeCondition] of [
["test:copy", "flag"],
["test:cut", "!(flag)"],
]) {
const edge = joins.find(
(candidate) => candidate.properties.channel === channel,
);
expect(edge?.properties.bridge_conditions).toEqual([
expect.objectContaining({ expression: bridgeCondition }),
]);
expect(edge?.properties.handler_conditions).toEqual([
expect.objectContaining({
expression: channel === "test:copy" ? "!flag" : "flag",
}),
expect.objectContaining({ expression: "allowed(event)" }),
]);
}
},
);
@@ -0,0 +1,132 @@
import pino from "pino";
import { expect, it, vi } from "vitest";
import { AnalysisOutputError } from "../../../src/domain/analysisErrorCore.js";
import { err } from "../../../src/domain/result.js";
import { registerReverseEngineeringCommands } from "../../../src/cli/reverseEngineeringCommands.js";
import { CLI_COMMANDS } from "../../../src/cliCommandNames.js";
import type { CliInstance } from "../../../src/cli/types.js";
import type { GdbSessionManager } from "../../../src/gdb/GdbSessionManager.js";
const registerGdbCommand = (
createManager: () => GdbSessionManager,
): {
run(input: {
args: { command: string };
options: { inferiorTty: string };
}): Promise<unknown>;
} => {
const commands = new Map<
string,
{
run(input: {
args: { command: string };
options: { inferiorTty: string };
}): Promise<unknown>;
}
>();
const cli = {
command: (
name: string,
definition: {
run(input: {
args: { command: string };
options: { inferiorTty: string };
}): Promise<unknown>;
},
) => {
commands.set(name, definition);
return cli;
},
} as unknown as CliInstance;
registerReverseEngineeringCommands(cli, pino({ enabled: false }), {}, () =>
createManager(),
);
const command = commands.get(CLI_COMMANDS.debugWithGdb);
if (command === undefined)
throw new Error("GDB CLI command was not registered");
return command;
};
it.each([
"source /tmp/gdbinit",
"python print('x')",
"def custom-command",
"run > /tmp/out",
"set inferior-t /dev/null",
"with inferior-t /dev/null -- run",
])("rejects one-shot command %s before starting GDB", async (inputCommand) => {
const manager = {
start: vi.fn(),
closeAll: vi.fn(),
} as unknown as GdbSessionManager;
const command = registerGdbCommand(() => manager);
const result = await command.run({
args: { command: inputCommand },
options: { inferiorTty: "/dev/pts/42" },
});
expect(result).toMatchObject({
code: "invalid_request",
details: {
issues: [
expect.objectContaining({
message: expect.stringContaining("persistent GDB session workflow"),
}),
],
},
});
expect(manager.start).not.toHaveBeenCalled();
expect(manager.closeAll).not.toHaveBeenCalled();
});
it("retries retained GDB cleanup when CLI session startup fails", async () => {
const closeAll = vi.fn(async () => undefined);
const manager = {
start: vi.fn(async () =>
err(new AnalysisOutputError("start_gdb_session", "startup failed")),
),
closeAll,
} as unknown as GdbSessionManager;
const originalExitCode = process.exitCode;
const command = registerGdbCommand(() => manager);
try {
const result = await command.run({
args: { command: "info files" },
options: { inferiorTty: "/dev/pts/42" },
});
expect(result).toMatchObject({ code: "unreadable_output" });
expect(manager.start).toHaveBeenCalledOnce();
expect(manager.start).toHaveBeenCalledWith(expect.anything(), {
inferiorTty: "/dev/pts/42",
});
expect(closeAll).toHaveBeenCalledOnce();
} finally {
process.exitCode = originalExitCode;
}
});
it("marks the CLI failed when retained GDB cleanup remains incomplete", async () => {
const manager = {
start: vi.fn(async () =>
err(new AnalysisOutputError("start_gdb_session", "startup failed")),
),
closeAll: vi.fn(async () => {
throw new Error("process still owned");
}),
} as unknown as GdbSessionManager;
const originalExitCode = process.exitCode;
const command = registerGdbCommand(() => manager);
try {
const result = await command.run({
args: { command: "info files" },
options: { inferiorTty: "/dev/pts/42" },
});
expect(result).toMatchObject({ code: "unreadable_output" });
expect(manager.closeAll).toHaveBeenCalledOnce();
expect(process.exitCode).toBe(1);
} finally {
process.exitCode = originalExitCode;
}
});
@@ -1,6 +1,6 @@
import { chmod, copyFile, rm } from "node:fs/promises";
import { describe, expect, onTestFinished } from "vitest";
import { describe, expect } from "vitest";
import { z } from "zod";
import { workspaceCliTest } from "../../support/cli/workspaceCliFixture.js";
@@ -39,7 +39,57 @@ describe("Hopper launcher failure through the one-shot CLI", () => {
const targetPath = workspace.path("probe");
await copyFile("/usr/bin/true", targetPath);
const loaderArgs = ["--probe"];
onTestFinished(async () => {
try {
for (const attempt of ["first", "retry"]) {
const result = await cli.run({
arguments: [
"analyze",
targetPath,
"--provider",
"hopper",
"--json",
],
environment: {
...workspace.environment,
HOPPER_LAUNCHER_PATH: launcherPath,
HOPPER_LOADER_ARGS_JSON: JSON.stringify(loaderArgs),
REA_LOG_LEVEL: "silent",
},
timeoutMs: 45_000,
});
const retained = RetainedRuntime.safeParse(result.json);
if (retained.success)
await rm(
retained.data.details.diagnostics.cleanup_error.details
.diagnostics.runtime_root,
{ recursive: true, force: true },
);
expect(result.exitCode, attempt).toBe(1);
expect(result.json, attempt).toMatchObject({
code: "cleanup_incomplete",
details: {
cleanup: "incomplete",
diagnostics: {
primary_error: {
code: "provider_unavailable",
details: {
stage: "launch",
launcher: {
exit_code: 2,
stderr: {
text: expect.stringContaining(
"Document state is unknown",
),
},
},
},
},
},
},
});
}
} finally {
const recovered = await acquireHopperTargetLease({
targetPath,
targetKind: "executable",
@@ -48,50 +98,6 @@ describe("Hopper launcher failure through the one-shot CLI", () => {
});
expect(recovered.acquired).toBe(true);
if (recovered.acquired) await recovered.lease.release();
});
for (const attempt of ["first", "retry"]) {
const result = await cli.run({
arguments: ["analyze", targetPath, "--provider", "hopper", "--json"],
environment: {
...workspace.environment,
HOPPER_LAUNCHER_PATH: launcherPath,
HOPPER_LOADER_ARGS_JSON: JSON.stringify(loaderArgs),
REA_LOG_LEVEL: "silent",
},
timeoutMs: 45_000,
});
const retained = RetainedRuntime.safeParse(result.json);
if (retained.success)
await rm(
retained.data.details.diagnostics.cleanup_error.details.diagnostics
.runtime_root,
{ recursive: true, force: true },
);
expect(result.exitCode, attempt).toBe(1);
expect(result.json, attempt).toMatchObject({
code: "cleanup_incomplete",
details: {
cleanup: "incomplete",
diagnostics: {
primary_error: {
code: "provider_unavailable",
details: {
stage: "launch",
launcher: {
exit_code: 2,
stderr: {
text: expect.stringContaining(
"Document state is unknown",
),
},
},
},
},
},
},
});
}
},
);
@@ -15,6 +15,19 @@ const run = async (arguments_: readonly string[]): Promise<unknown> => {
return JSON.parse(stdout);
};
const runFailure = async (arguments_: readonly string[]): Promise<unknown> => {
try {
await run(arguments_);
} catch (cause: unknown) {
if (typeof cause !== "object" || cause === null || !("stdout" in cause))
throw cause;
const stdout = cause.stdout;
if (typeof stdout !== "string") throw cause;
return JSON.parse(stdout);
}
throw new Error("Expected the CLI command to fail");
};
it.each(["analyze-javascript-application", "analyze"])(
"%s carries the integrity policy into shared JavaScript analysis",
async (command) => {
@@ -46,3 +59,48 @@ it("rejects the JavaScript integrity policy on binary-only inspection", async ()
stdout: expect.stringContaining("Unknown flag: --integrityPolicy"),
});
});
it.each(["fail", "record-and-continue"] as const)(
"rejects the explicitly selected %s integrity policy on a binary analyze target",
async (policy) => {
const failure = await runFailure([
"analyze",
"unused.bin",
"--integrity-policy",
policy,
]);
expect(failure).toMatchObject({
code: "invalid_request",
details: {
issues: [
{
path: ["integrity_policy"],
reason: "invalid_value",
message:
"An integrity policy requires the static JavaScript ASAR/directory analysis lane; binary_overview accepts no input.",
},
],
},
});
},
);
it("still routes a binary analyze target without an integrity policy", async () => {
await expect(run(["analyze", "unused.bin"])).rejects.toMatchObject({
code: 1,
stdout: expect.stringContaining("target does not exist"),
});
});
it("advertises the optional integrity policy without an undefined union", async () => {
const schema = (await run(["analyze", "--schema"])) as {
options?: { properties?: { integrityPolicy?: unknown } };
};
const policy = schema.options?.properties?.integrityPolicy;
expect(policy).toMatchObject({
type: "string",
enum: ["fail", "record-and-continue"],
description: "Behavior when declared application integrity does not match",
});
expect(JSON.stringify(policy)).not.toContain("undefined");
});
@@ -0,0 +1,429 @@
import pino from "pino";
import { Cli, z } from "incur";
import { afterEach, expect, it, vi } from "vitest";
import { rm } from "node:fs/promises";
import { registerReverseEngineeringCommands } from "../../../src/cli/reverseEngineeringCommands.js";
import { CLI_COMMANDS } from "../../../src/cliCommandNames.js";
import {
AnalysisCancelledError,
AnalysisTimeoutError,
AnalysisOutputError,
} from "../../../src/domain/analysisErrorCore.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import {
createEvidence,
evidenceSchema,
} from "../../../src/domain/evidence.js";
import { err, ok } from "../../../src/domain/result.js";
import { RizinDebugSessionManager } from "../../../src/rizin/RizinDebugSessionManager.js";
import { ReverseEngineeringService as CoreReverseEngineeringService } from "../../../src/application/reverse/ReverseEngineeringService.js";
import { createReverseEngineeringCommandPort } from "../../../src/composition/reverseEngineering.js";
import { OwnedCommandFailure } from "../../../src/process/OwnedCommand.js";
import type { ProviderProcessSupervisor } from "../../../src/process/ProviderProcess.js";
import {
createArtifact,
providerSnapshot,
} from "../../support/reverseEngineeringCompositionFixtures.js";
import type { CliInstance } from "../../../src/cli/types.js";
import type { ReverseEngineeringService } from "../../../src/application/reverse/ReverseEngineeringService.js";
const originalExitCode = process.exitCode;
afterEach(() => {
process.exitCode = originalExitCode;
});
const observation = (completionStatus: "complete" | "unknown") =>
createEvidence(
undefined,
{ id: "gnu.objdump", name: "GNU objdump", version: null },
{
predicateType: "rea.reverse-engineering.command-observation",
operation: "inspect_with_objdump",
parameters: { operation: "file_headers" },
result: { completion_status: completionStatus },
rawResult: { completion_status: completionStatus },
},
);
const runObjdump = async (
service: Partial<ReverseEngineeringService>,
path = "/tmp/sample",
) => {
const commands = new Map<
string,
{
run(input: {
args: { path: string; operation: string };
options: { followDebugLinks: boolean };
}): Promise<unknown>;
}
>();
const cli = {
command: (
name: string,
definition: {
run(input: {
args: { path: string; operation: string };
options: { followDebugLinks: boolean };
}): Promise<unknown>;
},
) => {
commands.set(name, definition);
return cli;
},
} as unknown as CliInstance;
registerReverseEngineeringCommands(
cli,
pino({ enabled: false }),
{},
undefined,
() => service as ReverseEngineeringService,
);
const command = commands.get(CLI_COMMANDS.inspectWithObjdump);
if (command === undefined)
throw new Error("objdump CLI command was not registered");
return command.run({
args: { path, operation: "file_headers" },
options: { followDebugLinks: false },
});
};
it("lists objdump architectures without inventing an artifact path", async () => {
const evidence = observation("complete");
const inspectWithObjdump = vi.fn(async (_input: unknown) => ok(evidence));
const commands = new Map<
string,
{
readonly args?: { safeParse(input: unknown): { success: boolean } };
run(input: { args?: unknown; options?: unknown }): Promise<unknown>;
}
>();
const cli = {
command: (_name: string, definition: unknown) => {
commands.set(
_name,
definition as {
readonly args?: {
safeParse(input: unknown): { success: boolean };
};
run(input: { args?: unknown; options?: unknown }): Promise<unknown>;
},
);
return cli;
},
} as unknown as CliInstance;
registerReverseEngineeringCommands(
cli,
pino({ enabled: false }),
{},
undefined,
() =>
({
inspectWithObjdump,
close: vi.fn(async () => undefined),
}) as unknown as ReverseEngineeringService,
);
const command = commands.get(CLI_COMMANDS.listObjdumpArchitectures);
if (command === undefined)
throw new Error("architecture command was not registered");
const result = await command.run({});
expect(result).toEqual(evidence);
expect(inspectWithObjdump).toHaveBeenCalledWith(
{ operation: "architectures" },
expect.objectContaining({ signal: expect.any(AbortSignal) }),
);
const artifactCommand = commands.get(CLI_COMMANDS.inspectWithObjdump);
expect(
artifactCommand?.args?.safeParse({
path: "/tmp/sample",
operation: "dwarf",
}).success,
).toBe(true);
expect(
artifactCommand?.args?.safeParse({
path: "/tmp/sample",
operation: "architectures",
}).success,
).toBe(false);
});
it("promotes only complete production cleanup-only Evidence after CLI cleanup retry", async () => {
const { directory, path } = await createArtifact();
const owner = {
stop: vi.fn(async () => ({ status: "verified-cleanup" as const })),
} as unknown as ProviderProcessSupervisor;
const service = new CoreReverseEngineeringService({
commands: createReverseEngineeringCommandPort({}),
runOwned: vi.fn(async () => {
throw new OwnedCommandFailure(
"process",
"Cleanup after process completion was incomplete.",
providerSnapshot(),
"provider process still running",
undefined,
["owned-run"],
owner,
);
}),
});
const inspect = service.inspectWithObjdump.bind(service);
let producedCleanupFailure: AnalysisOutputError | undefined;
let cleanupIncompleteBeforeClose: boolean | undefined;
let completionBeforeClose: unknown;
vi.spyOn(service, "inspectWithObjdump").mockImplementation(
async (...args) => {
const result = await inspect(...args);
if (!result.ok && result.error instanceof AnalysisOutputError) {
producedCleanupFailure = result.error;
cleanupIncompleteBeforeClose = result.error.cleanupIncomplete;
const partialEvidence = evidenceSchema.safeParse(
result.error.partialObservation,
);
if (partialEvidence.success)
completionBeforeClose = partialEvidence.data.normalized_result;
}
return result;
},
);
try {
const result = await runObjdump(service, path);
expect(result).toMatchObject({
provider: { id: "gnu.objdump" },
normalized_result: { completion_status: "complete" },
});
expect(producedCleanupFailure?.cleanupOnly).toBe(true);
expect(cleanupIncompleteBeforeClose).toBe(true);
expect(completionBeforeClose).toMatchObject({
completion_status: "complete",
});
expect(producedCleanupFailure).toMatchObject({
cleanupIncomplete: false,
cleanup: { resources: ["owned-run"] },
partialObservation: {
normalized_result: { completion_status: "complete" },
},
});
expect(owner.stop).toHaveBeenCalledOnce();
} finally {
await service.close().catch(() => undefined);
await rm(directory, { recursive: true, force: true });
}
});
it("preserves an operation timeout and unknown partial Evidence after cleanup retry", async () => {
const { directory, path } = await createArtifact();
const owner = {
stop: vi.fn(async () => ({ status: "verified-cleanup" as const })),
} as unknown as ProviderProcessSupervisor;
const service = new CoreReverseEngineeringService({
commands: createReverseEngineeringCommandPort({}),
runOwned: vi.fn(async () => {
throw new OwnedCommandFailure(
"timeout",
"Provider command timed out.",
providerSnapshot({ exitCode: null }),
"provider process still running",
undefined,
["owned-run"],
owner,
);
}),
});
let timeout: AnalysisTimeoutError | undefined;
const inspect = service.inspectWithObjdump.bind(service);
vi.spyOn(service, "inspectWithObjdump").mockImplementation(
async (...args) => {
const result = await inspect(...args);
if (!result.ok && result.error instanceof AnalysisTimeoutError)
timeout = result.error;
return result;
},
);
try {
const result = await runObjdump(service, path);
expect(result).toMatchObject({
code: "provider_timeout",
details: {
partial_observation: {
normalized_result: { completion_status: "unknown" },
},
},
});
expect(timeout).toBeInstanceOf(AnalysisTimeoutError);
expect(timeout?.cleanupIncomplete).toBe(false);
expect(owner.stop).toHaveBeenCalledOnce();
} finally {
await service.close().catch(() => undefined);
await rm(directory, { recursive: true, force: true });
}
});
it("preserves an independent timeout after cleanup succeeds", async () => {
const evidence = observation("unknown");
const error = new AnalysisTimeoutError("inspect_with_objdump", 1_000, {
cleanup: { reason: "first stop incomplete", resources: ["owned-run"] },
partialObservation: evidence,
});
const service = {
inspectWithObjdump: vi.fn(async () => err(error)),
close: vi.fn(async () => {
error.resolveCleanup();
}),
};
const result = await runObjdump(service);
expect(result).toMatchObject({
code: "provider_timeout",
details: {
partial_observation: {
normalized_result: { completion_status: "unknown" },
},
},
});
expect(error.cleanupIncomplete).toBe(false);
expect(projectAnalysisError(error).details).not.toHaveProperty("cleanup");
});
it("does not project cancellation cleanup as incomplete after a successful retry", async () => {
const error = new AnalysisCancelledError("inspect_with_objdump", {
cleanup: { reason: "first stop incomplete", resources: ["owned-run"] },
partialObservation: observation("unknown"),
});
const service = {
inspectWithObjdump: vi.fn(async () => err(error)),
close: vi.fn(async () => {
error.resolveCleanup();
}),
};
await runObjdump(service);
expect(error.cleanupIncomplete).toBe(false);
expect(projectAnalysisError(error).details).toMatchObject({
cleanup: "complete",
});
});
it("parses the Rizin inferior TTY as an option and passes it to the manager", async () => {
const commands = new Map<
string,
{
run(input: {
args: Record<string, unknown>;
options: Record<string, unknown>;
}): Promise<unknown>;
}
>();
const cli = {
command: (
name: string,
definition: {
run(input: {
args: Record<string, unknown>;
options: Record<string, unknown>;
}): Promise<unknown>;
},
) => {
commands.set(name, definition);
return cli;
},
} as unknown as CliInstance;
const evidence = createEvidence(
undefined,
{ id: "rizin.debugger", name: "Rizin debugger", version: null },
{
predicateType: "rea.debugger.command-observation",
operation: "rizin_debug_command",
parameters: {
session_id: "session-1",
command: "dr",
inferior_tty: "/dev/pts/7",
},
result: { output: "registers" },
rawResult: { output: "registers" },
},
);
const start = vi
.spyOn(RizinDebugSessionManager.prototype, "start")
.mockResolvedValue(ok({ session_id: "session-1", backend: null }));
const execute = vi
.spyOn(RizinDebugSessionManager.prototype, "execute")
.mockResolvedValue(
ok({
evidence,
result: {
command: "dr",
output: "registers",
output_scope: "command_and_interleaved_session_output",
output_truncated: false,
completion_status: "complete",
backend: null,
},
}),
);
vi.spyOn(RizinDebugSessionManager.prototype, "close").mockResolvedValue(
ok({ target_state: "unknown" }),
);
vi.spyOn(RizinDebugSessionManager.prototype, "closeAll").mockResolvedValue(
undefined,
);
registerReverseEngineeringCommands(cli, pino({ enabled: false }), {});
const command = commands.get(CLI_COMMANDS.debugWithRizin);
if (command === undefined)
throw new Error("Rizin CLI command was not registered");
await command.run({
args: { path: "./sample.bin", command: "dr" },
options: { inferiorTty: "/dev/pts/7" },
});
expect(start).toHaveBeenCalledWith(
{ path: "./sample.bin", command: "dr", inferior_tty: "/dev/pts/7" },
expect.any(AbortSignal),
);
expect(execute).toHaveBeenCalledWith(
"session-1",
"dr",
expect.any(AbortSignal),
);
const parserCli = Cli.create("rea-test", { version: "1.0.0", sync: false });
registerReverseEngineeringCommands(
parserCli as unknown as CliInstance,
pino({ enabled: false }),
{},
);
const commandContract = Cli.toCommands
.get(parserCli)
?.get(CLI_COMMANDS.debugWithRizin);
expect(commandContract).toBeDefined();
const argsSchema =
commandContract === undefined
? undefined
: Reflect.get(commandContract, "args");
const optionsSchema =
commandContract === undefined
? undefined
: Reflect.get(commandContract, "options");
if (
!(argsSchema instanceof z.ZodObject) ||
!(optionsSchema instanceof z.ZodObject)
)
throw new Error("Rizin CLI args/options schemas were not registered");
expect(argsSchema.parse({ path: "./sample.bin", command: "dr" })).toEqual({
path: "./sample.bin",
command: "dr",
});
expect(optionsSchema.parse({ inferiorTty: "/dev/pts/7" })).toMatchObject({
inferiorTty: "/dev/pts/7",
});
});
@@ -228,7 +228,7 @@ describe("case-distinct APK resource names", () => {
await runProviderAnalysis(path, "inventory_artifact", {}),
);
expect(inventory.normalized_result).toMatchObject({
coverage_status: "partial",
coverage_status: "complete",
});
const result = projectAndroidApplicationEvidence({
inventory_evidence: [inventory],
@@ -238,11 +238,11 @@ describe("case-distinct APK resource names", () => {
);
expect(projection.root_format).toBe("apk");
expect(projection.coverage).toEqual({
status: "partial",
status: "complete-within-inventory",
inventory_complete: true,
});
expect(projection.limitations).toContain(
"Source inventory coverage is partial; absence is unknown.",
expect(projection.limitations.join(" ")).toContain(
"case-insensitive destination",
);
expect(projection.components.manifests).toHaveLength(1);
expect(projection.components.dex).toHaveLength(1);
@@ -75,7 +75,7 @@ async function createCompleteAppleProjection() {
}
describe("Apple application projection", () => {
it("keeps a case-colliding real IPA inventory partial", async () => {
it("retains complete traversal and case-collision limits for a real IPA", async () => {
const root = await createTestTempDirectory("rea-apple-case-collision-");
const path = join(root, "CaseCollision.ipa");
const writer = new ZipWriter(new Uint8ArrayWriter());
@@ -93,7 +93,7 @@ describe("Apple application projection", () => {
await runProviderAnalysis(path, "inventory_artifact", {}),
);
expect(inventory.normalized_result).toMatchObject({
coverage_status: "partial",
coverage_status: "complete",
});
const result = projectAppleApplicationEvidence({
inventory_evidence: [inventory],
@@ -103,11 +103,11 @@ describe("Apple application projection", () => {
);
expect(projection.coverage).toEqual({
status: "partial",
status: "complete-within-inventory",
inventory_complete: true,
});
expect(projection.limitations).toContain(
"Source inventory coverage is partial; absence is unknown.",
expect(projection.limitations.join(" ")).toContain(
"case-insensitive destination",
);
});
@@ -2,6 +2,7 @@ import { chmod, mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { fragmentInventoryEvidence } from "../../fixtures/artifactEvidence.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
@@ -77,7 +78,11 @@ describe("leaf artifact comparison", () => {
// Persisted inventory Evidence predates coverage_status. The known leaf
// notice remains complete when normalized at the inventory boundary.
const parsed = artifactInventoryResultSchema.parse(left.normalized_result);
const { coverage_status: _coverageStatus, ...legacyInventory } = parsed;
const {
coverage: _coverage,
coverage_status: _coverageStatus,
...legacyInventory
} = parsed;
const legacy = createEvidence(
{
path: left.subject!.local_path,
@@ -157,7 +162,7 @@ describe("artifact inventory coverage", () => {
const graph = artifactInventoryResultSchema.parse(
complete.normalized_result,
);
const partial = createEvidence(
const contradictory = createEvidence(
{
path: complete.subject!.local_path,
sha256: complete.subject!.digest.sha256,
@@ -168,6 +173,29 @@ describe("artifact inventory coverage", () => {
operation: "inventory_artifact",
parameters: {},
result: jsonValueSchema.parse({ ...graph, coverage_status: "partial" }),
confidence: "derived",
authority: "shipped-artifact",
},
);
expect(() => parseArtifactInventoryEvidence(contradictory)).toThrow(
"Artifact inventory has conflicting coverage declarations",
);
const { coverage: _coverage, ...legacyStatusGraph } = graph;
const partial = createEvidence(
{
path: complete.subject!.local_path,
sha256: complete.subject!.digest.sha256,
format: complete.subject!.format,
},
PROVIDER,
{
operation: "inventory_artifact",
parameters: {},
result: jsonValueSchema.parse({
...legacyStatusGraph,
coverage_status: "partial",
}),
confidence: "observed",
authority: "shipped-artifact",
},
@@ -180,7 +208,8 @@ describe("artifact inventory coverage", () => {
summary: { unchanged: 0, unknown: 1 },
});
const { coverage_status: _coverageStatus, ...legacyGraph } = graph;
const { coverage_status: _coverageStatus, ...legacyGraph } =
legacyStatusGraph;
const unknownLegacy = createEvidence(
{
path: complete.subject!.local_path,
@@ -219,6 +248,7 @@ describe("artifact inventory coverage", () => {
const fragmentGraph = artifactInventoryResultSchema.parse(
fragment.normalized_result,
);
const { coverage: _coverage, ...legacyFragmentGraph } = fragmentGraph;
const mixed = createEvidence(
{
path: fragment.subject!.local_path,
@@ -230,7 +260,7 @@ describe("artifact inventory coverage", () => {
operation: "inventory_artifact",
parameters: fragment.parameters,
result: jsonValueSchema.parse({
...fragmentGraph,
...legacyFragmentGraph,
coverage_status: "partial",
}),
confidence: "derived",
@@ -239,7 +269,7 @@ describe("artifact inventory coverage", () => {
);
expect(() =>
parseArtifactInventoryEvidence([firstFragment, mixed]),
).toThrow("Artifact inventory pages disagree on coverage status");
).toThrow("Artifact inventory pages do not share one coverage declaration");
});
});
@@ -314,6 +344,61 @@ describe("artifact comparison", () => {
});
describe("artifact comparison completeness", () => {
it("does not infer child changes from root-only coverage", async () => {
const root = await createTestTempDirectory("rea-artifact-root-coverage-");
const leftPath = join(root, "left.app");
const rightPath = join(root, "right.app");
await Promise.all([mkdir(leftPath), mkdir(rightPath)]);
await Promise.all([
writeFile(join(leftPath, "left-only.txt"), "left"),
writeFile(join(rightPath, "right-only.txt"), "right"),
]);
const [left, right] = await Promise.all([
observe(leftPath),
observe(rightPath),
]);
const rootOnly = (evidence: Awaited<ReturnType<typeof observe>>) => {
const inventory = artifactInventoryResultSchema.parse(
evidence.normalized_result,
);
return createEvidence(
{
path: evidence.subject?.local_path ?? "",
sha256: inventory.manifest.root_sha256,
format: inventory.manifest.root_format,
},
PROVIDER,
{
operation: "inventory_artifact",
parameters: {},
result: jsonValueSchema.parse({
...inventory,
coverage: { scope: "root", status: "complete" },
}),
confidence: "derived",
authority: "shipped-artifact",
},
);
};
const compared = compareArtifacts(rootOnly(left), rootOnly(right));
expect(compared.status).toBe("unknown");
expect(compared.summary).toMatchObject({ added: 0, removed: 0 });
expect(
compared.changes
.filter(({ logical_path }) => logical_path !== ".")
.map(({ logical_path, classification }) => ({
logical_path,
classification,
})),
).toEqual([
{ logical_path: "left-only.txt", classification: "unknown" },
{ logical_path: "right-only.txt", classification: "unknown" },
]);
expect(compared.limitations).toContain(
"Container entry coverage is unavailable for child paths.",
);
});
it("compares every graph member for inventories larger than 500 entries", async () => {
const root = await createTestTempDirectory("rea-artifact-pages-");
const entryCount = 501;
@@ -358,7 +443,9 @@ describe("artifact comparison completeness", () => {
changes: [],
});
}, 15_000);
});
describe("artifact comparison fragment integrity", () => {
it("assembles real inventory fragments and retains every citation", async () => {
const parent = await createTestTempDirectory("rea-artifact-fragments-");
const leftPath = join(parent, "left.app");
@@ -415,6 +502,30 @@ describe("artifact comparison completeness", () => {
evidence_links: citations,
})),
});
const fragment = leftFragments[0];
if (fragment === undefined) throw new Error("Expected inventory fragments");
const conflictingScope = createEvidence(
{
path: leftPath,
sha256: left.subject?.digest.sha256 ?? "",
format: "directory",
},
PROVIDER,
{
operation: "inventory_artifact",
parameters: {},
result: jsonValueSchema.parse({
...artifactInventoryResultSchema.parse(fragment.normalized_result),
coverage: { scope: "root", status: "complete" },
}),
},
);
expect(() =>
compareArtifacts(
[conflictingScope, ...leftFragments.slice(1)],
rightFragments,
),
).toThrow(/coverage declaration/u);
}, 15_000);
it("rejects non-inventory and tampered Evidence", async () => {
@@ -445,3 +556,90 @@ describe("artifact comparison completeness", () => {
);
});
});
describe("ZIP non-entry coverage", () => {
it("retains pre-directory APK block changes and compares historical scope descriptions", async () => {
const root = await createTestTempDirectory("rea-apk-block-compare-");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("classes.dex", new TextReader("unchanged entry"));
const zip = Buffer.from(await writer.close());
const eocd = zip.length - 22;
expect(zip.readUInt32LE(eocd)).toBe(0x06054b50);
const directory = zip.readUInt32LE(eocd + 16);
// APK Signing Block framing with one opaque padding pair, not a verified signature.
// https://source.android.com/docs/security/features/apksigning/v2#apk-signing-block
const block = Buffer.alloc(48);
block.writeBigUInt64LE(40n, 0);
block.writeBigUInt64LE(8n, 8);
block.writeUInt32LE(0x42726577, 16);
block.writeBigUInt64LE(40n, 24);
block.write("APK Sig Block 42", 32, "ascii");
const paths = [join(root, "before.apk"), join(root, "after.apk")];
for (const [index, path] of paths.entries()) {
block.writeUInt32LE(index, 20);
const apk = Buffer.concat([
zip.subarray(0, directory),
block,
zip.subarray(directory),
]);
apk.writeUInt32LE(directory + block.length, eocd + block.length + 16);
await writeFile(path, apk);
}
const left = await observe(paths[0]!);
const right = await observe(paths[1]!);
const inventory = artifactInventoryResultSchema.parse(
left.normalized_result,
);
expect(inventory.limitations).toContain(
"ZIP inventory lists central-directory entries only. Non-entry bytes, including an APK Signing Block before the central directory or a ZIP comment after it, are not occurrences.",
);
expect(
inventory.occurrences.map(({ logical_path }) => logical_path).sort(),
).toEqual([".", "classes.dex"]);
expect(compareArtifacts(left, right)).toMatchObject({
status: "changed",
summary: { changed: 1, unchanged: 1, unknown: 0 },
changes: [
expect.objectContaining({ logical_path: ".", dimensions: ["content"] }),
],
});
const {
coverage: _coverage,
coverage_status: _coverageStatus,
...legacyInventory
} = inventory;
const withLimitation = (limitation: string) =>
createEvidence(
{
path: paths[0]!,
sha256: inventory.manifest.root_sha256,
format: "apk",
},
PROVIDER,
{
operation: "inventory_artifact",
parameters: {},
result: jsonValueSchema.parse({
...legacyInventory,
limitations: [limitation],
}),
confidence: "observed",
authority: "shipped-artifact",
},
);
const historical = withLimitation(
"ZIP inventory lists central-directory entries only. Bytes after the central directory, including an APK Signing Block or a ZIP comment, are not occurrences.",
);
expect(compareArtifacts(historical, left)).toMatchObject({
status: "unchanged",
summary: { unchanged: 2, unknown: 0 },
changes: [],
});
expect(
compareArtifacts(
withLimitation("ZIP entry bytes could not be read."),
left,
).status,
).toBe("unknown");
});
});
@@ -52,3 +52,22 @@ it("rejects a root path replaced between its initial stat and open", async () =>
message: `Root artifact changed before inventory: ${path}`,
});
});
it("keeps unavailable container traversal distinct from observed root bytes", async () => {
const root = await createTestTempDirectory("rea-artifact-root-scope-");
const path = join(root, "fixture.pkg");
// The recognized XAR prefix selects PKG inventory; no child decoder is installed.
await writeFile(path, Buffer.from("xar!fixture"));
const inventory = await inventoryArtifact(path);
expect(inventory.manifest).toMatchObject({
root_format: "pkg",
node_count: 1,
occurrence_count: 1,
edge_count: 0,
});
expect(inventory.occurrences[0]?.hash_status).toBe("verified");
expect(inventory.coverage).toEqual({
scope: "container-entries",
status: "unknown",
});
});
@@ -26,6 +26,7 @@ import {
thinMach,
} from "../../../src/domain/binaryTarget.fixture.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { parseExecutableHeader } from "../../../src/domain/binaryTarget.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
@@ -424,6 +425,65 @@ describe("binary target I/O: explicit kinds and executable headers", () => {
});
});
it("extracts CodeView RSDS debug metadata from a PE target", async () => {
const directory = await createTestTempDirectory("rea-target-");
const path = join(directory, "symbols.exe");
await writeFile(
path,
pe(0x8664, 64, 0x0002, false, {
type: "RSDS",
pdbPath: "C:\\build\\test.pdb",
guid: "12345678-abcd-ef01-2345-6789abcdef01",
age: 3,
}),
);
const result = await parseBinaryTarget(path, {
cwd: directory,
hostArchitecture: "x64",
});
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
expect(result.value).toMatchObject({
format: "pe",
architecture: "x86_64",
codeView: {
pdbPath: "C:\\build\\test.pdb",
pdbFileName: "test.pdb",
guid: "12345678-abcd-ef01-2345-6789abcdef01",
age: 3,
},
});
});
it("extracts CodeView NB10 debug metadata from a PE target", async () => {
const directory = await createTestTempDirectory("rea-target-");
const path = join(directory, "legacy.exe");
await writeFile(
path,
pe(0x014c, 64, 0x0002, false, {
type: "NB10",
pdbPath: "D:\\old\\legacy.pdb",
age: 1,
}),
);
const result = await parseBinaryTarget(path, {
cwd: directory,
hostArchitecture: "ia32",
});
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
expect(result.value).toMatchObject({
format: "pe",
architecture: "x86",
codeView: {
pdbPath: "D:\\old\\legacy.pdb",
pdbFileName: "legacy.pdb",
guid: null,
age: 1,
},
});
});
it("refuses a truncated Mach-O header before any provider sees it", async () => {
const directory = await createTestTempDirectory("rea-target-");
const path = join(directory, "truncated");
@@ -884,3 +944,43 @@ it.each([
});
},
);
describe("binary target I/O: PE CodeView header ranges", () => {
it.each(["RSDS", "NB10"] as const)(
"reads bounded %s header debug records and rejects unfinished names",
async (type) => {
const directory = await createTestTempDirectory("rea-target-");
const path = join(directory, "header-symbols.exe");
const bytes = pe(0x8664, 64, 0x0002, false, {
type,
pdbPath: "header.pdb",
});
const optionalHeader = 64 + 24;
bytes.writeUInt32LE(512, optionalHeader + 60);
bytes.copy(bytes, 384, 512);
bytes.writeUInt32LE(384, optionalHeader + 112 + 6 * 8);
bytes.writeUInt32LE(412, 384 + 20);
bytes.writeUInt32LE(0, 384 + 24);
for (const complete of [true, false]) {
if (!complete) {
const dataSize = bytes.readUInt32LE(384 + 16);
bytes[412 + dataSize - 1] = 0x61;
}
await writeFile(path, bytes);
const resolved = await parseBinaryTarget(path, {
hostArchitecture: "x64",
});
const buffered = parseExecutableHeader(bytes, "x64");
if (!resolved.ok) throw resolved.error;
if (!buffered.ok) throw new Error(buffered.error);
for (const value of [resolved.value, buffered.value]) {
if (complete)
expect(value).toMatchObject({
codeView: { pdbPath: "header.pdb" },
});
else expect(value).not.toHaveProperty("codeView");
}
}
},
);
});
@@ -0,0 +1,247 @@
import { execFileSync } from "node:child_process";
import { chmod, readFile, readdir, writeFile } from "node:fs/promises";
import { delimiter, join } from "node:path";
import { describe, expect, it } from "vitest";
import { parse } from "yaml";
import { z } from "zod";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const repository = process.cwd();
const actionPath = join(repository, ".github/actions/npm-cache/action.yml");
const readAction = async () =>
z
.object({
outputs: z.record(z.string(), z.object({ value: z.string() })),
runs: z.object({
steps: z.array(
z.object({
id: z.string().optional(),
if: z.string().optional(),
uses: z.string().optional(),
with: z.record(z.string(), z.string()).optional(),
run: z.string().optional(),
env: z.record(z.string(), z.string()).optional(),
}),
),
}),
})
.parse(parse(await readFile(actionPath, "utf8")));
const readWorkflows = async () => {
const directory = join(repository, ".github/workflows");
const files = (await readdir(directory)).filter((file) =>
/\.ya?ml$/u.test(file),
);
return Promise.all(
files.map(async (file) => ({
file,
workflow: z
.object({
jobs: z
.record(
z.string(),
z.object({
steps: z.array(z.record(z.string(), z.unknown())).optional(),
}),
)
.optional(),
})
.parse(parse(await readFile(join(directory, file), "utf8"))),
})),
);
};
describe("hosted npm download-cache policy", () => {
it("only allows shared writes for trusted original default-branch events", async () => {
const action = await readAction();
const policy = action.runs.steps.find((step) => step.id === "context");
const command = z.string().parse(policy?.run);
const outputDirectory = await createTestTempDirectory(
"rea-ci-cache-policy-",
);
const npmStub = join(outputDirectory, "npm");
await writeFile(
npmStub,
String.raw`#!/bin/sh
printf '%s\n' 'C:\Users\runner with spaces\AppData\Local\npm-cache'
`,
);
await chmod(npmStub, 0o755);
for (const [event, ref, defaultBranch, expected] of [
["push", "refs/heads/main", "main", "true"],
["schedule", "refs/heads/main", "main", "true"],
["workflow_dispatch", "refs/heads/main", "main", "true"],
["push", "refs/heads/stable", "stable", "true"],
["pull_request", "refs/heads/main", "main", "false"],
["pull_request_target", "refs/heads/main", "main", "false"],
["workflow_call", "refs/heads/main", "main", "false"],
["push", "refs/heads/feature/cache", "main", "false"],
["push", "refs/heads/main", "stable", "false"],
["push", "refs/heads/main", "", "false"],
]) {
const outputPath = join(
outputDirectory,
`policy-${Date.now()}-${Math.random()}`,
);
execFileSync("bash", ["-euo", "pipefail", "-c", command], {
env: {
...process.env,
PATH: `${outputDirectory}${delimiter}${process.env.PATH ?? ""}`,
GITHUB_EVENT_NAME: event,
GITHUB_REF: ref,
GITHUB_OUTPUT: outputPath,
DEFAULT_BRANCH: defaultBranch,
LOCKFILES_HASH: "lock-hash",
RUNNER_OS: "Windows",
},
});
const output = await readFile(outputPath, "utf8");
expect(output).toContain(`can-save=${expected}\n`);
expect(output).toContain(
`path=${String.raw`C:\Users\runner with spaces\AppData\Local\npm-cache`}\n`,
);
expect(output).toContain(
`key=npm-download-Windows-${process.arch}-lock-hash\n`,
);
}
});
it("uses a lockfile-, npmrc-, OS-, and runtime-architecture-scoped download cache", async () => {
const action = await readAction();
const policy = action.runs.steps.find((step) => step.id === "context");
const restoreAndSave = action.runs.steps.find((step) =>
step.uses?.startsWith("actions/cache@"),
);
const restoreOnly = action.runs.steps.find((step) =>
step.uses?.startsWith("actions/cache/restore@"),
);
expect(action.outputs["can-save"]?.value).toBe(
"${{ steps.context.outputs.can-save }}",
);
expect(action.outputs.path?.value).toBe(
"${{ steps.context.outputs.path }}",
);
expect(policy?.env?.DEFAULT_BRANCH).toBe(
"${{ github.event.repository.default_branch }}",
);
expect(policy?.env?.LOCKFILES_HASH).toBe(
"${{ hashFiles('package-lock.json', 'npm-shrinkwrap.json', '.npmrc') }}",
);
expect(policy?.run).toContain(
'cache_key="npm-download-${RUNNER_OS}-${runtime_arch}-${LOCKFILES_HASH}"',
);
expect(restoreAndSave?.uses).toBe(
"actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830",
);
expect(restoreAndSave?.if).toBe("steps.context.outputs.can-save == 'true'");
expect(restoreOnly?.uses).toBe(
"actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830",
);
expect(restoreOnly?.if).toBe("steps.context.outputs.can-save != 'true'");
expect(restoreAndSave?.with?.path).toBe(
"${{ steps.context.outputs.path }}",
);
expect(restoreOnly?.with?.path).toBe(restoreAndSave?.with?.path);
expect(restoreAndSave?.with?.key).toBe("${{ steps.context.outputs.key }}");
expect(restoreOnly?.with?.key).toBe(restoreAndSave?.with?.key);
expect(restoreAndSave?.with).not.toHaveProperty("restore-keys");
expect(restoreOnly?.with).not.toHaveProperty("restore-keys");
});
it("replaces every inline setup-node npm cache immediately and preserves conditions", async () => {
const workflows = await readWorkflows();
let npmCacheSteps = 0;
for (const { file, workflow } of workflows) {
const source = await readFile(
join(repository, ".github/workflows", file),
"utf8",
);
expect(source).not.toMatch(/^\s+cache:\s*npm\s*$/mu);
for (const [jobName, job] of Object.entries(workflow.jobs ?? {})) {
const steps = job.steps ?? [];
for (let index = 0; index < steps.length; index++) {
const step = steps[index];
if (step?.uses !== "./.github/actions/npm-cache") continue;
npmCacheSteps++;
expect(step.id).toBe("npm-cache");
const setup = steps[index - 1];
expect(
typeof setup?.uses === "string" &&
setup.uses.startsWith("actions/setup-node@"),
`${file}:${jobName} npm cache action must immediately follow setup-node`,
).toBe(true);
expect(step.if).toBe(setup?.if);
expect(setup?.with).not.toHaveProperty("cache", "npm");
const npmCiIndex = steps.findIndex(
(candidate, candidateIndex) =>
candidateIndex > index && candidate.run === "npm ci",
);
expect(
npmCiIndex,
`${file}:${jobName} retains npm ci after cache`,
).toBeGreaterThan(index);
}
}
}
expect(npmCacheSteps).toBeGreaterThan(0);
});
});
it("shares static task snapshots only after validation using the npm cache owner's write authority", async () => {
const workflows = await readWorkflows();
const ci = workflows.find(({ file }) => file === "ci.yml");
const steps = ci?.workflow.jobs?.static?.steps ?? [];
const restore = steps.find((step) => step.id === "static-cache");
const save = steps.find(
(step) => step.name === "Save validated static task cache",
);
expect(restore?.uses).toBe(
"actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830",
);
expect(restore?.if).toBe("needs.changes.outputs.code == 'true'");
expect(restore?.with).toMatchObject({ path: ".turbo/cache/" });
expect(save?.uses).toBe(
"actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830",
);
expect(save?.if).toContain("success()");
expect(save?.if).toContain("steps.npm-cache.outputs.can-save == 'true'");
expect(save?.with).toEqual({
path: ".turbo/cache/",
key: "${{ steps.static-cache.outputs.cache-primary-key }}",
});
expect(steps.indexOf(save!)).toBeGreaterThan(
steps.findIndex((step) => step.run === "npm run test:python"),
);
});
it("bounds the rolling static snapshot with Turbo age and size eviction", async () => {
const turbo = z
.object({
cacheMaxAge: z.string(),
cacheMaxSize: z.string(),
})
.parse(JSON.parse(await readFile(join(repository, "turbo.json"), "utf8")));
// The static job restores the previous snapshot by prefix and saves the
// whole .turbo/cache directory again. Without local eviction every main
// commit carries all historical entries into a new immutable GitHub cache,
// growing transfers toward the 10 GB repository limit.
expect(turbo.cacheMaxAge).toMatch(/^[1-9]\d*(s|m|h|d|w)$/u);
expect(turbo.cacheMaxAge).not.toBe("0");
const size = /^(\d+(?:\.\d+)?)(MB|GB|TB)$/iu.exec(turbo.cacheMaxSize);
expect(size, "cacheMaxSize must use an explicit MB/GB/TB budget").not.toBe(
null,
);
const value = Number(size?.[1] ?? "0");
const unit = (size?.[2] ?? "MB").toUpperCase();
const megabytes =
unit === "TB" ? value * 1024 * 1024 : unit === "GB" ? value * 1024 : value;
expect(megabytes).toBeGreaterThan(0);
expect(megabytes).toBeLessThanOrEqual(1024);
});
@@ -215,6 +215,146 @@ it("does not charge a documentation PR for unrelated implementation updates on m
});
});
it.each([
"src/gdb/GdbSessionManager.ts",
"src/rizin/RizinDebugSessionManager.ts",
"src/cutter/CutterBridgeClient.ts",
"src/objdump/ObjdumpCommand.ts",
"tests/boundary/providers/GdbSessionManagerCoverage.test.ts",
"tests/boundary/providers/GdbCommandQueue.test.ts",
"tests/boundary/providers/RizinDebugSessionCoverage.part3.test.ts",
"tests/boundary/providers/RizinCommandTimeout.test.ts",
"tests/boundary/providers/RizinTimeoutEvidence.test.ts",
"tests/boundary/providers/GdbSessionReviewRegressions.test.ts",
"tests/boundary/providers/gdbTestHelpers.ts",
"tests/boundary/providers/RizinDebugSessionReviewRegressions.test.ts",
"tests/boundary/mcp/gdbCancellationMcp.test.ts",
"tests/boundary/mcp/rizinDebuggerCancellationMcp.test.ts",
"tests/composition/reverseEngineeringAdmission.test.ts",
"tests/support/reverseEngineeringMcpHarness.ts",
"tests/support/reverseEngineeringCompositionEdgeCases.ts",
"tests/support/reverseEngineeringCompositionFixtures.ts",
"tests/support/reverseEngineeringService.ts",
"tests/support/ownedRizinCommandEvidenceTests.ts",
"tests/support/reverseDebuggerMcpTestHelpers.ts",
"tests/boundary/cli/gdbStartupCleanupCli.test.ts",
"vitest.reverse-tools.config.ts",
"vitest.reverse-tools-semantics.config.ts",
"stryker.config.mjs",
"stryker.semantics.config.mjs",
"tsconfig.reverse-tools-mutation.json",
"scripts/prepare-reverse-tools-mutation.mjs",
"scripts/lib/reverse-tools-mutation-targets.mjs",
])(
"selects the reverse-tool coverage and mutation gate for %s",
async (path) => {
const { directory, base } = await fixture();
const head = await change(directory, [path]);
expect(await classify(directory, base, head)).toMatchObject({
code: true,
reverse_tools: true,
});
},
);
const reverseToolsVitestConfig = await readFile(
new URL("../../../vitest.reverse-tools.config.ts", import.meta.url),
"utf8",
);
const reverseToolsVitestInputs = [
...reverseToolsVitestConfig.matchAll(/"((?:\.\/)?(?:src|tests)\/[^"]+)"/gu),
].flatMap((match) =>
match[1] === undefined ? [] : [match[1].replace(/^\.\//u, "")],
);
const reverseToolsMutationConfig = JSON.parse(
await readFile(
new URL("../../../tsconfig.reverse-tools-mutation.json", import.meta.url),
"utf8",
),
) as { include: string[] };
const reverseToolsInputs = [
...new Set([
...reverseToolsVitestInputs,
...reverseToolsMutationConfig.include.map((path) =>
path.replace(/^\.\//u, ""),
),
]),
];
it.each(reverseToolsInputs)(
"selects the reverse-tool quality gate for configured input %s",
async (path) => {
const { directory, base } = await fixture();
const head = await change(directory, [path]);
expect(await classify(directory, base, head)).toMatchObject({
code: true,
reverse_tools: true,
});
},
);
it("requires the reverse-tool gate when its scope is selected", async () => {
const workflow = parse(
await readFile(
new URL("../../../.github/workflows/ci.yml", import.meta.url),
"utf8",
),
);
expect(workflow.jobs["reverse-tools-quality"].if).toBe(
"needs.changes.outputs.reverse_tools == 'true'",
);
expect(workflow.jobs.required.needs).toContain("reverse-tools-quality");
const { CI_FLAGS } = await loadScopes();
const outputs = {
...Object.fromEntries(CI_FLAGS.map((flag) => [flag, "false"])),
tier: "fast",
reverse_tools: "true",
};
const command = new URL("../../../scripts/ci/required.mjs", import.meta.url)
.pathname;
await expect(
execFileAsync(process.execPath, [command], {
env: {
...process.env,
CI_JOBS: JSON.stringify({
changes: { result: "success", outputs },
static: { result: "success" },
test: { result: "success" },
"reverse-tools-quality": { result: "skipped" },
}),
},
}),
).rejects.toMatchObject({ code: 1 });
await expect(
execFileAsync(process.execPath, [command], {
env: {
...process.env,
CI_JOBS: JSON.stringify({
changes: { result: "success", outputs },
static: { result: "success" },
test: { result: "success" },
"reverse-tools-quality": { result: "failure" },
}),
},
}),
).rejects.toMatchObject({ code: 1 });
await expect(
execFileAsync(process.execPath, [command], {
env: {
...process.env,
CI_JOBS: JSON.stringify({
changes: { result: "success", outputs },
static: { result: "success" },
test: { result: "success" },
"reverse-tools-quality": { result: "success" },
}),
},
}),
).resolves.toMatchObject({
stdout: expect.stringContaining("Every selected CI lane passed"),
});
});
it.each([
"src/README.md",
"README.md.ts",
@@ -0,0 +1,435 @@
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { normalizeWorkflowRun } from "../../../scripts/ci/workflow-run.mjs";
import {
readStaticCheckArtifact,
selectStaticCheckArtifact,
} from "../../../scripts/ci/artifacts.mjs";
import {
classifyFailure,
createGitHubApi,
reportCiFailures,
type CiRun,
type CiJob,
type FailureReportApi,
} from "../../../scripts/ci/failure-report.mjs";
const sha = (digit: string) => digit.repeat(40);
const diagnostic = {
kind: "lint",
path: "src/example.ts",
code: "no-debugger",
message: "Unexpected debugger statement.",
severity: "error",
} as const;
const context = (
sourceSha: string,
taskHash = "a".repeat(16),
prHeadSha?: string,
) => ({
version: 1 as const,
sourceSha,
...(prHeadSha ? { prHeadSha } : {}),
sourceClean: true,
nodeVersion: "v24.18.0",
npmVersion: "11.16.0",
turboVersion: "2.11.7",
platform: "linux",
architecture: "x64",
taskHashes: { "lint:built": taskHash },
});
const run = (overrides: Partial<CiRun> = {}) =>
normalizeWorkflowRun({
id: 10,
run_attempt: 1,
status: "completed",
conclusion: "failure",
event: "pull_request",
path: ".github/workflows/ci.yml@main",
head_sha: sha("a"),
head_branch: "feature",
repository: { full_name: "owner/rea" },
pull_requests: [
{ base: { sha: sha("b"), repo: { full_name: "owner/rea" } } },
],
...overrides,
});
const job = (overrides: Partial<CiJob> = {}) => ({
name: "Static checks",
status: "completed",
conclusion: "failure",
...overrides,
});
const comparison = (): Parameters<typeof classifyFailure>[0] => ({
repository: "owner/rea",
defaultBranch: "main",
run: run(),
job: job(),
diagnostics: [diagnostic],
context: context(sha("a")),
mainRun: run({
id: 20,
event: "push",
head_sha: sha("c"),
head_branch: "main",
pull_requests: [],
}),
mainJob: job(),
mainDiagnostics: [diagnostic],
mainContext: context(sha("c")),
executionSourcesVerified: true,
ancestry: { status: "ahead", mergeBaseSha: sha("c") },
blobs: { "src/example.ts": true },
});
it("attributes only an identical structured lint failure with matching task, context, ancestry, and source blob", () => {
const result = classifyFailure(comparison());
expect(result).toEqual({
classification: "matching-main-diagnostics",
reason:
"supported_diagnostics_match_failed_task_and_source_on_verified_main_ancestor",
});
});
it.each([
["task hash", { mainContext: context(sha("c"), "b".repeat(16)) }],
["dirty source", { context: { ...context(sha("a")), sourceClean: false } }],
[
"toolchain",
{ mainContext: { ...context(sha("c")), turboVersion: "other" } },
],
[
"source sha",
{ context: context(sha("d")), executionSourcesVerified: false },
],
[
"diagnostic",
{ mainDiagnostics: [{ ...diagnostic, message: "different message" }] },
],
["content", { blobs: { "src/example.ts": false } }],
["ancestry", { ancestry: { status: "diverged", mergeBaseSha: sha("e") } }],
["canceled job", { job: job({ conclusion: "cancelled" }) }],
["not a static job", { job: job({ name: "Test shard (1)" }) }],
] as const)("does not attribute on mismatched %s", (_label, overrides) => {
const result = classifyFailure({ ...comparison(), ...overrides });
expect(result.classification).toBe("unknown");
});
it.each([
[{}, "diagnostic_source_blob_identity_unavailable"],
[
{ "src/example.ts": false },
"diagnostic_source_content_not_identical_at_main_and_tested_base",
],
] as const)(
"distinguishes unavailable blob identity from verified differences (%s)",
(blobs, reason) => {
expect(classifyFailure({ ...comparison(), blobs })).toEqual({
classification: "unknown",
reason,
});
},
);
it("writes informational JSON and Markdown from the supplied manifest using only read API calls", async () => {
const directory = await createTestTempDirectory("rea-ci-failure-test-");
const calls: string[] = [];
const manifest = {
repository: "owner/rea",
truncation: [],
coverage: { exhaustive: false },
runs: [
{
id: 10,
runAttempt: 1,
workflow: "CI",
event: "pull_request",
conclusion: "failure",
status: "collected",
},
{
id: 11,
runAttempt: 1,
workflow: "CI",
event: "pull_request",
conclusion: "success",
status: "collected",
},
],
};
const failedRun = run();
const api: FailureReportApi = {
async getRun(_repository, id) {
calls.push(`run:${id}`);
return failedRun;
},
async getJobs(_repository, id) {
calls.push(`jobs:${id}`);
return [{ ...job(), run_id: Number(id), run_attempt: 1 }];
},
async getStaticEvidence() {
calls.push("artifact");
return null;
},
async getAncestry() {
throw new Error("must not compare without evidence");
},
async verifyExecutionSource() {
throw new Error("must not verify source without evidence");
},
async getBlobIdentity() {
throw new Error("must not inspect blobs without evidence");
},
};
const report = await reportCiFailures({
repository: "owner/rea",
defaultBranch: "main",
batchManifest: manifest,
api,
outputDirectory: directory,
});
expect(calls).toEqual(["run:10", "jobs:10", "artifact"]);
expect(report).toMatchObject({
informationalOnly: true,
gateEffect: "none; this report never changes CI conclusions",
counts: { unknown: 1 },
});
const json = JSON.parse(
await readFile(join(directory, "report.json"), "utf8"),
);
const markdown = await readFile(join(directory, "report.md"), "utf8");
expect(json.failures[0]).toMatchObject({
classification: "unknown",
reason: "no_matching_verified_main_failure",
});
expect(markdown).toContain("Informational only");
expect(markdown).toContain("Unknown means evidence was incomplete");
});
it.each([
[22, false],
[6, true],
] as const)(
"finds verified main evidence after %s newer PR runs (extra incorrect main hint: %s)",
async (prCount, incorrectMainHints) => {
const directory = await createTestTempDirectory("rea-ci-main-proof-");
const mainSha = sha("c");
const prHeadSha = sha("a");
const mergeSha = sha("d");
const mainRun = run({
id: 20,
event: "push",
head_sha: mainSha,
head_branch: "main",
pull_requests: [],
});
const prRun = run({
head_sha: prHeadSha,
pull_requests: [
{ base: { sha: mainSha, repo: { full_name: "owner/rea" } } },
],
});
const evidence = (sourceSha: string, prHead?: string) => ({
context: context(sourceSha, undefined, prHead),
diagnostics: [diagnostic],
});
const lookups: number[] = [];
const api: FailureReportApi = {
async getRun(_repository, id) {
lookups.push(Number(id));
return Number(id) === 20 ? mainRun : { ...prRun, id };
},
async getJobs(_repository, id) {
return [{ ...job(), run_id: Number(id), run_attempt: 1 }];
},
async getStaticEvidence(_repository, selectedRun) {
return Number(selectedRun.id) === 20
? evidence(mainSha)
: evidence(mergeSha, prHeadSha);
},
async verifyExecutionSource(_repository, selectedRun, sourceContext) {
return selectedRun.event === "pull_request"
? sourceContext.sourceSha === mergeSha &&
sourceContext.prHeadSha === selectedRun.head_sha
: sourceContext.sourceSha === selectedRun.head_sha;
},
async getAncestry() {
return { status: "ahead", mergeBaseSha: mainSha };
},
async getBlobIdentity() {
return { "src/example.ts": true };
},
};
const result = await reportCiFailures({
repository: "owner/rea",
defaultBranch: "main",
batchManifest: {
repository: "owner/rea",
runs: [
...(incorrectMainHints
? [
{
id: 30,
runAttempt: 1,
workflow: "CI",
event: "push",
headBranch: "main",
conclusion: "failure",
status: "collected",
},
]
: []),
...Array.from({ length: prCount }, (_, index) => ({
id: 100 + index,
runAttempt: 1,
workflow: "CI",
event: "pull_request",
headBranch: "feature",
conclusion: "failure",
status: "collected",
})),
{
id: 20,
runAttempt: 1,
workflow: "CI",
event: "push",
headBranch: "main",
conclusion: "failure",
status: "collected",
},
],
},
api,
outputDirectory: directory,
});
expect(result.failures[0]).toMatchObject({
runId: 100,
classification: "matching-main-diagnostics",
reason:
"supported_diagnostics_match_failed_task_and_source_on_verified_main_ancestor",
});
expect(lookups).toHaveLength(
Math.min(prCount, 20) + 1 + Number(incorrectMainHints),
);
expect(lookups[0]).toBe(incorrectMainHints ? 30 : 20);
expect(new Set(lookups).size).toBe(lookups.length);
expect(result.boundedInput.mainCandidateRuns).toBe(1);
expect(result.failures).toHaveLength(Math.min(prCount, 20));
},
);
it("proves checkout merge parents in base-then-PR-head order and rejects false identities", async () => {
const baseSha = sha("b");
const headSha = sha("a");
const mergeSha = sha("c");
const prRun = run({
head_sha: headSha,
pull_requests: [
{ base: { sha: baseSha, repo: { full_name: "owner/rea" } } },
],
});
let parents = [baseSha, headSha];
const calls: string[] = [];
const api = createGitHubApi({
token: "fixture-token",
apiRequest: async (_method, endpoint) => {
calls.push(endpoint);
return {
sha: mergeSha,
parents: parents.map((parentSha) => ({ sha: parentSha })),
};
},
});
const mergeContext = context(mergeSha, undefined, headSha);
expect(
await api.verifyExecutionSource("owner/rea", prRun, mergeContext),
).toBe(true);
expect(calls).toEqual([`repos/owner/rea/commits/${mergeSha}`]);
parents = [headSha, baseSha];
expect(
await api.verifyExecutionSource("owner/rea", prRun, mergeContext),
).toBe(false);
expect(
await api.verifyExecutionSource("owner/rea", prRun, {
...mergeContext,
prHeadSha: sha("e"),
}),
).toBe(false);
});
it("uses static artifacts only when listing is complete, unique, and tied to this run attempt", () => {
const artifact = {
id: 12,
name: "static-check-reports",
expired: false,
workflow_run: { id: 10, head_sha: sha("a") },
};
const runRecord = { id: 10, head_sha: sha("a") };
expect(
selectStaticCheckArtifact(
{ total_count: 1, artifacts: [artifact] },
runRecord,
1,
),
).toBe(artifact);
expect(
selectStaticCheckArtifact(
{ total_count: 2, artifacts: [artifact] },
runRecord,
1,
),
).toBeNull();
expect(
selectStaticCheckArtifact(
{ total_count: 2, artifacts: [artifact, artifact] },
runRecord,
1,
),
).toBeNull();
expect(
selectStaticCheckArtifact(
{
total_count: 1,
artifacts: [
{ ...artifact, workflow_run: { id: 11, head_sha: sha("a") } },
],
},
runRecord,
1,
),
).toBeNull();
expect(
selectStaticCheckArtifact(
{ total_count: 1, artifacts: [artifact] },
runRecord,
2,
),
).toBeNull();
});
it("rejects artifact redirects that could send the bearer token to a non-HTTPS host", async () => {
const calls: string[] = [];
await expect(
readStaticCheckArtifact({
repository: "owner/rea",
artifactId: 12,
token: "fixture-token",
fetchImpl: (async (url: string | URL | Request) => {
calls.push(String(url));
return new Response(null, {
status: 302,
headers: { location: "http://untrusted.example/artifact.zip" },
});
}) as typeof fetch,
}),
).rejects.toThrow("static_artifact_redirect_invalid");
expect(calls).toEqual([
"https://api.github.com/repos/owner/rea/actions/artifacts/12/zip",
]);
});
@@ -0,0 +1,407 @@
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
reportCiFailures,
createGitHubApi,
type CiRun,
type FailureReportApi,
type StaticDiagnostic,
type StaticEvidence,
} from "../../../scripts/ci/failure-report.mjs";
const repository = "owner/rea";
const mainSha = "c".repeat(40);
const prSha = "a".repeat(40);
const diagnostic: StaticDiagnostic = {
kind: "lint",
path: "src/example.ts",
code: "no-debugger",
message: "Unexpected debugger statement.",
severity: "error",
};
const evidence = (
run: CiRun,
diagnostics: readonly StaticDiagnostic[],
): StaticEvidence => ({
context: {
version: 1,
sourceSha: run.head_sha!,
sourceClean: true,
nodeVersion: "v24.18.0",
npmVersion: "11.16.0",
turboVersion: "2.11.7",
platform: "linux",
architecture: "x64",
taskHashes: { "lint:built": "a".repeat(16) },
},
diagnostics,
});
const entry = (id: number, event = "pull_request", runAttempt = 1) => ({
id,
runAttempt,
workflow: "CI",
event,
headBranch: event === "pull_request" ? "feature" : "main",
status: "collected",
conclusion: "failure",
});
function fixture(mainIds: readonly number[], prCount: number) {
const jobs: number[] = [];
const artifacts: number[] = [];
const paths: (readonly string[])[] = [];
const runs: Array<
Omit<ReturnType<typeof entry>, "event"> & { event?: string }
> = [
...mainIds.map((id) => entry(id, "schedule")),
...Array.from({ length: prCount }, (_, index) => entry(100 + index)),
];
const api: FailureReportApi = {
async getRun(_repository, id) {
const selected = runs.find((run) => run.id === Number(id))!;
return {
id,
run_attempt: selected.runAttempt,
status: "completed",
conclusion: "failure",
...(selected.event ? { event: selected.event } : {}),
head_branch: selected.headBranch,
path: ".github/workflows/ci.yml@main",
head_sha: mainIds.includes(Number(id)) ? mainSha : prSha,
repository: { full_name: repository },
pull_requests:
selected.event === "pull_request"
? [{ base: { sha: mainSha, repo: { full_name: repository } } }]
: [],
};
},
async getJobs(_repository, id, attempt) {
jobs.push(Number(id));
return [
{
name: "Static checks",
status: "completed",
conclusion: "failure",
run_id: Number(id),
run_attempt: attempt,
},
];
},
async getStaticEvidence(_repository, run) {
artifacts.push(Number(run.id));
return evidence(run, [diagnostic]);
},
async getAncestry() {
return { status: "identical", mergeBaseSha: mainSha };
},
async getBlobIdentity(_repository, _ancestor, _descendant, requested) {
paths.push(requested);
return Object.fromEntries(requested.map((path) => [path, true]));
},
async verifyExecutionSource() {
return true;
},
};
return { api, runs, jobs, artifacts, paths };
}
async function report(input: ReturnType<typeof fixture>) {
return await reportCiFailures({
repository,
defaultBranch: "main",
batchManifest: { repository, runs: input.runs },
api: input.api,
outputDirectory: await createTestTempDirectory("rea-ci-budget-"),
});
}
it("selects PR failures before the cap even after a day of scheduled main failures", async () => {
const input = fixture(
Array.from({ length: 24 }, (_, index) => 20 + index),
1,
);
input.runs.push({
id: 200,
runAttempt: 1,
workflow: "CI",
headBranch: "feature",
status: "collected",
conclusion: "failure",
});
const result = await report(input);
expect(result.failures).toMatchObject([
{ runId: 100, classification: "matching-main-diagnostics" },
]);
expect(result.boundedInput).toMatchObject({
candidateRuns: 1,
mainCandidateRuns: 5,
manifestTruncated: false,
});
expect(input.jobs).toEqual([100, 20]);
});
it("reuses five main job/artifact observations across twenty completed PR comparisons", async () => {
const input = fixture([20, 21, 22, 23, 24], 20);
const load = input.api.getStaticEvidence;
input.api.getStaticEvidence = async (...args) => {
const result = await load(...args);
return Number(args[1].id) < 24
? evidence(args[1], [{ ...diagnostic, message: "different" }])
: result;
};
const result = await report(input);
expect(result.counts).toEqual({
"matching-main-diagnostics": 20,
unknown: 0,
});
expect(input.paths).toHaveLength(100);
expect(input.jobs).toHaveLength(25);
expect(input.artifacts).toHaveLength(25);
for (const id of [20, 21, 22, 23, 24]) {
expect(input.jobs.filter((item) => item === id)).toHaveLength(1);
expect(input.artifacts.filter((item) => item === id)).toHaveLength(1);
}
});
it.each(["missing", "artifact error", "job error", "wrong job attempt"])(
"reuses unavailable main evidence without retries: %s",
async (failure) => {
const input = fixture([20], 3);
const load = input.api.getStaticEvidence;
const jobs = input.api.getJobs;
input.api.getJobs = async (...args) => {
const result = await jobs(...args);
if (Number(args[1]) !== 20) return result;
if (failure === "job error") throw new Error("job_snapshot_unavailable");
return failure === "wrong job attempt"
? result.map((job) => ({ ...job, run_attempt: 2 }))
: result;
};
input.api.getStaticEvidence = async (...args) => {
const result = await load(...args);
if (Number(args[1].id) !== 20) return result;
if (failure === "artifact error") throw new Error("artifact_unavailable");
return null;
};
const result = await report(input);
expect(result.counts.unknown).toBe(3);
expect(input.jobs.filter((id) => id === 20)).toHaveLength(1);
expect(input.artifacts.filter((id) => id === 20)).toHaveLength(
failure === "job error" || failure === "wrong job attempt" ? 0 : 1,
);
},
);
it.each([1, 2])(
"refreshes unavailable main evidence in the next report (attempt %s)",
async (attempt) => {
const input = fixture([20], 1);
expect((await report(input)).counts["matching-main-diagnostics"]).toBe(1);
input.runs[0]!.runAttempt = attempt;
const load = input.api.getStaticEvidence;
input.api.getStaticEvidence = async (...args) => {
const result = await load(...args);
return Number(args[1].id) === 20 ? null : result;
};
expect((await report(input)).counts.unknown).toBe(1);
expect(input.jobs.filter((id) => id === 20)).toHaveLength(2);
expect(input.artifacts.filter((id) => id === 20)).toHaveLength(2);
},
);
it.each([1, 51])(
"fetches only PR paths with %s PR diagnostics and noisy main evidence",
async (count) => {
const input = fixture([20], 1);
const load = input.api.getStaticEvidence;
const diagnostics = Array.from({ length: count }, (_, index) => ({
...diagnostic,
path: `src/pr-${index}.ts`,
}));
input.api.getStaticEvidence = async (...args) => {
await load(...args);
const noise =
Number(args[1].id) === 20
? Array.from({ length: 60 }, (_, index) => ({
...diagnostic,
path: `src/main-${index}.ts`,
}))
: [];
return evidence(args[1], [...noise, ...diagnostics]);
};
const result = await report(input);
expect(input.paths).toEqual([
diagnostics.slice(0, 50).map((item) => item.path),
]);
expect(result.failures[0]!.classification).toBe(
count === 1 ? "matching-main-diagnostics" : "unknown",
);
if (count > 50)
expect(result.failures[0]!.reason).toBe(
"diagnostic_source_blob_identity_unavailable",
);
},
);
it.each(["jobs", "artifact", "comparison"])(
"continues after an isolated main %s failure and preserves its provenance",
async (failure) => {
const input = fixture([20, 21], 3);
const jobs = input.api.getJobs;
const load = input.api.getStaticEvidence;
input.api.getJobs = async (...args) => {
const result = await jobs(...args);
if (Number(args[1]) === 20 && failure === "jobs")
throw new Error("main_jobs_unavailable");
return result;
};
input.api.getStaticEvidence = async (...args) => {
const result = await load(...args);
if (Number(args[1].id) === 20 && failure === "artifact")
throw new Error("main_artifact_unavailable");
return Number(args[1].id) === 20 && failure === "comparison"
? {
...result!,
context: { ...result!.context, sourceSha: "d".repeat(40) },
}
: result;
};
input.api.verifyExecutionSource = async (_repository, run, context) => {
if (Number(run.id) === 20 && context.sourceSha !== run.head_sha)
throw new Error("main_comparison_unavailable");
return true;
};
const result = await report(input);
expect(result.counts).toEqual({
"matching-main-diagnostics": 3,
unknown: 0,
});
for (const item of result.failures) {
expect(item.candidateFailures).toEqual([
{
runId: 20,
runAttempt: 1,
reason: `main_${failure}_unavailable`,
},
]);
}
expect(input.jobs.filter((id) => id === 20)).toHaveLength(1);
expect(input.jobs.filter((id) => id === 21)).toHaveLength(1);
expect(input.artifacts.filter((id) => id === 20)).toHaveLength(
failure === "jobs" ? 0 : 1,
);
expect(input.artifacts.filter((id) => id === 21)).toHaveLength(1);
},
);
it.each([0, 1, 2])(
"preserves every failed job when artifact analysis fails at position %s",
async (position) => {
const input = fixture([20], 1);
const jobs = [
{ name: "Python producer", conclusion: "failure" },
{ name: "Test shard (1)", conclusion: "timed_out" },
];
jobs.splice(position, 0, { name: "Static checks", conclusion: "failure" });
input.api.getJobs = async (_repository, id, attempt) =>
jobs.map((job) => ({
...job,
status: "completed",
run_id: Number(id),
run_attempt: attempt,
}));
input.api.getStaticEvidence = async (_repository, _run, job) => {
if (job.name === "Static checks")
throw new Error("static_artifact_unavailable");
return null;
};
const result = await report(input);
expect(result.counts.unknown).toBe(3);
expect(result.failures).toEqual(
jobs.map((job) => ({
runId: 100,
runAttempt: 1,
runHead: prSha,
event: "pull_request",
job: job.name,
conclusion: job.conclusion,
classification: "unknown",
reason:
job.name === "Static checks"
? "static_artifact_unavailable"
: "no_matching_verified_main_failure",
})),
);
},
);
it("keeps unavailable job inventories at run scope", async () => {
const input = fixture([], 1);
input.api.getJobs = async () => {
throw new Error("job_inventory_unavailable");
};
expect((await report(input)).failures).toEqual([
{
runId: 100,
runAttempt: 1,
classification: "unknown",
reason: "job_inventory_unavailable",
},
]);
});
it.each([
["request", "github_api_temporarily_unavailable"],
["budget", "github_api_request_budget_exhausted"],
["missing sha", "github_content_blob_identity_unavailable"],
["invalid sha", "github_content_blob_identity_unavailable"],
["directory", "github_content_blob_identity_unavailable"],
] as const)(
"retains unavailable blob evidence as a comparison error: %s",
async (failure, reason) => {
const input = fixture([20], 1);
const contentApi = createGitHubApi({
token: "fixture-token",
apiRequest: async () => {
if (failure === "request") throw new Error(reason);
if (failure === "missing sha") return { type: "file" };
if (failure === "invalid sha")
return { type: "file", sha: "not-a-sha" };
if (failure === "directory") return [];
return { type: "file", sha: "e".repeat(40) };
},
});
if (failure === "budget") {
for (let id = 1; id <= 250; id++) await contentApi.getRun(repository, id);
}
input.api.getBlobIdentity = contentApi.getBlobIdentity;
const result = await report(input);
expect(result.failures).toMatchObject([
{
job: "Static checks",
classification: "unknown",
reason: "no_matching_verified_main_failure",
candidateFailures: [{ runId: 20, runAttempt: 1, reason }],
},
]);
},
);
it.each([true, false])(
"reports blob equality only from verified file SHAs (equal: %s)",
async (equal) => {
const api = createGitHubApi({
token: "fixture-token",
apiRequest: async (_method, endpoint) => ({
type: "file",
sha:
equal || endpoint.includes(`ref=${mainSha}`)
? "e".repeat(40)
: "f".repeat(40),
}),
});
expect(
await api.getBlobIdentity(repository, mainSha, prSha, ["src/example.ts"]),
).toEqual({ "src/example.ts": equal });
},
);
@@ -0,0 +1,313 @@
import { execFile } from "node:child_process";
import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { runInNewContext } from "node:vm";
import { expect, it } from "vitest";
import { parse } from "yaml";
import { z } from "zod";
import {
parseStaticTaskContext,
recordStaticTaskContext,
} from "../../../scripts/ci/static-task-context.mjs";
import { createGhApiRequest } from "../../../scripts/ci/github-api.mjs";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const execute = promisify(execFile);
const scopeFlags = async () =>
z
.object({ CI_FLAGS: z.array(z.string()) })
.parse(
await import(
new URL("../../../scripts/ci/scopes.mjs", import.meta.url).href
),
).CI_FLAGS;
const workflow = async () =>
z
.object({
jobs: z.record(
z.string(),
z
.object({
needs: z.union([z.string(), z.array(z.string())]).optional(),
if: z.string().optional(),
steps: z
.array(
z
.object({
run: z.string().optional(),
env: z.record(z.string(), z.string()).optional(),
})
.passthrough(),
)
.optional(),
})
.passthrough(),
),
})
.parse(
parse(
await readFile(
new URL("../../../.github/workflows/ci.yml", import.meta.url),
"utf8",
),
),
).jobs;
it("starts source feedback before build and requires both groups without waiving missing jobs", async () => {
const jobs = await workflow();
expect(
jobs.static?.steps?.find(
(step) => step.run === "npm run ci:static-context",
)?.["continue-on-error"],
).toBe(true);
expect(jobs["test-source"]?.needs).toBe("changes");
expect(jobs["test-shard"]?.needs).toEqual(["changes", "build"]);
expect(
jobs["test-source"]?.steps?.some(
(step) =>
step.run === "npm run test:fast -- --reporter=default --reporter=blob",
),
).toBe(true);
const required = fileURLToPath(
new URL("../../../scripts/ci/required.mjs", import.meta.url),
);
const flags = await scopeFlags();
for (const tier of ["fast", "full"]) {
for (const result of [
"success",
"failure",
"cancelled",
"skipped",
"missing",
]) {
const needs = Object.fromEntries(
Object.keys(jobs)
.filter((name) => name !== "required")
.map((name) => [name, { result: "success" }]),
);
const outputs = {
...Object.fromEntries(
flags.map((flag) => [flag, tier === "full" ? "true" : "false"]),
),
tier,
code: "true",
};
const context: Record<
string,
{ result: string; outputs?: Record<string, string> }
> = { ...needs, changes: { result: "success", outputs } };
if (result === "missing") delete context["test-source"];
else context["test-source"] = { result };
const run = execute(process.execPath, [required], {
env: {
...process.env,
CI_JOBS: JSON.stringify(context),
CI_QUALIFICATION_DIRECTORY: "",
},
});
if (
result === "success" ||
(tier === "full" && ["skipped", "missing"].includes(result))
)
await expect(run).resolves.toMatchObject({ stderr: "" });
else
await expect(run).rejects.toMatchObject({
code: 1,
stderr: expect.stringContaining("test-source"),
});
}
}
});
it("records the actual static task graph with explicit source identity and no ambient environment", async () => {
const directory = await createTestTempDirectory("rea-ci-context-");
const context = await recordStaticTaskContext({ outputDirectory: directory });
const head = await execute("git", ["rev-parse", "HEAD"]);
expect(context.sourceSha).toBe(head.stdout.trim());
expect(context.taskHashes["lint:built"]).toMatch(/^[a-f0-9]{16}$/u);
expect(context.taskHashes.jscpd).toMatch(/^[a-f0-9]{16}$/u);
expect(context).not.toHaveProperty("environmentVariables");
expect(context).not.toHaveProperty("env");
expect(
JSON.parse(await readFile(`${directory}/static-task-context.json`, "utf8")),
).toEqual(context);
for (const invalid of [
undefined,
{},
{ ...context, sourceSha: "bad" },
{ ...context, prHeadSha: "bad" },
{ ...context, taskHashes: { jscpd: "stale" } },
])
expect(() => parseStaticTaskContext(invalid)).toThrow();
});
it("rejects mutation methods at the shared GitHub transport before invoking the CLI", async () => {
const request = createGhApiRequest({ env: { PATH: "" } });
await expect(
request("POST", "repos/owner/repo/actions/runs/1/rerun", {
requests: 0,
startedAt: Date.now(),
limitMs: 1000,
}),
).rejects.toThrow("read-only GET");
});
it("collects basic CI telemetry before optional dependency installation can fail", async () => {
const { jobs } = z
.object({
jobs: z.object({
report: z.object({
steps: z.array(
z.object({
id: z.string().optional(),
run: z.string().optional(),
if: z.string().optional(),
"continue-on-error": z.boolean().optional(),
}),
),
}),
}),
})
.parse(
parse(
await readFile(
new URL("../../../.github/workflows/ci-timings.yml", import.meta.url),
"utf8",
),
),
);
const steps = jobs.report.steps;
const installation = steps.findIndex((step) => step.id === "failure-deps");
for (const script of ["pr-ci-health.mjs", "job-timings-batch.mjs"]) {
const collection = steps.findIndex(
(step) => step.run === `node scripts/ci/${script}`,
);
expect(collection).toBeGreaterThanOrEqual(0);
expect(installation).toBeGreaterThan(collection);
}
expect(steps[installation]).toMatchObject({
run: "npm ci",
"continue-on-error": true,
});
expect(
steps.find((step) => step.id === "npm-cache")?.["continue-on-error"],
).toBe(true);
expect(
steps.find((step) => step.run === "node scripts/ci/failure-report.mjs")?.if,
).toContain("steps.failure-deps.outcome == 'success'");
});
it("merges source and built reports exactly once using the workflow's shard matrix", async () => {
const jobs = await workflow();
const matrix = z
.object({
matrix: z.object({ shard: z.string().regex(/^\$\{\{.*\}\}$/u) }),
})
.parse(jobs["test-shard"]?.strategy).matrix.shard;
const shards = z
.array(z.string().regex(/^\d+\/\d+$/u))
.min(1)
.parse(
runInNewContext(
matrix.slice(3, -2),
{
fromJSON: JSON.parse,
needs: { changes: { outputs: { tier: "fast" } } },
},
{ timeout: 1_000 },
),
);
const labels = Object.fromEntries(
["source", "built"].map((group) => [
group,
z
.string()
.min(1)
.parse(
jobs[group === "source" ? "test-source" : "test-shard"]?.steps?.find(
(step) => step.env?.VITEST_BLOB_LABEL,
)?.env?.VITEST_BLOB_LABEL,
),
]),
);
const root = await createTestTempDirectory("rea-ci-group-merge-");
const config = join(root, "vitest.config.mjs");
await writeFile(
config,
`export default { test: { maxWorkers: 1, projects: [${["source", "built"].map((name) => `{ test: { name: "${name}", globals: true, include: ["${name}*.test.js"] } }`).join(",")}] } };`,
);
const files = [
"source.test.js",
...Array.from(
{ length: shards.length },
(_, index) => `built-${index}.test.js`,
),
];
for (const file of files)
await writeFile(
join(root, file),
'it("runs its selected group", () => expect(true).toBe(true));',
);
const vitest = fileURLToPath(
new URL("../../../node_modules/vitest/vitest.mjs", import.meta.url),
);
const blobs = new Map<string, Buffer>();
const runs = [
{ group: "source", shard: [] },
...shards.map((shard) => ({ group: "built", shard: [`--shard=${shard}`] })),
];
for (const { group, shard } of runs) {
await execute(
process.execPath,
[
vitest,
"run",
"--config",
config,
"--project",
group,
"--reporter=blob",
...shard,
],
{
cwd: root,
env: { ...process.env, VITEST_BLOB_LABEL: labels[group]! },
timeout: 20_000,
},
);
for (const filename of await readdir(join(root, ".vitest/blob"))) {
expect(blobs.has(filename)).toBe(false);
blobs.set(filename, await readFile(join(root, ".vitest/blob", filename)));
}
// Separate hosted jobs start with independent report directories.
await rm(join(root, ".vitest/blob"), { recursive: true });
}
expect(blobs.size).toBe(runs.length);
await mkdir(join(root, ".vitest/blob"), { recursive: true });
for (const [filename, bytes] of blobs)
await writeFile(join(root, ".vitest/blob", filename), bytes);
await execute(
process.execPath,
[
vitest,
"--config",
config,
"--merge-reports",
"--reporter=json",
"--outputFile.json=merged.json",
],
{ cwd: root, timeout: 20_000 },
);
const merged = z
.object({
success: z.literal(true),
testResults: z.array(z.object({ name: z.string() })),
})
.parse(JSON.parse(await readFile(join(root, "merged.json"), "utf8")));
expect(
merged.testResults.map(({ name }) => name.split("/").at(-1)).sort(),
).toEqual(files.toSorted());
});
@@ -18,6 +18,8 @@ it("collects the latest attempt for recent completed CI and Release runs into a
workflow_runs: [
{
id: 42,
event: "push",
head_branch: "main",
run_attempt: 3,
status: "completed",
conclusion: "failure",
@@ -43,51 +45,9 @@ it("collects the latest attempt for recent completed CI and Release runs into a
},
],
},
[
{
jobs: [
{
name: "Release lane",
status: "completed",
conclusion: "success",
created_at: recent,
started_at: recent,
completed_at: new Date(Date.parse(recent) + 50_000).toISOString(),
steps: [],
},
],
},
],
[
{
jobs: [
{
name: "Failed lane",
status: "completed",
conclusion: "failure",
created_at: recent,
started_at: recent,
completed_at: new Date(Date.parse(recent) + 55_000).toISOString(),
steps: [],
},
],
},
],
[
{
jobs: [
{
name: "Cancelled lane",
status: "completed",
conclusion: "cancelled",
created_at: recent,
started_at: recent,
completed_at: new Date(Date.parse(recent) + 30_000).toISOString(),
steps: [],
},
],
},
],
completedJobs("Release lane", "success", recent, 50),
completedJobs("Failed lane", "failure", recent, 55),
completedJobs("Cancelled lane", "cancelled", recent, 30),
]);
const result = await runBatch(fixture);
const manifest = JSON.parse(
@@ -116,8 +76,20 @@ it("collects the latest attempt for recent completed CI and Release runs into a
expect(manifest.errors).toEqual([]);
expect(manifest.runs).toMatchObject([
{ id: 43, runAttempt: 2, conclusion: "success" },
{ id: 42, runAttempt: 3, conclusion: "failure" },
{ id: 41, runAttempt: 1, conclusion: "cancelled" },
{
id: 42,
runAttempt: 3,
conclusion: "failure",
event: "push",
headBranch: "main",
},
{
id: 41,
runAttempt: 1,
conclusion: "cancelled",
event: null,
headBranch: null,
},
]);
expect(manifest.runs).toEqual(
expect.arrayContaining([
@@ -234,6 +206,31 @@ it("retains a partial manifest when its collection budget is exhausted", async (
expect(manifest.truncation.join(" ")).toContain("Time budget");
});
function completedJobs(
name: string,
conclusion: string,
startedAt: string,
seconds: number,
) {
return [
{
jobs: [
{
name,
status: "completed",
conclusion,
created_at: startedAt,
started_at: startedAt,
completed_at: new Date(
Date.parse(startedAt) + seconds * 1000,
).toISOString(),
steps: [],
},
],
},
];
}
async function createFixture(responses: unknown[]) {
const directory = await createTestTempDirectory("rea-ci-job-timings-batch-");
const fakeBin = join(directory, "bin");
@@ -0,0 +1,617 @@
import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
import { delimiter, join } from "node:path";
import { fileURLToPath } from "node:url";
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
classifyPrCi,
collectPrCiHealth,
matchRunToPullRequest,
writePrCiHealthReport,
} from "../../../scripts/ci/pr-ci-health.mjs";
import { createGhApiRequest } from "../../../scripts/ci/github-api.mjs";
import type {
PrCiPullRequest,
PrCiWorkflowRun,
} from "../../../scripts/ci/pr-ci-health.mjs";
import { executeWorkflowFixture } from "../../support/workflowGit.js";
const reporter = fileURLToPath(
new URL("../../../scripts/ci/pr-ci-health.mjs", import.meta.url),
);
const observedAt = Date.parse("2026-10-14T00:00:00Z");
const headSha = "a".repeat(40);
const mergeSha = "b".repeat(40);
it("classifies workflow states without confusing absent, pending, and completed CI", () => {
const pull = validPull();
const cases = [
[
"startup_failure",
run({ status: "completed", conclusion: "startup_failure" }),
],
[
"queued_pending_executing",
run({ status: "in_progress", conclusion: null }),
],
["approval_required", run({ status: "waiting", conclusion: null })],
["completed_failure", run({ status: "completed", conclusion: "failure" })],
[
"completed_canceled",
run({ status: "completed", conclusion: "cancelled" }),
],
["completed_success", run({ status: "completed", conclusion: "success" })],
["completed_other", run({ status: "completed", conclusion: "neutral" })],
[
"completed_other",
run({ status: "completed", conclusion: "constructor" }),
],
] as const;
for (const [category, evidence] of cases) {
for (const runsComplete of [true, false]) {
const result = classifyPrCi({
pull,
runs: [
{
run: { ...evidence, run_attempt: 1 },
basis: "event_pr_number_and_head_sha",
},
],
runsComplete,
pullRequestInventoryComplete: true,
ambiguousRuns: [],
});
expect(result).toMatchObject({
category: runsComplete ? category : "unknown",
...(runsComplete
? {}
: { reason: "workflow_run_inventory_incomplete" }),
runs: [
{
id: 77,
attempt: 1,
status: evidence.status,
conclusion: evidence.conclusion,
},
],
});
}
}
for (const runsComplete of [true, false]) {
expect(
classifyPrCi({
pull: { ...pull, mergeable: false },
runs: [],
runsComplete,
pullRequestInventoryComplete: true,
ambiguousRuns: [],
}).category,
).toBe("merge_conflict");
}
});
it("requires complete inventories, known mergeability, and immutable head identity to report missing", () => {
const pull = validPull({ mergeable: true });
const classify = (overrides = {}) =>
classifyPrCi({
pull,
runs: [],
runsComplete: true,
pullRequestInventoryComplete: true,
ambiguousRuns: [],
...overrides,
});
expect(classify().category).toBe("missing");
expect(classify({ runsComplete: false })).toMatchObject({
category: "deferred",
reason: "lookup_inventory_incomplete",
});
expect(classify({ pullRequestInventoryComplete: false }).category).toBe(
"deferred",
);
expect(
classify({
ambiguousRuns: [{ run: run(), basis: "ambiguous_head_identity" }],
}).category,
).toBe("unknown");
expect(classify({ pull: { ...pull, mergeable: undefined } }).category).toBe(
"unknown",
);
expect(classify({ pull: { ...pull, identityValid: false } }).category).toBe(
"unknown",
);
});
it("accepts event PR/head evidence for merge-SHA runs and refuses ambiguous branch identities", () => {
const pull = validPull();
const associatedMergeRun = run({
head_sha: mergeSha,
pull_requests: [
{
number: pull.number!,
head: { sha: headSha, repo: { id: pull.head.repositoryId } },
},
],
});
expect(
matchRunToPullRequest({
run: associatedMergeRun,
pull,
identityCounts: new Map([["73\u0000feature", 1]]),
}),
).toEqual({ kind: "match", basis: "event_pr_number_and_head_sha" });
expect(
matchRunToPullRequest({
run: run({
pull_requests: [
{ number: pull.number!, head: { sha: "c".repeat(40) } },
],
}),
pull,
identityCounts: new Map([["73\u0000feature", 1]]),
}).kind,
).toBe("none");
const branchRun = run({ pull_requests: [] });
expect(
matchRunToPullRequest({
run: branchRun,
pull,
identityCounts: new Map([["73\u0000feature", 1]]),
inventoryComplete: false,
}).kind,
).toBe("ambiguous");
expect(
matchRunToPullRequest({
run: branchRun,
pull,
identityCounts: new Map([["73\u0000feature", 1]]),
}),
).toEqual({
kind: "match",
basis: "event_unique_head_ref_and_repository_id",
});
expect(
matchRunToPullRequest({
run: run({ head_sha: mergeSha, pull_requests: [] }),
pull,
identityCounts: new Map([["73\u0000feature", 1]]),
}).kind,
).toBe("none");
expect(
matchRunToPullRequest({
run: run({
pull_requests: [{ number: pull.number!, head: { sha: headSha } }],
}),
pull,
identityCounts: new Map([["73\u0000feature", 1]]),
}).kind,
).toBe("ambiguous");
expect(
matchRunToPullRequest({
run: branchRun,
pull,
identityCounts: new Map([["73\u0000feature", 2]]),
}).kind,
).toBe("ambiguous");
expect(
matchRunToPullRequest({
run: run({ event: "workflow_dispatch" }),
pull,
identityCounts: new Map([["73\u0000feature", 1]]),
}).kind,
).toBe("none");
});
it("scans target-branch PRs through public gh GET requests and writes JSON and Markdown", async () => {
const fixture = await createFixture();
const calls: string[] = [];
const apiRequest: NonNullable<
Parameters<typeof collectPrCiHealth>[0]["apiRequest"]
> = async (method, endpoint) => {
calls.push(`${method} ${endpoint}`);
if (method !== "GET") throw new Error("fixture rejected a non-GET request");
if (endpoint.includes("/pulls?"))
return [
rawPull(42, { mergeable: true }),
rawPull(43, { mergeable: false }),
rawPull(44, {
base: { ref: "release", repo: { id: 11 } },
mergeable: true,
}),
rawPull(45, { draft: true, mergeable: true }),
];
if (endpoint.includes("/actions/workflows/ci.yml/runs?"))
return {
total_count: 1,
workflow_runs: [
run({
id: 9001,
event: "pull_request",
status: "completed",
conclusion: "failure",
head_sha: mergeSha,
pull_requests: [
{
number: 42,
head: { sha: headSha, repo: { id: 73 } },
},
],
}),
],
};
throw new Error(`unexpected GET endpoint: ${endpoint}`);
};
const report = await collectPrCiHealth({
repository: "owner/rea",
repositoryId: 11,
defaultBranch: "main",
now: observedAt,
apiRequest,
});
expect(calls).toHaveLength(2);
expect(calls.every((call) => call.startsWith("GET "))).toBe(true);
expect(calls[0]).toContain("state=open");
expect(calls[0]).not.toContain("base=");
expect(calls[1]).toContain("event=pull_request");
expect(report.pullRequests).toHaveLength(2);
expect(report.pullRequests.map(({ number }) => number)).toEqual([42, 43]);
expect(report.pullRequests.map(({ ci }) => ci.category)).toEqual([
"completed_failure",
"merge_conflict",
]);
expect(report.scan).toMatchObject({
status: "complete",
pullRequestInventoryComplete: true,
workflowRunInventoryComplete: true,
apiRequests: 2,
});
const output = join(fixture.directory, ".cache", "ci-pr-health");
const paths = await writePrCiHealthReport(report, output);
const written = JSON.parse(await readFile(paths.jsonPath, "utf8"));
const markdown = await readFile(paths.markdownPath, "utf8");
expect(written.counts.completed_failure).toBe(1);
expect(markdown).toContain("# Pull request CI health snapshot");
expect(markdown).toContain("#42");
expect(markdown).toContain("completed_failure");
});
it("counts older open PRs when deciding whether a branch/ref fallback is unique", async () => {
const olderPull = rawPull(63, {
created_at: "2026-09-01T00:00:00Z",
head: { ...rawPull(63).head, ref: "shared-feature" },
});
const currentPull = rawPull(64, {
mergeable: true,
head: { ...olderPull.head },
});
const apiRequest: NonNullable<
Parameters<typeof collectPrCiHealth>[0]["apiRequest"]
> = async (_method, endpoint) => {
if (endpoint.includes("/pulls?")) return [currentPull, olderPull];
if (endpoint.includes("/actions/workflows/ci.yml/runs?"))
return {
workflow_runs: [
run({
head_branch: "shared-feature",
pull_requests: [],
}),
],
};
throw new Error(`unexpected GET endpoint: ${endpoint}`);
};
const report = await collectPrCiHealth({
repository: "owner/rea",
repositoryId: 11,
defaultBranch: "main",
now: observedAt,
apiRequest,
});
expect(report.scan.pullRequestInventoryComplete).toBe(true);
expect(report.pullRequests.map(({ number }) => number)).toEqual([64]);
expect(report.pullRequests[0]?.ci).toMatchObject({
category: "unknown",
reason: "workflow_run_identity_ambiguous",
});
});
it.each([false, true])(
"keeps page-capped scans uncertain (observed success: %s)",
async (observedSuccess) => {
const pull = rawPull(62, { mergeable: true });
const apiRequest: NonNullable<
Parameters<typeof collectPrCiHealth>[0]["apiRequest"]
> = async (_method, endpoint) => {
if (endpoint.includes("/pulls?")) return [pull];
const page = Number(
new URL(`https://fixture.invalid/${endpoint}`).searchParams.get("page"),
);
return {
workflow_runs: Array.from({ length: 100 }, (_item, index) =>
observedSuccess && page === 1 && index === 0
? run({
run_attempt: 1,
pull_requests: [
{ number: 62, head: { sha: headSha, repo: { id: 73 } } },
],
})
: run({
id: page * 100 + index,
head_branch: "different-branch",
head_repository: { id: 999 },
pull_requests: [],
}),
),
};
};
const report = await collectPrCiHealth({
repository: "owner/rea",
repositoryId: 11,
defaultBranch: "main",
now: observedAt,
apiRequest,
});
expect(report.scan.workflowRunPages).toBe(5);
expect(report.scan.workflowRunInventoryComplete).toBe(false);
const firstPull = report.pullRequests[0];
if (firstPull === undefined) throw new Error("fixture PR was not scanned");
expect(firstPull.ci).toMatchObject({
category: observedSuccess ? "unknown" : "deferred",
reason: observedSuccess
? "workflow_run_inventory_incomplete"
: "lookup_inventory_incomplete",
});
expect(firstPull.ci.runs).toHaveLength(observedSuccess ? 1 : 0);
},
);
it("keeps the result unknown when the head changes between API snapshots", async () => {
const apiRequest: NonNullable<
Parameters<typeof collectPrCiHealth>[0]["apiRequest"]
> = async (_method, endpoint) => {
if (endpoint.includes("/pulls?")) return [rawPull(63)];
if (endpoint.includes("/actions/workflows/ci.yml/runs?"))
return { workflow_runs: [] };
return {
...rawPull(63, { mergeable: true }),
head: {
...rawPull(63).head,
sha: mergeSha,
},
};
};
const report = await collectPrCiHealth({
repository: "owner/rea",
repositoryId: 11,
defaultBranch: "main",
now: observedAt,
apiRequest,
});
expect(report.pullRequests[0]).toMatchObject({
identityChangedDuringScan: true,
ci: { category: "unknown", reason: "pull_request_head_identity_invalid" },
});
expect(report.scan).toMatchObject({
status: "partial",
errors: ["pull_request_identity_changed_during_scan"],
});
});
it("public CLI uses only GET and produces a report from fixture GitHub responses", async () => {
const fixture = await createFixture();
const ghCalls = join(fixture.directory, "gh-calls.jsonl");
const ghResponse = join(fixture.directory, "gh-response.json");
const fakeGh = join(fixture.fakeBin, "gh");
await writeFile(
ghResponse,
JSON.stringify([
[rawPull(51, { mergeable: true })],
{ total_count: 0, workflow_runs: [] },
]),
);
await writeFile(
fakeGh,
`#!/usr/bin/env node\nconst fs=require("node:fs");\nconst args=process.argv.slice(2);\nfs.appendFileSync(process.env.CI_GH_CALLS, JSON.stringify(args)+"\\n");\nif(args[0]!=="api"||args[1]!=="--method"||args[2]!=="GET")process.exit(41);\nconst page=Number(new URL("https://fixture.invalid/"+args.at(-1)).searchParams.get("page"));\nconst responses=JSON.parse(fs.readFileSync(process.env.CI_GH_RESPONSE,"utf8"));\nprocess.stdout.write(JSON.stringify(responses[page===1&&args.at(-1).includes("/pulls?")?0:1]));\n`,
);
await chmod(fakeGh, 0o755);
const outputDirectory = join(fixture.directory, ".cache", "ci-pr-health");
await executeWorkflowFixture(process.execPath, [reporter], {
cwd: fixture.directory,
env: {
...process.env,
PATH: `${fixture.fakeBin}${delimiter}${process.env.PATH ?? ""}`,
CI_REPOSITORY: "owner/rea",
CI_REPOSITORY_ID: "11",
CI_DEFAULT_BRANCH: "main",
CI_PR_HEALTH_DIRECTORY: outputDirectory,
CI_GH_CALLS: ghCalls,
CI_GH_RESPONSE: ghResponse,
},
});
const calls = (await readFile(ghCalls, "utf8"))
.trim()
.split("\n")
.map((line) => JSON.parse(line));
expect(calls).toHaveLength(2);
expect(
calls.every(
(args: string[]) => args[1] === "--method" && args[2] === "GET",
),
).toBe(true);
const report = JSON.parse(
await readFile(join(outputDirectory, "report.json"), "utf8"),
);
expect(report.pullRequests[0].ci.category).toBe("missing");
await expect(
readFile(join(outputDirectory, "summary.md"), "utf8"),
).resolves.toContain("missing");
});
it("rejects non-GET methods before launching the GitHub client", async () => {
const fixture = await createFixture();
const request = createGhApiRequest({
env: {
...process.env,
PATH: `${fixture.fakeBin}${delimiter}${process.env.PATH ?? ""}`,
CI_GH_CALLS: join(fixture.directory, "should-not-exist"),
},
});
await expect(
request("POST", "repos/owner/rea/pulls", {
requests: 0,
startedAt: observedAt,
limitMs: 1_000,
}),
).rejects.toThrow("read-only GET");
await expect(
readFile(join(fixture.directory, "should-not-exist")),
).rejects.toMatchObject({ code: "ENOENT" });
});
function validPull(overrides: Partial<PrCiPullRequest> = {}): PrCiPullRequest {
return {
number: 42,
identityValid: true,
mergeable: true,
head: { repositoryId: 73, ref: "feature", sha: headSha },
...overrides,
};
}
it.each([
["newer run", { id: 78, created_at: "2026-10-13T01:00:00Z" }, "unknown"],
[
"older run",
{ id: 78, created_at: "2026-10-12T23:00:00Z" },
"completed_success",
],
["equal timestamps", { id: 78 }, "unknown"],
[
"retry of an older run",
{ id: 78, created_at: "2026-10-12T23:00:00Z", run_attempt: 2 },
"unknown",
],
["unknown timestamp", { id: 78, created_at: "invalid" }, "unknown"],
["newer attempt", { run_attempt: 3 }, "unknown"],
["older attempt", { run_attempt: 1 }, "completed_success"],
] as const)(
"retains ambiguity evidence for a %s without reporting a stale completion",
(_label, overrides, category) => {
const currentAttempt = "id" in overrides ? 1 : 2;
const result = classifyPrCi({
pull: validPull(),
runs: [
{
run: run({ run_attempt: currentAttempt }),
basis: "event_pr_number_and_head_sha",
},
],
ambiguousRuns: [
{
run: run({ run_attempt: currentAttempt, ...overrides }),
basis: "ambiguous_head_identity",
},
],
runsComplete: true,
pullRequestInventoryComplete: true,
});
expect(result.category).toBe(category);
expect(result.runs).toHaveLength(2);
},
);
it("does not let an older proven run hide a newer run with an unverified repository ID", async () => {
const pull = rawPull(42);
const older = run({
id: 70,
created_at: "2026-10-13T00:00:00Z",
pull_requests: [{ number: 42, head: { sha: headSha, repo: { id: 73 } } }],
});
const newer = run({
id: 71,
created_at: "2026-10-13T01:00:00Z",
status: "in_progress",
conclusion: null,
pull_requests: [{ number: 42, head: { sha: headSha } }],
});
const report = await collectPrCiHealth({
repository: "owner/rea",
repositoryId: 11,
defaultBranch: "main",
now: observedAt,
apiRequest: async (_method, endpoint) => {
if (endpoint.includes("/pulls?")) return [pull];
if (endpoint.endsWith("/pulls/42")) return { ...pull, mergeable: true };
return { workflow_runs: [newer, older] };
},
});
expect(report.pullRequests[0]?.ci).toMatchObject({
category: "unknown",
reason: "workflow_run_identity_ambiguous",
});
expect(report.pullRequests[0]?.ci.runs).toHaveLength(2);
});
it("keeps a proven newest run even when two older matched runs have equal timestamps", () => {
const result = classifyPrCi({
pull: validPull(),
runs: [
run({ id: 70, run_attempt: 1 }),
run({ id: 71, run_attempt: 1, conclusion: "failure" }),
run({
id: 72,
run_attempt: 1,
created_at: "2026-10-13T01:00:00Z",
status: "in_progress",
conclusion: null,
}),
].map((run) => ({ run, basis: "event_pr_number_and_head_sha" })),
ambiguousRuns: [],
runsComplete: true,
pullRequestInventoryComplete: true,
});
expect(result.category).toBe("queued_pending_executing");
expect(result.runs).toHaveLength(3);
});
function run(overrides: Partial<PrCiWorkflowRun> = {}): PrCiWorkflowRun {
return {
id: 77,
event: "pull_request",
head_branch: "feature",
head_repository: { id: 73 },
head_sha: headSha,
status: "completed",
conclusion: "success",
created_at: "2026-10-13T00:00:00Z",
pull_requests: [],
...overrides,
};
}
function rawPull(number: number, overrides: Record<string, unknown> = {}) {
return {
number,
draft: false,
created_at: "2026-10-13T00:00:00Z",
html_url: `https://github.com/owner/rea/pull/${String(number)}`,
base: { ref: "main", repo: { id: 11 } },
head: {
ref: `feature-${String(number)}`,
sha: headSha,
repo: { id: 73, full_name: "contributor/rea" },
},
...overrides,
};
}
async function createFixture() {
const directory = await createTestTempDirectory("rea-ci-pr-health-");
const fakeBin = join(directory, "bin");
await mkdir(fakeBin);
return { directory, fakeBin };
}
@@ -44,7 +44,7 @@ function run(overrides: Record<string, unknown> = {}) {
id: 7,
status: "completed",
conclusion: "success",
path: ".github/workflows/ci.yml",
path: ".github/workflows/ci.yml@main",
event: "schedule",
created_at: new Date(now - 120_000).toISOString(),
head_sha: validSha,
@@ -121,7 +121,11 @@ it("exports every canonical scope with read authority for admission and keeps te
);
expect(timings.on.workflow_run).toBeUndefined();
expect(timings.on.schedule).toHaveLength(1);
expect(timings.permissions).toEqual({ contents: "read", actions: "read" });
expect(timings.permissions).toEqual({
contents: "read",
actions: "read",
"pull-requests": "read",
});
const checkout = timings.jobs.report.steps.find((step) =>
step.uses?.startsWith("actions/checkout@"),
);
@@ -154,6 +158,7 @@ it("holds native and provider fan-out behind static validation while portable fe
"static",
"build",
"test-shard",
"test-source",
"test",
"docs",
"required",
@@ -369,7 +374,7 @@ it("keeps fast feedback separate from complete qualification and release proof",
// release their concurrency slot without waiting for another runner.
expect(ci.jobs.required?.if).toBe("${{ !cancelled() }}");
const shards = ci.jobs["test-shard"]?.steps ?? [];
const fast = shards.find((step) => step.run?.includes("npm run test:run"));
const fast = shards.find((step) => step.run?.includes("npm run test:built"));
const full = shards.find((step) => step.run?.includes("test:ci:shard:run"));
expect(fast?.if).toBe("needs.changes.outputs.tier == 'fast'");
expect(fast?.run).toContain("--reporter=blob");
@@ -506,3 +511,44 @@ it("rejects incomplete or malformed classification even when available jobs succ
});
}
});
it("fails fast only for ordinary PR matrices and rejects partial portable feedback", async () => {
const { jobs } = await workflow();
expect(jobs["test-shard"]?.strategy).toMatchObject({
"fail-fast":
"${{ github.event_name == 'pull_request' && needs.changes.outputs.tier == 'fast' }}",
});
expect(jobs["package-e2e"]?.strategy).toMatchObject({ "fail-fast": false });
const flags = await scopeFlags();
for (const result of ["failure", "cancelled", "skipped", "missing"]) {
// Even an incorrectly successful report merge cannot hide matrix failure.
const needs: Record<string, unknown> = {
changes: {
result: "success",
outputs: {
...Object.fromEntries(flags.map((flag) => [flag, "false"])),
tier: "fast",
code: "true",
},
},
static: { result: "success" },
build: { result: "success" },
test: { result: "success" },
...(result === "missing" ? {} : { "test-shard": { result } }),
};
await expect(
executeWorkflowFixture(
process.execPath,
[
fileURLToPath(
new URL("../../../scripts/ci/required.mjs", import.meta.url),
),
],
{ env: { ...process.env, CI_JOBS: JSON.stringify(needs) } },
),
).rejects.toMatchObject({
code: 1,
stderr: expect.stringContaining("test-shard"),
});
}
});
@@ -0,0 +1,99 @@
import { execFile } from "node:child_process";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { expect, it } from "vitest";
import { parseStaticArchive } from "../../../scripts/ci/artifacts.mjs";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const execute = promisify(execFile);
const producer = fileURLToPath(
new URL("../../../scripts/ci/static-check-report.mjs", import.meta.url),
);
it.each([3.5, 100, 0])(
"retains real lint failures when the duplication threshold is %s",
async (threshold) => {
const root = await createTestTempDirectory("rea-ci-static-archive-");
await mkdir(join(root, "src"));
await mkdir(join(root, "tests"));
await writeFile(
join(root, ".oxlintrc.json"),
JSON.stringify({ rules: { "no-debugger": "error" } }),
);
await writeFile(
join(root, ".jscpd.json"),
JSON.stringify({ threshold, minLines: 5, minTokens: 50 }),
);
await writeFile(
join(root, "src/example.ts"),
"debugger;\nexport const example = true;\n",
);
const duplicate =
"export function compute(value: number) {\n" +
Array.from({ length: 20 }, (_, index) => ` value += ${index};\n`).join(
"",
) +
" return value;\n}\n";
for (const name of threshold === 3.5 ? [] : ["first", "second"])
await writeFile(join(root, `src/${name}.ts`), duplicate);
await expect(
execute(process.execPath, [producer, "lint", "src/example.ts"], {
cwd: root,
}),
).rejects.toMatchObject({ code: 1 });
const duplication = execute(process.execPath, [producer, "duplicates"], {
cwd: root,
});
if (threshold === 0)
await expect(duplication).rejects.toMatchObject({ code: 1 });
else await duplication;
const reports = join(root, ".cache/static-checks");
expect(
JSON.parse(
await readFile(join(reports, "jscpd/jscpd-report.json"), "utf8"),
),
).toMatchObject({ reaCheck: { exitCode: threshold === 0 ? 1 : 0 } });
await writeFile(
join(reports, "static-task-context.json"),
JSON.stringify({
version: 1,
sourceSha: "a".repeat(40),
sourceClean: true,
nodeVersion: process.version,
npmVersion: "11.16.0",
turboVersion: "2.11.7",
platform: process.platform,
architecture: process.arch,
taskHashes: { "lint:built": "a".repeat(16), jscpd: "b".repeat(16) },
}),
);
const archive = join(root, "reports.zip");
await execute(
"zip",
[
"-q",
archive,
"oxlint.json",
"jscpd/jscpd-report.json",
"static-task-context.json",
],
{ cwd: reports },
);
const evidence = await parseStaticArchive(archive);
expect(evidence.diagnostics.filter(({ kind }) => kind === "lint")).toEqual([
expect.objectContaining({
kind: "lint",
path: "src/example.ts",
severity: "error",
}),
]);
const duplicates = evidence.diagnostics.filter(
({ kind }) => kind === "jscpd",
);
if (threshold === 0) expect(duplicates.length).toBeGreaterThan(0);
else expect(duplicates).toEqual([]);
},
);
@@ -35,7 +35,7 @@ function run(id: number, overrides: Record<string, unknown> = {}) {
id,
status: "completed",
conclusion: "success",
path: ".github/workflows/ci.yml",
path: ".github/workflows/ci.yml@main",
event: "schedule",
created_at: new Date(now - 120_000).toISOString(),
head_branch: "main",
@@ -0,0 +1,75 @@
import { execFileSync } from "node:child_process";
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import {
BUILT_TEST_PROJECTS,
SOURCE_TEST_PROJECTS,
projectForTest,
} from "../../../scripts/lib/test-projects.mjs";
import {
developmentTestPlan,
parseDevelopmentTestRequest,
} from "../../../scripts/lib/development-tests.mjs";
const repository = process.cwd();
describe("canonical test-project ownership", () => {
it("assigns every tracked test file exactly once to source or built", () => {
const files = execFileSync("git", ["ls-files", "*.test.ts"], {
cwd: repository,
encoding: "utf8",
})
.trim()
.split("\n")
.filter(Boolean);
const grouped = new Map<string, string[]>();
for (const file of files) {
const project = projectForTest(file);
grouped.set(project.group, [...(grouped.get(project.group) ?? []), file]);
}
expect(grouped.get("source")).not.toBeUndefined();
expect(grouped.get("built")).not.toBeUndefined();
expect(
(grouped.get("source")?.length ?? 0) +
(grouped.get("built")?.length ?? 0),
).toBe(files.length);
expect(
SOURCE_TEST_PROJECTS.reduce(
(count, project) => count + project.include.length,
0,
),
).toBeGreaterThan(0);
expect(
BUILT_TEST_PROJECTS.every((project) => project.group === "built"),
).toBe(true);
expect(() => projectForTest("tests/unowned/example.test.ts")).toThrow(
"No test project owns",
);
});
it("owns the Hopper real-provider conformance test as built and requires preparation", () => {
const testPath =
"tests/conformance/providers/hopper/realHopperSearch.test.ts";
expect(projectForTest(testPath)).toMatchObject({
name: "boundary",
group: "built",
});
expect(() => parseDevelopmentTestRequest("local", [testPath])).toThrow(
`Use test:focused for built test projects: ${testPath}`,
);
const request = parseDevelopmentTestRequest("focused", [testPath]);
expect(developmentTestPlan(request)).toMatchObject({ needsBuild: true });
});
it("uses canonical selectors in Vitest while retaining independent runner policy", async () => {
const config = await readFile(join(repository, "vitest.config.ts"), "utf8");
expect(config).toContain(
"[...SOURCE_TEST_PROJECTS, ...BUILT_TEST_PROJECTS]",
);
expect(config).toContain("PROJECT_POLICIES");
expect(config).not.toContain('"src/{contracts,domain}/**/*.test.ts"');
});
});
+176 -52
View File
@@ -3,6 +3,7 @@ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { runInNewContext } from "node:vm";
import { expect, it } from "vitest";
import { parse } from "yaml";
@@ -16,6 +17,32 @@ import { workflowGit } from "../../support/workflowGit.js";
const execute = promisify(execFile);
const script = new URL("../../../scripts/ci/test-report.mjs", import.meta.url);
// Each report invocation owns its CI state and summary destination. Inherited
// workflow flags must not change fixture outcomes or append to the real job.
const executeTimingReport = async (
root: string,
environment: NodeJS.ProcessEnv = {},
) => {
const summary = join(root, "summary.md");
await writeFile(summary, "");
const output = await execute(process.execPath, [fileURLToPath(script)], {
cwd: root,
env: {
...process.env,
SHARD_RESULT: "success",
MERGE_RESULT: "success",
SOURCE_REQUIRED: "false",
SOURCE_RESULT: "",
CI_VERIFY_TEST_INVENTORY: "false",
CI_TEST_SELECTION: "",
...environment,
GITHUB_STEP_SUMMARY: summary,
},
});
return { ...output, summary: await readFile(summary, "utf8") };
};
const stepsSchema = z.array(
z.object({
name: z.string().optional(),
@@ -48,9 +75,7 @@ const workflow = async () =>
it("merges available failed-shard diagnostics and skips unavailable shard reports", async () => {
const steps = (await workflow()).test!.steps;
const download = steps.find(
(step) =>
step.uses?.includes("actions/download-artifact") &&
step.with?.pattern === "vitest-report-*",
(step) => step.with?.pattern === "vitest-report-*",
);
const merge = steps.findIndex((step) => step.run?.includes("test:ci:merge"));
const upload = steps.findIndex((step) => step.with?.name === "test-results");
@@ -59,8 +84,7 @@ it("merges available failed-shard diagnostics and skips unavailable shard report
);
expect(merge).toBeGreaterThan(0);
expect(download?.if).toContain("!cancelled()");
expect(download?.if).toContain("needs.test-shard.result == 'success'");
expect(download?.if).toContain("needs.test-shard.result == 'failure'");
expect(upload).toBeGreaterThan(merge);
expect(gate).toBeGreaterThan(upload);
const merges = steps.filter((step) => step.run?.includes("--reporter=json"));
@@ -70,8 +94,6 @@ it("merges available failed-shard diagnostics and skips unavailable shard report
"--reporter=./scripts/ci/test-timing-reporter.mjs",
);
expect(step.if).toContain("!cancelled()");
expect(step.if).toContain("needs.test-shard.result == 'success'");
expect(step.if).toContain("needs.test-shard.result == 'failure'");
}
expect(steps[upload]?.with?.path).toContain("test-timings.json");
expect(steps[upload]?.with).toMatchObject({ "include-hidden-files": true });
@@ -86,12 +108,23 @@ it("merges available failed-shard diagnostics and skips unavailable shard report
);
const command = steps[gate]?.run;
if (command === undefined) throw new Error("Missing shard result gate");
for (const result of ["failure", "cancelled", "skipped", ""]) {
await expect(
execute("bash", ["-c", command], {
env: { ...process.env, CODE_REQUIRED: "true", SHARD_RESULT: result },
}),
).rejects.toMatchObject({ code: 1 });
for (const tier of ["fast", "full"]) {
for (const shard of ["success", "failure", "cancelled", "skipped", ""]) {
for (const source of ["success", "failure", "cancelled", "skipped", ""]) {
const check = execute("bash", ["-c", command], {
env: {
...process.env,
CODE_REQUIRED: "true",
SHARD_RESULT: shard,
SOURCE_REQUIRED: String(tier === "fast"),
SOURCE_RESULT: source,
},
});
if (shard === "success" && (tier !== "fast" || source === "success"))
await expect(check).resolves.toMatchObject({ stderr: "" });
else await expect(check).rejects.toMatchObject({ code: 1 });
}
}
}
await expect(
execute("bash", ["-c", command], {
@@ -100,6 +133,80 @@ it("merges available failed-shard diagnostics and skips unavailable shard report
).resolves.toMatchObject({ stderr: "" });
});
// These workflow conditions use the shared boolean/string expression subset.
// Evaluate the checked-in expressions so failure-state coverage cannot drift
// into a separate test implementation of the collection policy.
function conditionValue(
condition: string | undefined,
needs: Record<string, unknown>,
canceled: boolean,
) {
if (!condition) throw new Error("Missing report collection condition");
return runInNewContext(
condition
.replaceAll("needs.test-shard", 'needs["test-shard"]')
.replaceAll("needs.test-source", 'needs["test-source"]'),
{ needs, cancelled: () => canceled },
{ timeout: 1_000 },
);
}
it("collects either fast test group while keeping full reports tied to full shards", async () => {
const steps = (await workflow()).test.steps;
const download = steps.find(
(step) => step.with?.pattern === "vitest-report-*",
);
const fast = steps.find(
(step) => step.name === "Merge fast-suite JUnit and timing reports",
);
const full = steps.find(
(step) => step.name === "Merge coverage, JUnit, and timing reports",
);
for (const tier of ["fast", "full"]) {
for (const shard of ["success", "failure", "cancelled", "skipped", ""]) {
for (const source of ["success", "failure", "cancelled", "skipped", ""]) {
for (const [code, canceled] of [
["true", false],
["true", true],
["false", false],
["false", true],
] as const) {
const needs = {
changes: { outputs: { code, tier } },
"test-shard": { result: shard },
"test-source": { result: source },
};
const builtAvailable = ["success", "failure"].includes(shard);
const sourceAvailable = ["success", "failure"].includes(source);
const enabled = code === "true" && !canceled;
const available =
builtAvailable || (tier === "fast" && sourceAvailable);
const expected = enabled
? {
download: available,
fast: tier === "fast" && available,
full: tier === "full" && builtAvailable,
}
: { download: false, fast: false, full: false };
expect(conditionValue(download?.if, needs, canceled)).toBe(
expected.download,
);
expect(conditionValue(fast?.if, needs, canceled)).toBe(expected.fast);
expect(conditionValue(full?.if, needs, canceled)).toBe(expected.full);
}
}
}
}
const summary = steps.find((step) =>
step.run?.includes("scripts/ci/test-report.mjs"),
);
expect(summary?.env?.SHARD_RESULT).toBe("${{ needs.test-shard.result }}");
expect(summary?.env?.SOURCE_RESULT).toBe("${{ needs.test-source.result }}");
expect(summary?.env?.SOURCE_REQUIRED).toBe(
"${{ needs.changes.outputs.tier == 'fast' }}",
);
});
it("keeps diagnosis available after merge failure and publishes only complete successful history", async () => {
const steps = (await workflow()).test!.steps;
const diagnosis = steps.find((step) => step.with?.name === "test-results");
@@ -144,14 +251,8 @@ it("rejects successful shard reports with missing or duplicate portable files",
files: names.map((name) => ({ name, durationMs: 1 })),
}),
);
return execute(process.execPath, [fileURLToPath(script)], {
cwd: root,
env: {
...process.env,
SHARD_RESULT: "success",
MERGE_RESULT: "success",
CI_VERIFY_TEST_INVENTORY: "true",
},
return executeTimingReport(root, {
CI_VERIFY_TEST_INVENTORY: "true",
});
};
await expect(
@@ -220,17 +321,18 @@ it("exports portable timing history and removes it on a failed, partial, or inva
{ name: join(root, "tests/fast.test.ts"), durationMs: 10 },
],
};
const run = async (value: unknown, shards = "success", merge = "success") => {
const run = async (
value: unknown,
shards = "success",
merge = "success",
source?: string,
) => {
await writeFile(join(root, "test-timings.json"), JSON.stringify(value));
await writeFile(summary, "");
return execute(process.execPath, [fileURLToPath(script)], {
cwd: root,
env: {
...process.env,
GITHUB_STEP_SUMMARY: summary,
SHARD_RESULT: shards,
MERGE_RESULT: merge,
},
return executeTimingReport(root, {
SHARD_RESULT: shards,
SOURCE_REQUIRED: String(source !== undefined),
SOURCE_RESULT: source ?? "",
MERGE_RESULT: merge,
});
};
await run(report);
@@ -256,6 +358,24 @@ it("exports portable timing history and removes it on a failed, partial, or inva
await expect(readFile(history)).rejects.toMatchObject({ code: "ENOENT" });
expect(await readFile(summary, "utf8")).toContain("diagnostic only");
}
await run(report, "success", "success", "success");
expect(await readFile(history, "utf8")).toContain('"success":true');
for (const [shards, source] of [
["skipped", "success"],
["success", "skipped"],
["success", "cancelled"],
["success", "failure"],
["success", ""],
]) {
await run(report);
await run(report, shards, "success", source);
await expect(readFile(history)).rejects.toMatchObject({ code: "ENOENT" });
const text = await readFile(summary, "utf8");
expect(text).toContain(`Source result: ${source}.`);
expect(text).toContain("diagnostic only");
if (shards === "skipped" || source !== "failure")
expect(text).toContain("Partial test diagnostics");
}
await run(report);
await expect(
run({
@@ -352,10 +472,17 @@ it("recovers complete module costs from real blob reports without executing test
expect(file.durationMs).toBeCloseTo(
Object.values(file.phases).reduce((sum, value) => sum + value, 0),
);
await execute(process.execPath, [fileURLToPath(script)], {
cwd: root,
env: { ...process.env, SHARD_RESULT: "success", MERGE_RESULT: "success" },
const partial = await executeTimingReport(root, {
SHARD_RESULT: "skipped",
SOURCE_REQUIRED: "true",
SOURCE_RESULT: "success",
});
expect(partial.summary).toContain("Partial test diagnostics");
expect(partial.summary).toContain("sample.test.js");
await expect(
readFile(join(root, ".cache/ci-test-history/test-results.json")),
).rejects.toMatchObject({ code: "ENOENT" });
await executeTimingReport(root);
expect(
parseTestDurations(
await readFile(
@@ -387,10 +514,7 @@ it("recovers complete module costs from real blob reports without executing test
files: [{ state: "failed" }],
});
// Even a caller accidentally marking the merge successful cannot publish this report.
await execute(process.execPath, [fileURLToPath(script)], {
cwd: root,
env: { ...process.env, SHARD_RESULT: "success", MERGE_RESULT: "success" },
});
await executeTimingReport(root);
await expect(
readFile(join(root, ".cache/ci-test-history/test-results.json")),
).rejects.toMatchObject({ code: "ENOENT" });
@@ -420,21 +544,19 @@ it("records failed omissions from full reports without treating partial or unhan
state: index === 1 ? "failed" : "passed",
})),
};
const run = async (report: unknown) => {
const run = async (report: unknown, source = "failure") => {
await writeFile(join(root, "test-timings.json"), JSON.stringify(report));
await execute(process.execPath, [fileURLToPath(script)], {
cwd: root,
env: {
...process.env,
SHARD_RESULT: "failure",
MERGE_RESULT: "failure",
CI_VERIFY_TEST_INVENTORY: "true",
CI_TEST_SELECTION: JSON.stringify(
planTestSelection(["src/sqlite/Provider.ts"], "pull_request", "fast"),
),
GITHUB_SHA: "merge-sha",
CI_PR_HEAD_SHA: "pr-head-sha",
},
await executeTimingReport(root, {
SHARD_RESULT: "failure",
SOURCE_REQUIRED: "true",
SOURCE_RESULT: source,
MERGE_RESULT: "failure",
CI_VERIFY_TEST_INVENTORY: "true",
CI_TEST_SELECTION: JSON.stringify(
planTestSelection(["src/sqlite/Provider.ts"], "pull_request", "fast"),
),
GITHUB_SHA: "merge-sha",
CI_PR_HEAD_SHA: "pr-head-sha",
});
return JSON.parse(
await readFile(
@@ -458,6 +580,8 @@ it("records failed omissions from full reports without treating partial or unhan
{ ...timing, reason: "interrupted" },
])
expect(await run(report)).toMatchObject({ complete: false });
for (const source of ["skipped", "cancelled", ""])
expect(await run(timing, source)).toMatchObject({ complete: false });
await expect(run({ ...timing, files: "invalid" })).rejects.toMatchObject({
code: 1,
});
@@ -0,0 +1,54 @@
import { expect, it } from "vitest";
import { normalizeWorkflowRun } from "../../../scripts/ci/workflow-run.mjs";
it.each([
[".github/workflows/ci.yml", ".github/workflows/ci.yml", null],
[".github/workflows/ci.yml@main", ".github/workflows/ci.yml", "main"],
[
".github/workflows/ci.yml@refs/heads/release/v1",
".github/workflows/ci.yml",
"refs/heads/release/v1",
],
[
".github/workflows/ci.yml@feature@v1",
".github/workflows/ci.yml",
"feature@v1",
],
[
".github/workflows/release.yaml@main",
".github/workflows/release.yaml",
"main",
],
])(
"preserves API path %s while separating its file identity and ref",
(path, file, ref) => {
const raw = { id: 10, path, head_sha: "a".repeat(40) };
const parsed = normalizeWorkflowRun(raw);
expect(parsed).toEqual({ ...raw, workflowPath: { file, ref } });
expect(raw).not.toHaveProperty("workflowPath");
},
);
it.each([
undefined,
null,
42,
"",
".github/workflows/ci.yml@",
".github/workflows/ci.yml@main\n",
".github/workflows/ci.yml@main\0",
"../.github/workflows/ci.yml",
".github/workflows/../ci.yml@main",
".github/workflows/ci.yml-extra@main",
"https://example.test/ci.yml@main",
])(
"keeps malformed workflow path %s unknown instead of inventing a file identity",
(path) => {
const parsed = normalizeWorkflowRun({
path,
workflowPath: { file: ".github/workflows/ci.yml", ref: "main" },
});
expect(parsed.path).toBe(path);
expect(parsed.workflowPath).toBeNull();
},
);
@@ -67,6 +67,7 @@ describe("client configuration filesystem lifecycle", () => {
"kimi",
"vscode",
"trae",
"workbuddy",
"grok_build",
"omp",
"pi",
@@ -23,10 +23,27 @@ it("threads the selected host and environment into system diagnostics", async ()
environment,
execFileOutput: async (command, arguments_, options) => {
calls.push({ command, arguments: arguments_, environment: options?.env });
if (command === "sw_vers") return { stdout: "15.0\n", stderr: "" };
if (command === "ldd") return { stdout: "linux-vdso.so.1", stderr: "" };
if (command === "sw_vers")
return {
stdout: "15.0\n",
stderr: "",
stdoutBytes: 5,
stderrBytes: 0,
};
if (command === "ldd")
return {
stdout: "linux-vdso.so.1",
stderr: "",
stdoutBytes: Buffer.byteLength("linux-vdso.so.1"),
stderrBytes: 0,
};
if (command === "which")
return { stdout: "/selected/bin/rea\n", stderr: "" };
return {
stdout: "/selected/bin/rea\n",
stderr: "",
stdoutBytes: 18,
stderrBytes: 0,
};
throw new Error(`Unexpected diagnostic command: ${command}`);
},
});
@@ -88,7 +105,12 @@ it.each([
environment: { HOME: join(root, "home") },
execFileOutput: async (_command, arguments_) => {
calls.push(arguments_);
return { stdout: `${caskroom}\n`, stderr: "" };
return {
stdout: `${caskroom}\n`,
stderr: "",
stdoutBytes: Buffer.byteLength(`${caskroom}\n`),
stderrBytes: 0,
};
},
});
@@ -111,7 +133,12 @@ it("reports no Homebrew Hopper when the cask has no receipt", async () => {
environment: { HOME: caskroom },
execFileOutput: async (_command, arguments_) => {
calls.push(arguments_);
return { stdout: `${caskroom}\n`, stderr: "" };
return {
stdout: `${caskroom}\n`,
stderr: "",
stdoutBytes: Buffer.byteLength(`${caskroom}\n`),
stderrBytes: 0,
};
},
});
@@ -55,6 +55,8 @@ const host: GhidraInstallationHost = {
readText: () => "application.version=12.1.3\napplication.java.min=21\n",
executable: () => true,
probeJava: () => ({
osArch: "amd64",
osName: "Linux",
version: "21.0.12",
major: 21,
home: "/jdk-21",
@@ -20,7 +20,7 @@ import { artifactInventoryResultSchema } from "../../../../src/domain/artifactGr
import { parseBinaryTarget } from "../../../../src/application/BinaryTargetResolver.js";
import {
ZIP_PACKAGE_FORMATS,
ZIP_NON_ENTRY_TAIL_LIMITATION,
ZIP_NON_ENTRY_LIMITATION,
} from "../../../../src/domain/zipPackageFormat.js";
const { runProviderAnalysis } = createDirectAnalysis({});
@@ -214,7 +214,7 @@ describe("HarmonyOS packaging boundaries", () => {
});
describe("HarmonyOS inventory coverage", () => {
it("keeps a case-colliding inventory partial in the application projection", async () => {
it("retains complete traversal and case-collision limits in the application projection", async () => {
const path = await writeApplicationZip(
"rea-harmony-case-collision-",
"Fixture.hap",
@@ -225,7 +225,7 @@ describe("HarmonyOS inventory coverage", () => {
);
const inventory = await inventoryApplicationPackage(path);
expect(inventory.normalized_result).toMatchObject({
coverage_status: "partial",
coverage_status: "complete",
});
const projection = requireDeterministicProjection(
@@ -234,11 +234,11 @@ describe("HarmonyOS inventory coverage", () => {
harmonyApplicationProjectionResultSchema,
);
expect(projection.coverage).toEqual({
status: "partial",
status: "complete-within-inventory",
inventory_complete: true,
});
expect(projection.limitations).toContain(
"Source inventory coverage is partial; absence is unknown.",
expect(projection.limitations.join(" ")).toContain(
"case-insensitive destination",
);
});
@@ -264,7 +264,7 @@ describe("HarmonyOS inventory coverage", () => {
artifact_kind: "container",
artifact_format: format,
});
expect(inventory.limitations).toContain(ZIP_NON_ENTRY_TAIL_LIMITATION);
expect(inventory.limitations).toContain(ZIP_NON_ENTRY_LIMITATION);
},
);
@@ -114,18 +114,34 @@ describe("Hermes YAML shape diagnostics", () => {
"!!omap [{rea: {command: rea, args: [mcp]}}]",
"!!timestamp 2001-12-15",
"!!binary cmVh",
].flatMap((value) => [
{
original: `${value}\n`,
problem: "The configuration root must be an object",
},
{
original: `mcp_servers: ${value}\n`,
problem: '"mcp_servers" must be an object',
},
]),
]
.flatMap((value) => [
{
original: `${value}\n`,
problem: "The configuration root must be an object",
},
{
original: `mcp_servers: ${value}\n`,
problem: '"mcp_servers" must be an object',
},
])
.concat(
// An explicit null root is a value, not an empty file.
[
"null\n",
"~\n",
"# Hermes configuration\nnull\n",
"--- ~\n",
"--- !!null\n",
'!!null ""\n',
"--- &empty\n",
].map((original) => ({
original,
problem: "The configuration root must be an object",
})),
),
)(
"blocks setup and uninstall before changes for tagged non-record YAML: $original",
"blocks setup and uninstall before changes for tagged or null non-record YAML: $original",
async ({ original, problem }) => {
const { home, client } = await hermesClient();
const cursor = join(home, ".cursor", "mcp.json");
@@ -281,7 +297,36 @@ mcp_servers:
});
});
it.each(["", "\n"])(
// Comments and a bare document marker parse to a null document, like an
// empty file, and are kept ahead of the new registration.
});
describe("Hermes YAML empty configurations", () => {
it("rejects multiple YAML documents before treating an empty first root as absent", async () => {
const { client } = await hermesClient();
const original =
"---\n---\nmcp_servers:\n rea:\n command: rea\n args: [mcp]\n";
await writeFile(client.configPath, original);
expect(await inspectClientConfiguration(client, {}, command)).toMatchObject(
{ status: "invalid" },
);
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "failed",
reason: "readback",
});
expect(await readFile(client.configPath, "utf8")).toBe(original);
await expect(
readFile(`${client.configPath}.rea.backup`, "utf8"),
).rejects.toThrow();
});
it.each([
"",
"\n",
"# Hermes configuration\n",
"---\n",
"---\n# Hermes configuration\n",
])(
"configures an empty config.yaml %j as a new document",
async (original) => {
const { home, client } = await hermesClient();
@@ -289,7 +334,10 @@ mcp_servers:
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
expect(parseYaml(await readFile(client.configPath, "utf8"))).toEqual({
const text = await readFile(client.configPath, "utf8");
const kept = original.trimEnd();
expect(text.slice(0, kept.length)).toBe(kept);
expect(parseYaml(text)).toEqual({
mcp_servers: {
rea: { command: command[0], args: command.slice(1), enabled: true },
},
@@ -67,6 +67,11 @@ describe("static Electron application analysis", () => {
});
});
it(
"keeps Electron runtime entrypoints on their declared filenames",
exactRuntimeEntrypointFixture,
);
it("keeps computed identifier member keys unknown", async () => {
const root = await computedMemberFixtureDirectory();
@@ -153,9 +158,210 @@ describe("static Electron application analysis", () => {
});
});
const exactRuntimeEntrypointFixture = async (): Promise<void> => {
const root = await createTestTempDirectory("rea-electron-exact-entrypoints-");
await mkdir(join(root, "renderer/page"), { recursive: true });
await Promise.all([
writeFile(
join(root, "main.cjs"),
String.raw`
const { BrowserWindow, utilityProcess } = require("electron");
const path = require("node:path");
new BrowserWindow({ webPreferences: { preload: "./entry" } });
new BrowserWindow().loadURL("file:///renderer/index.html");
new BrowserWindow().loadURL("renderer/bare.html");
new BrowserWindow().loadURL("#home");
new BrowserWindow().loadURL("");
new BrowserWindow().loadURL("./renderer/other.html?theme=dark#home");
new BrowserWindow().loadURL("./renderer/missing.html");
new BrowserWindow().loadFile("./renderer/page");
new BrowserWindow({ webPreferences: { preload: path.join(__dirname, "preload") } });
new BrowserWindow({ webPreferences: { preload: "./explicit-preload.js" } });
utilityProcess.fork("./worker");
utilityProcess.fork("./worker#v1.js");
utilityProcess.fork("./service.js");
`,
),
writeFile(join(root, "entry.html"), "<title>sibling</title>"),
writeFile(join(root, "preload.html"), "<title>sibling</title>"),
writeFile(join(root, "worker.js"), "module.exports = {};"),
writeFile(join(root, "renderer/index.html"), "<title>renderer</title>"),
writeFile(
join(root, "renderer/bare.html"),
"<title>bare renderer URL</title>",
),
writeFile(join(root, "renderer/other.html"), "<title>other</title>"),
writeFile(join(root, "renderer/missing.html.js"), "module.exports = {};"),
writeFile(
join(root, "renderer/page/index.html"),
"<title>directory</title>",
),
writeFile(join(root, "explicit-preload.js"), "module.exports = {};"),
writeFile(join(root, "service.js"), "module.exports = {};"),
]);
const result = await reconstructJavaScriptArtifact({ input_path: root });
const graph = parseJavaScriptApplicationGraph(result.graph);
expectSuffixOnlyRenderersUnresolved(graph);
expectExactRendererPaths(graph);
const roles = graph.nodes.filter(({ kind }) => kind === "electron-preload");
const roleByDeclaration = new Map(
roles.map((role) => [role.observations[0]?.properties.declared_path, role]),
);
expect(result.electron_summary.resolved_utility_entrypoints).toBe(2);
for (const [declaredPath, candidatePath] of [
["./entry", "entry"],
["preload", "preload"],
]) {
const role = roleByDeclaration.get(declaredPath);
expect(role?.observations[0]?.properties).toMatchObject({
declared_path: declaredPath,
resolved_path: null,
resolution_status: "not-found",
candidate_path: candidatePath,
limitations: [
expect.stringContaining(
"extension and directory fallback were not attempted",
),
],
});
expect(
graph.edges.some(
(edge) =>
edge.source_node_id === role?.node_id && edge.relation === "maps_to",
),
).toBe(false);
}
expect(
roleByDeclaration.get("./explicit-preload.js")?.observations[0]?.properties,
).toMatchObject({
resolved_path: "explicit-preload.js",
resolution_status: "resolved",
});
const utilityLaunches = graph.edges.filter(
(edge) =>
edge.evidence.extractor.operation === "map-utility-process-launch",
);
const resolvedWorker = utilityLaunches.find(
(edge) => edge.properties.declared_path === "./worker",
);
expect(resolvedWorker?.evidence).toMatchObject({
authority: "static-relationship-inference",
state: "inferred",
limitations: expect.arrayContaining([
"Static syntax does not prove that this relationship executes at runtime.",
]),
});
expect(utilityLaunches).toEqual(
expect.arrayContaining([
expect.objectContaining({
properties: expect.objectContaining({
declared_path: "./worker",
resolved_path: "worker.js",
resolution_status: "resolved",
}),
}),
expect.objectContaining({
properties: expect.objectContaining({
declared_path: "./worker#v1.js",
resolved_path: null,
resolution_status: "not-found",
}),
}),
expect.objectContaining({
properties: expect.objectContaining({
declared_path: "./service.js",
resolved_path: "service.js",
resolution_status: "resolved",
}),
}),
]),
);
expect(
graph.edges.some(
(edge) =>
edge.evidence.extractor.operation ===
"resolve-utility-process-entrypoint" &&
edge.properties.resolved_path === "worker.html",
),
).toBe(false);
};
type Reconstruction = Awaited<ReturnType<typeof reconstructJavaScriptArtifact>>;
type ApplicationGraph = ReturnType<typeof parseJavaScriptApplicationGraph>;
const expectSuffixOnlyRenderersUnresolved = (graph: ApplicationGraph): void => {
const renderers = new Map(
graph.nodes
.filter(({ kind }) => kind === "electron-renderer")
.map((renderer) => [
renderer.observations[0]?.properties.declared_path,
renderer,
]),
);
expect(
renderers.get("file:///renderer/index.html")?.observations[0]?.properties,
).toMatchObject({
resolved_path: "renderer/index.html",
resolution_status: "resolved",
});
for (const declaredPath of [
"./renderer/other.html?theme=dark#home",
"renderer/bare.html",
"./renderer/missing.html",
"#home",
"",
]) {
const renderer = renderers.get(declaredPath);
expect(renderer?.observations[0]?.properties).toMatchObject({
resolved_path: null,
resolution_status: "unavailable",
});
expect(renderer?.observations[0]?.properties.limitations).toEqual(
expect.arrayContaining([
expect.stringContaining("requires a URL protocol"),
]),
);
expect(
graph.edges.some(
(edge) =>
edge.source_node_id === renderer?.node_id &&
edge.relation === "maps_to",
),
).toBe(false);
}
};
const expectExactRendererPaths = (graph: ApplicationGraph): void => {
const renderers = new Map(
graph.nodes
.filter(({ kind }) => kind === "electron-renderer")
.map((renderer) => [
renderer.observations[0]?.properties.declared_path,
renderer,
]),
);
for (const [declaredPath, candidatePath] of [
["./renderer/page", "renderer/page"],
]) {
const renderer = renderers.get(declaredPath);
expect(renderer?.observations[0]?.properties).toMatchObject({
resolved_path: null,
resolution_status: "not-found",
candidate_path: candidatePath,
});
expect(
graph.edges.some(
(edge) =>
edge.source_node_id === renderer?.node_id &&
edge.relation === "maps_to",
),
).toBe(false);
}
};
const expectElectronSummary = (result: Reconstruction): void => {
expect(result.electron_summary).toMatchObject({
browser_windows: 3,
@@ -1,6 +1,6 @@
import { writeFile } from "node:fs/promises";
import { mkdir, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { join, relative, sep } from "node:path";
import { dirname, join, relative, sep } from "node:path";
import { describe, expect, it } from "vitest";
@@ -133,3 +133,66 @@ describe("literal CommonJS paths in application graphs", () => {
},
);
});
describe("literal CommonJS percent bytes in application graphs", () => {
it("agrees with Node for requests whose literal names contain %2e or %2F", async () => {
const root = await createTestTempDirectory("rea-literal-percent-require-");
const files = {
"app/lit%2eb.js": "module.exports = 'lit%2eb.js';",
"app/x%2Fy.js": "module.exports = 'x%2Fy.js';",
"app/sub/%2e%2e/x.js": "module.exports = 'sub/%2e%2e/x.js';",
"app/x.js": "module.exports = 'decoy for a decoded parent';",
"app/pkg/package.json": JSON.stringify({ main: "lit%2eb" }),
"app/pkg/lit%2eb.js": "module.exports = 'pkg/lit%2eb.js';",
"app/node_modules/dep/package.json": JSON.stringify({ name: "dep" }),
"app/node_modules/dep/lit%2eb.js": "module.exports = 'dep/lit%2eb.js';",
"escape.js": "module.exports = 'decoy outside the request directory';",
};
const specifiers = [
"./lit%2eb",
"./x%2Fy",
"./sub/%2e%2e/x",
"./pkg",
"dep/lit%2eb",
];
// CommonJS reads %2e%2e as a directory name, never as a parent segment.
const literalSegment = "./%2e%2e/escape";
for (const [path, text] of Object.entries(files)) {
await mkdir(dirname(join(root, path)), { recursive: true });
await writeFile(join(root, path), text);
}
const main = join(root, "app", "main.cjs");
await writeFile(
main,
[...specifiers, literalSegment]
.map((specifier) => `require(${JSON.stringify(specifier)});`)
.join("\n"),
);
const nodeRequire = createRequire(main);
const nodePath = (specifier: string) =>
relative(root, nodeRequire.resolve(specifier)).split(sep).join("/");
expect(() => nodeRequire.resolve(literalSegment)).toThrow(
/Cannot find module/u,
);
const { graph } = await analyze(root);
const requests = (specifier: string) =>
graph.edges.filter(
(edge) =>
edge.relation === "imports" &&
edge.properties.specifier === specifier,
);
for (const specifier of specifiers) {
const edges = requests(specifier);
expect(edges.length, specifier).toBeGreaterThan(0);
for (const edge of edges)
expect(edge.properties.resolved_path, specifier).toBe(
nodePath(specifier),
);
}
const unresolved = requests(literalSegment);
expect(unresolved.length).toBeGreaterThan(0);
for (const edge of unresolved)
expect(edge.properties.resolved_path).toBeNull();
});
});
@@ -19,6 +19,9 @@ import {
GHIDRA_PROVIDER_IDENTITY,
GHIDRA_OPERATIONS,
} from "../../../src/ghidra/GhidraProviderCapabilities.js";
import { OBJDUMP_PROVIDER_IDENTITY } from "../../../src/objdump/ObjdumpCommand.js";
import { RIZIN_PROVIDER_IDENTITY } from "../../../src/rizin/RizinCommand.js";
import { GDB_PROVIDER_IDENTITY } from "../../../src/gdb/GdbSessionManager.js";
import {
documentationFactIssues,
skillReferenceIssues,
@@ -118,6 +121,16 @@ describe("canonical product catalog", () => {
expect(catalog.setup_clients.map(({ id }) => id)).toEqual(
SUPPORTED_CLIENT_DEFINITIONS.map(({ name }) => name),
);
expect(catalog.cli.commands).toHaveLength(CLI_COMMAND_NAMES.length);
expect(catalog.providers.map(({ id }) => id)).toEqual(
expect.arrayContaining(
[
OBJDUMP_PROVIDER_IDENTITY,
RIZIN_PROVIDER_IDENTITY,
GDB_PROVIDER_IDENTITY,
].map(({ id }) => id),
),
);
expect(
catalog.providers.find(({ id }) => id === HOPPER_PROVIDER_IDENTITY.id)
?.capabilities,
@@ -0,0 +1,78 @@
import { execFileSync } from "node:child_process";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const root = fileURLToPath(new URL("../../../", import.meta.url));
const runNode = (source: string, ...arguments_: string[]): string =>
execFileSync(
process.execPath,
["--input-type=module", "-e", source, ...arguments_],
{ cwd: root, encoding: "utf8" },
);
describe("reverse-tools mutation configuration", () => {
it("loads nonempty targets from both actual Stryker configs", () => {
const result = runNode(
`const [mainUrl, semanticsUrl] = process.argv.slice(1);
const main = await import(mainUrl);
const semantics = await import(semanticsUrl);
process.stdout.write(JSON.stringify({
main: main.default.mutate.length,
semantics: semantics.default.mutate.length,
}));`,
pathToFileURL(join(root, "stryker.config.mjs")).href,
pathToFileURL(join(root, "stryker.semantics.config.mjs")).href,
);
const targets = JSON.parse(result) as {
main: number;
semantics: number;
};
expect(targets.main).toBeGreaterThan(0);
expect(targets.semantics).toBeGreaterThan(0);
});
it("fails closed when an owned mutation method is missing", async () => {
const directory = await createTestTempDirectory("rea-mutation-selector-");
const source = join(directory, "source.ts");
await writeFile(source, "class Present { run() {} }\n");
const result = runNode(
`import { mutationRanges } from "./scripts/lib/reverse-tools-mutation-targets.mjs";
const [source] = process.argv.slice(1);
try {
mutationRanges(source, [{ kind: "method", owner: "Missing", name: "run" }]);
throw new Error("missing owner unexpectedly selected");
} catch (error) {
if (!(error instanceof Error) || !error.message.includes("found 0")) throw error;
process.stdout.write(error.message);
}`,
source,
);
expect(result).toMatch(/found 0/u);
});
it("fails closed when an owned mutation method is ambiguous", async () => {
const directory = await createTestTempDirectory("rea-mutation-selector-");
const source = join(directory, "source.ts");
await writeFile(source, "class Owner { run() {} run(value: string) {} }\n");
const result = runNode(
`import { mutationRanges } from "./scripts/lib/reverse-tools-mutation-targets.mjs";
const [source] = process.argv.slice(1);
try {
mutationRanges(source, [{ kind: "method", owner: "Owner", name: "run" }]);
throw new Error("ambiguous target unexpectedly selected");
} catch (error) {
if (!(error instanceof Error) || !error.message.includes("found 2")) throw error;
process.stdout.write(error.message);
}`,
source,
);
expect(result).toMatch(/found 2/u);
});
});
@@ -49,7 +49,7 @@ const lintDiagnostics = async (root: string) =>
),
).diagnostics;
it("includes every actually linted file in both cached lint task inputs", () => {
it("covers the lint inventory and root tool configs in resolved cache inputs", () => {
const scan = spawnSync(
process.execPath,
[join(repository, "node_modules/oxlint/bin/oxlint"), "--debug=files"],
@@ -69,6 +69,7 @@ it("includes every actually linted file in both cached lint task inputs", () =>
"run",
"lint",
"lint:built",
"knip",
"--dry=json",
],
{
@@ -99,6 +100,14 @@ it("includes every actually linted file in both cached lint task inputs", () =>
files.filter((file) => !Object.hasOwn(task.inputs, file)),
`${task.task} omits actual checker inputs`,
).toEqual([]);
const knip = tasks.find(({ task }) => task === "knip");
expect(knip).toBeDefined();
expect(
files.filter(
(file) => !file.includes("/") && !Object.hasOwn(knip!.inputs, file),
),
"knip omits root tool configuration inputs",
).toEqual([]);
});
it("summarizes warnings without losing their complete diagnostic records", async () => {
@@ -0,0 +1,290 @@
import { spawnSync } from "node:child_process";
import { mkdir, readFile, rm, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { expect, it } from "vitest";
import { z } from "zod";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { workflowGit } from "../../support/workflowGit.js";
const repository = fileURLToPath(new URL("../../../", import.meta.url));
const turbo = join(repository, "node_modules/turbo/bin/turbo");
const reportScript = join(repository, "scripts/ci/static-check-report.mjs");
const rootConfigSchema = z.object({
globalDependencies: z.array(z.string()).optional(),
globalPassThroughEnv: z.array(z.string()).optional(),
tasks: z.record(z.string(), z.record(z.string(), z.unknown())),
});
const dryRunSchema = z.object({
tasks: z.array(z.object({ taskId: z.string(), hash: z.string() })),
});
const execute = (command: string, args: string[], cwd: string) =>
spawnSync(process.execPath, [command, ...args], {
cwd,
encoding: "utf8",
timeout: 30_000,
maxBuffer: 16 * 1024 * 1024,
env: process.env,
});
const readRootConfig = async () =>
rootConfigSchema.parse(
JSON.parse(await readFile(join(repository, "turbo.json"), "utf8")),
);
const writeTaskFixture = async (
root: string,
taskNames: string[],
scripts: Record<string, string>,
) => {
const config = await readRootConfig();
const tasks = Object.fromEntries(
taskNames.map((name) => {
const task = config.tasks[name];
if (task === undefined) throw new Error(`Missing Turbo task ${name}`);
// These tests measure a task's own inputs. Drop dependency edges so the
// unrelated compile task cannot add fixture-specific inputs or outputs.
const { dependsOn: _dependsOn, ...definition } = task;
return [name, definition];
}),
);
await writeFile(
join(root, "turbo.json"),
JSON.stringify(
{
...(config.globalDependencies === undefined
? {}
: { globalDependencies: config.globalDependencies }),
...(config.globalPassThroughEnv === undefined
? {}
: { globalPassThroughEnv: config.globalPassThroughEnv }),
tasks,
},
null,
2,
),
);
await writeFile(
join(root, "package.json"),
JSON.stringify({
name: "rea-static-task-cache-fixture",
version: "1.0.0",
private: true,
packageManager: "npm@11.16.0",
scripts,
}),
);
await writeFile(
join(root, "package-lock.json"),
JSON.stringify({
name: "rea-static-task-cache-fixture",
version: "1.0.0",
lockfileVersion: 3,
packages: {
"": { name: "rea-static-task-cache-fixture", version: "1.0.0" },
},
}),
);
};
const runTurbo = (
root: string,
task: string,
cacheDirectory: string,
dryRun = false,
) =>
execute(
turbo,
[
"run",
task,
...(dryRun ? ["--dry=json"] : ["--output-logs=errors-only"]),
"--cache=local:rw,remote:r",
"--cache-dir",
cacheDirectory,
],
root,
);
const taskHash = (root: string, task: string, cacheDirectory: string) => {
const result = runTurbo(root, task, cacheDirectory, true);
expect(result.error).toBeUndefined();
expect(result.status, result.stderr).toBe(0);
const { tasks } = dryRunSchema.parse(JSON.parse(result.stdout));
const entry = tasks.find(({ taskId }) => taskId === task);
if (entry === undefined) throw new Error(`Turbo omitted task ${task}`);
return entry.hash;
};
it("restores a real lint report across cold, warm, and fresh consumer checkouts", async () => {
const producer = await createTestTempDirectory("rea-static-cache-producer-");
const consumer = await createTestTempDirectory("rea-static-cache-consumer-");
const cache = await createTestTempDirectory("rea-static-cache-store-");
const script = "node scripts/ci/static-check-report.mjs lint";
for (const root of [producer, consumer]) {
await mkdir(join(root, "scripts/ci"), { recursive: true });
await mkdir(join(root, "src"), { recursive: true });
await symlink(
join(repository, "node_modules"),
join(root, "node_modules"),
"junction",
);
await writeTaskFixture(root, ["lint"], { lint: script });
await writeFile(
join(root, ".nvmrc"),
await readFile(join(repository, ".nvmrc")),
);
await writeFile(join(root, ".gitignore"), ".cache/\nnode_modules/\n");
await writeFile(
join(root, ".oxlintrc.json"),
JSON.stringify({ rules: { "no-debugger": "error" } }),
);
await writeFile(join(root, "src/check.js"), "export const ready = true;\n");
await writeFile(
join(root, "scripts/ci/static-check-report.mjs"),
await readFile(reportScript, "utf8"),
);
await workflowGit(root, ["init", "--initial-branch=main"]);
await workflowGit(root, ["add", "."]);
await workflowGit(root, ["commit", "-m", "test: seed static task cache"]);
}
const cold = runTurbo(producer, "lint", cache);
expect(cold.error).toBeUndefined();
expect(cold.status, cold.stderr).toBe(0);
expect(cold.stdout).toMatch(/Cached:\s+0 cached/u);
const report = join(producer, ".cache/static-checks/oxlint.json");
const cleanReport = await readFile(report, "utf8");
await rm(join(producer, ".cache"), { recursive: true });
const warm = runTurbo(producer, "lint", cache);
expect(warm.error).toBeUndefined();
expect(warm.status, warm.stderr).toBe(0);
expect(warm.stdout).toMatch(/Cached:\s+1 cached/u);
expect(await readFile(report, "utf8")).toBe(cleanReport);
const freshConsumer = runTurbo(consumer, "lint", cache);
expect(freshConsumer.error).toBeUndefined();
expect(freshConsumer.status, freshConsumer.stderr).toBe(0);
expect(freshConsumer.stdout).toMatch(/Cached:\s+1 cached/u);
expect(
await readFile(join(consumer, ".cache/static-checks/oxlint.json"), "utf8"),
).toBe(cleanReport);
await writeFile(join(consumer, "src/check.js"), "debugger;\n");
const invalid = runTurbo(consumer, "lint", cache);
expect(invalid.error).toBeUndefined();
expect(invalid.status).not.toBe(0);
expect(invalid.stdout).toMatch(/Cached:\s+0 cached/u);
const { diagnostics } = z
.object({
diagnostics: z.array(
z.object({ code: z.string().optional(), severity: z.string() }),
),
})
.parse(
JSON.parse(
await readFile(
join(consumer, ".cache/static-checks/oxlint.json"),
"utf8",
),
),
);
expect(diagnostics).toContainEqual(
expect.objectContaining({
code: "eslint(no-debugger)",
severity: "error",
}),
);
});
it("invalidates checker task hashes for Node, ignore, and VitePress config changes", async () => {
const root = await createTestTempDirectory("rea-static-cache-inputs-");
const cache = await createTestTempDirectory("rea-static-cache-hashes-");
await mkdir(join(root, "docs/.vitepress"), { recursive: true });
await mkdir(join(root, "src"), { recursive: true });
await mkdir(join(root, "tests"), { recursive: true });
await writeTaskFixture(
root,
["jscpd", "knip", "metadata:check", "scan:todos"],
// This fixture probes only Turbo's real task hash; the checker commands
// are intentionally inert so the hash test cannot invoke large suites.
{
jscpd: 'node -e "process.exit(0)"',
knip: 'node -e "process.exit(0)"',
"metadata:check": 'node -e "process.exit(0)"',
"scan:todos": 'node -e "process.exit(0)"',
},
);
await writeFile(join(root, ".nvmrc"), "24.18.0\n");
await writeFile(join(root, ".npmrc"), "engine-strict=true\n");
await writeFile(join(root, ".gitignore"), ".cache/\n");
await writeFile(join(root, ".jscpd.json"), "{}\n");
await writeFile(join(root, "docs/.vitepress/config.ts"), "export {};\n");
await writeFile(
join(root, "vitest.config.ts"),
'import { CiTestSequencer } from "./tests/ciTestSequencer.js";\nexport const sequencer = CiTestSequencer;\n',
);
await writeFile(join(root, "src/input.ts"), "export {};\n");
await writeFile(join(root, "tests/input.ts"), "export {};\n");
const initial = new Map<string, string>();
for (const task of ["jscpd", "knip", "metadata:check", "scan:todos"])
initial.set(task, taskHash(root, task, cache));
await writeFile(join(root, ".nvmrc"), "24.19.0\n");
for (const task of ["jscpd", "metadata:check", "scan:todos"])
expect(
taskHash(root, task, cache),
`${task} must hash the Node pin`,
).not.toBe(initial.get(task));
await writeFile(join(root, ".nvmrc"), "24.18.0\n");
await writeFile(join(root, ".npmrc"), "engine-strict=false\n");
for (const task of ["jscpd", "knip", "metadata:check", "scan:todos"])
expect(
taskHash(root, task, cache),
`${task} must hash npm settings`,
).not.toBe(initial.get(task));
await writeFile(join(root, ".npmrc"), "engine-strict=true\n");
for (const task of ["jscpd", "metadata:check", "scan:todos"])
expect(taskHash(root, task, cache), `${task} restores after Node pin`).toBe(
initial.get(task),
);
await writeFile(join(root, ".gitignore"), ".cache/\ncoverage/\n");
for (const task of ["jscpd", "knip"])
expect(taskHash(root, task, cache), `${task} must hash gitignore`).not.toBe(
initial.get(task),
);
await writeFile(join(root, ".gitignore"), ".cache/\n");
for (const task of ["jscpd", "knip"])
expect(
taskHash(root, task, cache),
`${task} restores after gitignore`,
).toBe(initial.get(task));
await writeFile(
join(root, "docs/.vitepress/config.ts"),
"export const configRevision = 2;\n",
);
expect(
taskHash(root, "knip", cache),
"knip must hash its configured VitePress entry",
).not.toBe(initial.get("knip"));
await writeFile(join(root, "docs/.vitepress/config.ts"), "export {};\n");
await writeFile(join(root, "vitest.config.ts"), "export {};\n");
expect(
taskHash(root, "knip", cache),
"knip must hash vitest.config.ts so unused sequencer imports invalidate the cache",
).not.toBe(initial.get("knip"));
for (const task of ["jscpd", "metadata:check", "scan:todos"])
expect(
taskHash(root, task, cache),
`${task} must ignore vitest.config.ts`,
).toBe(initial.get(task));
});
@@ -0,0 +1,159 @@
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
import { npxRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js";
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
import { skillDestinations } from "../../../src/application/SetupSkill.js";
import { supportedClients } from "../../../src/application/SupportedClients.js";
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { clearClientLocationEnvironment } from "../../fixtures/clientEnvironment.js";
/**
* The registration command setup writes on the host running the tests. Windows
* wraps it in `cmd.exe /d /c`, so the expected entry follows the host too.
*/
const command = npxRegistrationCommand(process.platform);
beforeEach(clearClientLocationEnvironment);
afterEach(() => vi.unstubAllEnvs());
const workbuddyPath = (
home: string,
platform: NodeJS.Platform = process.platform,
env: Parameters<typeof supportedClients>[2] = {},
) =>
supportedClients(home, platform, env).find(
({ name }) => name === "workbuddy",
);
describe("WorkBuddy configuration paths", () => {
it("resolves the global mcp.json under the home root", () => {
expect(workbuddyPath("/home/a")?.configPath).toBe(
join("/home/a", ".workbuddy", "mcp.json"),
);
expect(workbuddyPath("/Users/a")?.markerPath).toBe(
join("/Users/a", ".workbuddy"),
);
expect(workbuddyPath("C:\\Users\\a", "win32")?.configPath).toBe(
join("C:\\Users\\a", ".workbuddy", "mcp.json"),
);
});
it("resolves the registration format as the plain mcpServers JSON dialect", () => {
expect(workbuddyPath("/home/a")?.format).toBe("json");
});
it("resolves the personal skills directory under the home root", () => {
expect(
skillDestinations("/home/a", ["workbuddy"]).map(({ path }) => path),
).toEqual([
join("/home/a", ".workbuddy", "skills", "reverse-engineer-anything"),
]);
expect(
skillDestinations("C:\\Users\\a", ["workbuddy"], {}, "win32").map(
({ path }) => path,
),
).toEqual([
join("C:\\Users\\a", ".workbuddy", "skills", "reverse-engineer-anything"),
]);
});
});
describe("WorkBuddy JSON registration", () => {
const workbuddyClient = async () => {
const home = await createTestTempDirectory("rea-workbuddy-");
const client = workbuddyPath(home, process.platform);
if (client?.markerPath === undefined)
throw new Error("missing WorkBuddy client");
await mkdir(client.markerPath, { recursive: true });
return { home, client };
};
it("upserts rea into mcpServers while preserving unrelated settings", async () => {
const { home, client } = await workbuddyClient();
await writeFile(
client.configPath,
`{
"mcpServers": {
"other": { "command": "other-server" }
}
}`,
);
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
expect(parsed.mcpServers.other).toEqual({ command: "other-server" });
expect(parsed.mcpServers.rea).toEqual({
command: command[0],
args: command.slice(1),
});
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "unchanged",
});
expect(
(
await readClientRegistrationStatuses(home, undefined, {
platform: process.platform,
environment: {},
})
).find(({ client }) => client === "workbuddy"),
).toMatchObject({ state: "aligned", command });
});
it("creates the mcpServers table in an existing mcp.json without servers", async () => {
const { client } = await workbuddyClient();
await writeFile(
client.configPath,
JSON.stringify({ unrelated: { setting: true } }, null, 2),
);
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
expect(parsed.unrelated).toEqual({ setting: true });
expect(parsed.mcpServers.rea).toEqual({
command: command[0],
args: command.slice(1),
});
});
it("registers into an empty mcp.json", async () => {
const { client } = await workbuddyClient();
await writeFile(client.configPath, "");
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
expect(parsed.mcpServers.rea).toEqual({
command: command[0],
args: command.slice(1),
});
});
it("removes only the rea entry on uninstall", async () => {
const { home, client } = await workbuddyClient();
await writeFile(
client.configPath,
JSON.stringify(
{ mcpServers: { other: { command: "other-server" } } },
null,
2,
),
);
await configureClientConfiguration(client, {}, command);
expect((await systemUninstallHost(home).removeClient(client)).status).toBe(
"removed",
);
const parsed = JSON.parse(await readFile(client.configPath, "utf8"));
expect(parsed.mcpServers.other).toEqual({ command: "other-server" });
expect(parsed.mcpServers.rea).toBeUndefined();
});
});
+21
View File
@@ -6,6 +6,7 @@ import {
machoImage,
} from "../../../src/artifacts/apple/MachoImage.fixture.js";
import { readGoBinaryImage } from "../../../src/go/GoBinaryImage.js";
import { readGoMachoImage } from "../../../src/go/GoMachoImage.js";
import {
createGoBinaryFixture,
GO_MODULE_TEXT,
@@ -519,6 +520,26 @@ it("rejects build-info declared inside an unmapped Mach-O segment", () => {
expect(() => readGoBinaryImage(fixture.bytes)).toThrowError(/unmapped/i);
});
it("does not mark Mach-O section bytes outside their owning segment as read-only", () => {
const fixture = createGoBinaryFixture({ format: "macho" });
const command = 32;
const section = command + 72;
fixture.bytes.write("__TEXT", command + 8, "ascii");
fixture.bytes.writeBigUInt64LE(1024n, command + 48);
fixture.bytes.writeUInt32LE(1, command + 56);
fixture.bytes.writeUInt32LE(1, command + 60);
fixture.bytes.write("__debug_info", section, "ascii");
fixture.bytes.write("__TEXT", section + 16, "ascii");
fixture.bytes.writeBigUInt64LE(0x10c00n, section + 32);
fixture.bytes.writeBigUInt64LE(128n, section + 40);
fixture.bytes.writeUInt32LE(3072, section + 48);
const image = readGoMachoImage(fixture.bytes);
expect(image.sections[0]).toMatchObject({
file_backed: false,
read_only: false,
});
});
it.each(["elf", "pe", "macho"] as const)(
"refuses file aliases overlapping only part of a zero-filled %s module header",
(format) => {
@@ -0,0 +1,87 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it } from "vitest";
import { ArtifactResourceScope } from "../../../src/artifacts/ArtifactResourceScope.js";
import type { JavaScriptApplicationAnalysisResult } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import { buildJavaScriptNativeHandoffs } from "../../../src/domain/javascript/javascriptNativeHandoff.js";
import { analyzeJavaScriptApplication } from "../../../src/application/javascript/JavaScriptApplicationService.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const analyzeFixture = async (source: string) => {
const fixture = await createTestTempDirectory("rea-native-types-");
const scope = new ArtifactResourceScope();
try {
await writeFile(join(fixture, "main.ts"), `${source}\n`);
await writeFile(join(fixture, "addon.node"), "");
const result = await analyzeJavaScriptApplication(
{ input_path: fixture, format: "directory" },
scope,
);
if (!result.ok) throw result.error;
return result.value
.normalized_result as unknown as JavaScriptApplicationAnalysisResult;
} finally {
await scope.close();
}
};
it("does not request native-addon members from erased TypeScript names", async () => {
const typeImport = await analyzeFixture(
'import type { NativeThing } from "./addon.node";',
);
expect(typeImport.summary.native_addon_bindings).toBe(0);
expect(typeImport.summary.resolved_native_addon_bindings).toBe(0);
expect(
typeImport.graph.nodes.filter((node) => node.kind === "native-export"),
).toEqual([]);
expect(
buildJavaScriptNativeHandoffs(
typeImport.graph.nodes,
typeImport.graph.edges,
[],
).flatMap((handoff) => handoff.requested_exports),
).toEqual([]);
const typeReexport = await analyzeFixture(
'export type { Extra } from "./addon.node";',
);
expect(typeReexport.summary.native_addon_bindings).toBe(0);
expect(
typeReexport.graph.nodes.filter((node) => node.kind === "native-export"),
).toEqual([]);
expect(
buildJavaScriptNativeHandoffs(
typeReexport.graph.nodes,
typeReexport.graph.edges,
[],
).flatMap((handoff) => handoff.requested_exports),
).toEqual([]);
const mixed = await analyzeFixture(
'import { type OtherThing, load } from "./addon.node"; load();',
);
expect(mixed.summary.native_addon_bindings).toBe(1);
const mixedExports = mixed.graph.nodes.filter(
(node) => node.kind === "native-export",
);
expect(mixedExports).toHaveLength(1);
expect(
mixedExports[0]?.observations[0]?.properties.requested_members,
).toEqual(["load"]);
expect(
buildJavaScriptNativeHandoffs(mixed.graph.nodes, mixed.graph.edges, []).map(
(handoff) => handoff.requested_exports,
),
).toEqual([["load"]]);
const value = await analyzeFixture(
'import { load } from "./addon.node"; load();',
);
expect(value.summary.native_addon_bindings).toBe(1);
expect(
value.graph.nodes.filter((node) => node.kind === "native-export")[0]
?.observations[0]?.properties.requested_members,
).toEqual(["load"]);
}, 30_000);
@@ -70,6 +70,57 @@ const connect = async (
return { client, session };
};
it("projects opted-in query names identically from retained and portable MCP Evidence", async () => {
const { client, session } = await connect();
const capture = analysisViewCaptureFixture();
capture.records = capture.records.slice(0, 2);
capture.total_records = 2;
capture.records.forEach((record, index) => {
record.reported = {
request: {
method: "GET",
url:
index === 0
? "https://api.test/products?a+b=one&a%2Bb=two&=three&a+b=four"
: "https://api.test/products?a+b=five&snow=six#ignored",
},
};
});
const parent = analysisViewCaptureEvidence(capture);
const retained = session.recordEvidence(parent);
if (!retained.ok) throw retained.error;
const outputs = [];
for (const source of [
{ kind: "inline", evidence: parent },
{ kind: "retained-evidence", evidence_id: parent.evidence_id },
]) {
const response = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source,
view: { kind: "api-surface", include_query_parameter_names: true },
},
});
expect(response.isError).not.toBe(true);
const evidence = parseEvidence(response.structuredContent);
expect(evidence.normalized_result).toMatchObject({
parent_evidence_id: parent.evidence_id,
groups: [
{
query_parameter_names: [
{ name: "", record_ordinals: [0] },
{ name: "a b", record_ordinals: [0, 1] },
{ name: "a+b", record_ordinals: [0] },
{ name: "snow", record_ordinals: [1] },
],
},
],
});
outputs.push(evidence.normalized_result);
}
expect(outputs[0]).toEqual(outputs[1]);
});
it("discovers an oversized native dossier by exact metadata and reads its retained view", async () => {
const { client, session } = await connect();
const advertised = (await client.listTools()).tools.find(
@@ -278,6 +329,39 @@ it("advertises exact schemas and projects one layout section from retained Evide
);
});
it("points omitted inline messages to the caller's parent without promising session recovery", async () => {
const { client, session } = await connect();
const messages = Array.from(
{ length: 65 },
(_, index) => `Limitation ${String(index).padStart(2, "0")}`,
).concat("z".repeat(300_000));
const parent = analysisViewLayoutEvidence({
...analysisViewLayoutFixture(),
limitations: messages,
});
expect(session.evidenceById(parent.evidence_id)).toBeUndefined();
const response = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: { kind: "inline", evidence: parent },
view: { kind: "summary" },
},
});
expect(response.isError).not.toBe(true);
const view = toolContract("inspect_analysis_view").outputSchema.parse(
response.structuredContent,
);
const projected = z
.object({ limitations: z.array(z.string()) })
.parse(view.normalized_result);
expect(projected.limitations).toEqual([
...messages.slice(0, 65),
`1 additional limitations omitted from this view; consult source parent Evidence ${parent.evidence_id} for the complete list (the caller-supplied record, or its retaining session).`,
]);
expect(session.evidenceById(parent.evidence_id)).toBeUndefined();
expect(session.evidenceById(view.evidence_id)).toEqual(parseEvidence(view));
});
it("reports a tampered inline Evidence ID at its full MCP source path", async () => {
const { client } = await connect();
const parent = analysisViewLayoutEvidence();
@@ -254,8 +254,11 @@ const assertHistoricalInventory = async (
const { archive, parent, inventoryEvidence, graph } = input;
// Historical records may omit a later inventory field. Input parsing must
// not insert defaults inside that authenticated child Evidence.
const { integrity_contradictions: _contradictions, ...legacyInventory } =
graph;
const {
integrity_contradictions: _contradictions,
coverage: _coverage,
...legacyInventory
} = graph;
const legacyTarget = {
path: archive,
sha256: graph.manifest.root_sha256,
@@ -275,6 +278,9 @@ const assertHistoricalInventory = async (
expect(
legacyInspection.substeps[0]?.evidence.normalized_result,
).not.toHaveProperty("integrity_contradictions");
expect(
legacyInspection.substeps[0]?.evidence.normalized_result,
).not.toHaveProperty("coverage");
const legacyParent = createEvidence(legacyTarget, parent.provider, {
operation: "inspect_artifact",
parameters: {},
+27 -15
View File
@@ -1,5 +1,7 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
import { artifactInventoryResultSchema } from "../../../src/domain/artifactGraph.js";
import { ok as resultOk } from "../../../src/domain/result.js";
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -98,20 +100,6 @@ it.each([
20_000,
);
const artifactInventoryResultSchema = z.object({
occurrences: z.array(
z.object({ logical_path: z.string(), hash_status: z.string() }),
),
integrity_contradictions: z.array(
z.object({
logical_path: z.string(),
declared_sha256: z.string(),
observed_sha256: z.string(),
trust: z.literal("observed-untrusted"),
}),
),
});
it("extracts an active archive through MCP when requested", async () => {
const root = await createTestTempDirectory("rea-artifact-extract-mcp-");
const archive = join(root, "fixture.zip");
@@ -318,6 +306,30 @@ it("records an explicitly continued mismatch, preserves verified siblings, and n
}),
]),
});
const { coverage: _coverage, ...legacyInventory } = inventory;
const historical = createEvidence(
{ path: archive, sha256: inventory.manifest.root_sha256, format: "asar" },
compact.provider,
{
operation: "inventory_artifact",
parameters: {},
result: jsonValueSchema.parse(legacyInventory),
},
);
const retainedComparison = await client.callTool({
name: "compare_artifacts",
arguments: { left: evidence, right: historical },
});
expect(
retainedComparison.isError,
JSON.stringify(retainedComparison),
).not.toBe(true);
expect(
toolEvidence(retainedComparison.structuredContent).normalized_result,
).toMatchObject({
status: "contradiction",
summary: { unchanged: 2, contradiction: 2, unknown: 0 },
});
} finally {
await Promise.allSettled([client.close(), server.close(), session.close()]);
}
@@ -0,0 +1,168 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { McpServer } from "@modelcontextprotocol/server";
import { expect, it } from "vitest";
import { CutterBridgeService } from "../../../src/cutter/CutterBridgeService.js";
import { registerCutterTools } from "../../../src/server/registerCutterTools.js";
import { createToolResultDelivery } from "../../../src/server/toolResult.js";
import { silentLogger } from "../../../src/logger.js";
it("propagates MCP cancellation into an active Cutter command and reports uncertain completion", async () => {
let markDispatched: (() => void) | undefined;
let observedAbort = false;
const dispatched = new Promise<void>((resolve) => {
markDispatched = resolve;
});
const service = new CutterBridgeService({
listSessions: async () => ({
sessions: [],
bridge_directory: "/private/bridge",
discovery_status: "no_live_bridge_found",
bridge_directory_security: "private_verified",
}),
execute: async ({ signal }) => {
markDispatched?.();
await new Promise<void>((resolve) => {
signal?.addEventListener(
"abort",
() => {
observedAbort = true;
resolve();
},
{ once: true },
);
});
return {
requestId: "4b18ce4d-bf31-456e-ae31-e8c547b2f9db",
output: null,
currentFile: null,
documentGeneration: 1,
identityStatus: "partial" as const,
cutterVersion: "Cutter fixture version",
executionState: "unknown" as const,
error: "transport-response-missing",
message: "The command may have completed; do not retry automatically",
outputTruncated: false,
};
},
});
const server = new McpServer({ name: "cutter-cancellation", version: "1" });
registerCutterTools(
server,
service,
silentLogger,
createToolResultDelivery(undefined),
);
const client = new Client({ name: "cutter-cancellation", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const controller = new AbortController();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const request = client.callTool(
{
name: "cutter_command",
arguments: {
session_id: "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a",
expected_generation: 1,
command: "Ps /tmp/possibly-saved.rzdb",
json: false,
},
},
{ signal: controller.signal },
);
await dispatched;
controller.abort();
await expect(request).rejects.toThrow(/abort/iu);
await expect.poll(() => observedAbort).toBe(true);
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
it("shares one cleanup proof across concurrent Cutter MCP commands without BinarySession", async () => {
let releaseProof!: () => void;
let enterProof!: () => void;
const proof = new Promise<void>((resolve) => {
releaseProof = resolve;
});
const entered = new Promise<void>((resolve) => {
enterProof = resolve;
});
let confirmations = 0;
let dispatches = 0;
const service = new CutterBridgeService({
listSessions: async () => ({
sessions: [],
bridge_directory: "/private/bridge",
discovery_status: "no_live_bridge_found",
bridge_directory_security: "private_verified",
}),
confirmCommandCompletion: async () => {
confirmations += 1;
if (confirmations > 1) {
await proof;
await new Promise<void>((resolve) => setImmediate(resolve));
return { ok: true, value: false };
}
enterProof();
await proof;
return { ok: true, value: true };
},
execute: async ({ command }) => {
dispatches += 1;
return {
requestId: `00000000-0000-4000-8000-${String(dispatches).padStart(12, "0")}`,
output: command,
currentFile: null,
documentGeneration: 1,
identityStatus: "partial",
cutterVersion: "fixture",
executionState: dispatches === 1 ? "unknown" : "complete",
error: dispatches === 1 ? "transport-response-missing" : null,
message: null,
outputTruncated: false,
};
},
});
const server = new McpServer({ name: "cutter-cleanup-race", version: "1" });
registerCutterTools(
server,
service,
silentLogger,
createToolResultDelivery(undefined),
);
const client = new Client({ name: "cutter-cleanup-race", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const call = (command: string) =>
client.callTool({
name: "cutter_command",
arguments: {
session_id: "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a",
expected_generation: 1,
command,
},
});
let pending: Promise<unknown>[] = [];
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
expect((await call("lost response")).isError).toBe(true);
const first = call("first queued command");
const second = call("second queued command");
pending = [first, second];
await entered;
await new Promise<void>((resolve) => setImmediate(resolve));
releaseProof();
const results = await Promise.all([first, second]);
for (const result of results) expect(result.isError).not.toBe(true);
expect(confirmations).toBe(1);
expect(dispatches).toBe(3);
} finally {
releaseProof();
await Promise.allSettled(pending);
await Promise.allSettled([client.close(), server.close()]);
}
});
+260
View File
@@ -0,0 +1,260 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { chmod, writeFile } from "node:fs/promises";
import { createServer as createNetServer } from "node:net";
import { createHmac } from "node:crypto";
import { join } from "node:path";
import { expect, it, onTestFinished } from "vitest";
import {
createTestBinarySession,
createCacheProvider,
} from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { createServer } from "../../../src/server/createServer.js";
import { silentLogger } from "../../../src/logger.js";
const assertUncertainEvidence = async (
client: Client,
session: ReturnType<typeof createTestBinarySession>,
sessionId: string,
): Promise<void> => {
const uncertain = await client.callTool({
name: "cutter_command",
arguments: {
session_id: sessionId,
expected_generation: 3,
command: "Ps /tmp/uncertain.rzdb",
},
});
expect(uncertain.isError).toBe(true);
const uncertainText = uncertain.content
.filter(
(block): block is { type: "text"; text: string } => block.type === "text",
)
.map((block) => block.text)
.join("\n");
const uncertainError = JSON.parse(uncertainText) as {
error: { details: { partial_observation: { evidence_id: string } } };
};
const uncertainEvidence = session.evidenceById(
uncertainError.error.details.partial_observation.evidence_id,
);
expect(uncertainEvidence).toBeDefined();
if (uncertainEvidence === undefined)
throw new Error("partial Evidence missing");
expect(uncertainEvidence.normalized_result).toMatchObject({
execution_state: "unknown",
error: "transport-response-missing",
message: expect.stringContaining("do not retry automatically"),
document_generation: 3,
});
expect(uncertainEvidence.limitations).toContain(
"Command completion or its output could not be confirmed; " +
"do not retry automatically because the command may have produced " +
"partial or persistent effects.",
);
};
const assertNotStartedEvidenceAndAdmission = async (
client: Client,
sessionId: string,
): Promise<void> => {
const rejected = await client.callTool({
name: "cutter_command",
arguments: {
session_id: sessionId,
expected_generation: 3,
command: "Ps /tmp/not-started.rzdb",
},
});
expect(rejected.isError, JSON.stringify(rejected)).not.toBe(true);
expect(
parseEvidence(rejected.structuredContent).normalized_result,
).toMatchObject({
execution_state: "not_started",
error: "session-poisoned-after-ui-timeout",
});
const admitted = await client.callTool({
name: "cutter_command",
arguments: {
session_id: sessionId,
expected_generation: 3,
command: "iI",
},
});
expect(admitted.isError).not.toBe(true);
};
const createMcpBridge = async (
directory: string,
sessionId: string,
token: string,
): Promise<ReturnType<typeof createNetServer>> => {
let connectionOrdinal = 0;
const bridge = createNetServer((connection) => {
const ordinal = ++connectionOrdinal;
let payload = "";
let clientNonce = "";
let serverNonce = "";
connection.setEncoding("utf8");
connection.on("data", (chunk: string) => {
payload += chunk;
const newline = payload.indexOf("\n");
if (newline < 0) return;
const frame = JSON.parse(payload.slice(0, newline)) as Record<
string,
unknown
>;
payload = payload.slice(newline + 1);
if (frame.kind === "rea-auth-v2") {
clientNonce = String(frame.nonce);
serverNonce = `${ordinal.toString(16).padStart(16, "0")}${"c".repeat(48)}`;
const proof = createHmac("sha256", token)
.update(
`rea-cutter-server-v2:${sessionId}:${clientNonce}:${serverNonce}`,
)
.digest("hex");
connection.write(
`${JSON.stringify({ session_id: sessionId, nonce: serverNonce, proof })}\n`,
);
return;
}
const requestBytes = String(frame.request);
const request = JSON.parse(requestBytes) as Record<string, unknown>;
const expected = createHmac("sha256", token)
.update(
`rea-cutter-client-v2:${sessionId}:${clientNonce}:${serverNonce}:${requestBytes}`,
)
.digest("hex");
if (frame.proof !== expected) {
connection.destroy();
return;
}
if (request.command === "Ps /tmp/uncertain.rzdb") {
connection.destroy();
return;
}
const notStarted = request.command === "Ps /tmp/not-started.rzdb";
const status = request.kind === "status";
const response = JSON.stringify(
request.kind === "ack"
? { ok: true, acknowledged: false }
: {
ok: !notStarted,
...(notStarted
? {
execution_state: "not_started",
error: "session-poisoned-after-ui-timeout",
}
: {}),
session_id: request.session_id,
output: status ? undefined : "synthetic Cutter command output",
current_file: "/fixtures/sample.bin",
document_generation: 3,
...(status
? {
completed_connection: (ordinal - 1)
.toString(16)
.padStart(16, "0"),
completed_commands: [],
}
: {}),
cutter_version: "Cutter fixture version",
identity_status: "partial",
},
);
const responseProof = createHmac("sha256", token)
.update(
`rea-cutter-response-v2:${sessionId}:${clientNonce}:${serverNonce}:${response}`,
)
.digest("hex");
connection.end(`${JSON.stringify({ response, proof: responseProof })}\n`);
});
});
await new Promise<void>((resolve) => bridge.listen(0, "127.0.0.1", resolve));
const address = bridge.address();
if (address === null || typeof address === "string")
throw new Error("Expected an ephemeral IPv4 Cutter test bridge.");
await writeFile(
join(directory, `cutter-${process.pid}-${sessionId}.json`),
JSON.stringify({
session_id: sessionId,
pid: process.pid,
host: "127.0.0.1",
port: address.port,
token,
document_generation: 2,
current_file: null,
cutter_version: "Cutter fixture version",
identity_status: "partial",
}),
{ mode: 0o600 },
);
return bridge;
};
it("preserves live Cutter command Evidence and parity through the MCP boundary", async () => {
const directory = await createTestTempDirectory("rea-cutter-mcp-");
if (process.platform !== "win32") await chmod(directory, 0o700);
const sessionId = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a";
const token = "synthetic-cutter-bridge-token-for-mcp-test";
const bridge = await createMcpBridge(directory, sessionId, token);
onTestFinished(
async () => new Promise<void>((resolve) => bridge.close(() => resolve())),
);
const session = createTestBinarySession(createCacheProvider([]));
const server = createServer(
{ kind: "session", session },
{
logger: silentLogger,
providerEnvironment: { ...process.env, REA_CUTTER_BRIDGE_DIR: directory },
},
);
const client = new Client({ name: "cutter-mcp-boundary", version: "1" });
onTestFinished(async () => {
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const discovery = await client.callTool({
name: "list_cutter_sessions",
arguments: {},
});
expect(discovery.isError).not.toBe(true);
expect(discovery.structuredContent).toMatchObject({
discovery_status: "sessions_found",
sessions: [{ session_id: sessionId, document_generation: 3 }],
});
const command = await client.callTool({
name: "cutter_command",
arguments: {
session_id: sessionId,
expected_generation: 3,
command: "iI",
},
});
expect(command.isError).not.toBe(true);
const evidence = parseEvidence(command.structuredContent);
expect(evidence).toMatchObject({
operation: "cutter_command",
provider: { id: "cutter.python-plugin" },
normalized_result: {
command: "iI",
output: "synthetic Cutter command output",
document_generation: 3,
cutter_version: "Cutter fixture version",
},
});
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
await assertNotStartedEvidenceAndAdmission(client, sessionId);
await assertUncertainEvidence(client, session, sessionId);
});
@@ -313,4 +313,38 @@ describe("overview document identity through MCP", () => {
.isError,
).toBe(true);
});
it("reports document selection unavailable when neither current-document nor list-documents is supported", async () => {
const client = await connect({
execute: (name) => {
if (name === "current_document" || name === "list_documents")
return Promise.resolve(
err(
new AnalysisCapabilityUnavailableError(
"fixture",
name,
"provider lacks document selection",
),
),
);
if (name === "list_segments") return Promise.resolve(ok([]));
if (name === "list_procedures" || name === "list_strings")
return Promise.resolve(ok([]));
throw new Error(`Unexpected analysis operation: ${name}`);
},
});
const result = await client.callTool({
name: "binary_overview",
arguments: {},
});
expect(result.isError).toBe(true);
expect(parseMcpToolError(result).error).toMatchObject({
code: "capability_unavailable",
details: {
provider_id: "fixture",
operation: "list_documents",
reason: expect.stringContaining("provider lacks document selection"),
},
});
});
});
@@ -0,0 +1,643 @@
import { createHash } from "node:crypto";
import { setImmediate } from "node:timers/promises";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type {
Device,
DeviceManager,
FridaMessage,
Script,
Session,
} from "frida";
import { expect, it, onTestFinished } from "vitest";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { evidenceBundleSchema } from "../../../src/domain/evidenceBundle.js";
import { FridaInstrumentationManager } from "../../../src/frida/FridaInstrumentationManager.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
const gate = () => {
let markEntered = () => {};
let release = () => {};
const entered = new Promise<void>((resolve) => {
markEntered = resolve;
});
const released = new Promise<void>((resolve) => {
release = resolve;
});
return {
entered,
release,
async wait() {
markEntered();
await released;
},
};
};
const nativeFixture = () => {
const created: string[] = [];
const loaded: string[] = [];
const unloaded: string[] = [];
const scripts: Script[] = [];
const scriptsAtResume: string[][] = [];
const controls = {
attach: async () => {},
create: async () => {},
load: async () => {},
afterLoad: () => {},
discover: async () => {},
unloadFailures: 0,
detachFailures: 0,
detachCalls: 0,
resumes: 0,
remoteRemovals: 0,
removalFailures: 0,
};
let detached = false;
const nativeSession: Session = {
pid: 512,
detached: { connect() {}, disconnect() {} },
isDetached: () => detached,
async detach() {
controls.detachCalls += 1;
if (controls.detachFailures > 0) {
controls.detachFailures -= 1;
throw new Error("transient detach failure");
}
detached = true;
},
async createScript(source) {
created.push(source);
await controls.create();
let destroyed = false;
let listener:
| ((message: FridaMessage, data: Buffer | null) => void)
| undefined;
const script: Script = {
get isDestroyed() {
return destroyed;
},
message: {
connect(handler) {
listener = handler;
},
disconnect() {
listener = undefined;
},
},
async load() {
await controls.load();
loaded.push(source);
listener?.({ type: "send", payload: source }, null);
controls.afterLoad();
},
async unload() {
unloaded.push(source);
if (controls.unloadFailures > 0) {
controls.unloadFailures -= 1;
throw new Error("transient unload failure");
}
destroyed = true;
},
};
scripts.push(script);
return script;
},
};
const device: Device = {
id: "local",
name: "Local fixture",
type: "local",
async enumerateProcesses() {
await controls.discover();
return [{ pid: 512, name: "fixture" }];
},
async getProcessByPid() {
return { pid: 512, name: "fixture" };
},
async spawn() {
return 512;
},
async resume() {
scriptsAtResume.push(
created.filter((_, index) => scripts[index]?.isDestroyed === false),
);
controls.resumes += 1;
},
async attach() {
await controls.attach();
return nativeSession;
},
};
const deviceManager: DeviceManager = {
async enumerateDevices() {
return [device];
},
async getDeviceById() {
return device;
},
async addRemoteDevice() {
return device;
},
async removeRemoteDevice() {
controls.remoteRemovals += 1;
if (controls.removalFailures > 0) {
controls.removalFailures -= 1;
throw new Error("transient remote removal failure");
}
},
};
return {
controls,
created,
loaded,
unloaded,
scripts,
scriptsAtResume,
deviceManager,
};
};
const connectedFixture = async () => {
const native = nativeFixture();
const manager = new FridaInstrumentationManager({
deviceManager: native.deviceManager,
});
const session = createTestBinarySession(() => {
throw new Error("Binary provider must not start");
});
const server = createServer(
{ kind: "session", session },
{ fridaInstrumentation: manager },
);
const client = new Client({ name: "frida-lifecycle", version: "1" });
onTestFinished(async () => {
native.controls.detachFailures = 0;
native.controls.removalFailures = 0;
await client.close();
await server.close();
await manager.closeAll();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const start = async () => {
const result = await client.callTool({
name: "start_frida_session",
arguments: {
mode: "spawn",
program: "/fixture",
device_id: "local",
},
});
return toolContract("start_frida_session").outputSchema.parse(
result.structuredContent,
).session_id;
};
const load = (sessionId: string, source: string, signal?: AbortSignal) =>
client.callTool(
{
name: "load_frida_script",
arguments: { session_id: sessionId, source_kind: "inline", source },
},
signal === undefined ? undefined : { signal },
);
return { ...native, manager, session, server, client, start, load };
};
const scriptLoadFixture = async (stage: "create" | "load" = "load") => {
const fixture = await connectedFixture();
const id = await fixture.start();
const original = await fixture.load(id, "original");
const held = gate();
onTestFinished(held.release);
fixture.controls[stage] = held.wait;
return { fixture, id, original, held };
};
const pendingShutdown = async (server: { close(): Promise<void> }) => {
let closed = false;
const closing = server
.close()
.then(
() => undefined,
(cause: unknown) => cause,
)
.finally(() => {
closed = true;
});
await setImmediate();
expect(closed).toBe(false);
return { closing };
};
const retryCancelledScriptUnload = async (
fixture: Awaited<ReturnType<typeof connectedFixture>>,
sessionId: string,
scriptId = fixture.manager.status(sessionId)?.scripts[1]?.scriptId,
) => {
if (scriptId === undefined)
throw new Error("Cancelled script was not retained");
const retry = await fixture.client.callTool({
name: "unload_frida_script",
arguments: {
session_id: sessionId,
script_id: scriptId,
},
});
expect(retry.isError).not.toBe(true);
};
const retainedScriptObservation = async (
fixture: Awaited<ReturnType<typeof connectedFixture>>,
sessionId: string,
source: string,
) => {
const response = await fixture.client.callTool({
name: "get_evidence_bundle",
arguments: {},
});
const bundle = evidenceBundleSchema.parse(
toolContract("get_evidence_bundle").outputSchema.parse(
response.structuredContent,
).result,
);
const sourceSha256 = createHash("sha256").update(source).digest("hex");
const records = bundle.records.filter((record) => {
const result = record.normalized_result;
return (
record.operation === "load_frida_script" &&
result !== null &&
typeof result === "object" &&
!Array.isArray(result) &&
result.source_sha256 === sourceSha256
);
});
expect(records).toHaveLength(1);
expect(records[0]?.parameters).toEqual({ session_id: sessionId });
const observation = records[0]?.normalized_result;
if (
observation === undefined ||
observation === null ||
typeof observation !== "object" ||
Array.isArray(observation)
)
throw new Error("Missing retained script observation");
expect(observation).toMatchObject({
script_id: expect.any(String),
source_kind: "inline",
source_path: null,
source_sha256: sourceSha256,
messages_truncated: false,
});
return observation;
};
it.each(["load", "resume", "unload"] as const)(
"finishes an earlier MCP %s request before closing its Frida session",
async (operation) => {
const fixture = await connectedFixture();
const id = await fixture.start();
const original = await fixture.load(id, "original");
const scriptId = toolContract("load_frida_script").outputSchema.parse(
original.structuredContent,
).normalized_result.script_id;
const pending = fixture.client.callTool({
name: {
load: "load_frida_script",
resume: "resume_frida_session",
unload: "unload_frida_script",
}[operation],
arguments: {
session_id: id,
...(operation === "load"
? { source_kind: "inline", source: "last-script" }
: {}),
...(operation === "unload" ? { script_id: scriptId } : {}),
},
});
const closing = fixture.client.callTool({
name: "close_frida_session",
arguments: { session_id: id },
});
expect((await pending).isError).not.toBe(true);
expect((await closing).isError).not.toBe(true);
expect(fixture.loaded).toEqual(
operation === "load" ? ["original", "last-script"] : ["original"],
);
expect(fixture.unloaded).toEqual(fixture.loaded);
expect(fixture.controls.detachCalls).toBe(1);
expect(fixture.controls.resumes).toBe(1);
expect(fixture.manager.status(id)).toBeUndefined();
},
);
it.each(["load", "resume", "unload"] as const)(
"does not dispatch a cancelled queued Frida %s through MCP",
async (operation) => {
const { fixture, id, original, held } = await scriptLoadFixture();
const scriptId = toolContract("load_frida_script").outputSchema.parse(
original.structuredContent,
).normalized_result.script_id;
const first = fixture.load(id, "blocking");
await held.entered;
const controller = new AbortController();
const cancelled =
operation === "load"
? fixture.load(id, "cancelled", controller.signal)
: fixture.client.callTool(
{
name:
operation === "resume"
? "resume_frida_session"
: "unload_frida_script",
arguments: {
session_id: id,
...(operation === "unload" ? { script_id: scriptId } : {}),
},
},
{ signal: controller.signal },
);
const rejected = expect(cancelled).rejects.toThrow(
"cancel queued operation",
);
await fixture.client.ping();
controller.abort(new Error("cancel queued operation"));
await fixture.client.ping();
await rejected;
held.release();
await first;
await fixture.load(id, "barrier");
expect(fixture.created).toEqual(["original", "blocking", "barrier"]);
expect(fixture.unloaded).toEqual([]);
expect(fixture.controls.resumes).toBe(0);
expect(fixture.manager.status(id)?.scripts).toHaveLength(3);
},
);
it.each(["create", "load"] as const)(
"releases only the new script when MCP cancellation arrives during native %s",
async (stage) => {
const { fixture, id, held } = await scriptLoadFixture(stage);
const controller = new AbortController();
const cancelled = fixture.load(id, "cancelled-native", controller.signal);
const rejected = expect(cancelled).rejects.toThrow(
"cancel native operation",
);
await held.entered;
controller.abort(new Error("cancel native operation"));
await fixture.client.ping();
await rejected;
held.release();
await fixture.load(id, "barrier");
await fixture.client.ping();
expect(fixture.unloaded).toEqual(["cancelled-native"]);
expect(fixture.loaded).toEqual(
stage === "create"
? ["original", "barrier"]
: ["original", "cancelled-native", "barrier"],
);
expect(fixture.controls.detachCalls).toBe(0);
expect(fixture.controls.resumes).toBe(0);
expect(fixture.manager.status(id)?.scripts).toHaveLength(2);
const observation = await retainedScriptObservation(
fixture,
id,
"cancelled-native",
);
expect(observation).toMatchObject({
messages:
stage === "create"
? []
: [expect.objectContaining({ payload: "cancelled-native" })],
script_cleanup: "released",
cleanup_error: null,
});
},
);
it("awaits an admitted attach on server shutdown and retries failed native cleanup", async () => {
const fixture = await connectedFixture();
const held = gate();
onTestFinished(held.release);
fixture.controls.attach = held.wait;
fixture.controls.detachFailures = 1;
const starting = fixture.client
.callTool({
name: "start_frida_session",
arguments: {
mode: "attach",
pid: 512,
device_id: "local",
},
})
.catch(() => undefined);
await held.entered;
const { closing } = await pendingShutdown(fixture.server);
expect(fixture.controls.detachCalls).toBe(0);
held.release();
expect(await closing).toBeInstanceOf(AggregateError);
await starting;
expect(fixture.controls.detachCalls).toBe(1);
await fixture.server.close();
expect(fixture.controls.detachCalls).toBe(2);
await fixture.server.close();
expect(fixture.controls.detachCalls).toBe(2);
const afterClose = await fixture.manager.startSession({
mode: "attach",
pid: 512,
});
expect(afterClose).toMatchObject({
ok: false,
error: { _tag: "AnalysisCapabilityUnavailableError" },
});
});
it("drains remote discovery before shutdown and retains failed connection cleanup", async () => {
const fixture = await connectedFixture();
const held = gate();
onTestFinished(held.release);
fixture.controls.discover = held.wait;
fixture.controls.removalFailures = 2;
const discovering = fixture.client
.callTool({
name: "list_frida_processes",
arguments: {
remote: { address: "127.0.0.1:27042" },
},
})
.catch(() => undefined);
await held.entered;
const { closing } = await pendingShutdown(fixture.server);
held.release();
expect(await closing).toBeInstanceOf(AggregateError);
await discovering;
expect(fixture.controls.remoteRemovals).toBe(2);
await fixture.server.close();
expect(fixture.controls.remoteRemovals).toBe(3);
});
it.each(["create", "load"] as const)(
"retains the identity of a cancelled native %s for an explicit MCP unload retry",
async (stage) => {
const { fixture, id, held } = await scriptLoadFixture(stage);
fixture.controls.unloadFailures = 1;
const controller = new AbortController();
const cancelled = fixture.load(id, "cancelled-native", controller.signal);
const rejected = expect(cancelled).rejects.toThrow(
"cancel retained script",
);
await held.entered;
controller.abort(new Error("cancel retained script"));
await fixture.client.ping();
await rejected;
held.release();
await fixture.load(id, "barrier");
await fixture.client.ping();
expect(fixture.manager.status(id)?.scripts).toHaveLength(3);
const observation = await retainedScriptObservation(
fixture,
id,
"cancelled-native",
);
expect(observation).toMatchObject({
messages:
stage === "create"
? []
: [expect.objectContaining({ payload: "cancelled-native" })],
script_cleanup: "incomplete_or_unknown",
cleanup_error: expect.stringContaining("transient unload failure"),
});
const scriptId = observation.script_id;
if (typeof scriptId !== "string")
throw new Error("Missing cancelled script identity");
expect(fixture.manager.status(id)?.scripts[1]?.scriptId).toBe(scriptId);
const resuming = await fixture.client.callTool({
name: "resume_frida_session",
arguments: { session_id: id },
});
expect(resuming.isError).toBe(true);
expect(fixture.controls.resumes).toBe(0);
await retryCancelledScriptUnload(fixture, id, scriptId);
expect(fixture.unloaded).toEqual(["cancelled-native", "cancelled-native"]);
expect(fixture.loaded).toEqual(
stage === "create"
? ["original", "barrier"]
: ["original", "cancelled-native", "barrier"],
);
expect(fixture.manager.status(id)?.scripts).toHaveLength(2);
expect(fixture.controls.detachCalls).toBe(0);
},
);
it.each([0, 1])(
"settles cancelled native-load cleanup before a queued resume (unload failures: %i)",
async (unloadFailures) => {
const { fixture, id, held } = await scriptLoadFixture();
fixture.controls.unloadFailures = unloadFailures;
const controller = new AbortController();
const loading = fixture.load(id, "cancelled-native", controller.signal);
const rejected = expect(loading).rejects.toThrow(
"cancel before queued resume",
);
await held.entered;
const resume = () =>
fixture.client.callTool({
name: "resume_frida_session",
arguments: { session_id: id },
});
const resuming = resume();
await fixture.client.ping();
controller.abort(new Error("cancel before queued resume"));
await fixture.client.ping();
await rejected;
held.release();
const resumed = await resuming;
await fixture.client.ping();
expect(fixture.unloaded).toEqual(["cancelled-native"]);
expect(fixture.scriptsAtResume).toEqual(
unloadFailures === 0 ? [["original"]] : [],
);
expect(fixture.controls.detachCalls).toBe(0);
expect(fixture.session.exportEvidenceBundle().records).toContainEqual(
expect.objectContaining({
operation: "load_frida_script",
normalized_result: expect.objectContaining({
messages: [expect.objectContaining({ payload: "cancelled-native" })],
script_cleanup:
unloadFailures === 0 ? "released" : "incomplete_or_unknown",
}),
}),
);
if (unloadFailures === 0) {
expect(resumed.isError).not.toBe(true);
expect(fixture.manager.status(id)?.scripts).toHaveLength(1);
return;
}
expect(resumed.isError).toBe(true);
expect(fixture.manager.status(id)?.state).toBe("paused");
expect((await resume()).isError).toBe(true);
await retryCancelledScriptUnload(fixture, id);
expect((await resume()).isError).not.toBe(true);
expect(fixture.scriptsAtResume).toEqual([["original"]]);
},
);
it.each([0, 1, 2, 3, 4, 8])(
"keeps MCP load Evidence consistent with queued resume across settlement timing %i",
async (microtasks) => {
const { fixture, id, held } = await scriptLoadFixture();
const controller = new AbortController();
fixture.controls.afterLoad = () => {
let remaining = microtasks;
const abort = () => {
if (remaining-- > 0) queueMicrotask(abort);
else controller.abort(new Error("cancel around load completion"));
};
abort();
};
const loading = fixture.load(id, "settling-native", controller.signal);
const observed = loading.catch(() => undefined);
await held.entered;
const resuming = fixture.client.callTool({
name: "resume_frida_session",
arguments: { session_id: id },
});
await fixture.client.ping();
held.release();
await observed;
expect((await resuming).isError).not.toBe(true);
fixture.controls.afterLoad = () => {};
await fixture.load(id, "barrier");
await fixture.client.ping();
const records = fixture.session
.exportEvidenceBundle()
.records.filter(
(record) =>
record.operation === "load_frida_script" &&
JSON.stringify(record.normalized_result).includes("settling-native"),
);
expect(records).toHaveLength(1);
const recorded = records[0]?.normalized_result;
if (
recorded === null ||
typeof recorded !== "object" ||
Array.isArray(recorded)
)
throw new Error("Missing script load Evidence");
if (recorded.script_cleanup === "released") {
expect(fixture.scriptsAtResume).toEqual([["original"]]);
expect(fixture.unloaded).toEqual(["settling-native"]);
} else {
expect(recorded.script_cleanup).toBeUndefined();
expect(fixture.scriptsAtResume).toEqual([
["original", "settling-native"],
]);
expect(fixture.unloaded).toEqual([]);
}
},
);
@@ -0,0 +1,138 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it } from "vitest";
import { FUNCTION_COMPARISON_EXAMPLE } from "../../../src/contracts/functionComparisonExample.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { functionDossierSchema } from "../../../src/domain/hopperValues.js";
import type { RelationshipCoverage } from "../../../src/domain/relationshipCoverage.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
const observe = (relationshipCoverage: RelationshipCoverage) => {
const template = FUNCTION_COMPARISON_EXAMPLE.left;
if (template.subject === null)
throw new Error("Expected artifact-bound fixture");
const dossier = functionDossierSchema.parse(template.normalized_result);
return createEvidence(
{
path: template.subject.local_path,
sha256: template.subject.digest.sha256,
format: template.subject.format,
},
template.provider,
{
operation: "analyze_function",
parameters: template.parameters,
result: { ...dossier, callees: [], unresolved_calls: [] },
confidence: template.confidence,
authority: template.authority,
relationshipCoverage,
},
);
};
it("preserves directional gaps through advertised schemas and public path reconstruction", async () => {
const session = createTestBinarySession(() => {
throw new Error("Offline call paths must not launch a provider");
});
const server = createServer({ kind: "session", session });
const client = new Client({ name: "function-call-directions", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const advertised = (await client.listTools()).tools.find(
({ name }) => name === "build_call_path",
);
if (advertised === undefined)
throw new Error("Missing build_call_path contract");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
expect(ajv.validateSchema(advertised.inputSchema)).toBe(true);
const validate = ajv.compile(advertised.inputSchema);
for (const { directions, status, exhaustive } of [
{
directions: ["callers"] as ["callers"],
status: "not_found",
exhaustive: true,
},
{
directions: ["callees"] as ["callees"],
status: "unknown",
exhaustive: false,
},
{
directions: ["callers", "callees"] as ["callers", "callees"],
status: "unknown",
exhaustive: false,
},
]) {
const limitation =
"An observed call reference is absent from the inventory.";
const coverage: RelationshipCoverage = {
status: "partial",
limitations: [limitation],
limited_directions: directions,
};
const observation = observe(coverage);
expect(session.recordEvidence(observation).ok).toBe(true);
const input = {
functions: [observation],
start: { address: "0x1000" },
goal: { address: "0x9999" },
};
expect(validate(input), JSON.stringify(validate.errors)).toBe(true);
for (const limited_directions of [
[],
["callers", "callers"],
["callees", "callees"],
["callers", "callees", "callers"],
["incoming"],
])
expect(
validate({
...input,
functions: [
{
...observation,
relationship_coverage: {
...coverage,
limited_directions,
},
},
],
}),
).toBe(false);
const result = await client.callTool({
name: "build_call_path",
arguments: input,
});
if (result.isError) throw new Error(JSON.stringify(result));
expect(result.structuredContent).toMatchObject({
normalized_result: {
status,
search_scope: { exhaustive },
limitations: expect.arrayContaining([limitation]),
},
});
const comparison = await client.callTool({
name: "compare_functions",
arguments: { left: observation, right: observation },
});
if (comparison.isError) throw new Error(JSON.stringify(comparison));
expect(comparison.structuredContent).toMatchObject({
normalized_result: {
dimensions: expect.arrayContaining([
expect.objectContaining({ dimension: "calls", status: "unknown" }),
]),
},
});
// Each scenario owns its Evidence and residual-unknown ledger.
const closed = await session.close();
if (!closed.ok) throw closed.error;
}
} finally {
await Promise.allSettled([session.close(), client.close(), server.close()]);
}
});
@@ -0,0 +1,532 @@
import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { McpServer } from "@modelcontextprotocol/server";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it } from "vitest";
import { z } from "zod";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import {
AnalysisCapabilityUnavailableError,
AnalysisTimeoutError,
} from "../../../src/domain/analysisErrorCore.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { thinMach } from "../../../src/domain/binaryTarget.fixture.js";
import { err, ok } from "../../../src/domain/result.js";
import { GdbSessionManager } from "../../../src/gdb/GdbSessionManager.js";
import { silentLogger } from "../../../src/logger.js";
import { registerGdbTools } from "../../../src/server/registerGdbTools.js";
import type { GdbToolManager } from "../../../src/server/registerGdbTools.js";
import { createToolResultDelivery } from "../../../src/server/toolResult.js";
import {
createBinarySessionTargets,
createCacheProvider,
createTestBinarySession,
} from "../../fixtures/binarySession.js";
import {
validateDebuggerStatusResponse,
waitForStartedFile,
} from "../../support/reverseDebuggerMcpTestHelpers.js";
it.skipIf(process.platform === "win32")(
"propagates MCP cancellation into a running GDB command",
async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-gdb-mcp-cancel-"));
const provider = join(directory, "fake-gdb.mjs");
const commandPath = join(directory, "command-started");
await writeFile(
provider,
`#!${process.execPath}
process.stdout.write("(gdb)\\n");
process.stdin.setEncoding("utf8");
process.stdin.on("data", async (chunk) => {
for (const line of chunk.split("\\n")) {
const match = /^(\\d+)/.exec(line);
if (!match) continue;
if (line.includes("auto-load off")) process.stdout.write(match[1] + "^done\\n");
else await import("node:fs/promises").then((fs) => fs.writeFile(${JSON.stringify(commandPath)}, "started"));
}
});
`,
);
await chmod(provider, 0o700);
const manager = new GdbSessionManager({
platform: "linux",
environment: { REA_GDB_COMMAND: provider },
});
const server = new McpServer({ name: "gdb-cancellation", version: "1" });
registerGdbTools(
server,
manager,
silentLogger,
createToolResultDelivery(undefined),
);
const client = new Client({ name: "gdb-cancellation", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const started = await client.callTool({
name: "start_gdb_session",
arguments: {},
});
const sessionId = z
.object({ session_id: z.string().uuid() })
.parse(started.structuredContent).session_id;
const controller = new AbortController();
const command = client.callTool(
{
name: "gdb_console",
arguments: { session_id: sessionId, command: "shell sleep 600" },
},
{ signal: controller.signal },
);
await waitForStartedFile(commandPath);
controller.abort();
await expect(command).rejects.toThrow(/abort/iu);
const status = await validateDebuggerStatusResponse(
client,
"gdb_session_status",
sessionId,
);
expect(status.state).toBe("closed");
expect(status).toHaveProperty("diagnostics_truncated");
} finally {
await Promise.allSettled([client.close(), server.close()]);
await manager.closeAll().catch(() => undefined);
await rm(directory, { recursive: true, force: true });
}
},
);
it.skipIf(process.platform === "win32")(
"accepts caller-selected inferior_tty and exposes verified sink status through MCP",
async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-gdb-mcp-tty-"));
const provider = join(directory, "fake-gdb.mjs");
const tty = `${directory}/inferior-"terminal-Ω"`;
await writeFile(
provider,
`#!${process.execPath}
process.stdout.write("(gdb)\\n");
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
for (const line of chunk.split("\\n")) {
const match = /^(\\d+)/.exec(line);
if (!match) continue;
if (line.includes("inferior-tty-show")) process.stdout.write(match[1] + "^done,inferior_tty_terminal=" + ${JSON.stringify(JSON.stringify(tty))} + "\\n");
else if (line.includes("list-thread-groups")) process.stdout.write(match[1] + "^done,groups=[]\\n");
else process.stdout.write(match[1] + "^done\\n");
}
});
`,
);
await chmod(provider, 0o700);
const manager = new GdbSessionManager({
platform: "linux",
environment: { REA_GDB_COMMAND: provider },
});
const server = new McpServer({ name: "gdb-inferior-tty", version: "1" });
registerGdbTools(
server,
manager,
silentLogger,
createToolResultDelivery(undefined),
);
const client = new Client({ name: "gdb-inferior-tty", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const contract = toolContract("start_gdb_session");
expect(contract.inputSchema.safeParse({}).success).toBe(true);
expect(
contract.inputSchema.safeParse({ inferior_tty: tty }).success,
).toBe(true);
expect(contract.inputSchema.safeParse({ inferior_tty: "" }).success).toBe(
false,
);
const listed = (await client.listTools()).tools.find(
(tool) => tool.name === "start_gdb_session",
);
expect(listed?.inputSchema).toBeDefined();
expect(
new Ajv2020({ strict: false, validateFormats: false }).validate(
z.record(z.string(), z.unknown()).parse(listed?.inputSchema),
{ inferior_tty: tty },
),
).toBe(true);
const started = await client.callTool({
name: "start_gdb_session",
arguments: { inferior_tty: tty },
});
const sessionId = z
.object({ session_id: z.string().uuid() })
.parse(started.structuredContent).session_id;
const status = await validateDebuggerStatusResponse(
client,
"gdb_session_status",
sessionId,
);
expect(status).toMatchObject({
inferior_tty: tty,
inferior_tty_verified: true,
});
} finally {
await Promise.allSettled([client.close(), server.close()]);
await manager.closeAll().catch(() => undefined);
await rm(directory, { recursive: true, force: true });
}
},
);
it.skipIf(process.platform === "win32")(
"exposes lossy GDB MI decoding through the strict status MCP contract",
async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-gdb-mcp-mi-utf8-"));
const provider = join(directory, "fake-gdb.mjs");
await writeFile(
provider,
`#!${process.execPath}
process.stdout.write("(gdb)\\n");
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
for (const line of chunk.split("\\n")) {
const match = /^(\\d+)/.exec(line);
if (!match) continue;
if (line.includes("auto-load off")) {
process.stdout.write(match[1] + "^done\\n");
process.stdout.write(Buffer.from([0xff, 0x0a]));
} else if (line.includes("list-thread-groups")) process.stdout.write(match[1] + "^done,groups=[]\\n");
else process.stdout.write(match[1] + "^done\\n");
}
});
`,
);
await chmod(provider, 0o700);
const manager = new GdbSessionManager({
platform: "linux",
environment: { REA_GDB_COMMAND: provider },
});
const server = new McpServer({ name: "gdb-mi-utf8", version: "1" });
registerGdbTools(
server,
manager,
silentLogger,
createToolResultDelivery(undefined),
);
const client = new Client({ name: "gdb-mi-utf8", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const started = await client.callTool({
name: "start_gdb_session",
arguments: {},
});
const sessionId = z
.object({ session_id: z.string().uuid() })
.parse(started.structuredContent).session_id;
await expect
.poll(() => manager.status(sessionId)?.mi_invalid_utf8)
.toBe(true);
const status = await validateDebuggerStatusResponse(
client,
"gdb_session_status",
sessionId,
);
expect(status.mi_invalid_utf8).toBe(true);
} finally {
await Promise.allSettled([client.close(), server.close()]);
await manager.closeAll().catch(() => undefined);
await rm(directory, { recursive: true, force: true });
}
},
);
it("records partial GDB Evidence from an MCP command error", async () => {
const evidence = createEvidence(
undefined,
{
id: "gnu.gdb",
name: "GNU GDB",
version: null,
},
{
predicateType: "rea.debugger.console-observation",
operation: "gdb_console",
parameters: {
session_id: "00000000-0000-4000-8000-000000000001",
command: "info registers",
},
result: {
command: "info registers",
mi: "",
records: ["~partial"],
console: "~partial",
target: "",
log: "",
process_exit_observed: true,
process_exit_code: 7,
process_exit_signal: null,
output_truncated: false,
completion_status: "unknown",
},
rawResult: {
command: "info registers",
mi: "",
records: ["~partial"],
console: "~partial",
target: "",
log: "",
process_exit_observed: true,
process_exit_code: 7,
process_exit_signal: null,
output_truncated: false,
completion_status: "unknown",
},
subjectUnavailableReason:
"The debugger session does not identify an inferior.",
},
);
expect(
toolContract("gdb_console").outputSchema.parse(evidence),
).toMatchObject({
normalized_result: {
process_exit_observed: true,
process_exit_code: 7,
process_exit_signal: null,
},
});
const manager = {
start: async () =>
ok({
session_id: "00000000-0000-4000-8000-000000000001",
mi_version: "mi3" as const,
}),
execute: async () =>
err(
new AnalysisTimeoutError("gdb_console", 10, {
partialObservation: evidence,
cleanup: {
reason: "MI output was unsynchronized",
resources: [evidence.parameters.session_id as string],
},
}),
),
status: () => undefined,
close: async () => ok({ target_state: "unknown" as const }),
retryCleanupFailures: async () => ok(null),
} satisfies GdbToolManager;
const recorded: string[] = [];
const server = new McpServer({ name: "gdb-partial-evidence", version: "1" });
registerGdbTools(
server,
manager,
silentLogger,
createToolResultDelivery(undefined),
(value) => {
recorded.push(value.evidence_id);
return ok("added");
},
);
const client = new Client({ name: "gdb-partial-evidence", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const response = await client.callTool({
name: "gdb_console",
arguments: {
session_id: "00000000-0000-4000-8000-000000000001",
command: "info registers",
},
});
expect(recorded).toEqual([evidence.evidence_id]);
expect(response.isError).toBe(true);
expect(response.structuredContent).toMatchObject({
error: {
details: { partial_observation: { evidence_id: evidence.evidence_id } },
},
});
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
it("recovers only the owning debugger cleanup and reopens admitted analysis", async () => {
const [fixture] = await createBinarySessionTargets();
const target = fixture.replace(/first\.hop$/u, "first.macho");
await writeFile(target, thinMach(0xfeedfacf, 0x0100000c));
const analysisSession = createTestBinarySession(createCacheProvider([]));
expect((await analysisSession.open(target)).ok).toBe(true);
const ownerId = "00000000-0000-4000-8000-000000000001";
const otherId = "00000000-0000-4000-8000-000000000002";
const closeCalls: string[] = [];
const retainedFailure = new AnalysisCapabilityUnavailableError(
"gdb",
"gdb_console",
"The owned debugger process could not be confirmed stopped.",
{
cleanup: { reason: "owned writer remains", resources: [ownerId] },
},
);
const manager = {
start: async () => ok({ session_id: ownerId, mi_version: "mi3" as const }),
execute: async () => err(retainedFailure),
status: () => undefined,
close: async (sessionId: string) => {
closeCalls.push(sessionId);
if (sessionId === ownerId) retainedFailure.resolveCleanup();
return ok({ target_state: "unknown" as const });
},
retryCleanupFailures: async () => ok(null),
} satisfies GdbToolManager;
const server = new McpServer({ name: "gdb-owned-cleanup", version: "1" });
registerGdbTools(
server,
manager,
silentLogger,
createToolResultDelivery(undefined),
undefined,
analysisSession,
);
const client = new Client({ name: "gdb-owned-cleanup", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const command = await client.callTool({
name: "gdb_console",
arguments: { session_id: ownerId, command: "shell writer" },
});
expect(command.isError).toBe(true);
const wrongOwner = await client.callTool({
name: "close_gdb_session",
arguments: { session_id: otherId },
});
expect(wrongOwner.isError).toBe(true);
expect(closeCalls).toEqual([]);
expect((await analysisSession.open(target)).ok).toBe(false);
const recovered = await client.callTool({
name: "close_gdb_session",
arguments: { session_id: ownerId },
});
expect(recovered.isError ?? false).toBe(false);
expect(closeCalls).toEqual([ownerId]);
expect(retainedFailure.cleanupIncomplete).toBe(false);
expect((await analysisSession.open(target)).ok).toBe(true);
expect(analysisSession.activeTarget()?.path).toBe(target);
expect(
(await analysisSession.execute("address_name", { address: "0x1" })).ok,
).toBe(true);
} finally {
await Promise.allSettled([client.close(), server.close()]);
await analysisSession.close();
}
});
it("records partial GDB startup Evidence from an MCP start error", async () => {
const evidence = createEvidence(
undefined,
{
id: "gnu.gdb",
name: "GNU GDB",
version: null,
},
{
predicateType: "rea.debugger.startup-observation",
operation: "start_gdb_session",
parameters: { command: "GDB startup" },
result: {
command: "GDB startup",
mi: "",
records: ["~startup output"],
console: "~startup output",
target: "",
log: "",
process_exit_observed: true,
process_exit_code: 7,
process_exit_signal: null,
output_truncated: false,
completion_status: "unknown",
},
rawResult: {
command: "GDB startup",
mi: "",
records: ["~startup output"],
console: "~startup output",
target: "",
log: "",
process_exit_observed: true,
process_exit_code: 7,
process_exit_signal: null,
output_truncated: false,
completion_status: "unknown",
},
subjectUnavailableReason:
"No debugger session became ready before GDB exited.",
},
);
const manager = {
start: async () =>
err(
new AnalysisTimeoutError("start_gdb_session", 10, {
partialObservation: evidence,
}),
),
execute: async () =>
err(new AnalysisCapabilityUnavailableError("gdb", "unused", "unused")),
status: () => undefined,
close: async () => ok({ target_state: "unknown" as const }),
retryCleanupFailures: async () => ok(null),
} satisfies GdbToolManager;
const recorded: string[] = [];
const server = new McpServer({
name: "gdb-startup-partial-evidence",
version: "1",
});
registerGdbTools(
server,
manager,
silentLogger,
createToolResultDelivery(undefined),
(value) => {
recorded.push(value.evidence_id);
return ok("added");
},
);
const client = new Client({
name: "gdb-startup-partial-evidence",
version: "1",
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const response = await client.callTool({
name: "start_gdb_session",
arguments: {},
});
expect(recorded).toEqual([evidence.evidence_id]);
expect(response.isError).toBe(true);
expect(response.structuredContent).toMatchObject({
error: {
details: { partial_observation: { evidence_id: evidence.evidence_id } },
},
});
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";
import { EnhancedTools } from "../../../src/application/EnhancedTools.js";
import { connectGhidraMcp, sessionEvidence } from "./ghidraMcpHarness.js";
import { functionDossierSchema } from "../../../src/domain/hopperValues.js";
import { functionComparisonResultSchema } from "../../../src/domain/functionComparisonSchemas.js";
import { ghidraFunctionDossier } from "../../../src/domain/ghidraValues.fixture.js";
import {
jsonValueSchema,
@@ -14,6 +15,107 @@ import {
type GhidraFunctionOperation,
} from "../../../src/ghidra/GhidraFunctionValues.js";
it.each([
{ pseudocodeAvailable: true, reportsCoverage: true },
{ pseudocodeAvailable: false, reportsCoverage: true },
{ pseudocodeAvailable: true, reportsCoverage: false },
{ pseudocodeAvailable: false, reportsCoverage: false },
])(
"compares observed empty Ghidra facets with pseudocode=$pseudocodeAvailable and coverage=$reportsCoverage",
async ({ pseudocodeAvailable, reportsCoverage }) => {
const coverage = reportsCoverage
? { status: "complete" as const }
: undefined;
const dossier = functionDossierSchema.parse(ghidraFunctionDossier());
Object.assign(dossier, {
comments: [],
callers: [],
callees: [],
incoming_references: [],
outgoing_references: [],
referenced_strings: [],
referenced_names: [],
pseudocode: pseudocodeAvailable ? dossier.pseudocode : "",
facet_availability: {
pseudocode: pseudocodeAvailable
? { available: true }
: { available: false, reason: "Ghidra did not supply pseudocode." },
assembly: { available: true },
comments: { available: true },
callers: { available: true },
callees: { available: true },
references: { available: true },
strings_names: { available: true },
cfg: { available: true },
},
});
const harness = await connectGhidraMcp(
"ghidra-empty-dossier-coverage",
(operation) => {
if (operation !== "analyze_function")
throw new Error(`Unexpected operation: ${operation}`);
return Promise.resolve(
ok({
value: jsonValueSchema.parse(dossier),
limitations: [],
...(coverage === undefined
? {}
: { relationship_coverage: coverage }),
}),
);
},
);
try {
const analyzed = await harness.mcp.callTool({
name: "analyze_function",
arguments: { procedure: dossier.procedure.address },
});
expect(analyzed.isError).not.toBe(true);
const evidence = sessionEvidence(
harness.session,
analyzed.structuredContent,
);
expect(evidence.relationship_coverage).toEqual(coverage ?? null);
expect(evidence.normalized_result).toEqual(dossier);
const reply = await harness.mcp.callTool({
name: "compare_functions",
arguments: { left: evidence, right: evidence },
});
expect(reply.isError).not.toBe(true);
const comparison = functionComparisonResultSchema.parse(
sessionEvidence(harness.session, reply.structuredContent)
.normalized_result,
);
expect(
Object.fromEntries(
comparison.dimensions.map(({ dimension, status }) => [
dimension,
status,
]),
),
).toEqual({
identity: "unchanged",
pseudocode: pseudocodeAvailable ? "unchanged" : "unknown",
assembly: "unchanged",
comments: "unchanged",
calls: reportsCoverage ? "unchanged" : "unknown",
references: "unchanged",
strings_names: "unchanged",
cfg: "unchanged",
});
const replay = await harness.session.execute(
"analyze_function",
evidence.parameters,
);
if (!replay.ok) throw replay.error;
expect(replay.value.relationshipCoverage).toEqual(coverage);
expect(harness.calls).toEqual(["analyze_function"]);
} finally {
await harness.close();
}
},
);
it("retains terminal-call qualifications across function views and snapshot replay", async () => {
const limitation =
"Ghidra Listing reports a terminal call at 0x401000 to EXTERNAL:0x20 __tls_get_addr (external=true, thunk=false, hasNoReturn=true); fallthrough is excluded by Ghidra's flow model. This records Ghidra's FunctionManager flag, not an independent verification that the callee cannot return.";
@@ -1,6 +1,6 @@
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { expect, it } from "vitest";
import { writeFile } from "node:fs/promises";
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { nativeAotPeFixture } from "../../fixtures/nativeaotPe.js";
@@ -13,7 +13,6 @@ import {
sessionEvidence,
} from "./ghidraMcpHarness.js";
import { spawn } from "node:child_process";
import { mkdir } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { GhidraClient } from "../../../src/ghidra/GhidraClient.js";
+3 -4
View File
@@ -106,6 +106,8 @@ export const ghidraInstallationHost = (): GhidraInstallationHost => ({
readText: () => "application.version=12.1.4\napplication.java.min=21\n",
executable: () => true,
probeJava: () => ({
osArch: "amd64",
osName: "Linux",
version: "21.0.11",
major: 21,
home: "/usr/lib/jvm/jdk-21",
@@ -246,10 +248,7 @@ const resultBuilders = new Map<GhidraOperation, GhidraResultBuilder>([
}),
],
["xrefs", () => ["0x401001"]],
[
"analyze_function",
(input) => ghidraFunctionDossier(input.include_assembly === true),
],
["analyze_function", () => ghidraFunctionDossier()],
]);
const resultFor = (
+2
View File
@@ -102,6 +102,8 @@ const installationHost: GhidraInstallationHost = {
readText: () => "application.version=12.1.4\napplication.java.min=21\n",
executable: () => true,
probeJava: () => ({
osArch: "amd64",
osName: "Linux",
version: "21.0.11",
major: 21,
home: "/fixture/jdk-21",
@@ -0,0 +1,121 @@
import { chmod, mkdtemp, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { Client } from "@modelcontextprotocol/client";
import { expect, it } from "vitest";
import { createProviderEnvironmentMcpHarness } from "../../support/reverseDebuggerMcpTestHelpers.js";
const writeProvider = async (path: string, output: string): Promise<void> => {
await writeFile(
path,
`#!${process.execPath}\nprocess.stdout.write('${output}');\n`,
);
await chmod(path, 0o755);
};
const connectProviderClient = (options: {
readonly directory: string;
readonly clientName: string;
readonly configuredProvider: string;
readonly providerEnvironment?: { REA_RIZIN_COMMAND: string };
}) =>
createProviderEnvironmentMcpHarness({
directory: options.directory,
clientName: options.clientName,
serverOptions: {
environment: { REA_RIZIN_COMMAND: options.configuredProvider },
...(options.providerEnvironment === undefined
? {}
: { providerEnvironment: options.providerEnvironment }),
},
});
const executeRizinCommand = async (
client: Client,
artifact: string,
): Promise<Awaited<ReturnType<Client["callTool"]>>> => {
const response = await client.callTool({
name: "execute_rizin_command",
arguments: { path: artifact, command: "iI" },
});
expect(response.isError).not.toBe(true);
return response;
};
it("uses the captured server environment to resolve reverse-engineering providers", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-provider-environment-"));
const provider = join(directory, "selected-rizin");
const artifact = join(directory, "fixture.bin");
await writeFile(artifact, "fixture");
await writeProvider(provider, "captured-environment-provider");
const { client } = await connectProviderClient({
directory,
clientName: "reverse-provider-environment",
configuredProvider: provider,
});
const response = await executeRizinCommand(client, artifact);
expect(JSON.stringify(response.structuredContent)).toContain(
"captured-environment-provider",
);
});
it("prefers an explicit provider environment over the captured server environment", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-provider-override-"));
const configured = join(directory, "captured-rizin");
const override = join(directory, "override-rizin");
const artifact = join(directory, "fixture.bin");
await writeFile(artifact, "fixture");
for (const [path, output] of [
[configured, "captured"],
[override, "explicit-override"],
] as const) {
await writeProvider(path, output);
}
const { client } = await connectProviderClient({
directory,
clientName: "reverse-provider-override",
configuredProvider: configured,
providerEnvironment: { REA_RIZIN_COMMAND: override },
});
const response = await executeRizinCommand(client, artifact);
expect(JSON.stringify(response.structuredContent)).toContain(
"explicit-override",
);
expect(JSON.stringify(response.structuredContent)).not.toContain(
'"captured"',
);
});
it("snapshots an explicit provider environment when the server is created", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-provider-snapshot-"));
const configured = join(directory, "captured-rizin");
const override = join(directory, "explicit-rizin");
const artifact = join(directory, "fixture.bin");
await writeFile(artifact, "fixture");
for (const [path, output] of [
[configured, "captured"],
[override, "explicit-snapshot"],
] as const) {
await writeProvider(path, output);
}
const providerEnvironment = { REA_RIZIN_COMMAND: override };
const { client } = await connectProviderClient({
directory,
clientName: "reverse-provider-snapshot",
configuredProvider: configured,
providerEnvironment,
});
providerEnvironment.REA_RIZIN_COMMAND = configured;
const response = await executeRizinCommand(client, artifact);
expect(JSON.stringify(response.structuredContent)).toContain(
"explicit-snapshot",
);
expect(JSON.stringify(response.structuredContent)).not.toContain(
'"captured"',
);
});
@@ -0,0 +1,507 @@
import pino from "pino";
import { mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { expect, it, vi } from "vitest";
import { TestReverseEngineeringService as ReverseEngineeringService } from "../../support/reverseEngineeringService.js";
import { AnalysisInputError } from "../../../src/domain/analysisErrorCore.js";
import {
createBinarySessionTargets,
createCacheProvider,
createTestBinarySession,
} from "../../fixtures/binarySession.js";
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
import { EvidenceIntegrityError } from "../../../src/domain/evidenceErrors.js";
import { err, ok } from "../../../src/domain/result.js";
import type { WithAdmittedAnalysis } from "../../../src/server/analysisAdmission.js";
import { createToolResultDelivery } from "../../../src/server/toolResult.js";
import { registerReverseEngineeringTools } from "../../../src/server/registerReverseEngineeringTools.js";
import {
createReverseEngineeringMcpHarness,
invokeWithLiveSignal,
} from "../../support/reverseEngineeringMcpHarness.js";
const createTimedOutRizinService = (): ReverseEngineeringService =>
new ReverseEngineeringService({
run: async () => {
throw Object.assign(new Error("timed out"), {
stdout: "partial provider output",
stderr: "",
code: "ETIMEDOUT",
signal: null,
killed: true,
});
},
});
it("records partial Evidence and references it in the original MCP error", async () => {
const { server, handler } = createReverseEngineeringMcpHarness();
const service = createTimedOutRizinService();
const recordEvidence = vi.fn(() => ok("added" as const));
registerReverseEngineeringTools(
server,
service,
pino({ enabled: false }),
createToolResultDelivery(2 * 1024 * 1024),
recordEvidence,
);
const invoke = handler("execute_rizin_command");
const response = (await invokeWithLiveSignal(invoke, {
path: "package.json",
command: "iI",
})) as {
readonly isError?: boolean;
readonly structuredContent?: {
readonly error?: {
readonly details?: Readonly<Record<string, unknown>>;
};
};
};
expect(response.isError).toBe(true);
expect(recordEvidence).toHaveBeenCalledTimes(1);
expect(response.structuredContent?.error?.details).toMatchObject({
partial_observation: {
kind: "retained-evidence",
evidence_id: expect.any(String),
},
});
});
it("admits Rizin mutation after invalidating before dispatch", async () => {
const { server, handler } = createReverseEngineeringMcpHarness();
const events: string[] = [];
const service = new ReverseEngineeringService({
run: async () => {
events.push("dispatch");
return { stdout: "rizin output", stderr: "" };
},
});
registerReverseEngineeringTools(
server,
service,
pino({ enabled: false }),
createToolResultDelivery(2 * 1024 * 1024),
undefined,
undefined,
() => events.push("invalidate"),
async (_path, _signal, operation) => {
events.push("admit");
return ok(await operation());
},
);
const invoke = handler("execute_rizin_command");
await invoke(
{ path: "package.json", command: "iI" },
{ mcpReq: { signal: new AbortController().signal } },
);
expect(events).toEqual(["admit", "invalidate", "dispatch"]);
});
it("invalidates the snapshot in the legacy Rizin admission path", async () => {
const { server, handler } = createReverseEngineeringMcpHarness();
const invalidateSnapshot = vi.fn();
const service = new ReverseEngineeringService({
run: async () => ({ stdout: "rizin output", stderr: "" }),
});
registerReverseEngineeringTools(
server,
service,
pino({ enabled: false }),
createToolResultDelivery(2 * 1024 * 1024),
undefined,
undefined,
invalidateSnapshot,
);
const invoke = handler("execute_rizin_command");
const response = (await invokeWithLiveSignal(invoke, {
path: "package.json",
command: "iI",
})) as { readonly isError?: boolean };
expect(response.isError).not.toBe(true);
expect(invalidateSnapshot).toHaveBeenCalledOnce();
});
it("skips snapshot invalidation for malformed Rizin input", async () => {
const { server, handler } = createReverseEngineeringMcpHarness();
const invalidateSnapshot = vi.fn();
const executeRizinCommand = vi.fn(async () =>
err(new AnalysisInputError("execute_rizin_command")),
);
const service = {
executeRizinCommand,
} as unknown as ReverseEngineeringService;
registerReverseEngineeringTools(
server,
service,
pino({ enabled: false }),
createToolResultDelivery(2 * 1024 * 1024),
undefined,
undefined,
invalidateSnapshot,
);
const invoke = handler("execute_rizin_command");
const response = (await invokeWithLiveSignal(invoke, {
path: "package.json",
})) as { readonly isError?: boolean };
expect(response.isError).toBe(true);
expect(executeRizinCommand).toHaveBeenCalledOnce();
expect(invalidateSnapshot).not.toHaveBeenCalled();
});
it("delivers failed Rizin execution after external admission", async () => {
const { server, handler } = createReverseEngineeringMcpHarness();
const service = new ReverseEngineeringService({
run: async () => {
throw new Error("Rizin command failed");
},
});
registerReverseEngineeringTools(
server,
service,
pino({ enabled: false }),
createToolResultDelivery(2 * 1024 * 1024),
undefined,
undefined,
undefined,
async (_path, _signal, operation) => ok(await operation()),
);
const invoke = handler("execute_rizin_command");
const response = (await invokeWithLiveSignal(invoke, {
path: "package.json",
command: "iI",
})) as { readonly isError?: boolean };
expect(response.isError).toBe(true);
});
it("preserves the Rizin operation error when analysis retirement also fails", async () => {
const { server, handler } = createReverseEngineeringMcpHarness();
const service = {
retryCleanup: async () => ok(null),
executeRizinCommand: async () =>
err(new AnalysisInputError("execute_rizin_command")),
} as unknown as ReverseEngineeringService;
const observedOperationResult = vi.fn();
registerReverseEngineeringTools(
server,
service,
pino({ enabled: false }),
createToolResultDelivery(2 * 1024 * 1024),
undefined,
undefined,
undefined,
async (_path, _signal, operation, rebindFailure) => {
const result = await operation();
observedOperationResult(result);
return err(rebindFailure(result, new AnalysisInputError("rebind")));
},
);
const invoke = handler("execute_rizin_command");
const response = (await invoke(
{ path: "package.json", command: "iI" },
{ mcpReq: { signal: new AbortController().signal } },
)) as {
readonly isError?: boolean;
readonly structuredContent?: {
readonly error?: {
readonly code?: string;
readonly details?: { readonly reason?: string };
};
};
};
expect(response.isError).toBe(true);
expect(observedOperationResult).toHaveBeenCalledWith(
expect.objectContaining({ ok: false }),
);
expect(response.structuredContent?.error).toMatchObject({
code: "invalid_request",
});
});
it.each(["success", "timeout"])(
"retains %s output and requires reopening after a symlink command",
async (outcome) => {
const [target] = await createBinarySessionTargets();
const alias = join(dirname(target), "active-target-alias.hop");
await symlink(target, alias);
const session = createTestBinarySession(createCacheProvider([]));
expect((await session.open(target)).ok).toBe(true);
expect(session.activeTarget()?.path).toBe(target);
const originalDigest = session.activeTarget()?.sha256;
const { server, handler } = createReverseEngineeringMcpHarness();
const service = new ReverseEngineeringService({
run: async () => {
await writeFile(alias, "changed by Rizin");
if (outcome === "timeout")
throw Object.assign(new Error("timed out"), {
stdout: "partial analysis output",
stderr: "timeout diagnostics",
code: "ETIMEDOUT",
signal: null,
killed: true,
});
return { stdout: "partial analysis output", stderr: "" };
},
});
const recordEvidence = vi.fn(() => ok("added" as const));
registerReverseEngineeringTools(
server,
service,
pino({ enabled: false }),
createToolResultDelivery(2 * 1024 * 1024),
recordEvidence,
undefined,
() => session.invalidateSnapshotForExternalMutation(),
(path, signal, operation, rebindFailure) =>
session.withAdmittedExternalMutation(
path,
signal,
operation,
rebindFailure,
),
);
const invoke = handler("execute_rizin_command");
const response = (await invoke(
{ path: alias, command: "wx 00 @ 0" },
{ mcpReq: { signal: new AbortController().signal } },
)) as {
readonly isError?: boolean;
readonly structuredContent?: {
readonly error?: {
readonly code?: string;
readonly details?: Readonly<Record<string, unknown>>;
};
};
};
expect(response.isError ?? false).toBe(outcome === "timeout");
if (outcome === "timeout") {
expect(response.structuredContent?.error?.code).toBe("provider_timeout");
expect(response.structuredContent?.error?.details).toMatchObject({
captured_output: {
stdout: "partial analysis output",
stderr: "timeout diagnostics",
},
});
expect(response.structuredContent?.error?.details).toMatchObject({
partial_observation: {
kind: "retained-evidence",
evidence_id: expect.any(String),
},
});
}
expect(recordEvidence).toHaveBeenCalledTimes(1);
expect(session.activeTarget()).toBeUndefined();
expect((await session.execute("address_name", {})).ok).toBe(false);
expect((await session.open(target)).ok).toBe(true);
expect(session.activeTarget()?.sha256).not.toBe(originalDigest);
await session.close();
await rm(dirname(target), { recursive: true, force: true });
},
);
it("preserves a partial MCP error without claiming failed Evidence retention", async () => {
const { server, handler } = createReverseEngineeringMcpHarness();
const service = createTimedOutRizinService();
const recordEvidence = vi.fn((_evidence: unknown) =>
err(new EvidenceIntegrityError("retention failed")),
);
registerReverseEngineeringTools(
server,
service,
pino({ enabled: false }),
createToolResultDelivery(2 * 1024 * 1024),
recordEvidence,
);
const invoke = handler("execute_rizin_command");
const response = (await invokeWithLiveSignal(invoke, {
path: "package.json",
command: "iI",
})) as {
readonly isError?: boolean;
readonly structuredContent?: {
readonly error?: {
readonly details?: Readonly<Record<string, unknown>>;
};
};
};
expect(response.isError).toBe(true);
expect(response.structuredContent?.error?.details).toMatchObject({
partial_observation: expect.objectContaining({
operation: "execute_rizin_command",
}),
});
expect(
JSON.stringify(response.structuredContent?.error?.details),
).not.toContain("retained-evidence");
});
it("delivers pathless objdump capability Evidence and input errors through its named tool", async () => {
const { server, handler } = createReverseEngineeringMcpHarness();
const service = new ReverseEngineeringService({
run: async () => ({ stdout: "objdump output", stderr: "" }),
});
const delivery = createToolResultDelivery(2 * 1024 * 1024);
registerReverseEngineeringTools(
server,
service,
pino({ enabled: false }),
delivery,
);
const context = { mcpReq: { signal: new AbortController().signal } };
const objdump = handler("inspect_with_objdump");
const rizin = handler("execute_rizin_command");
const success = (await objdump(
{ path: "package.json", operation: "file_headers" },
context,
)) as { readonly isError?: boolean };
const architectures = (await objdump(
{ operation: "architectures" },
context,
)) as {
readonly isError?: boolean;
};
const objdumpFailure = (await objdump({}, context)) as {
readonly isError?: boolean;
};
const failure = (await rizin({}, context)) as {
readonly isError?: boolean;
readonly structuredContent?: {
readonly error?: { readonly code?: string };
};
};
const cancelled = new AbortController();
cancelled.abort();
const cancelledContext = { mcpReq: { signal: cancelled.signal } };
const cancelledObjdump = (await objdump(
{ path: "package.json", operation: "file_headers" },
cancelledContext,
)) as { readonly isError?: boolean };
const cancelledRizin = (await rizin(
{ path: "package.json", command: "iI" },
cancelledContext,
)) as { readonly isError?: boolean };
expect(success.isError).not.toBe(true);
expect(architectures.isError).not.toBe(true);
expect(objdumpFailure.isError).toBe(true);
expect(failure.isError).toBe(true);
expect(cancelledObjdump.isError).toBe(true);
expect(cancelledRizin.isError).toBe(true);
});
it("does not treat a malformed partial observation as retained Evidence", async () => {
const { server, handler } = createReverseEngineeringMcpHarness();
const invalidError = Object.assign(
new AnalysisInputError("execute_rizin_command"),
{ partialObservation: { evidence_id: 42 } },
);
const service = {
inspectWithObjdump: async () => err(invalidError),
executeRizinCommand: async () => err(invalidError),
} as unknown as ReverseEngineeringService;
const recordEvidence = vi.fn(() => ok("added" as const));
registerReverseEngineeringTools(
server,
service,
pino({ enabled: false }),
createToolResultDelivery(2 * 1024 * 1024),
recordEvidence,
);
const invoke = handler("execute_rizin_command");
const response = (await invoke(
{ path: "package.json", command: "iI" },
{ mcpReq: { signal: new AbortController().signal } },
)) as { readonly isError?: boolean };
expect(response.isError).toBe(true);
expect(recordEvidence).not.toHaveBeenCalled();
});
it("keeps provider execution and Evidence recording inside analysis admission", async () => {
const { server, handler } = createReverseEngineeringMcpHarness();
const events: string[] = [];
const service = new ReverseEngineeringService({
run: async () => {
events.push("provider");
return { stdout: "objdump output", stderr: "" };
},
});
const recordEvidence = vi.fn(() => {
events.push("record");
return ok("added" as const);
});
const admission: WithAdmittedAnalysis = async (_name, _signal, operation) => {
events.push("admission-start");
const result = await operation({} as AnalysisOperationPort);
events.push("admission-end");
return ok(result);
};
registerReverseEngineeringTools(
server,
service,
pino({ enabled: false }),
createToolResultDelivery(2 * 1024 * 1024),
recordEvidence,
admission,
);
const invoke = handler("inspect_with_objdump");
await invoke(
{ path: "package.json", operation: "file_headers" },
{ mcpReq: { signal: new AbortController().signal } },
);
expect(events).toEqual([
"admission-start",
"provider",
"record",
"admission-end",
]);
});
it("returns admission failures without invoking a reverse-engineering provider", async () => {
const { server, handler } = createReverseEngineeringMcpHarness();
const inspectWithObjdump = vi.fn();
const service = {
inspectWithObjdump,
executeRizinCommand: vi.fn(),
} as unknown as ReverseEngineeringService;
const admission: WithAdmittedAnalysis = async () =>
err(new AnalysisInputError("inspect_with_objdump"));
registerReverseEngineeringTools(
server,
service,
pino({ enabled: false }),
createToolResultDelivery(2 * 1024 * 1024),
undefined,
admission,
);
const invoke = handler("inspect_with_objdump");
const response = (await invoke(
{ path: "package.json", operation: "file_headers" },
{ mcpReq: { signal: new AbortController().signal } },
)) as { readonly isError?: boolean };
expect(response.isError).toBe(true);
expect(inspectWithObjdump).not.toHaveBeenCalled();
});
@@ -0,0 +1,84 @@
import { chmod, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it } from "vitest";
import { createServer } from "../../../src/server/createServer.js";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
import { ok } from "../../../src/domain/result.js";
const analysis = {
execute: async () =>
ok(
createAnalysisExecution({}, { id: "test", name: "Test", version: null }),
),
};
const writeRizin = async (directory: string, output: string): Promise<void> => {
const executable = join(directory, "rizin");
await writeFile(executable, `#!/bin/sh\nprintf '%s\\n' '${output}'\n`);
await chmod(executable, 0o755);
};
it("uses the server-selected environment unless a provider environment overrides it", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-reverse-env-"));
const selectedPath = join(directory, "selected");
const overridePath = join(directory, "override");
const artifactPath = join(directory, "sample.bin");
await Promise.all([mkdir(selectedPath), mkdir(overridePath)]);
await Promise.all([
writeRizin(selectedPath, "selected environment"),
writeRizin(overridePath, "provider override"),
writeFile(artifactPath, "fixture"),
]);
try {
for (const scenario of [
{
environment: selectedPath,
expected: "selected environment",
},
{
environment: selectedPath,
provider: overridePath,
expected: "provider override",
},
]) {
const server = createServer(
{ kind: "fixed", analysis },
{
environment: { ...process.env, PATH: scenario.environment },
...(scenario.provider === undefined
? {}
: {
providerEnvironment: {
...process.env,
PATH: scenario.provider,
},
}),
},
);
const client = new Client({ name: "reverse-env-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const result = await client.callTool({
name: "execute_rizin_command",
arguments: { path: artifactPath, command: "iI" },
});
expect(result.isError).not.toBe(true);
expect(result.structuredContent).toMatchObject({
raw_result: { stdout: `${scenario.expected}\n` },
});
} finally {
await Promise.all([client.close(), server.close()]);
}
}
} finally {
await rm(directory, { recursive: true, force: true });
}
});
@@ -0,0 +1,251 @@
import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { McpServer } from "@modelcontextprotocol/server";
import { expect, it } from "vitest";
import { z } from "zod";
import { AnalysisCapabilityUnavailableError } from "../../../src/domain/analysisErrorCore.js";
import { thinMach } from "../../../src/domain/binaryTarget.fixture.js";
import { evidenceSchema } from "../../../src/domain/evidence.js";
import { err, ok } from "../../../src/domain/result.js";
import {
createRizinTestManager,
rizinTestInferiorTty,
} from "../providers/RizinTestInferiorTty.js";
import { silentLogger } from "../../../src/logger.js";
import { registerRizinDebugTools } from "../../../src/server/registerRizinDebugTools.js";
import type { RizinDebugToolManager } from "../../../src/server/registerRizinDebugTools.js";
import { createToolResultDelivery } from "../../../src/server/toolResult.js";
import {
createBinarySessionTargets,
createCacheProvider,
createTestBinarySession,
} from "../../fixtures/binarySession.js";
import {
validateDebuggerStatusResponse,
waitForStartedFile,
} from "../../support/reverseDebuggerMcpTestHelpers.js";
it.skipIf(process.platform === "win32")(
"reports Rizin launch provenance and lossy frame decoding through MCP",
async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-rizin-provenance-"));
const provider = join(directory, "fake-rizin-provenance.mjs");
await writeFile(
provider,
`#!/usr/bin/env node
process.stdout.write("\\0");
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n");
if (boundary < 0) break;
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
if (line === "dr") process.stdout.write(Buffer.from([0xff, 0]));
else if (line.startsWith("!echo ")) process.stdout.write(line.slice(6) + "\\0");
}
});
`,
);
await chmod(provider, 0o700);
const manager = createRizinTestManager({ REA_RIZIN_COMMAND: provider });
const server = new McpServer({
name: "rizin-evidence-provenance",
version: "1",
});
registerRizinDebugTools(
server,
manager,
silentLogger,
createToolResultDelivery(undefined),
);
const client = new Client({
name: "rizin-evidence-provenance",
version: "1",
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const callerPath = "./relative/../rizin-fixture.bin";
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const started = await client.callTool({
name: "start_rizin_debug_session",
arguments: {
path: callerPath,
inferior_tty: await rizinTestInferiorTty(),
},
});
const sessionId = z
.object({ session_id: z.string().uuid() })
.parse(started.structuredContent).session_id;
const command = await client.callTool({
name: "rizin_debug_command",
arguments: { session_id: sessionId, command: "dr" },
});
expect(command.isError).not.toBe(true);
const evidence = evidenceSchema.parse(command.structuredContent);
expect(evidence.parameters.launch_provenance).toEqual({
caller_selected_path: callerPath,
resolved_path: resolve(callerPath),
});
expect(evidence.normalized_result).toMatchObject({
output_invalid_utf8: true,
});
expect(evidence.limitations).toContain(
"Launch provenance records the original and resolved startup paths; it does not establish the current target after unrestricted debugger commands.",
);
const status = await validateDebuggerStatusResponse(
client,
"rizin_debug_session_status",
sessionId,
);
expect(status.output_invalid_utf8).toBe(true);
expect(status.recent_output).toContain("�");
} finally {
await Promise.allSettled([client.close(), server.close()]);
await manager.closeAll().catch(() => undefined);
await rm(directory, { recursive: true, force: true });
}
},
);
it("admits Rizin startup across a bound analysis session", async () => {
const [fixture] = await createBinarySessionTargets();
const target = fixture.replace(/first\.hop$/u, "first.macho");
await writeFile(target, thinMach(0xfeedfacf, 0x0100000c));
const analysisSession = createTestBinarySession(createCacheProvider([]));
expect((await analysisSession.open(target)).ok).toBe(true);
const initialRunId = z
.object({ analysis_run: z.object({ run_id: z.string() }) })
.parse(analysisSession.status()).analysis_run.run_id;
const manager = {
start: async () => ({
ok: true,
value: {
session_id: "00000000-0000-4000-8000-000000000001",
backend: null,
},
}),
execute: async () =>
err(new AnalysisCapabilityUnavailableError("rizin", "unused", "unused")),
status: () => undefined,
close: async () => ({ ok: true, value: { target_state: "unknown" } }),
retryCleanupFailures: async () => ok(null),
} satisfies RizinDebugToolManager;
const server = new McpServer({ name: "rizin-start-admission", version: "1" });
registerRizinDebugTools(
server,
manager,
silentLogger,
createToolResultDelivery(undefined),
undefined,
analysisSession,
);
const client = new Client({ name: "rizin-start-admission", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const started = await client.callTool({
name: "start_rizin_debug_session",
arguments: { path: target, inferior_tty: "/dev/null" },
});
expect(started.isError ?? false).toBe(false);
expect(
z
.object({ session_id: z.string().uuid() })
.parse(started.structuredContent).session_id,
).toBe("00000000-0000-4000-8000-000000000001");
expect(analysisSession.activeTarget()).toBeUndefined();
expect((await analysisSession.open(target)).ok).toBe(true);
const currentRunId = z
.object({ analysis_run: z.object({ run_id: z.string() }) })
.parse(analysisSession.status()).analysis_run.run_id;
expect(currentRunId).not.toBe(initialRunId);
expect(analysisSession.activeTarget()?.path).toBe(target);
} finally {
await Promise.allSettled([client.close(), server.close()]);
await analysisSession.close();
}
});
it.skipIf(process.platform === "win32")(
"propagates MCP cancellation into a running Rizin debugger command",
async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-rizin-mcp-cancel-"));
const provider = join(directory, "fake-rizin.mjs");
const commandPath = join(directory, "command-started");
await writeFile(
provider,
`#!/usr/bin/env node
process.stdout.write("\\0");
process.stdin.setEncoding("utf8");
process.stdin.on("data", async (chunk) => {
for (const line of chunk.split("\\n")) {
if (line.startsWith("!echo ")) continue;
await import("node:fs/promises").then((fs) => fs.writeFile(${JSON.stringify(commandPath)}, "started"));
}
});
`,
);
await chmod(provider, 0o700);
const manager = createRizinTestManager({
REA_RIZIN_COMMAND: provider,
});
const server = new McpServer({ name: "rizin-cancellation", version: "1" });
registerRizinDebugTools(
server,
manager,
silentLogger,
createToolResultDelivery(undefined),
);
const client = new Client({ name: "rizin-cancellation", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const started = await client.callTool({
name: "start_rizin_debug_session",
arguments: {
path: "/tmp/fixture.bin",
inferior_tty: await rizinTestInferiorTty(),
},
});
const sessionId = z
.object({ session_id: z.string().uuid() })
.parse(started.structuredContent).session_id;
const controller = new AbortController();
const command = client.callTool(
{
name: "rizin_debug_command",
arguments: { session_id: sessionId, command: "dr" },
},
{ signal: controller.signal },
);
await waitForStartedFile(commandPath);
controller.abort();
await expect(command).rejects.toThrow(/abort/iu);
const status = await validateDebuggerStatusResponse(
client,
"rizin_debug_session_status",
sessionId,
);
expect(status.state).toBe("closed");
expect(status).toHaveProperty("diagnostics_truncated");
} finally {
await Promise.allSettled([client.close(), server.close()]);
await manager.closeAll().catch(() => undefined);
await rm(directory, { recursive: true, force: true });
}
},
);
+122
View File
@@ -0,0 +1,122 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import {
createRustImage,
createRustHashOverflowImage,
} from "../../fixtures/rust/image.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { mcpTest, type TestMcp } from "../../support/mcp/mcpFixture.js";
const connect = async (mcp: TestMcp) => {
const session = createTestBinarySession(() => {
throw new Error("Rust metadata must not start a deep provider");
});
const client = await mcp.connect(createServer({ kind: "session", session }));
return { client, session };
};
mcpTest(
"advertises inspect_rust_binary and reads an embedded dependency list",
async ({ mcp }) => {
const { client, session } = await connect(mcp);
try {
const advertised = (await client.listTools()).tools.find(
(tool) => tool.name === "inspect_rust_binary",
);
expect(advertised?.annotations).toMatchObject({
readOnlyHint: false,
idempotentHint: true,
});
const root = await createTestTempDirectory("rea-rust-mcp-");
const path = join(root, "sample.elf");
await writeFile(path, createRustImage({ format: "elf" }));
const response = await client.callTool({
name: "inspect_rust_binary",
arguments: { path },
});
expect(response.isError, JSON.stringify(response.content)).not.toBe(true);
const evidence = toolContract("inspect_rust_binary").outputSchema.parse(
response.structuredContent,
);
expect(evidence.normalized_result.auditable_metadata?.packages).toEqual([
expect.objectContaining({ name: "itoa", version: "1.0.18" }),
expect.objectContaining({
name: "sample",
version: "0.1.0",
root: true,
}),
]);
const missing = join(root, "plain.elf");
await writeFile(
missing,
createRustImage({ format: "pe", omitSection: true }),
);
const absent = await client.callTool({
name: "inspect_rust_binary",
arguments: { path: missing },
});
expect(absent.isError).not.toBe(true);
const absentEvidence = toolContract(
"inspect_rust_binary",
).outputSchema.parse(absent.structuredContent);
expect(absentEvidence.normalized_result.auditable_metadata).toBeNull();
} finally {
await session.close();
}
},
);
mcpTest(
"requires an absolute path for inspect_rust_binary",
async ({ mcp }) => {
const { client, session } = await connect(mcp);
try {
const response = await client.callTool({
name: "inspect_rust_binary",
arguments: { path: "sample" },
});
expect(response.isError).toBe(true);
expect(parseMcpToolError(response).error).toMatchObject({
code: "invalid_request",
details: { operation: "inspect_rust_binary" },
});
} finally {
await session.close();
}
},
);
mcpTest(
"preserves rustc hash capacity units through the public error contract",
async ({ mcp }) => {
const { client, session } = await connect(mcp);
try {
const root = await createTestTempDirectory("rea-rust-mcp-");
const path = join(root, "many-hashes.elf");
await writeFile(path, createRustHashOverflowImage());
const response = await client.callTool({
name: "inspect_rust_binary",
arguments: { path },
});
expect(response.isError).toBe(true);
expect(parseMcpToolError(response).error).toMatchObject({
code: "resource_constraint",
details: {
operation: "inspect_rust_binary",
resource: "capacity",
reported_limits: { maximum_rustc_hashes: 64 },
},
});
expect(parseMcpToolError(response).error.details).not.toHaveProperty(
"reported_limits.maximum_bytes",
);
} finally {
await session.close();
}
},
);
@@ -112,6 +112,12 @@ function expectKnownAuthorityHints(tools: readonly ToolSchemas[]): void {
idempotentHint: false,
openWorldHint: false,
},
start_gdb_session: {
readOnlyHint: false,
destructiveHint: false,
idempotentHint: false,
openWorldHint: true,
},
export_web_scripts: {
readOnlyHint: false,
destructiveHint: false,
@@ -143,6 +149,12 @@ function expectKnownAuthorityHints(tools: readonly ToolSchemas[]): void {
readOnlyHint: false,
destructiveHint: false,
},
execute_rizin_command: {
readOnlyHint: false,
destructiveHint: true,
idempotentHint: false,
openWorldHint: true,
},
} as const;
for (const [name, annotations] of Object.entries(expected))
@@ -1,5 +1,5 @@
import { parseConfig } from "../../../src/config/parseConfig.js";
import { writeFile } from "node:fs/promises";
import { access, chmod, readFile, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
@@ -21,6 +21,7 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
import { readAnalysisSnapshot } from "../../../src/application/binary/AnalysisSnapshotFiles.js";
import { ok } from "../../../src/domain/result.js";
import { evidenceBundleSchema } from "../../../src/domain/evidenceBundle.js";
import { silentLogger } from "../../../src/logger.js";
import { createServer } from "../../../src/server/createServer.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
@@ -41,6 +42,114 @@ afterEach(async () => {
await Promise.all(resources.splice(0).map((resource) => resource.close()));
});
describe("MCP external command snapshot retirement", () => {
it.skipIf(process.platform === "win32")(
"rejects a queued snapshot after mutation and preserves Evidence through explicit reopening",
async () => {
const { targetPaths, snapshotPath } = await createWorkflowFiles(
"rea-mcp-admitted-reverse-",
["target.hop"],
);
const targetPath = targetPaths[0];
if (targetPath === undefined)
throw new Error("Expected one workflow target");
const fixtureDirectory = dirname(snapshotPath);
const startedPath = join(fixtureDirectory, "rizin-started");
const releasePath = join(fixtureDirectory, "rizin-release");
const providerPath = join(fixtureDirectory, "rizin-fixture.mjs");
await writeFile(
providerPath,
`#!${process.execPath}\nimport { existsSync, writeFileSync } from "node:fs";\nwriteFileSync(${JSON.stringify(startedPath)}, "started");\nwhile (!existsSync(${JSON.stringify(releasePath)})) await new Promise((resolve) => setTimeout(resolve, 5));\nprocess.stdout.write("Rizin fixture output\\n");\n`,
);
await chmod(providerPath, 0o755);
const session = createWorkflowSession(makeProvider([], []));
const { mcp } = await connectWorkflowMcp(
session,
"admitted-reverse-engineering",
{ REA_RIZIN_COMMAND: providerPath },
);
await openWorkflowTarget(mcp, targetPath);
const analysisRequest = mcp.callTool({
name: "execute_rizin_command",
arguments: { path: targetPath, command: "iI" },
});
const readyDeadline = Date.now() + 5_000;
while (Date.now() < readyDeadline) {
try {
await access(startedPath);
break;
} catch {
await new Promise((resolve) => setTimeout(resolve, 10));
}
}
await expect(access(startedPath)).resolves.toBeUndefined();
let closeSettled = false;
const closeRequest = mcp
.callTool({
name: "close_binary",
arguments: { snapshot_path: snapshotPath },
})
.finally(() => {
closeSettled = true;
});
await new Promise((resolve) => setTimeout(resolve, 50));
expect(closeSettled).toBe(false);
await expect(access(snapshotPath)).rejects.toMatchObject({
code: "ENOENT",
});
await writeFile(releasePath, "release");
const analyzed = await analysisRequest;
expect(analyzed.isError, JSON.stringify(analyzed.content)).not.toBe(true);
const evidence = toolContract("execute_rizin_command").outputSchema.parse(
analyzed.structuredContent,
);
const closed = await closeRequest;
expect(closed.isError).toBe(true);
expect(JSON.stringify(closed.content)).toContain(
"Analysis snapshots are unavailable",
);
expect(session.activeTarget()).toBeUndefined();
await expect(access(snapshotPath)).rejects.toMatchObject({
code: "ENOENT",
});
const exported = await mcp.callTool({
name: "export_evidence_bundle",
arguments: { path: join(fixtureDirectory, "observations.json") },
});
expect(exported.isError ?? false).toBe(false);
const observations = evidenceBundleSchema.parse(
JSON.parse(
await readFile(join(fixtureDirectory, "observations.json"), "utf8"),
),
);
expect(observations.records).toContainEqual(
expect.objectContaining({ evidence_id: evidence.evidence_id }),
);
// The provider process has completed; explicitly open fresh analysis
// before saving an immutable snapshot of the new binding.
await openWorkflowTarget(mcp, targetPath);
const saved = await mcp.callTool({
name: "close_binary",
arguments: { snapshot_path: snapshotPath },
});
expect(saved.isError ?? false).toBe(false);
const snapshot = await readAnalysisSnapshot(snapshotPath);
if (!snapshot.ok) throw snapshot.error;
expect(snapshot.value.evidence_bundle.records).toContainEqual(
expect.objectContaining({
evidence_id: evidence.evidence_id,
operation: "execute_rizin_command",
subject: expect.objectContaining({ local_path: targetPath }),
}),
);
},
);
});
describe("MCP composed workflow target admission", () => {
it("keeps a composed result and snapshot on its admitted target across queued close and open", async () => {
const { targetPaths, snapshotPath } = await createWorkflowFiles(
@@ -448,10 +557,14 @@ const createWorkflowSession = (provider: AnalysisProvider) =>
const connectWorkflowMcp = async (
session: ReturnType<typeof createWorkflowSession>,
clientName: string,
providerEnvironment?: Readonly<NodeJS.ProcessEnv>,
): Promise<{ readonly mcp: Client }> => {
const server = createServer(
{ kind: "session", session },
{ logger: silentLogger },
{
logger: silentLogger,
...(providerEnvironment === undefined ? {} : { providerEnvironment }),
},
);
const mcp = new Client({ name: clientName, version: "1.0.0" });
const [clientTransport, serverTransport] =
@@ -0,0 +1,323 @@
import { chmod, mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, vi } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
processTest,
type TestProcesses,
} from "../../support/process/processFixture.js";
const script = `
import { PlaywrightElectronActiveProvider } from "./dist/browser/PlaywrightElectronActiveProvider.js";
import { electronActiveObservationInputSchema } from "./dist/domain/javascript/electronActiveObservation.js";
const [scenario, executable, root] = JSON.parse(process.argv[1]);
let observedRejections = 0;
if (scenario === "oneFailureWithManySuccesses" || scenario === "externalListenerSeesUnrelatedOnce")
process.on("unhandledRejection", () => { observedRejections += 1; });
const orphanStack = (message, file) =>
message + "\\n at waitForLine (/app/node_modules/playwright-core/lib/server/" + file + ":247:21)";
const playwrightError = (message, file = "electron/electron.js") => {
const error = new Error(message);
error.stack = "Error: " + orphanStack(message, file);
return error;
};
const rejectLater = (error, ms) => setTimeout(() => void Promise.reject(error), ms);
const fakeApplication = { process: () => ({ pid: undefined }), close: async () => undefined };
const launchFailure = (message) =>
new Error("electron.launch: " + message + "\\nCall log:\\n - <launching>");
const after = (ms, action) => new Promise((resolve, reject) => setTimeout(() => {
try { resolve(action()); } catch (error) { reject(error); }
}, ms));
const orphans = (message) => {
for (let index = 0; index < 3; index += 1) void Promise.reject(playwrightError(message));
};
let during = -1;
const launches = {
realLaunch: undefined,
realWithUnrelatedPlaywrightRejection: async (options) => {
void Promise.reject(playwrightError("unrelated playwright failure", "page.js"));
return (await import("playwright-core"))._electron.launch(options);
},
failureWithOrphans: async () => {
during = process.listenerCount("unhandledRejection");
orphans("Process failed to launch!");
await after(10, () => { throw launchFailure("Process failed to launch!"); });
},
failureInOneTick: async () => {
orphans("Process failed to launch!");
throw launchFailure("Process failed to launch!");
},
failureWithUnrelatedPlaywrightRejection: async () => {
orphans("Process failed to launch!");
void Promise.reject(playwrightError("Target page, context or browser has been closed", "page.js"));
await after(10, () => { throw launchFailure("Process failed to launch!"); });
},
externalListenerSeesUnrelatedOnce: async () => {
void Promise.reject(playwrightError("unrelated playwright failure", "page.js"));
await after(10, () => { throw launchFailure("Process failed to launch!"); });
},
pendingWithUnrelatedRejection: () => {
setInterval(() => {}, 1000);
rejectLater(new Error("unrelated application failure"), 20);
return new Promise(() => {});
},
success: async () => {
during = process.listenerCount("unhandledRejection");
return fakeApplication;
},
successWithPlaywrightRejection: async () => {
void Promise.reject(playwrightError("stray playwright failure", "page.js"));
await after(10, () => fakeApplication);
return fakeApplication;
},
};
const input = (executablePath) => ({
...electronActiveObservationInputSchema.parse({
executable_path: executablePath,
application_path: root,
}),
application_root: root,
});
const capture = (launch, executablePath = executable) =>
new PlaywrightElectronActiveProvider({}, launch).capture(input(executablePath));
const before = process.listenerCount("unhandledRejection");
let results;
if (scenario === "concurrentFailures" || scenario === "failureThenSuccess" || scenario === "successThenFailure" || scenario === "oneFailureWithManySuccesses") {
const failing = (message, orphanAt, settleAt) => async () => {
during = Math.max(during, process.listenerCount("unhandledRejection"));
await after(orphanAt, () => orphans(message));
await after(settleAt - orphanAt, () => { throw launchFailure(message); });
};
const succeeding = (settleAt) => () => {
during = Math.max(during, process.listenerCount("unhandledRejection"));
return after(settleAt, () => fakeApplication);
};
const pair = {
concurrentFailures: [failing("alpha failed", 10, 30), failing("beta failed", 20, 50)],
failureThenSuccess: [failing("alpha failed", 10, 20), succeeding(40)],
successThenFailure: [failing("alpha failed", 20, 40), succeeding(30)],
oneFailureWithManySuccesses: [failing("alpha failed", 10, 80), ...[20, 30, 40, 50].map(succeeding)],
}[scenario];
results = await Promise.all(pair.map((launch) => capture(launch)));
} else {
results = [await capture(launches[scenario] ?? undefined)];
}
await new Promise((resolve) => setTimeout(resolve, 50));
console.log(JSON.stringify({
before,
during,
after: process.listenerCount("unhandledRejection"),
observedRejections,
reasons: results.map((result) => result.ok ? null : result.error.reason ?? null),
ok: results.map((result) => result.ok),
causeReasons: results.map((result) => result.ok ? null : result.error.cause?.reason ?? null),
cleanupResources: results.map((result) => result.ok ? null : result.error.cleanupResources ?? null),
causes: results.map((result) => result.ok ? null : String(result.error.cause?.message).split("\\n")[0]),
}));
`;
// A cold macOS Swift toolchain may spend up to 120 seconds building the
// ownership reader before any child launch reaches its assertion.
vi.setConfig({ testTimeout: 180_000 });
type Outcome = {
readonly before: number;
readonly during: number;
readonly after: number;
readonly ok: readonly boolean[];
readonly causes: readonly (string | null)[];
readonly observedRejections: number;
readonly reasons: readonly (string | null)[];
readonly causeReasons: readonly (string | null)[];
readonly cleanupResources: readonly (readonly string[] | null)[];
};
const run = async (
processes: TestProcesses,
scenario: string,
executable = "/not/launched",
root = "/",
) =>
processes.run(
process.execPath,
[
"--input-type=module",
"--eval",
script,
JSON.stringify([scenario, executable, root]),
],
{ timeoutMs: 150_000 },
);
const outcome = (result: { readonly stdout: string }): Outcome =>
JSON.parse(result.stdout.trim().split("\n").at(-1) ?? "") as Outcome;
const earlyExit = async () => {
const root = await createTestTempDirectory("rea-launch-rejections-");
const executable = join(root, "exits-immediately");
await mkdir(join(root, "app"));
await writeFile(executable, "#!/bin/sh\nexit 0\n");
await chmod(executable, 0o755);
return { executable, root: join(root, "app") };
};
processTest(
"absorbs the orphaned rejections of a failed launch and removes its listener",
async ({ processes }) => {
const result = await run(processes, "failureWithOrphans");
expect(result.exitCode, result.stderr).toBe(0);
expect(outcome(result)).toMatchObject({
during: outcome(result).before + 1,
after: outcome(result).before,
ok: [false],
causes: ["electron.launch: Process failed to launch!"],
});
},
);
processTest(
"absorbs orphans raised in the same tick as the launch failure",
async ({ processes }) => {
const result = await run(processes, "failureInOneTick");
expect(result.exitCode, result.stderr).toBe(0);
expect(outcome(result)).toMatchObject({ ok: [false] });
},
);
processTest.skipIf(process.platform === "win32")(
"absorbs the orphans of a real Playwright launch that exits at once",
async ({ processes }) => {
const { executable, root } = await earlyExit();
const result = await run(processes, "realLaunch", executable, root);
expect(result.exitCode, result.stderr).toBe(0);
expect(outcome(result)).toMatchObject({
ok: [false],
causes: ["electron.launch: Process failed to launch!"],
});
expect(outcome(result).after).toBe(outcome(result).before);
},
);
processTest.skipIf(process.platform === "win32")(
"still fails on an unrelated Playwright rejection during a real failing launch",
async ({ processes }) => {
const { executable, root } = await earlyExit();
const result = await run(
processes,
"realWithUnrelatedPlaywrightRejection",
executable,
root,
);
expect(result.exitCode, result.stderr).toBe(1);
expect(result.stderr).toContain("unrelated playwright failure");
expect(result.stdout).toBe("");
},
);
processTest(
"does not replay an unrelated orphan to a listener that already received it",
async ({ processes }) => {
const result = await run(processes, "externalListenerSeesUnrelatedOnce");
expect(result.exitCode, result.stderr).toBe(0);
expect(outcome(result)).toMatchObject({
observedRejections: 1,
ok: [false],
causes: ["electron.launch: Process failed to launch!"],
});
},
);
processTest(
"still fails on an unrelated Playwright rejection beside a failing launch's own orphans",
async ({ processes }) => {
const result = await run(
processes,
"failureWithUnrelatedPlaywrightRejection",
);
expect(result.exitCode, result.stderr).toBe(1);
expect(result.stderr).toContain(
"Target page, context or browser has been closed",
);
expect(result.stdout).toBe("");
},
);
processTest(
"still fails at once on an unrelated rejection while a launch is pending",
async ({ processes }) => {
const result = await run(processes, "pendingWithUnrelatedRejection");
expect(result.exitCode, result.stderr).toBe(1);
expect(result.stderr).toContain("unrelated application failure");
expect(result.stdout).toBe("");
},
);
processTest(
"removes its listener after a successful launch",
async ({ processes }) => {
const result = await run(processes, "success");
expect(result.exitCode, result.stderr).toBe(0);
expect(outcome(result)).toMatchObject({
during: outcome(result).before + 1,
after: outcome(result).before,
});
},
);
processTest(
"re-raises a Playwright rejection when the launch succeeds",
async ({ processes }) => {
const result = await run(processes, "successWithPlaywrightRejection");
expect(result.exitCode, result.stderr).toBe(1);
expect(result.stderr).toContain("stray playwright failure");
expect(result.stdout).toBe("");
},
);
processTest.for([
"concurrentFailures",
"failureThenSuccess",
"successThenFailure",
])(
"keeps overlapping launches from re-raising each other's orphans (%s)",
async (scenario, { processes }) => {
const result = await run(processes, scenario);
expect(result.exitCode, result.stderr).toBe(0);
expect(outcome(result).after).toBe(outcome(result).before);
},
);
processTest(
"holds each orphan once across many overlapping successful launches",
async ({ processes }) => {
const result = await run(processes, "oneFailureWithManySuccesses");
expect(result.exitCode, result.stderr).toBe(0);
const observed = outcome(result);
expect(observed.during).toBe(observed.before + 1);
expect(observed.after).toBe(observed.before);
expect(observed.observedRejections).toBe(3);
expect(observed.ok).toEqual([false, false, false, false, false]);
expect(observed.causes[0]).toBe("electron.launch: alpha failed");
expect(observed.reasons).toEqual([
null,
"cleanup_failed",
"cleanup_failed",
"cleanup_failed",
"cleanup_failed",
]);
expect(observed.causeReasons).toEqual([
null,
...Array.from({ length: 4 }, () => "process_ownership_unavailable"),
]);
expect(observed.cleanupResources).toEqual([
[],
...Array.from({ length: 4 }, () => ["owned_process_group"]),
]);
},
);
+125 -1
View File
@@ -12,7 +12,10 @@ import {
cleanupOwnedProcessGroup,
type ProcessCleanupResult,
} from "../../../src/process/ProcessOwnership.js";
import { prepareProcessOwnershipInspection } from "../../../src/process/ProcessOwnershipObservation.js";
import {
prepareProcessOwnershipInspection,
systemProcessOwnershipHost,
} from "../../../src/process/ProcessOwnershipObservation.js";
import { waitForProviderProcessReady } from "../../fixtures/providerProcess.js";
const command = (script: string) => ({
@@ -152,6 +155,127 @@ it("fails an accepted nonzero command when an output stream errors and cleans it
expect(cleanup).toHaveBeenCalledOnce();
});
it("marks an output collection error when the process itself exits zero", async () => {
const stdout = new PassThrough();
const stderr = new PassThrough();
class FakeProcess extends EventEmitter {
readonly stdout = stdout;
readonly stderr = stderr;
exitCode: number | null = null;
signalCode: NodeJS.Signals | null = null;
readonly pid = 41235;
kill(): boolean {
return true;
}
}
const child = new FakeProcess();
const request = command("unused fake launcher command");
const failure = runOwnedCommand(
request,
{ timeoutMs: 2_000, diagnosticBytes: 1024, acceptNonZeroExit: true },
{
launcher: async () => {
setImmediate(() => {
stdout.write("partial output");
stdout.destroy(new Error("fixture read failure"));
stderr.end();
child.exitCode = 0;
child.emit("exit", 0, null);
child.emit("close", 0, null);
});
return {
process: child,
ownership: {
runId: request.runId,
leaderPid: child.pid,
processGroupId: child.pid,
},
cleanup: async () => ({ cleaned: true, signaled: false }),
};
},
},
);
await expect(failure).rejects.toMatchObject({
reason: "process",
collectionFailure: true,
message: "stdout stream failed: fixture read failure",
snapshot: { stdout: { text: "partial output" }, exitCode: 0 },
});
});
it.skipIf(process.platform === "win32")(
"sweeps detached run-token descendants and preserves a pre-existing unrelated process",
async () => {
const runId = `rea-owned-descendant-test-${randomUUID()}`;
const unrelated = await spawnOwnedProviderProcess({
command: process.execPath,
arguments: ["-e", "setInterval(() => undefined, 1000)"],
runId: `${runId}-unrelated`,
hostEnvironment: process.env,
});
let descendantPid: number | undefined;
try {
const result = await runOwnedCommand(
{
...command(`
const { spawn } = require("node:child_process");
const child = spawn(process.execPath, ["-e", "setInterval(() => undefined, 1000)"], {
detached: true,
stdio: "ignore",
});
child.unref();
process.stdout.write(String(child.pid));
`),
runId,
sweepTokenOwnedProcesses: true,
},
{ timeoutMs: 5_000, diagnosticBytes: 1024 },
);
descendantPid = Number(result.stdout.text);
expect(Number.isSafeInteger(descendantPid)).toBe(true);
let remainsLive = true;
const deadline = Date.now() + 2_000;
while (remainsLive && Date.now() < deadline) {
remainsLive = (await systemProcessOwnershipHost.listProcesses()).some(
({ pid }) => pid === descendantPid,
);
if (remainsLive) await delay(25);
}
expect(remainsLive).toBe(false);
expect(() => process.kill(unrelated.process.pid!, 0)).not.toThrow();
} finally {
if (descendantPid !== undefined) {
try {
process.kill(descendantPid, "SIGKILL");
} catch {
// The run-token sweep may already have removed it.
}
}
await cleanupOwnedProcessGroup(unrelated.ownership);
}
},
);
it.skipIf(process.platform === "win32")(
"fails before provider spawn when a requested ownership baseline cannot be captured",
async () => {
const baseline = vi
.spyOn(systemProcessOwnershipHost, "captureBaseline")
.mockRejectedValue(new Error("baseline unavailable"));
try {
await expect(
runOwnedCommand(
{ ...command("process.exit(0)"), sweepTokenOwnedProcesses: true },
{ timeoutMs: 2_000, diagnosticBytes: 1024 },
),
).rejects.toThrow("baseline unavailable");
} finally {
baseline.mockRestore();
}
},
);
it("cancels a real acquired process and independently releases it", async () => {
const controller = new AbortController();
let pid: number | undefined;
File diff suppressed because it is too large Load Diff
@@ -188,6 +188,40 @@ describe("provider process runtime and wait primitives", () => {
});
describe("provider process output and cleanup primitives", () => {
it("marks retained provider output that cannot be represented as UTF-8", async () => {
const child = spawnProviderProcessFixture("invalid-utf8");
const supervisor = new ProviderProcessSupervisor({
process: child,
ownsProcessLifetime: true,
});
await expect(supervisor.waitForOutputClose(2_000)).resolves.toBe(true);
expect(supervisor.snapshot()).toMatchObject({
stdout: { text: "a�b", invalidUtf8: true },
stderr: { text: "c�d", invalidUtf8: true },
});
await expect(supervisor.stop()).resolves.toMatchObject({
status: "already-exited",
});
});
it("marks a retained byte prefix that cuts a valid multibyte UTF-8 character", async () => {
const child = spawnProviderProcessFixture("valid-multibyte");
const supervisor = new ProviderProcessSupervisor(
{ process: child, ownsProcessLifetime: true },
{ maxDiagnosticBytes: 2 },
);
await expect(supervisor.waitForOutputClose(2_000)).resolves.toBe(true);
expect(supervisor.snapshot()).toMatchObject({
stdout: { text: "�", bytes: 2, observedBytes: 3, invalidUtf8: true },
diagnosticTruncated: true,
});
await expect(supervisor.stop()).resolves.toMatchObject({
status: "already-exited",
});
});
it("retains complete stdout and stderr beyond the former fixed ceiling", async () => {
const outputBytes = 70_000;
const child = spawnProviderProcessFixture("burst", outputBytes);
@@ -1,4 +1,7 @@
import { expect, it } from "vitest";
import { expect, it, vi } from "vitest";
import type { Socket } from "node:net";
import { EventEmitter } from "node:events";
import { PassThrough } from "node:stream";
import {
ProviderProcessSupervisor,
type ProviderProcessDiagnostic,
@@ -8,6 +11,26 @@ import {
stopProviderProcessFixture,
} from "../../fixtures/providerProcess.js";
it("unreferences inherited output streams without closing them", async () => {
const child = spawnProviderProcessFixture("stubborn");
const supervisor = new ProviderProcessSupervisor({
process: child,
ownsProcessLifetime: true,
});
const stdoutUnref = vi.spyOn(child.stdout as Socket, "unref");
const stderrUnref = vi.spyOn(child.stderr as Socket, "unref");
try {
supervisor.unrefOutputStreams();
expect(stdoutUnref).toHaveBeenCalledOnce();
expect(stderrUnref).toHaveBeenCalledOnce();
expect(child.stdout!.destroyed).toBe(false);
expect(child.stderr!.destroyed).toBe(false);
} finally {
await supervisor.stop();
await stopProviderProcessFixture(child);
}
});
it("bounds capture before diagnostic callbacks while draining both output streams", async () => {
const child = spawnProviderProcessFixture("burst", 70_000);
const diagnostics: ProviderProcessDiagnostic[] = [];
@@ -46,3 +69,30 @@ it("bounds capture before diagnostic callbacks while draining both output stream
await stopProviderProcessFixture(child);
}
});
it("bounds additional late output while retaining observed byte counts", () => {
const child = Object.assign(new EventEmitter(), {
stdout: new PassThrough(),
stderr: new PassThrough(),
exitCode: null as number | null,
signalCode: null as NodeJS.Signals | null,
kill: vi.fn(() => true),
});
const supervisor = new ProviderProcessSupervisor({
process: child,
ownsProcessLifetime: true,
});
supervisor.limitAdditionalOutputBytes(5);
child.stdout.write("abc");
supervisor.limitAdditionalOutputBytes(5);
child.stdout.write("defgh");
child.stderr.write("ijkl");
const snapshot = supervisor.snapshot();
expect(snapshot.stdout.text + snapshot.stderr.text).toHaveLength(5);
expect(snapshot.stdout.observedBytes).toBe(8);
expect(snapshot.stderr.observedBytes).toBe(4);
expect(snapshot.diagnosticTruncated).toBe(true);
supervisor.dispose();
});
@@ -0,0 +1,132 @@
import { randomUUID } from "node:crypto";
import { chmod, writeFile } from "node:fs/promises";
import { createServer, type Socket } from "node:net";
import { join } from "node:path";
import { expect, it } from "vitest";
import { CutterBridgeClient } from "../../../src/cutter/CutterBridgeClient.js";
import { CutterBridgeService } from "../../../src/cutter/CutterBridgeService.js";
import { cutterDiscoverySchema } from "../../../src/contracts/cutterToolContracts.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const descriptor = async (directory: string, port: number): Promise<string> => {
const sessionId = randomUUID();
await writeFile(
join(directory, `cutter-${process.pid}-${sessionId}.json`),
JSON.stringify({
session_id: sessionId,
pid: process.pid,
host: "127.0.0.1",
port,
token: "capacity-test-token-123456789",
document_generation: 0,
current_file: null,
cutter_version: null,
identity_status: "partial",
}),
{ mode: 0o600 },
);
return sessionId;
};
it("reports descriptor capacity without opening candidates or claiming no live sessions", async () => {
const directory = await createTestTempDirectory("rea-cutter-capacity-");
await chmod(directory, 0o700);
const selectedSession = await descriptor(directory, 1);
for (let index = 1; index < 257; index += 1) await descriptor(directory, 1);
const client = new CutterBridgeClient(
{ REA_CUTTER_BRIDGE_DIR: directory },
{ platform: "linux" },
);
const result = await client.listSessions();
expect(cutterDiscoverySchema.parse(result)).toMatchObject({
sessions: [],
discovery_status: "bridge_directory_capacity_exceeded",
bridge_directory_security: "private_verified",
});
const service = new CutterBridgeService(client);
expect(
await service.execute({
session_id: selectedSession,
expected_generation: 0,
command: "iI",
json: false,
}),
).toMatchObject({
ok: false,
error: {
_tag: "AnalysisResourceConstraintError",
cleanupIncomplete: false,
},
});
});
it("bounds simultaneous socket probes while examining every admitted descriptor", async () => {
const directory = await createTestTempDirectory("rea-cutter-probes-");
await chmod(directory, 0o700);
const sockets = new Set<Socket>();
let peak = 0;
let probes = 0;
const server = createServer((socket) => {
sockets.add(socket);
probes += 1;
peak = Math.max(peak, sockets.size);
socket.once("close", () => sockets.delete(socket));
setTimeout(() => socket.destroy(), 20);
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
try {
const address = server.address();
if (address === null || typeof address === "string")
throw new Error("listener missing");
for (let index = 0; index < 24; index += 1)
await descriptor(directory, address.port);
const client = new CutterBridgeClient(
{ REA_CUTTER_BRIDGE_DIR: directory },
{ platform: "linux" },
);
expect((await client.listSessions()).discovery_status).toBe(
"no_live_bridge_found",
);
expect(probes).toBe(24);
expect(peak).toBeGreaterThan(1);
expect(peak).toBeLessThanOrEqual(8);
} finally {
for (const socket of sockets) socket.destroy();
await new Promise<void>((resolve) => server.close(() => resolve()));
}
});
it("rejects expanded authenticated frames before dispatch and retains no cleanup owner", async () => {
const directory = await createTestTempDirectory("rea-cutter-frame-");
await chmod(directory, 0o700);
const sessionId = await descriptor(directory, 1);
const service = new CutterBridgeService(
new CutterBridgeClient(
{ REA_CUTTER_BRIDGE_DIR: directory },
{ platform: "linux" },
),
);
const input = { session_id: sessionId, expected_generation: 0, json: false };
const rejected = await service.execute({
...input,
command: '"'.repeat(4 * 1024 * 1024 + 1024),
});
expect(rejected).toMatchObject({
ok: false,
error: {
_tag: "AnalysisResourceConstraintError",
cleanupIncomplete: false,
},
});
expect(await service.retryCleanup()).toEqual({ ok: true, value: null });
// A later valid command reaches transport, rather than replaying the resource failure.
expect(await service.execute({ ...input, command: "iI" })).toMatchObject({
ok: false,
error: {
_tag: "AnalysisCapabilityUnavailableError",
cleanupIncomplete: false,
},
});
});
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,177 @@
import { createServer } from "node:net";
import { createHmac } from "node:crypto";
import { readFileSync } from "node:fs";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, expect, it } from "vitest";
import { CutterBridgeClient } from "../../../src/cutter/CutterBridgeClient.js";
const SESSION_ID = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a";
const TOKEN = "synthetic-cutter-bridge-token-for-test";
let directory: string | undefined;
let server: ReturnType<typeof createServer> | undefined;
afterEach(async () => {
if (server !== undefined)
await new Promise<void>((resolve) => server?.close(() => resolve()));
if (directory !== undefined)
await rm(directory, { recursive: true, force: true });
server = undefined;
directory = undefined;
});
const listen = async (
listener: ReturnType<typeof createServer>,
): Promise<number> => {
await new Promise<void>((resolve) =>
listener.listen(0, "127.0.0.1", resolve),
);
const address = listener.address();
if (address === null || typeof address === "string")
throw new Error("Expected an ephemeral IPv4 listener");
return address.port;
};
const bridgeServer = (
currentFile: string | null,
documentGeneration: number,
): ReturnType<typeof createServer> => {
let ordinal = 0;
return createServer((connection) => {
const connectionOrdinal = ++ordinal;
connection.setEncoding("utf8");
let input = "";
let clientNonce = "";
let serverNonce = "";
connection.on("data", (chunk: string) => {
input += chunk;
const newline = input.indexOf("\n");
if (newline < 0) return;
const frame = JSON.parse(input.slice(0, newline)) as Record<
string,
unknown
>;
input = input.slice(newline + 1);
if (frame.kind === "rea-auth-v2") {
clientNonce = String(frame.nonce);
serverNonce =
connectionOrdinal.toString(16).padStart(16, "0") + "d".repeat(48);
connection.write(
`${JSON.stringify({ session_id: SESSION_ID, nonce: serverNonce, proof: createHmac("sha256", TOKEN).update(`rea-cutter-server-v2:${SESSION_ID}:${clientNonce}:${serverNonce}`).digest("hex") })}\n`,
);
return;
}
const requestBytes = String(frame.request);
const request = JSON.parse(requestBytes) as Record<string, unknown>;
const expected = createHmac("sha256", TOKEN)
.update(
`rea-cutter-client-v2:${SESSION_ID}:${clientNonce}:${serverNonce}:${requestBytes}`,
)
.digest("hex");
if (frame.proof !== expected) {
connection.destroy();
return;
}
if (!["status", "command", "ack"].includes(String(request.kind)))
throw new Error(`Unmodeled bridge request: ${String(request.kind)}`);
const response = JSON.stringify(
request.kind === "ack"
? {
ok: true,
acknowledged: false,
}
: {
ok: true,
session_id: request.session_id,
current_file: currentFile,
document_generation: documentGeneration,
cutter_version: "Cutter fixture version",
identity_status: "partial",
...(request.kind === "status"
? {
completed_connection: (connectionOrdinal - 1)
.toString(16)
.padStart(16, "0"),
completed_commands: [],
}
: { execution_state: "complete" }),
},
);
const proof = createHmac("sha256", TOKEN)
.update(
`rea-cutter-response-v2:${SESSION_ID}:${clientNonce}:${serverNonce}:${response}`,
)
.digest("hex");
connection.end(`${JSON.stringify({ response, proof })}\n`);
});
});
};
const clientFor = (bridgeDirectory: string): CutterBridgeClient =>
process.platform === "win32"
? new CutterBridgeClient(
{ REA_CUTTER_BRIDGE_DIR: bridgeDirectory },
{
windowsPrivateReader: {
verifyDirectory: () => true,
readDescriptor: (root, name, maxBytes) => {
const bytes = readFileSync(join(root, name));
if (bytes.byteLength > maxBytes)
throw new Error("Descriptor too large");
return bytes;
},
},
},
)
: new CutterBridgeClient({ REA_CUTTER_BRIDGE_DIR: bridgeDirectory });
const writeDescriptor = async (port: number): Promise<void> => {
if (directory === undefined) throw new Error("Test directory is unavailable");
await writeFile(
join(directory, `cutter-${process.pid}-${SESSION_ID}.json`),
JSON.stringify({
session_id: SESSION_ID,
pid: process.pid,
host: "127.0.0.1",
port,
token: TOKEN,
document_generation: 1,
current_file: "/old/sample.bin",
cutter_version: "Cutter fixture version",
identity_status: "partial",
}),
{ mode: 0o600 },
);
};
it("preserves a live Cutter status that explicitly has no active document", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-cutter-null-status-"));
server = bridgeServer(null, 2);
await writeDescriptor(await listen(server));
const result = await clientFor(directory).listSessions();
expect(result.sessions[0]).toMatchObject({
session_id: SESSION_ID,
document_generation: 2,
current_file: null,
});
});
it("preserves a null active document returned after a Cutter command", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-cutter-null-command-"));
server = bridgeServer(null, 2);
await writeDescriptor(await listen(server));
const result = await clientFor(directory).execute({
sessionId: SESSION_ID,
expectedGeneration: 2,
command: "ij",
json: true,
});
expect(result.currentFile).toBeNull();
});
@@ -0,0 +1,406 @@
import { expect, it, vi } from "vitest";
import { CutterBridgeService } from "../../../src/cutter/CutterBridgeService.js";
const cutterInput = {
session_id: "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a",
expected_generation: 7,
command: "pd 4",
};
it("retains uncertain command completion as Evidence without encouraging a retry", async () => {
const service = new CutterBridgeService({
listSessions: async () => ({
sessions: [],
bridge_directory: "/private/bridge",
discovery_status: "no_live_bridge_found",
bridge_directory_security: "private_verified",
}),
execute: async () => ({
requestId: "4b18ce4d-bf31-456e-ae31-e8c547b2f9db",
output: null,
currentFile: "/fixtures/sample.bin",
documentGeneration: 7,
identityStatus: "partial",
cutterVersion: "Cutter fixture version",
executionState: "unknown",
error: "transport-response-missing",
message: "The command may have completed; do not retry automatically",
outputTruncated: false,
}),
});
const result = await service.execute({
session_id: "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a",
expected_generation: 7,
command: "Ps /tmp/project.rzdb",
});
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisOutputError",
cleanupIncomplete: true,
partialObservation: {
normalized_result: {
command: "Ps /tmp/project.rzdb",
output: null,
execution_state: "unknown",
error: "transport-response-missing",
message: expect.stringContaining("do not retry automatically"),
document_generation: 7,
cutter_version: "Cutter fixture version",
},
limitations: expect.arrayContaining([
"Command completion or its output could not be confirmed; do not retry automatically because the command may have produced partial or persistent effects.",
]),
provider: { version: "Cutter fixture version" },
},
},
});
});
it("clears a poisoned command only after its exact UI-dispatcher receipt", async () => {
const requestId = "4b18ce4d-bf31-456e-ae31-e8c547b2f9db";
const wrongId = "8ca93d11-107d-41ed-8b40-31dd53cd26a6";
let receipt: string | undefined;
let uiPending = true;
let dispatches = 0;
const confirmCommandCompletion = vi.fn(
async (_session: string, id: string) =>
receipt === id && !uiPending
? { ok: true as const, value: true }
: { ok: true as const, value: false },
);
const service = new CutterBridgeService({
listSessions: async () => ({
sessions: [],
bridge_directory: "/private/bridge",
discovery_status: "no_live_bridge_found",
bridge_directory_security: "private_verified",
}),
confirmCommandCompletion,
execute: async () => {
dispatches += 1;
return {
requestId,
output: null,
currentFile: "/fixtures/sample.bin",
documentGeneration: 7,
identityStatus: "partial",
cutterVersion: "Cutter fixture version",
executionState: dispatches === 1 ? "unknown" : "complete",
error: dispatches === 1 ? "ui-thread-request-timeout" : null,
message: null,
outputTruncated: false,
};
},
});
const first = await service.execute(cutterInput);
expect(first).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
});
for (const unconfirmed of [
undefined,
"ede4bbfd-6348-46aa-963b-0de0e78ccbdc",
wrongId,
]) {
receipt = unconfirmed;
const blocked = await service.execute(cutterInput);
expect(blocked).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
});
expect(dispatches).toBe(1);
}
receipt = requestId;
const pending = await service.execute(cutterInput);
expect(pending).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
});
expect(dispatches).toBe(1);
expect(confirmCommandCompletion).toHaveBeenLastCalledWith(
cutterInput.session_id,
requestId,
undefined,
);
receipt = requestId;
uiPending = false;
const recovered = await service.execute(cutterInput);
expect(recovered.ok).toBe(true);
expect(dispatches).toBe(2);
});
it("recovers canceled command A after B and does not retain poisoned B", async () => {
const requestA = "4b18ce4d-bf31-456e-ae31-e8c547b2f9db";
const completionTokenA = "0000000000000007";
const requestB = "8ca93d11-107d-41ed-8b40-31dd53cd26a6";
const receipts = new Set<string>();
let dispatches = 0;
const confirmCommandCompletion = vi.fn(
async (_session: string, id: string) =>
receipts.delete(id)
? { ok: true as const, value: true }
: { ok: true as const, value: false },
);
const execute = async () => {
dispatches += 1;
if (dispatches === 1) {
receipts.add(requestA);
return {
requestId: requestA,
output: null,
currentFile: "/fixtures/sample.bin",
documentGeneration: 7,
identityStatus: "partial" as const,
cutterVersion: null,
executionState: "unknown" as const,
error: "transport-response-missing",
message: "cancelled after dispatch",
outputTruncated: false,
completionToken: completionTokenA,
};
}
if (dispatches === 2)
return {
requestId: requestB,
output: "B complete",
currentFile: "/fixtures/sample.bin",
documentGeneration: 7,
identityStatus: "partial" as const,
cutterVersion: null,
executionState: "complete" as const,
error: null,
message: null,
outputTruncated: false,
};
if (dispatches === 3)
return {
requestId: requestB,
output: null,
currentFile: "/fixtures/sample.bin",
documentGeneration: 7,
identityStatus: "partial" as const,
cutterVersion: null,
executionState: "not_started" as const,
error: "session-poisoned-after-ui-timeout",
message: null,
outputTruncated: false,
};
return {
requestId: "c31130c6-fc6c-46ad-949e-586724d8fd84",
output: "recovered",
currentFile: "/fixtures/sample.bin",
documentGeneration: 7,
identityStatus: "partial" as const,
cutterVersion: null,
executionState: "complete" as const,
error: null,
message: null,
outputTruncated: false,
};
};
const client = {
listSessions: async () => ({
sessions: [],
bridge_directory: "/private/bridge",
discovery_status: "no_live_bridge_found" as const,
bridge_directory_security: "private_verified" as const,
}),
confirmCommandCompletion,
execute,
};
const callerA = new CutterBridgeService(client);
const callerB = new CutterBridgeService(client);
const cancelledA = await callerA.execute(cutterInput);
expect(cancelledA).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
});
expect(await callerB.execute(cutterInput)).toMatchObject({ ok: true });
expect(receipts.has(requestA)).toBe(true);
const poisonedB = await callerA.execute(cutterInput);
expect(poisonedB).toMatchObject({
ok: true,
value: { normalized_result: { execution_state: "not_started" } },
});
expect(confirmCommandCompletion).toHaveBeenCalledTimes(1);
expect(confirmCommandCompletion).toHaveBeenCalledWith(
cutterInput.session_id,
requestA,
completionTokenA,
);
expect(await callerA.execute(cutterInput)).toMatchObject({ ok: true });
expect(confirmCommandCompletion).toHaveBeenCalledTimes(1);
expect(dispatches).toBe(4);
});
it("rejects malformed Cutter commands and pre-aborted calls", async () => {
const service = new CutterBridgeService({
listSessions: async () => ({
sessions: [],
bridge_directory: "/private/bridge",
discovery_status: "no_live_bridge_found",
bridge_directory_security: "private_verified",
}),
execute: async () => {
throw new Error("must not dispatch");
},
});
const malformed = await service.execute({ ...cutterInput, command: "" });
expect(malformed).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
});
const controller = new AbortController();
controller.abort();
const cancelled = await service.execute(cutterInput, {
signal: controller.signal,
});
expect(cancelled).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
});
it.each([
[new Error("session generation changed"), "AnalysisInputError"],
[new Error("bridge disconnected"), "AnalysisCapabilityUnavailableError"],
["plain failure", "AnalysisCapabilityUnavailableError"],
])("maps a Cutter bridge failure to %s", async (failure, tag) => {
const service = new CutterBridgeService({
listSessions: async () => ({
sessions: [],
bridge_directory: "/private/bridge",
discovery_status: "no_live_bridge_found",
bridge_directory_security: "private_verified",
}),
execute: async () => {
throw failure;
},
});
const result = await service.execute(cutterInput);
expect(result).toMatchObject({ ok: false, error: { _tag: tag } });
});
it("preserves cancellation unless the bridge reports an ambiguous completion", async () => {
const createService = (message: string, controller: AbortController) =>
new CutterBridgeService({
listSessions: async () => ({
sessions: [],
bridge_directory: "/private/bridge",
discovery_status: "no_live_bridge_found",
bridge_directory_security: "private_verified",
}),
execute: async () => {
controller.abort();
throw new Error(message);
},
});
const cancelledController = new AbortController();
const cancelled = await createService(
"transport cancelled",
cancelledController,
).execute(cutterInput, { signal: cancelledController.signal });
expect(cancelled).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
const uncertainController = new AbortController();
const uncertain = await createService(
"command may have completed",
uncertainController,
).execute(cutterInput, { signal: uncertainController.signal });
expect(uncertain).toMatchObject({
ok: false,
error: { _tag: "AnalysisCapabilityUnavailableError" },
});
});
it("shares one cleanup attempt when commands retry the same receipt together", async () => {
const requestId = "4b18ce4d-bf31-456e-ae31-e8c547b2f9db";
let receiptPresent = false;
let releaseConfirm: (() => void) | undefined;
let confirms = 0;
const confirmCommandCompletion = vi.fn(async () => {
confirms += 1;
if (!receiptPresent) return { ok: true as const, value: false };
if (confirms === 1) {
await new Promise<void>((resolve) => {
releaseConfirm = resolve;
});
}
if (!receiptPresent) return { ok: true as const, value: false };
receiptPresent = false;
return { ok: true as const, value: true };
});
let dispatches = 0;
const service = new CutterBridgeService({
listSessions: async () => ({
sessions: [],
bridge_directory: "/private/bridge",
discovery_status: "no_live_bridge_found",
bridge_directory_security: "private_verified",
}),
confirmCommandCompletion,
execute: async () => {
dispatches += 1;
if (dispatches === 1) {
receiptPresent = true;
return {
requestId,
output: null,
currentFile: "/fixtures/sample.bin",
documentGeneration: 7,
identityStatus: "partial" as const,
cutterVersion: null,
executionState: "unknown" as const,
error: "transport-response-missing",
message: "cancelled after dispatch",
outputTruncated: false,
};
}
return {
requestId: "8ca93d11-107d-41ed-8b40-31dd53cd26a6",
output: "complete",
currentFile: "/fixtures/sample.bin",
documentGeneration: 7,
identityStatus: "partial" as const,
cutterVersion: null,
executionState: "complete" as const,
error: null,
message: null,
outputTruncated: false,
};
},
});
const blocked = await service.execute(cutterInput);
expect(blocked).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
});
const concurrent = [
service.execute(cutterInput),
service.execute(cutterInput),
];
if (releaseConfirm === undefined) throw new Error("cleanup did not start");
releaseConfirm();
const recovered = await Promise.all(concurrent);
expect(recovered.every((result) => result.ok)).toBe(true);
expect(confirms).toBe(1);
expect(dispatches).toBe(3);
});
@@ -0,0 +1,145 @@
import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, expect, it } from "vitest";
import { GdbSessionManager } from "../../../src/gdb/GdbSessionManager.js";
let directory: string | undefined;
const managers: GdbSessionManager[] = [];
afterEach(async () => {
await Promise.all(
managers
.splice(0)
.map((manager) => manager.closeAll().catch(() => undefined)),
);
if (directory !== undefined)
await rm(directory, { recursive: true, force: true });
directory = undefined;
});
it("bounds active and queued GDB commands, including cancelled placeholders", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-gdb-command-queue-limit-"));
const provider = join(directory, "fake-gdb-queue.mjs");
const activePath = join(directory, "active-command");
const releasePath = join(directory, "release-command");
await writeFile(
provider,
`#!${process.execPath}
import { access, writeFile } from "node:fs/promises";
process.stdout.write("(gdb)\\n");
let input = "";
let firstConsoleCommand = true;
process.stdin.setEncoding("utf8");
process.stdin.on("data", async (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n");
if (boundary < 0) break;
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
const match = /^(\\d+)/.exec(line);
if (!match) continue;
if (line.includes("-interpreter-exec console") && firstConsoleCommand) {
firstConsoleCommand = false;
await writeFile(${JSON.stringify(activePath)}, "active");
for (;;) {
try { await access(${JSON.stringify(releasePath)}); break; }
catch { await new Promise((resolve) => setTimeout(resolve, 10)); }
}
}
process.stdout.write(match[1] + "^done\\n");
}
});
`,
);
await chmod(provider, 0o700);
const manager = new GdbSessionManager({
platform: "linux",
environment: { REA_GDB_COMMAND: provider },
});
managers.push(manager);
const started = await manager.start();
expect(started.ok).toBe(true);
if (!started.ok) return;
const active = manager.execute(started.value.session_id, "hold");
let activeSeen = false;
for (let attempt = 0; attempt < 100 && !activeSeen; attempt += 1) {
try {
await readFile(activePath, "utf8");
activeSeen = true;
} catch {
await new Promise((resolve) => setTimeout(resolve, 10));
}
}
expect(activeSeen).toBe(true);
const controllers = Array.from({ length: 15 }, () => new AbortController());
const queued = controllers.map((controller, index) =>
manager.execute(
started.value.session_id,
`queued-${index}`,
controller.signal,
),
);
const safetyRelease = setTimeout(() => {
void writeFile(releasePath, "safety release");
}, 250);
const overflow = await manager.execute(started.value.session_id, "overflow");
clearTimeout(safetyRelease);
expect(overflow).toMatchObject({
ok: false,
error: {
_tag: "AnalysisResourceConstraintError",
operation: "gdb_console",
resource: "transport",
reportedLimits: {
max_pending_commands: 16,
active_or_queued_commands: 16,
},
},
});
for (const controller of controllers) controller.abort();
const cancelled = await Promise.all(queued);
expect(cancelled).toHaveLength(15);
expect(
cancelled.every(
(result) => !result.ok && result.error._tag === "AnalysisCancelledError",
),
).toBe(true);
const cancellationSafetyRelease = setTimeout(() => {
void writeFile(releasePath, "safety release after cancellation");
}, 250);
try {
await expect(
manager.execute(
started.value.session_id,
"cannot-bypass-cancelled-placeholders",
),
).resolves.toMatchObject({
ok: false,
error: {
_tag: "AnalysisResourceConstraintError",
reportedLimits: { active_or_queued_commands: 16 },
},
});
} finally {
clearTimeout(cancellationSafetyRelease);
}
await writeFile(releasePath, "release");
expect((await active).ok).toBe(true);
const admittedAfterDrain = await manager.execute(
started.value.session_id,
"admitted-after-drain",
);
expect(admittedAfterDrain.ok).toBe(true);
await expect(
manager.execute(started.value.session_id, "after-drain"),
).resolves.toMatchObject({
ok: true,
value: { result: { completion_status: "complete" } },
});
});
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,109 @@
import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { GdbSessionManager } from "../../../src/gdb/GdbSessionManager.js";
describe("persistent debugger session managers", () => {
let directory: string | undefined;
const managers: Array<{ closeAll(): Promise<void> }> = [];
afterEach(async () => {
await Promise.all(
managers
.splice(0)
.map((manager) => manager.closeAll().catch(() => undefined)),
);
if (directory !== undefined)
await rm(directory, { recursive: true, force: true });
directory = undefined;
});
it("runs a correlated GDB MI command, reports status, and closes its owned process", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-gdb-manager-"));
const provider = join(directory, "fake-gdb.mjs");
await writeFile(
provider,
`#!${process.execPath}
process.stdout.write("(gdb)\\n");
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n");
if (boundary < 0) break;
const line = input.slice(0, boundary);
input = input.slice(boundary + 1);
const match = /^(\\d+)/.exec(line);
if (match && line.includes("list-thread-groups"))
process.stdout.write(match[1] + "^done,groups=[]\\n");
else if (match) process.stdout.write(match[1] + "^done\\n");
}
});
`,
);
await chmod(provider, 0o700);
const manager = new GdbSessionManager({
platform: "linux",
environment: { REA_GDB_COMMAND: provider },
});
managers.push(manager);
const started = await manager.start();
expect(started.ok).toBe(true);
if (!started.ok) return;
expect(manager.status(started.value.session_id)?.state).toBe("ready");
const result = await manager.execute(
started.value.session_id,
"show version",
);
expect(result.ok).toBe(true);
if (result.ok) expect(result.value.result.mi).toMatch(/^\d+\^done/u);
const closed = await manager.close(started.value.session_id);
expect(closed.ok).toBe(true);
expect(manager.status(started.value.session_id)).toBeUndefined();
});
it("does not start GDB when it rejects the required auto-load setting", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-gdb-autoload-"));
const provider = join(directory, "fake-gdb-reject.mjs");
await writeFile(
provider,
`#!${process.execPath}
process.stdout.write("(gdb)\\n");
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n");
if (boundary < 0) break;
const line = input.slice(0, boundary);
input = input.slice(boundary + 1);
const match = /^(\\d+)(.*)/.exec(line);
if (match) process.stdout.write(match[1] + (match[2].includes("-gdb-set auto-load off") ? "^error,msg=\\"rejected\\"\\n" : "^done\\n"));
}
});
`,
);
await chmod(provider, 0o700);
const manager = new GdbSessionManager({
platform: "linux",
environment: { REA_GDB_COMMAND: provider },
});
managers.push(manager);
const started = await manager.start();
expect(started.ok).toBe(false);
if (!started.ok)
expect(JSON.stringify(started.error)).toContain(
"automatic-loading disable command",
);
});
});
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,28 @@
import { describe, expect, it } from "vitest";
import {
createRizinCommandTimeoutError,
isRizinCommandDeadlineExpired,
RizinCommandTimeoutError,
} from "../../../src/rizin/RizinDebugSessionManager.js";
describe("Rizin command timeout semantics", () => {
it("treats zero and negative remaining time as expired", () => {
expect(isRizinCommandDeadlineExpired(1)).toBe(false);
expect(isRizinCommandDeadlineExpired(0)).toBe(true);
expect(isRizinCommandDeadlineExpired(-1)).toBe(true);
});
it("retains partial frames separated by newlines in the timeout error", () => {
const error = createRizinCommandTimeoutError([
"first frame",
"second frame",
]);
expect(error).toBeInstanceOf(RizinCommandTimeoutError);
expect(error.partialOutput).toBe("first frame\nsecond frame");
expect(error.message).toBe(
"Timed out waiting for Rizin's command-completion marker",
);
});
});
@@ -0,0 +1,245 @@
import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
import { EventEmitter } from "node:events";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { PassThrough, Writable } from "node:stream";
import { RizinDebugSessionManager } from "../../../src/rizin/RizinDebugSessionManager.js";
import {
createRizinTestManager,
rizinTestInferiorTty,
} from "./RizinTestInferiorTty.js";
import { stopOwnedDebuggerProcess } from "../../../src/process/ownedDebuggerSession.js";
import type {
ProviderProcessHandle,
SpawnedOwnedProviderProcess,
} from "../../../src/process/ProviderProcess.js";
interface InjectedProcessControl {
output(chunk: Buffer | string): void;
stdinError(): void;
closeStdin(): void;
exitLeader(signal?: NodeJS.Signals): void;
closeOutput(): void;
exit(signal?: NodeJS.Signals): void;
}
type InjectedSpawnProcess = NonNullable<
NonNullable<
ConstructorParameters<typeof RizinDebugSessionManager>[1]
>["spawnProcess"]
>;
export const incompleteStop: typeof stopOwnedDebuggerProcess = async (
session,
name,
) => {
await stopOwnedDebuggerProcess(session, name);
return { status: "incomplete", reason: "injected stop uncertainty" };
};
export const abortOnCheck = (targetCheck: number): AbortSignal => {
let checks = 0;
let aborted = false;
type Listener = Parameters<AbortSignal["addEventListener"]>[1];
const listeners = new Set<Listener>();
return {
get aborted() {
checks += 1;
if (checks >= targetCheck) aborted = true;
return aborted;
},
addEventListener: (
_type: Parameters<AbortSignal["addEventListener"]>[0],
listener: Listener,
) => {
if (listener !== null) listeners.add(listener);
},
removeEventListener: (
_type: Parameters<AbortSignal["removeEventListener"]>[0],
listener: Parameters<AbortSignal["removeEventListener"]>[1],
) => {
if (listener !== null) listeners.delete(listener);
},
dispatchEvent: () => true,
onabort: null,
reason: undefined,
throwIfAborted: () => undefined,
} as AbortSignal;
};
export const createInjectedProcess = (
options: {
readonly stdin?:
| "normal"
| "null"
| "destroyed"
| "throws"
| "throws-opaque"
| "write-error";
readonly onWrite?: (text: string, control: InjectedProcessControl) => void;
readonly startup?: (control: InjectedProcessControl) => void;
readonly beforeSpawnReturns?: () => void;
readonly spawnError?: unknown;
} = {},
): {
readonly spawnProcess: InjectedSpawnProcess;
readonly control: InjectedProcessControl;
} => {
const stdout = new PassThrough();
const stderr = new PassThrough();
let exitCode: number | null = null;
let signalCode: NodeJS.Signals | null = null;
const processHandle = new EventEmitter() as EventEmitter & {
pid: number;
stdout: PassThrough;
stdin: Writable | null;
stderr: PassThrough;
exitCode: number | null;
signalCode: NodeJS.Signals | null;
kill(signal?: NodeJS.Signals | number): boolean;
};
processHandle.pid = process.pid;
processHandle.stdout = stdout;
processHandle.stderr = stderr;
processHandle.exitCode = exitCode;
processHandle.signalCode = signalCode;
const control: InjectedProcessControl = {
output: (chunk) => stdout.emit("data", Buffer.from(chunk)),
stdinError: () => stdin?.emit("error", new Error("injected stdin error")),
closeStdin: () => stdin?.destroy(),
exitLeader: (signal = "SIGTERM") => {
exitCode = null;
signalCode = signal;
processHandle.exitCode = exitCode;
processHandle.signalCode = signalCode;
processHandle.emit("exit", exitCode, signalCode);
},
closeOutput: () => {
stdout.destroy();
stderr.destroy();
processHandle.emit("close", exitCode, signalCode);
},
exit: (signal = "SIGTERM") => {
control.exitLeader(signal);
control.closeOutput();
},
};
const stdin =
options.stdin === "null"
? null
: new Writable({
write(chunk, _encoding, callback) {
options.onWrite?.(Buffer.from(chunk).toString("utf8"), control);
callback(
options.stdin === "write-error"
? new Error("injected write callback failure")
: undefined,
);
},
});
if (stdin !== null) {
if (options.stdin === "destroyed")
Object.defineProperty(stdin, "destroyed", { value: true });
if (options.stdin === "throws" || options.stdin === "throws-opaque")
stdin.write = (() => {
if (options.stdin === "throws-opaque")
throw "injected opaque write failure";
throw new Error("injected synchronous write failure");
}) as typeof stdin.write;
processHandle.stdin = stdin;
} else processHandle.stdin = null;
processHandle.kill = (signal = "SIGTERM") => {
if (exitCode !== null || signalCode !== null) return false;
control.exit(typeof signal === "string" ? signal : "SIGTERM");
return true;
};
const spawnProcess: InjectedSpawnProcess = async (spawnOptions) => {
options.beforeSpawnReturns?.();
if (options.spawnError !== undefined) throw options.spawnError;
setImmediate(() => {
if (options.startup !== undefined) options.startup(control);
else control.output(Buffer.from([0]));
});
return {
process: processHandle as unknown as ProviderProcessHandle,
ownership: {
runId: spawnOptions.runId,
leaderPid: process.pid,
processGroupId: process.pid,
expectedParentPid: process.pid,
},
} satisfies SpawnedOwnedProviderProcess;
};
return { spawnProcess, control };
};
export const createRizinCoverageHarness = () => {
let directory: string | undefined;
const managers: RizinDebugSessionManager[] = [];
const track = (manager: RizinDebugSessionManager): void => {
managers.push(manager);
};
const makeProvider = async (
body: string,
shebang = "#!/usr/bin/env node",
): Promise<string> => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-coverage-"));
const provider = join(directory, "fake-rizin.mjs");
await writeFile(provider, `${shebang}\n${body}\n`);
await chmod(provider, 0o700);
return provider;
};
const start = async (
provider: string,
options: ConstructorParameters<typeof RizinDebugSessionManager>[1] = {},
): Promise<{ manager: RizinDebugSessionManager; sessionId: string }> => {
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: provider },
options,
);
track(manager);
const result = await manager.start({
path: "/tmp/coverage-target",
inferior_tty: await rizinTestInferiorTty(),
});
if (!result.ok) throw result.error;
return { manager, sessionId: result.value.session_id };
};
const startInjected = async (
spawnProcess: InjectedSpawnProcess,
options: ConstructorParameters<typeof RizinDebugSessionManager>[1] = {},
) => {
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{ ...options, spawnProcess },
);
track(manager);
const started = await manager.start({
path: "/tmp/injected",
inferior_tty: await rizinTestInferiorTty(),
});
return { manager, started };
};
const cleanup = async (): Promise<void> => {
await Promise.all(
managers
.splice(0)
.map((manager) => manager.closeAll().catch(() => undefined)),
);
if (directory !== undefined)
await rm(directory, { recursive: true, force: true });
directory = undefined;
};
const missingProviderPath = (): string => join(directory!, "does-not-exist");
return {
cleanup,
makeProvider,
missingProviderPath,
start,
startInjected,
track,
};
};
@@ -0,0 +1,422 @@
import { afterEach, expect, it, vi } from "vitest";
import { RizinDebugSessionManager } from "../../../src/rizin/RizinDebugSessionManager.js";
import {
createRizinTestManager,
stopFakeNoInferior,
rizinTestInferiorTty,
} from "./RizinTestInferiorTty.js";
import { rizinCommand } from "../../../src/rizin/RizinCommand.js";
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
import {
createRizinCoverageHarness,
createInjectedProcess,
abortOnCheck,
incompleteStop,
} from "./RizinDebugSessionCoverage.fixtures.js";
const {
cleanup,
makeProvider,
missingProviderPath,
start,
startInjected,
track,
} = createRizinCoverageHarness();
afterEach(cleanup);
it.skipIf(process.platform === "win32")(
"builds the one-shot command with the caller's path and command",
() => {
expect(rizinCommand({ path: "./sample file", command: "izz" })).toEqual([
"-N",
"-q",
"-c",
"izz",
expect.stringMatching(/sample file/u),
]);
},
);
it.skipIf(process.platform === "win32")(
"rejects unsupported, pre-cancelled, and failed startup requests",
async () => {
const windows = createRizinTestManager({}, { platform: "win32" });
expect(
(
await windows.start({
path: "/tmp/a",
inferior_tty: "unused-before-platform-admission",
})
).ok,
).toBe(false);
const aborted = new AbortController();
aborted.abort();
expect(
(
await windows.start(
{ path: "/tmp/a", inferior_tty: await rizinTestInferiorTty() },
aborted.signal,
)
).ok,
).toBe(false);
const failed = await makeProvider("process.exit(9);");
const manager = createRizinTestManager({
REA_RIZIN_COMMAND: failed,
});
track(manager);
const result = await manager.start({
path: "/tmp/a",
inferior_tty: await rizinTestInferiorTty(),
});
expect(result.ok).toBe(false);
const missing = createRizinTestManager({
REA_RIZIN_COMMAND: missingProviderPath(),
});
track(missing);
const spawnFailure = await missing.start({
path: "/tmp/a",
inferior_tty: await rizinTestInferiorTty(),
});
expect(spawnFailure.ok).toBe(false);
},
);
it.skipIf(process.platform === "win32")(
"returns a startup timeout when Rizin exits before its initial frame",
async () => {
const provider = await makeProvider("process.exit(0);");
const manager = createRizinTestManager({
REA_RIZIN_COMMAND: provider,
});
track(manager);
const result = await manager.start({
path: "/tmp/early-exit",
inferior_tty: await rizinTestInferiorTty(),
});
expect(result.ok).toBe(false);
},
);
it.skipIf(process.platform === "win32")(
"times out startup through the frame wait when Rizin never emits a frame",
async () => {
let resolveSpawned!: () => void;
const spawned = new Promise<void>((resolve) => {
resolveSpawned = resolve;
});
const injected = createInjectedProcess({
startup: () => undefined,
beforeSpawnReturns: resolveSpawned,
});
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{
spawnProcess: injected.spawnProcess,
stopProcess: async () => ({ status: "stopped" }),
},
);
track(manager);
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
try {
const starting = manager.start({
path: "/tmp/no-startup-frame",
inferior_tty: await rizinTestInferiorTty(),
});
await spawned;
await vi.advanceTimersByTimeAsync(30_001);
const result = await starting;
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error.message).toContain("timed out");
} finally {
vi.useRealTimers();
}
},
);
it.skipIf(process.platform === "win32")(
"does not spawn Rizin when cancellation arrives during TTY validation",
async () => {
let spawned = false;
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{
spawnProcess: async () => {
spawned = true;
throw new Error("must not spawn after cancellation");
},
},
);
const result = await manager.start(
{
path: "/tmp/cancel-before-spawn",
inferior_tty: await rizinTestInferiorTty(),
},
abortOnCheck(2),
);
expect(result.ok).toBe(false);
expect(spawned).toBe(false);
},
);
it.skipIf(process.platform === "win32")(
"rejects a non-TTY path before spawning Rizin",
async () => {
let spawned = false;
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{
spawnProcess: async () => {
spawned = true;
throw new Error("must not spawn with an invalid TTY");
},
},
);
const result = await manager.start({
path: "/tmp/not-a-tty-target",
inferior_tty: "/dev/null",
});
expect(result.ok).toBe(false);
expect(spawned).toBe(false);
},
);
it.skipIf(process.platform === "win32")(
"closeAll drains concurrent startups and blocks later admission",
async () => {
let spawnCount = 0;
let resolveSpawnCalls!: () => void;
const bothSpawnsCalled = new Promise<void>((resolve) => {
resolveSpawnCalls = resolve;
});
let releaseSpawns!: () => void;
const spawnGate = new Promise<void>((resolve) => {
releaseSpawns = resolve;
});
const injected = createInjectedProcess();
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{
spawnProcess: async (options) => {
spawnCount += 1;
if (spawnCount === 2) resolveSpawnCalls();
await spawnGate;
return injected.spawnProcess(options);
},
stopProcess: async () => ({ status: "stopped" }),
},
);
const tty = await rizinTestInferiorTty();
const starts = [
manager.start({ path: "/tmp/start-one", inferior_tty: tty }),
manager.start({ path: "/tmp/start-two", inferior_tty: tty }),
];
await bothSpawnsCalled;
let closeAllResolved = false;
const closing = manager.closeAll().then(() => {
closeAllResolved = true;
});
await Promise.resolve();
expect(closeAllResolved).toBe(false);
releaseSpawns();
const started = await Promise.all(starts);
expect(started.every((result) => result.ok)).toBe(true);
await closing;
expect(
manager.status(started[0]!.ok ? started[0]!.value.session_id : "missing"),
).toBeUndefined();
expect(
(await manager.start({ path: "/tmp/after-close-all", inferior_tty: tty }))
.ok,
).toBe(false);
expect((await manager.close("missing")).ok).toBe(false);
},
);
it.skipIf(process.platform === "win32")(
"rejects an oversized initial frame instead of marking the session ready",
async () => {
const provider = await makeProvider(
'process.stdout.write("x".repeat(16 * 1024 * 1024 + 1) + "\\0"); process.stdin.resume();',
);
const manager = createRizinTestManager({
REA_RIZIN_COMMAND: provider,
});
track(manager);
const result = await manager.start({
path: "/tmp/oversized-startup",
inferior_tty: await rizinTestInferiorTty(),
});
expect(result.ok).toBe(false);
},
);
it.skipIf(process.platform === "win32")(
"cancels startup while waiting for the initial NUL frame",
async () => {
let resolveSpawned!: () => void;
const spawned = new Promise<void>((resolve) => {
resolveSpawned = resolve;
});
const provider = await makeProvider(
'setTimeout(() => process.stdout.write("\\0"), 500); process.stdin.resume();',
);
const manager = createRizinTestManager(
{
REA_RIZIN_COMMAND: provider,
},
{
spawnProcess: async (options) => {
const launched = await spawnOwnedProviderProcess(options);
resolveSpawned();
return launched;
},
},
);
track(manager);
const abort = new AbortController();
const starting = manager.start(
{ path: "/tmp/cancel-start", inferior_tty: await rizinTestInferiorTty() },
abort.signal,
);
await spawned;
abort.abort();
expect((await starting).ok).toBe(false);
},
);
it.skipIf(process.platform === "win32")(
"preserves startup cleanup uncertainty after cancellation",
async () => {
let resolveSpawned!: () => void;
const spawned = new Promise<void>((resolve) => {
resolveSpawned = resolve;
});
const provider = await makeProvider(
"process.stdin.resume(); setInterval(() => {}, 1000);",
);
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: provider },
{
stopProcess: incompleteStop,
spawnProcess: async (options) => {
const launched = await spawnOwnedProviderProcess(options);
resolveSpawned();
return launched;
},
},
);
track(manager);
const abort = new AbortController();
const starting = manager.start(
{ path: "/tmp/cancel-start", inferior_tty: await rizinTestInferiorTty() },
abort.signal,
);
await spawned;
abort.abort();
const result = await starting;
expect(result.ok).toBe(false);
if (!result.ok)
expect(result.error.message).toContain("injected stop uncertainty");
},
);
it.skipIf(process.platform === "win32")(
"rejects commands for missing and pre-cancelled sessions",
async () => {
const provider = await makeProvider(
'process.stdout.write("\\0"); process.stdin.resume();',
);
const { manager, sessionId } = await start(provider);
expect((await manager.execute("missing", "dr")).ok).toBe(false);
const aborted = new AbortController();
aborted.abort();
expect((await manager.execute(sessionId, "dr", aborted.signal)).ok).toBe(
false,
);
expect(manager.status(sessionId)?.state).toBe("ready");
expect((await manager.close("missing")).ok).toBe(false);
},
);
it.skipIf(process.platform === "win32")(
"retains close failures and resolves their owner after cleanup retry",
async () => {
const provider = await makeProvider(
'process.stdout.write("\\0"); process.stdin.resume();',
);
let stopCalls = 0;
const { manager, sessionId } = await start(provider, {
stopProcess: async (session, name, options) => {
stopCalls += 1;
if (stopCalls === 1) {
session.launched.process.kill("SIGTERM");
return {
status: "incomplete",
reason: "first stop result is uncertain",
};
}
await session.supervisor.waitForExit(1000);
return stopFakeNoInferior(session, name, options);
},
});
const closed = await manager.close(sessionId);
expect(closed.ok).toBe(false);
if (!closed.ok) {
expect(closed.error.cleanupIncomplete).toBe(true);
expect(closed.error.cleanup?.resources).toEqual([sessionId]);
const retainedFailure = closed.error;
expect(await manager.retryCleanupFailures()).toEqual({
ok: true,
value: null,
});
expect(retainedFailure.cleanupIncomplete).toBe(false);
}
expect(stopCalls).toBe(2);
expect(manager.status(sessionId)).toBeUndefined();
},
);
it.skipIf(process.platform === "win32")(
"retains a Rizin close owner until inherited output writers close",
async () => {
const injected = createInjectedProcess();
const { manager, started } = await startInjected(injected.spawnProcess);
expect(started.ok).toBe(true);
if (!started.ok) return;
const sessionId = started.value.session_id;
injected.control.exitLeader();
const firstClose = await manager.close(sessionId);
expect(firstClose.ok).toBe(false);
if (!firstClose.ok) {
expect(firstClose.error.cleanupIncomplete).toBe(true);
expect(firstClose.error.message).toMatch(/inherited output streams/i);
}
expect(manager.status(sessionId)).toBeDefined();
injected.control.closeOutput();
const retried = await manager.retryCleanupFailures();
expect(retried).toEqual({ ok: true, value: null });
expect(manager.status(sessionId)).toBeUndefined();
},
);
it.skipIf(process.platform === "win32")(
"closes a session after unsolicited frames make command correlation unsafe",
async () => {
const provider = await makeProvider(
'process.stdout.write("\\0"); setTimeout(() => process.stdout.write("unexpected\\0"), 20); process.stdin.resume();',
);
const { manager, sessionId } = await start(provider);
await new Promise((resolve) => setTimeout(resolve, 50));
const result = await manager.execute(sessionId, "dr");
expect(result.ok).toBe(false);
expect(manager.status(sessionId)?.state).toBe("closed");
expect((await manager.close(sessionId)).ok).toBe(true);
},
);
@@ -0,0 +1,210 @@
import { afterEach, expect, it } from "vitest";
import { RizinDebugSessionManager } from "../../../src/rizin/RizinDebugSessionManager.js";
import {
createRizinTestManager,
rizinTestInferiorTty,
} from "./RizinTestInferiorTty.js";
import {
createRizinCoverageHarness,
abortOnCheck,
createInjectedProcess,
incompleteStop,
} from "./RizinDebugSessionCoverage.fixtures.js";
const { cleanup, makeProvider, start, startInjected, track } =
createRizinCoverageHarness();
afterEach(cleanup);
it.skipIf(process.platform === "win32")(
"stops the session when the provider closes its stdin pipe",
async () => {
const provider = await makeProvider(
'printf "\\000"; exec 0<&-; while :; do :; done',
"#!/bin/sh",
);
const { manager, sessionId } = await start(provider, {
frameTimeoutMs: 500,
});
const result = await manager.execute(sessionId, "dr");
expect(result.ok).toBe(false);
expect(manager.status(sessionId)?.state).toBe("closed");
},
);
it
.skipIf(process.platform === "win32")
.each([
"null",
"destroyed",
"throws",
"throws-opaque",
"write-error",
] as const)(
"fails safely when injected Rizin stdin is %s",
async (stdinMode) => {
const injected = createInjectedProcess({ stdin: stdinMode });
const { manager, started } = await startInjected(injected.spawnProcess);
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(started.value.session_id, "dr");
expect(result.ok).toBe(false);
},
);
it.skipIf(process.platform === "win32")(
"fails an active command when the injected stdin stream closes",
async () => {
const injected = createInjectedProcess();
const { manager, started } = await startInjected(injected.spawnProcess);
expect(started.ok).toBe(true);
if (!started.ok) return;
injected.control.closeStdin();
const result = await manager.execute(started.value.session_id, "dr");
expect(result.ok).toBe(false);
},
);
it.skipIf(process.platform === "win32").each([false, true])(
"uses protocol cleanup when an injected write callback fails (incomplete=%s)",
async (incomplete) => {
const injected = createInjectedProcess({ stdin: "write-error" });
const { manager, started } = await startInjected(injected.spawnProcess, {
stopProcess: incomplete
? incompleteStop
: async () => ({ status: "stopped" }),
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(started.value.session_id, "dr");
expect(result.ok).toBe(false);
if (!result.ok && incomplete)
expect(result.error.message).toContain("injected stop uncertainty");
},
);
it.skipIf(process.platform === "win32")(
"maps injected spawn errors and startup protocol failure",
async () => {
for (const spawnError of [new Error("injected spawn failure"), "opaque"]) {
const injected = createInjectedProcess({ spawnError });
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{ spawnProcess: injected.spawnProcess },
);
const result = await manager.start({
path: "/tmp/injected",
inferior_tty: await rizinTestInferiorTty(),
});
expect(result.ok).toBe(false);
}
const injected = createInjectedProcess({
startup: (control) => control.closeStdin(),
});
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{ spawnProcess: injected.spawnProcess },
);
const result = await manager.start({
path: "/tmp/injected",
inferior_tty: await rizinTestInferiorTty(),
});
expect(result.ok).toBe(false);
if (!result.ok)
expect(result.error.message).toContain("stdin stream closed");
},
);
it.skipIf(process.platform === "win32")(
"maps spawn rejection as cancellation when the signal changes during spawn",
async () => {
const abort = new AbortController();
const injected = createInjectedProcess({
beforeSpawnReturns: () => abort.abort(),
spawnError: new Error("spawn interrupted"),
});
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{ spawnProcess: injected.spawnProcess },
);
const result = await manager.start(
{ path: "/tmp/injected", inferior_tty: await rizinTestInferiorTty() },
abort.signal,
);
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error.message).toContain("cancelled");
},
);
it.skipIf(process.platform === "win32")(
"cancels startup after receiving its initial frame",
async () => {
const abort = new AbortController();
const injected = createInjectedProcess({
startup: (control) => {
control.output(Buffer.from([0]));
abort.abort();
},
});
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{ spawnProcess: injected.spawnProcess },
);
const result = await manager.start(
{ path: "/tmp/injected", inferior_tty: await rizinTestInferiorTty() },
abort.signal,
);
expect(result.ok).toBe(false);
},
);
it.skipIf(process.platform === "win32")(
"observes startup cancellation before the first frame waiter is installed",
async () => {
const abort = new AbortController();
const injected = createInjectedProcess({
beforeSpawnReturns: () => abort.abort(),
});
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{ spawnProcess: injected.spawnProcess },
);
const result = await manager.start(
{ path: "/tmp/injected", inferior_tty: await rizinTestInferiorTty() },
abort.signal,
);
expect(result.ok).toBe(false);
},
);
it.skipIf(process.platform === "win32")(
"cancels a command after its turn is granted",
async () => {
const injected = createInjectedProcess();
const { manager, started } = await startInjected(injected.spawnProcess);
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(
started.value.session_id,
"dr",
abortOnCheck(3),
);
expect(result.ok).toBe(false);
},
);
it.skipIf(process.platform === "win32")(
"cancels while waiting for the previous command turn",
async () => {
const injected = createInjectedProcess();
const { manager, started } = await startInjected(injected.spawnProcess);
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(
started.value.session_id,
"dr",
abortOnCheck(2),
);
expect(result.ok).toBe(false);
},
);
@@ -0,0 +1,291 @@
import { afterEach, expect, it, vi } from "vitest";
import { AnalysisInputError } from "../../../src/domain/analysisErrorCore.js";
import { RizinDebugSessionManager } from "../../../src/rizin/RizinDebugSessionManager.js";
import {
createRizinTestManager,
rizinTestInferiorTty,
} from "./RizinTestInferiorTty.js";
import {
createRizinCoverageHarness,
abortOnCheck,
createInjectedProcess,
} from "./RizinDebugSessionCoverage.fixtures.js";
const { cleanup, startInjected, track } = createRizinCoverageHarness();
afterEach(cleanup);
it.skipIf(process.platform === "win32")(
"times out when an active command produces no frame",
async () => {
const injected = createInjectedProcess();
const { manager, started } = await startInjected(injected.spawnProcess, {
frameTimeoutMs: 10,
stopProcess: async () => ({ status: "stopped" }),
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(started.value.session_id, "wait");
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.value.result.completion_status).toBe("unknown");
expect(result.value.evidence.raw_result).toEqual(result.value.result);
expect(result.value.evidence.parameters.launch_provenance).toEqual({
caller_selected_path: "/tmp/injected",
resolved_path: "/tmp/injected",
});
expect(result.value.evidence.limitations).toEqual([
"The current debugger target identity is not established by the Rizin session identifier.",
"The command timed out before its completion marker; retained output is partial and completion is unknown.",
"The owned debugger session was stopped because output correlation could no longer be guaranteed.",
"The command is unrestricted and may access local files, the shell, network, or mutate the target.",
"Launch provenance records the original and resolved startup paths; it does not establish the current target after unrestricted debugger commands.",
]);
}
},
);
it.skipIf(process.platform === "win32")(
"preserves frame separators in partial output when a command times out",
async () => {
const injected = createInjectedProcess({
onWrite: (_text, control) => {
control.output("first frame\0second frame\0");
},
});
const { manager, started } = await startInjected(injected.spawnProcess, {
frameTimeoutMs: 1000,
stopProcess: async () => ({ status: "stopped" }),
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(started.value.session_id, "wait");
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.value.result.output).toBe("first frame\nsecond frame");
expect(result.value.result.completion_status).toBe("unknown");
}
},
);
it.skipIf(process.platform === "win32")(
"preserves queued partial frames when the command deadline reaches zero",
async () => {
const injected = createInjectedProcess({
onWrite: (_text, control) => {
control.output("first frame\0second frame\0third frame\0");
},
});
const { manager, started } = await startInjected(injected.spawnProcess, {
frameTimeoutMs: 1000,
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const clock = vi.spyOn(Date, "now");
clock
.mockReturnValueOnce(100)
.mockReturnValueOnce(100)
.mockReturnValueOnce(100)
.mockReturnValue(1100);
let result;
try {
result = await manager.execute(started.value.session_id, "wait");
} finally {
clock.mockRestore();
}
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.value.result.output).toBe("first frame\nsecond frame");
expect(result.value.result.completion_status).toBe("unknown");
}
},
);
it.skipIf(process.platform === "win32")(
"does not convert an unexpected frame waiter error into a timeout",
async () => {
const injected = createInjectedProcess({
onWrite: (_text, control) => {
setImmediate(() => control.stdinError());
},
});
const { manager, started } = await startInjected(injected.spawnProcess, {
frameTimeoutMs: 100,
stopProcess: async () => ({ status: "stopped" }),
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(started.value.session_id, "wait");
expect(result.ok).toBe(false);
if (!result.ok)
expect(result.error.message).toContain("Rizin stdin stream failed");
},
);
it.skipIf(process.platform === "win32")(
"cancels a command after capturing its completion frame",
async () => {
let signal: AbortSignal;
const injected = createInjectedProcess({
onWrite: (text, control) => {
const marker = /!echo (.+)\n/u.exec(text)?.[1];
if (marker !== undefined) control.output(Buffer.from(`${marker}\0`));
},
});
const { manager, started } = await startInjected(injected.spawnProcess);
expect(started.ok).toBe(true);
if (!started.ok) return;
signal = abortOnCheck(5);
const result = await manager.execute(
started.value.session_id,
"dr",
signal,
);
expect(result.ok).toBe(false);
},
);
it.skipIf(process.platform === "win32")(
"handles cancellation observed immediately after installing the frame waiter",
async () => {
const injected = createInjectedProcess();
const { manager, started } = await startInjected(injected.spawnProcess, {
stopProcess: async () => ({ status: "stopped" }),
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(
started.value.session_id,
"wait",
abortOnCheck(5),
);
expect(result.ok).toBe(false);
},
);
it.skipIf(process.platform === "win32").each([false, true])(
"maps a frame-wait listener installation failure without losing cleanup (incomplete=%s)",
async (incomplete) => {
const injected = createInjectedProcess();
const { manager, started } = await startInjected(injected.spawnProcess, {
stopProcess: async () =>
incomplete
? { status: "incomplete", reason: "injected stop uncertainty" }
: { status: "stopped" },
frameTimeoutMs: 1000,
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const controller = new AbortController();
let registrations = 0;
const signal = {
get aborted() {
return false;
},
addEventListener(
type: Parameters<AbortSignal["addEventListener"]>[0],
listener: Parameters<AbortSignal["addEventListener"]>[1],
options?: Parameters<AbortSignal["addEventListener"]>[2],
) {
registrations += 1;
if (registrations === 2)
throw new Error("injected frame waiter registration failure");
controller.signal.addEventListener(type, listener, options);
},
removeEventListener: controller.signal.removeEventListener.bind(
controller.signal,
),
dispatchEvent: controller.signal.dispatchEvent.bind(controller.signal),
onabort: null,
reason: undefined,
throwIfAborted: () => undefined,
} as AbortSignal;
const result = await manager.execute(
started.value.session_id,
"wait",
signal,
);
expect(result.ok).toBe(false);
if (!result.ok && incomplete)
expect(result.error.message).toContain("injected stop uncertainty");
},
);
it.skipIf(process.platform === "win32")(
"correlates an injected command frame with its generated marker",
async () => {
const injected = createInjectedProcess({
onWrite: (text, control) => {
const marker = /!echo (.+)\n/u.exec(text)?.[1];
if (marker !== undefined)
setImmediate(() => control.output(Buffer.from(`output${marker}\0`)));
},
});
const { manager, started } = await startInjected(injected.spawnProcess);
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(started.value.session_id, "dr");
expect(result.ok).toBe(true);
if (result.ok) expect(result.value.result.output).toBe("output");
},
);
it.skipIf(process.platform === "win32")(
"preserves process-exit evidence when exit occurs before frame waiting",
async () => {
const injected = createInjectedProcess({
onWrite: (_text, control) => control.exit(),
});
const { manager, started } = await startInjected(injected.spawnProcess);
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(started.value.session_id, "dr");
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.value.result.completion_status).toBe("unknown");
expect(result.value.result).toMatchObject({
command: "dr",
output: "",
output_truncated: false,
completion_status: "unknown",
backend: null,
});
expect(result.value.evidence.raw_result).toEqual(result.value.result);
expect(result.value.evidence.limitations).toEqual([
"The current debugger target identity is not established by the Rizin session identifier.",
"Rizin exited before the command-completion marker; retained frame output is partial and command completion is unknown.",
"The command is unrestricted and may access local files, the shell, network, or mutate the target.",
"Launch provenance records the original and resolved startup paths; it does not establish the current target after unrestricted debugger commands.",
]);
}
},
);
it.skipIf(process.platform === "win32")(
"rejects a queued command when the process exits before its frame wait begins",
async () => {
const writes: string[] = [];
const injected = createInjectedProcess({
onWrite: (text, control) => {
writes.push(text);
const marker = /!echo (.+)\n/u.exec(text)?.[1];
if (marker !== undefined) setImmediate(() => control.exit());
},
});
const { manager, started } = await startInjected(injected.spawnProcess);
expect(started.ok).toBe(true);
if (!started.ok) return;
const first = manager.execute(started.value.session_id, "first");
const queued = manager.execute(started.value.session_id, "second");
expect((await first).ok).toBe(true);
const second = await queued;
expect(second.ok).toBe(false);
if (!second.ok) expect(second.error).toBeInstanceOf(AnalysisInputError);
expect(writes.some((text) => text.includes("second\n"))).toBe(false);
},
);
@@ -0,0 +1,266 @@
import { afterEach, expect, it } from "vitest";
import { evidenceSchema } from "../../../src/domain/evidence.js";
import { RizinDebugSessionManager } from "../../../src/rizin/RizinDebugSessionManager.js";
import {
createRizinTestManager,
rizinTestInferiorTty,
} from "./RizinTestInferiorTty.js";
import {
createRizinCoverageHarness,
createInjectedProcess,
incompleteStop,
} from "./RizinDebugSessionCoverage.fixtures.js";
const { cleanup, makeProvider, start, startInjected, track } =
createRizinCoverageHarness();
afterEach(cleanup);
it.skipIf(process.platform === "win32")(
"assembles a multi-chunk NUL frame once and preserves its command output",
async () => {
const chunk = Buffer.alloc(64 * 1024, 0x61);
const chunkCount = 32;
const outputBytes = chunk.length * chunkCount;
const injected = createInjectedProcess({
onWrite: (text, control) => {
const marker = /!echo (.+)\n/u.exec(text)?.[1];
if (marker !== undefined)
setImmediate(() => {
for (let index = 0; index < chunkCount; index += 1)
control.output(chunk);
control.output(Buffer.from([0]));
control.output(Buffer.from(`${marker}\0`));
});
},
});
const { manager, started } = await startInjected(injected.spawnProcess, {
frameTimeoutMs: 1000,
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(started.value.session_id, "chunked");
expect(result.ok).toBe(true);
if (result.ok) {
expect(Buffer.byteLength(result.value.result.output)).toBe(outputBytes);
expect(result.value.result.output).toBe("a".repeat(outputBytes));
expect(result.value.result.completion_status).toBe("complete");
}
},
);
it.skipIf(process.platform === "win32")(
"discards an oversized frame split across deterministic stream chunks",
async () => {
const injected = createInjectedProcess({
onWrite: (text, control) => {
const marker = /!echo (.+)\n/u.exec(text)?.[1];
if (marker !== undefined)
setImmediate(() => {
control.output(Buffer.alloc(16 * 1024 * 1024 + 1, 0x61));
control.output(Buffer.from("discard tail"));
control.output(Buffer.from([0]));
control.output(Buffer.from(`${marker}\0`));
});
},
});
const { manager, started } = await startInjected(injected.spawnProcess, {
frameTimeoutMs: 1000,
stopProcess: async () => ({ status: "stopped" }),
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(started.value.session_id, "large");
expect(result.ok).toBe(true);
if (result.ok) expect(result.value.result.output_truncated).toBe(true);
},
);
it.skipIf(process.platform === "win32")(
"closes an injected session on an oversized unsolicited frame",
async () => {
const injected = createInjectedProcess();
const { manager, started } = await startInjected(injected.spawnProcess);
expect(started.ok).toBe(true);
if (!started.ok) return;
injected.control.output(Buffer.alloc(16 * 1024 * 1024 + 1, 0x61));
expect(manager.status(started.value.session_id)?.state).toBe("closed");
},
);
it.skipIf(process.platform === "win32")(
"preserves unsolicited history and marks oversized recent frames",
async () => {
const provider = await makeProvider(
'process.stdout.write("\\0"); process.stdin.resume(); setTimeout(() => process.stdout.write("x".repeat(17000) + "\\0"), 20);',
);
const { manager, sessionId } = await start(provider);
await new Promise((resolve) => setTimeout(resolve, 100));
const status = manager.status(sessionId);
expect(status?.recent_output_truncated).toBe(true);
expect(status?.recent_output.at(-1)).toContain("[recent frame truncated]");
},
);
it.skipIf(process.platform === "win32")(
"bounds recent history after many unsolicited frames",
async () => {
const provider = await makeProvider(
'process.stdout.write("\\0" + Array.from({ length: 70 }, (_, i) => "frame" + i + "\\0").join("")); process.stdin.resume();',
);
const { manager, sessionId } = await start(provider);
const status = manager.status(sessionId);
expect(status?.recent_output).toHaveLength(64);
expect(status?.recent_output_truncated).toBe(true);
},
);
it.skipIf(process.platform === "win32")(
"returns partial unknown evidence when the process exits mid-command",
async () => {
const provider = await makeProvider(
'process.stdout.write("\\0"); process.stdin.setEncoding("utf8"); process.stdin.on("data", () => { process.stdout.write("partial\\0"); process.exit(0); });',
);
const { manager, sessionId } = await start(provider);
const result = await manager.execute(sessionId, "dr");
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.value.result).toMatchObject({
output: "partial",
completion_status: "unknown",
});
expect(result.value.evidence.limitations.join(" ")).toContain(
"Rizin exited before",
);
}
},
);
it.skipIf(process.platform === "win32")(
"cancels a command after sending it and stops its owned session",
async () => {
const provider = await makeProvider(
'process.stdout.write("\\0"); process.stdin.resume();',
);
const { manager, sessionId } = await start(provider);
const abort = new AbortController();
const execution = manager.execute(sessionId, "slow", abort.signal);
setTimeout(() => abort.abort(), 30);
expect((await execution).ok).toBe(false);
expect(manager.status(sessionId)?.state).toBe("closed");
},
);
it.skipIf(process.platform === "win32")(
"preserves partial timeout evidence when cleanup cannot be confirmed",
async () => {
const provider = await makeProvider(
'process.stdout.write("\\0"); process.stdin.setEncoding("utf8"); process.stdin.on("data", (chunk) => { if (chunk.includes("slow")) process.stdout.write("partial\\0"); });',
);
const { manager, sessionId } = await start(provider, {
frameTimeoutMs: 25,
stopProcess: incompleteStop,
});
const result = await manager.execute(sessionId, "slow");
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error.cleanupIncomplete).toBe(true);
expect(result.error.cleanupResources).toEqual([sessionId]);
const evidence = evidenceSchema.parse(result.error.partialObservation);
expect(evidence.normalized_result).toMatchObject({
completion_status: "unknown",
});
expect(evidence.limitations.join(" ")).toContain(
"injected stop uncertainty",
);
}
},
);
it.skipIf(process.platform === "win32")(
"preserves truncated output when cleanup cannot be confirmed",
async () => {
const provider = await makeProvider(
`process.stdout.write("\\0");
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const end = input.indexOf("\\n");
if (end < 0) break;
const line = input.slice(0, end); input = input.slice(end + 1);
if (line === "many") process.stdout.write(Array.from({ length: 4100 }, (_, i) => "frame" + i + "\\0").join(""));
else if (line.startsWith("!echo ")) process.stdout.write(line.slice(6) + "\\0");
}
});`,
);
const { manager, sessionId } = await start(provider, {
frameTimeoutMs: 1000,
stopProcess: incompleteStop,
});
const result = await manager.execute(sessionId, "many");
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error.cleanupIncomplete).toBe(true);
expect(result.error.cleanupResources).toEqual([sessionId]);
const evidence = evidenceSchema.parse(result.error.partialObservation);
expect(evidence.normalized_result).toMatchObject({
completion_status: "unknown",
});
expect(evidence.limitations.join(" ")).toContain(
"injected stop uncertainty",
);
}
},
);
it.skipIf(process.platform === "win32")(
"preserves the cleanup uncertainty when cancellation cannot confirm process stop",
async () => {
const provider = await makeProvider(
'process.stdout.write("\\0"); process.stdin.resume();',
);
const { manager, sessionId } = await start(provider, {
stopProcess: incompleteStop,
});
const abort = new AbortController();
const execution = manager.execute(sessionId, "slow", abort.signal);
setTimeout(() => abort.abort(), 30);
const result = await execution;
expect(result.ok).toBe(false);
if (!result.ok)
expect(result.error.message).toContain("injected stop uncertainty");
},
);
it.skipIf(process.platform === "win32")(
"cancels a queued command without sending it after the prior command completes",
async () => {
const provider = await makeProvider(
`process.stdout.write("\\0");
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const end = input.indexOf("\\n");
if (end < 0) break;
const line = input.slice(0, end); input = input.slice(end + 1);
if (line === "first") setTimeout(() => {}, 100);
else if (line.startsWith("!echo ")) setTimeout(() => process.stdout.write(line.slice(6) + "\\0"), 100);
}
});`,
);
const { manager, sessionId } = await start(provider, {
frameTimeoutMs: 300,
});
const first = manager.execute(sessionId, "first");
const abort = new AbortController();
const queued = manager.execute(sessionId, "second", abort.signal);
setTimeout(() => abort.abort(), 20);
expect((await queued).ok).toBe(false);
expect((await first).ok).toBe(true);
},
);
@@ -0,0 +1,198 @@
import { afterEach, expect, it } from "vitest";
import { createRizinCoverageHarness } from "./RizinDebugSessionCoverage.fixtures.js";
const { cleanup, makeProvider, start } = createRizinCoverageHarness();
afterEach(cleanup);
it.skipIf(process.platform === "win32")(
"keeps command output bounded when many frames arrive for a command",
async () => {
const provider = await makeProvider(
`process.stdout.write("\\0");
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const end = input.indexOf("\\n");
if (end < 0) break;
const line = input.slice(0, end); input = input.slice(end + 1);
if (line === "many") process.stdout.write(Array.from({ length: 4100 }, (_, i) => "frame" + i + "\\0").join(""));
else if (line.startsWith("!echo ")) process.stdout.write(line.slice(6) + "\\0");
}
});`,
);
const { manager, sessionId } = await start(provider, {
frameTimeoutMs: 1000,
});
const result = await manager.execute(sessionId, "many");
expect(result.ok).toBe(true);
if (result.ok)
expect(result.value.result).toMatchObject({
output_truncated: true,
completion_status: "unknown",
});
},
);
it.skipIf(process.platform === "win32")(
"returns partial evidence when the command frame deadline is already expired",
async () => {
const provider = await makeProvider(
'process.stdout.write("\\0"); process.stdin.resume();',
);
const { manager, sessionId } = await start(provider, {
frameTimeoutMs: 0,
});
const result = await manager.execute(sessionId, "dr");
expect(result.ok).toBe(true);
if (result.ok)
expect(result.value.result).toMatchObject({
output: "",
output_truncated: true,
completion_status: "unknown",
});
},
);
it.skipIf(process.platform === "win32")(
"does not exceed the exact command byte cap when marker output follows a full frame",
async () => {
const provider = await makeProvider(
`process.stdout.write("\\0");
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const end = input.indexOf("\\n");
if (end < 0) break;
const line = input.slice(0, end); input = input.slice(end + 1);
if (line === "full") process.stdout.write(Buffer.alloc(16 * 1024 * 1024, 0x61).toString() + "\\0");
else if (line.startsWith("!echo ")) process.stdout.write("x" + line.slice(6) + "\\0");
}
});`,
);
const { manager, sessionId } = await start(provider, {
frameTimeoutMs: 3000,
});
const result = await manager.execute(sessionId, "full");
expect(result.ok).toBe(true);
if (result.ok) {
expect(Buffer.byteLength(result.value.result.output, "utf8")).toBe(
16 * 1024 * 1024,
);
expect(result.value.result).toMatchObject({
output_truncated: true,
completion_status: "unknown",
});
}
},
);
it.skipIf(process.platform === "win32")(
"caps aggregate output across multiple valid NUL frames",
async () => {
const provider = await makeProvider(
`process.stdout.write("\\0");
let input = "";
let aggregatePending = false;
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const end = input.indexOf("\\n");
if (end < 0) break;
const line = input.slice(0, end); input = input.slice(end + 1);
if (line === "aggregate") {
process.stdout.write("a".repeat(10 * 1024 * 1024) + "\\0");
aggregatePending = true;
} else if (line.startsWith("!echo ")) {
process.stdout.write((aggregatePending ? "b".repeat(7 * 1024 * 1024) : "") + line.slice(6) + "\\0");
aggregatePending = false;
}
}
});`,
);
const { manager, sessionId } = await start(provider, {
frameTimeoutMs: 3000,
});
const result = await manager.execute(sessionId, "aggregate");
expect(result.ok).toBe(true);
if (result.ok) {
expect(Buffer.byteLength(result.value.result.output, "utf8")).toBe(
16 * 1024 * 1024,
);
expect(result.value.result.completion_status).toBe("unknown");
}
},
);
it.skipIf(process.platform === "win32")(
"truncates an oversized NUL frame without decoding a split UTF-8 character",
async () => {
const provider = await makeProvider(
`process.stdout.write("\\0");
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const end = input.indexOf("\\n");
if (end < 0) break;
const line = input.slice(0, end); input = input.slice(end + 1);
if (line === "large") {
process.stdout.write("prefix\\0");
process.stdout.write(Buffer.alloc(16 * 1024 * 1024 + 1, 0xF0));
} else if (line.startsWith("!echo ")) process.stdout.write("\\0" + line.slice(6) + "\\0");
}
});`,
);
const { manager, sessionId } = await start(provider, {
frameTimeoutMs: 2000,
});
const result = await manager.execute(sessionId, "large");
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.value.result).toMatchObject({
output_truncated: true,
completion_status: "unknown",
});
expect(result.value.result.output.startsWith("prefix\n")).toBe(true);
}
},
);
it.skipIf(process.platform === "win32")(
"truncates an oversized frame when its NUL boundary arrives with the crossing chunk",
async () => {
const provider = await makeProvider(
`process.stdout.write("\\0");
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const end = input.indexOf("\\n");
if (end < 0) break;
const line = input.slice(0, end); input = input.slice(end + 1);
if (line === "large") {
const frame = Buffer.alloc(16 * 1024 * 1024 + 2, 0x61);
frame[frame.length - 1] = 0;
process.stdout.write(frame);
} else if (line.startsWith("!echo ")) process.stdout.write(line.slice(6) + "\\0");
}
});`,
);
const { manager, sessionId } = await start(provider, {
frameTimeoutMs: 2000,
});
const result = await manager.execute(sessionId, "large");
expect(result.ok).toBe(true);
if (result.ok)
expect(result.value.result).toMatchObject({
output_truncated: true,
completion_status: "unknown",
});
},
);
@@ -0,0 +1,196 @@
import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { RizinDebugSessionManager } from "../../../src/rizin/RizinDebugSessionManager.js";
import {
createRizinTestManager,
rizinTestInferiorTty,
} from "./RizinTestInferiorTty.js";
describe.skipIf(process.platform === "win32")(
"persistent Rizin debugger session manager",
() => {
let directory: string | undefined;
const managers: Array<{ closeAll(): Promise<void> }> = [];
afterEach(async () => {
await Promise.all(
managers
.splice(0)
.map((manager) => manager.closeAll().catch(() => undefined)),
);
if (directory !== undefined)
await rm(directory, { recursive: true, force: true });
directory = undefined;
});
it("uses an absolute target path and waits for Rizin's completion marker", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-manager-"));
const provider = join(directory, "fake-rizin.mjs");
const argsFile = join(directory, "args.json");
await writeFile(
provider,
`#!/usr/bin/env node
const fs = await import("node:fs");
fs.writeFileSync(${JSON.stringify(argsFile)}, JSON.stringify(process.argv.slice(2)));
process.stdout.write("\\0");
let input = "";
let stalled = false;
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n");
if (boundary < 0) break;
const line = input.slice(0, boundary);
input = input.slice(boundary + 1);
if (line === "dr") process.stdout.write("backend-event\\0rax=0x1234\\0");
else if (line === "olj") process.stdout.write("[]\\0");
else if (line.startsWith("!echo ")) process.stdout.write(line.slice(6) + "\\n\\0");
}
});
`,
);
await chmod(provider, 0o700);
const manager = createRizinTestManager({
REA_RIZIN_COMMAND: provider,
});
managers.push(manager);
const started = await manager.start({
path: "-target.bin",
inferior_tty: await rizinTestInferiorTty(),
backend: "test-backend",
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const providerArgs = await import("node:fs/promises").then(
({ readFile }) => readFile(argsFile, "utf8"),
);
expect(JSON.parse(providerArgs)).toEqual([
"-N",
"-0",
"-d",
"-R",
`stdout=${await rizinTestInferiorTty()}`,
"-R",
`stderr=${await rizinTestInferiorTty()}`,
"-e",
"dbg.exitkills=false",
"-D",
"test-backend",
resolve("-target.bin"),
]);
const result = await manager.execute(started.value.session_id, "dr");
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.value.result.output).toBe("backend-event\nrax=0x1234");
expect(result.value.result.output_scope).toBe(
"command_and_interleaved_session_output",
);
expect(result.value.result.backend).toBe("test-backend");
}
expect((await manager.close(started.value.session_id)).ok).toBe(true);
expect(manager.status(started.value.session_id)).toBeUndefined();
});
it("stops and invalidates a Rizin session after its completion-marker timeout", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-timeout-"));
const provider = join(directory, "fake-rizin-stall.mjs");
await writeFile(
provider,
`#!/usr/bin/env node
process.stdout.write("\\0");
let input = "";
let stalled = false;
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n");
if (boundary < 0) break;
const line = input.slice(0, boundary);
input = input.slice(boundary + 1);
if (line === "dr") process.stdout.write("rax=0x1234\\0");
else if (line === "slow") {
stalled = true;
process.stdout.write("partial-timeout\\0");
}
else if (line.startsWith("!echo ") && !stalled) process.stdout.write(line.slice(6) + "\\n\\0");
}
});
`,
);
await chmod(provider, 0o700);
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: provider },
{ frameTimeoutMs: 50 },
);
managers.push(manager);
const started = await manager.start({
path: "/tmp/fixture.bin",
inferior_tty: await rizinTestInferiorTty(),
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const timedOut = await manager.execute(started.value.session_id, "slow");
expect(timedOut.ok).toBe(true);
if (timedOut.ok) {
expect(timedOut.value.result).toMatchObject({
output: "partial-timeout",
output_truncated: true,
completion_status: "unknown",
});
expect(timedOut.value.evidence.limitations.join(" ")).toContain(
"timed out",
);
}
expect(manager.status(started.value.session_id)?.state).toBe("closed");
expect((await manager.execute(started.value.session_id, "dr")).ok).toBe(
false,
);
expect((await manager.close(started.value.session_id)).ok).toBe(true);
});
},
);
it.skipIf(process.platform === "win32")(
"stops Rizin when empty unsolicited NUL frames exhaust the bounded queue",
async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-rizin-empty-frames-"));
const provider = join(directory, "fake-rizin-empty.mjs");
const manager = createRizinTestManager({
REA_RIZIN_COMMAND: provider,
});
try {
await writeFile(
provider,
`#!/usr/bin/env node
process.stdout.write("\\0");
setTimeout(() => process.stdout.write("\\0".repeat(5000)), 10);
process.stdin.resume();
`,
);
await chmod(provider, 0o700);
const started = await manager.start({
path: "/tmp/fixture.bin",
inferior_tty: await rizinTestInferiorTty(),
});
expect(started.ok).toBe(true);
if (!started.ok) return;
await new Promise((resolveDelay) => setTimeout(resolveDelay, 100));
expect(manager.status(started.value.session_id)?.state).toBe("closed");
expect((await manager.close(started.value.session_id)).ok).toBe(true);
} finally {
await manager.closeAll().catch(() => undefined);
await rm(directory, { recursive: true, force: true });
}
},
);
@@ -0,0 +1,894 @@
import { spawn, type ChildProcess } from "node:child_process";
import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { resolve } from "node:path";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, expect, it } from "vitest";
import { RizinDebugSessionManager } from "../../../src/rizin/RizinDebugSessionManager.js";
import {
spawnOwnedProviderProcess,
type ProviderProcessHandle,
} from "../../../src/process/ProviderProcess.js";
import { evidenceSchema } from "../../../src/domain/evidence.js";
import {
createRizinTestManager,
rizinTestInferiorTty,
} from "./RizinTestInferiorTty.js";
import { createInjectedProcess } from "./RizinDebugSessionCoverage.fixtures.js";
let directory: string | undefined;
const managers: Array<{ closeAll(): Promise<void> }> = [];
const inferiorProcesses: ChildProcess[] = [];
const startRizinWithProvider = async (
provider: string,
): Promise<{
manager: RizinDebugSessionManager;
sessionId: string | undefined;
}> => {
const manager = createRizinTestManager({ REA_RIZIN_COMMAND: provider });
managers.push(manager);
const started = await manager.start({
path: "/tmp/fixture.bin",
inferior_tty: await rizinTestInferiorTty(),
});
expect(started.ok).toBe(true);
return {
manager,
sessionId: started.ok ? started.value.session_id : undefined,
};
};
const startRizinWithOwnedStop = async (provider: string) => {
let debuggerProcess: ProviderProcessHandle | undefined;
const manager = new RizinDebugSessionManager(
{ ...process.env, REA_RIZIN_COMMAND: provider },
{
platform: "linux",
spawnProcess: async (options) => {
const launched = await spawnOwnedProviderProcess(options);
debuggerProcess = launched.process;
return launched;
},
},
);
managers.push(manager);
const started = await manager.start({
path: "/tmp/fixture.bin",
inferior_tty: await rizinTestInferiorTty(),
});
if (!started.ok) throw started.error;
return {
manager,
sessionId: started.value.session_id,
exitDebugger: async () => {
if (debuggerProcess === undefined)
throw new Error("Provider did not spawn");
const exited = new Promise<void>((resolve) =>
debuggerProcess?.once("exit", () => resolve()),
);
debuggerProcess.kill("SIGTERM");
await exited;
},
};
};
const expectOwnedProcessExited = async (pidText: string): Promise<void> => {
const pid = Number(pidText);
expect(Number.isInteger(pid)).toBe(true);
expect(() => process.kill(pid, 0)).toThrow();
};
afterEach(async () => {
for (const inferior of inferiorProcesses.splice(0)) {
if (inferior.exitCode !== null || inferior.signalCode !== null) continue;
const exited = new Promise<void>((resolveExit) =>
inferior.once("exit", () => resolveExit()),
);
inferior.kill("SIGTERM");
await exited;
}
await Promise.all(
managers
.splice(0)
.map((manager) => manager.closeAll().catch(() => undefined)),
);
if (directory !== undefined)
await rm(directory, { recursive: true, force: true });
directory = undefined;
});
const spawnTestInferior = async (): Promise<ChildProcess> => {
const inferior = spawn(
process.execPath,
["-e", "setInterval(() => {}, 1000)"],
{
stdio: "ignore",
},
);
inferiorProcesses.push(inferior);
await new Promise<void>((resolveSpawn, rejectSpawn) => {
inferior.once("spawn", resolveSpawn);
inferior.once("error", rejectSpawn);
});
return inferior;
};
const createInferiorInventoryProvider = async (
rows: readonly { readonly fd: number; readonly pid: number }[],
): Promise<string> => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-owned-inferior-"));
const provider = join(directory, "fake-rizin-owned-inferior.mjs");
await writeFile(
provider,
`#!/usr/bin/env node
process.stdout.write("\\0");
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n"); if (boundary < 0) break;
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
if (line === "olj") process.stdout.write(JSON.stringify(${JSON.stringify(rows.map(({ fd, pid }) => ({ fd, raised: true, uri: `ptrace://${pid}` })))} ) + "\\0");
else if (line === "e dbg.exitkills") process.stdout.write("true\\0");
else if (line.startsWith("!echo ")) process.stdout.write(line.slice(6) + "\\0");
else process.stdout.write("\\0");
}
});
`,
);
await chmod(provider, 0o700);
return provider;
};
it("keeps persistent Rizin sessions unavailable on Windows", async () => {
const rizin = await createRizinTestManager(
{ REA_RIZIN_COMMAND: "/missing/rizin" },
{ platform: "win32" },
).start({
path: "/tmp/fixture.bin",
inferior_tty: "unused-before-platform-admission",
});
expect(rizin.ok).toBe(false);
if (!rizin.ok) {
expect(rizin.error._tag).toBe("AnalysisCapabilityUnavailableError");
expect(rizin.error.message).toContain("Linux /proc descriptor readback");
}
});
it.skipIf(process.platform === "win32")(
"rejects startup when Rizin exits immediately after its initial frame",
async () => {
const injected = createInjectedProcess({
startup: (control) => {
control.output(Buffer.from("startup diagnostic\0partial trailing"));
control.exit();
},
});
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{ spawnProcess: injected.spawnProcess },
);
managers.push(manager);
const started = await manager.start({
path: "/tmp/fixture.bin",
inferior_tty: await rizinTestInferiorTty(),
});
expect(started.ok).toBe(false);
if (!started.ok) {
expect(started.error._tag).toBe("AnalysisCapabilityUnavailableError");
expect(started.error.message).toContain("exited");
expect(started.error.message).not.toContain("timed out");
expect(started.error.capturedOutput).toMatchObject({
stdout: "startup diagnostic\npartial trailing",
stderr: "",
truncated: false,
});
}
},
);
it.skipIf(process.platform === "win32")(
"preserves partial Rizin stdout when startup times out before its first frame",
async () => {
const injected = createInjectedProcess({
startup: (control) => control.output("partial startup diagnostic"),
});
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{ spawnProcess: injected.spawnProcess, startupTimeoutMs: 25 },
);
managers.push(manager);
const started = await manager.start({
path: "/tmp/fixture.bin",
inferior_tty: await rizinTestInferiorTty(),
});
expect(started.ok).toBe(false);
if (!started.ok) {
expect(started.error._tag).toBe("AnalysisTimeoutError");
expect(started.error.capturedOutput).toMatchObject({
stdout: expect.stringContaining("partial startup diagnostic"),
stderr: "",
truncated: false,
});
}
},
);
it.skipIf(process.platform === "win32")(
"keeps session UTF-8 status cumulative while command evidence reports only its frames",
async () => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-command-utf8-scope-"));
const provider = join(directory, "fake-rizin-command-utf8-scope.mjs");
await writeFile(
provider,
`#!/usr/bin/env node
process.stdout.write(Buffer.from([0xff, 0]));
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n"); if (boundary < 0) break;
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
if (line === "invalid-output") process.stdout.write(Buffer.from([0xfe, 0]));
else if (!line.startsWith("!echo ")) process.stdout.write("valid output\\0");
else process.stdout.write(line.slice(6) + "\\0");
}
});
`,
);
await chmod(provider, 0o700);
const { manager, sessionId } = await startRizinWithProvider(provider);
if (sessionId === undefined) return;
expect(manager.status(sessionId)?.output_invalid_utf8).toBe(true);
const firstValid = await manager.execute(sessionId, "valid-before-invalid");
expect(firstValid.ok).toBe(true);
if (firstValid.ok) {
expect(firstValid.value.result).not.toHaveProperty("output_invalid_utf8");
expect(firstValid.value.evidence.raw_result).not.toHaveProperty(
"output_invalid_utf8",
);
expect(firstValid.value.evidence.normalized_result).not.toHaveProperty(
"output_invalid_utf8",
);
expect(firstValid.value.evidence.limitations.join(" ")).not.toContain(
"Collected command frames contained invalid UTF-8 bytes",
);
}
const invalid = await manager.execute(sessionId, "invalid-output");
expect(invalid.ok).toBe(true);
if (invalid.ok) {
expect(invalid.value.result.output_invalid_utf8).toBe(true);
expect(invalid.value.evidence.raw_result).toMatchObject({
output_invalid_utf8: true,
});
expect(invalid.value.evidence.normalized_result).toMatchObject({
output_invalid_utf8: true,
});
expect(invalid.value.evidence.limitations.join(" ")).toContain(
"Collected command frames contained invalid UTF-8 bytes; decoded text may contain replacement characters.",
);
}
const laterValid = await manager.execute(sessionId, "valid-after-invalid");
expect(laterValid.ok).toBe(true);
if (laterValid.ok) {
expect(laterValid.value.result).not.toHaveProperty("output_invalid_utf8");
expect(laterValid.value.evidence.raw_result).not.toHaveProperty(
"output_invalid_utf8",
);
expect(laterValid.value.evidence.normalized_result).not.toHaveProperty(
"output_invalid_utf8",
);
expect(laterValid.value.evidence.limitations.join(" ")).not.toContain(
"Collected command frames contained invalid UTF-8 bytes",
);
}
expect(manager.status(sessionId)?.output_invalid_utf8).toBe(true);
},
);
it.skipIf(process.platform !== "linux")(
"clears retained Rizin cleanup after its identified inferior exits",
async () => {
const inferior = await spawnTestInferior();
const pid = inferior.pid;
expect(pid).toBeDefined();
if (pid === undefined) return;
const provider = await createInferiorInventoryProvider([{ fd: 12, pid }]);
const { manager, sessionId, exitDebugger } =
await startRizinWithOwnedStop(provider);
if (sessionId === undefined) return;
const firstClose = await manager.close(sessionId);
expect(firstClose.ok, JSON.stringify(firstClose)).toBe(false);
if (!firstClose.ok) expect(firstClose.error.cleanupIncomplete).toBe(true);
await exitDebugger();
expect((await manager.retryCleanupFailures()).ok).toBe(false);
expect(manager.status(sessionId)?.state).toBe("closed");
const inferiorExited = new Promise<void>((resolveExit) =>
inferior.once("exit", () => resolveExit()),
);
inferior.kill("SIGTERM");
await inferiorExited;
const retried = await manager.retryCleanupFailures();
expect(retried).toEqual({ ok: true, value: null });
if (!firstClose.ok) expect(firstClose.error.cleanupIncomplete).toBe(false);
expect(manager.status(sessionId)).toBeUndefined();
},
);
it.skipIf(process.platform !== "linux")(
"keeps Rizin cleanup unknown when an inferior inventory is only partially captured",
async () => {
const inferior = await spawnTestInferior();
const pid = inferior.pid;
expect(pid).toBeDefined();
if (pid === undefined) return;
const provider = await createInferiorInventoryProvider([
{ fd: 12, pid },
{ fd: 13, pid: 999_999_999 },
]);
const { manager, sessionId, exitDebugger } =
await startRizinWithOwnedStop(provider);
if (sessionId === undefined) return;
expect((await manager.close(sessionId)).ok).toBe(false);
await exitDebugger();
const closed = await manager.close(sessionId);
expect(closed.ok, JSON.stringify(closed)).toBe(false);
if (!closed.ok)
expect(closed.error.message).toContain("no owner proof confirms");
expect(manager.status(sessionId)).toBeDefined();
},
);
it.skipIf(process.platform === "win32")(
"retains Rizin cleanup when target state is unknown at debugger exit",
async () => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-unknown-target-"));
const provider = join(directory, "fake-rizin-unknown-target.mjs");
await writeFile(
provider,
`#!/usr/bin/env node
process.stdout.write("\\0");
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n"); if (boundary < 0) break;
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
if (line === "olj") process.stdout.write("not-json\\0");
else if (line.startsWith("!echo ")) process.stdout.write(line.slice(6) + "\\0");
}
});
`,
);
await chmod(provider, 0o700);
const { manager, sessionId, exitDebugger } =
await startRizinWithOwnedStop(provider);
if (sessionId === undefined) return;
expect((await manager.close(sessionId)).ok).toBe(false);
await exitDebugger();
const closed = await manager.close(sessionId);
expect(closed.ok, JSON.stringify(closed)).toBe(false);
if (!closed.ok)
expect(closed.error.message).toContain("no owner proof confirms");
expect(manager.status(sessionId)).toBeDefined();
},
);
it.skipIf(process.platform === "win32")(
"preserves command parameters in Rizin observation evidence",
async () => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-command-evidence-"));
const provider = join(directory, "fake-rizin-command-evidence.mjs");
const inferiorTty = await rizinTestInferiorTty();
await writeFile(
provider,
`#!/usr/bin/env node
process.stdout.write("\\0");
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n"); if (boundary < 0) break;
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
if (!line.startsWith("!echo ")) process.stdout.write("command output\\0");
else process.stdout.write(line.slice(6) + "\\0");
}
});
`,
);
await chmod(provider, 0o700);
const manager = createRizinTestManager({ REA_RIZIN_COMMAND: provider });
managers.push(manager);
const callerSelectedPath = "./relative/../fixture.bin";
const resolvedPath = resolve(callerSelectedPath);
const started = await manager.start({
path: callerSelectedPath,
inferior_tty: inferiorTty,
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const executed = await manager.execute(started.value.session_id, "dr");
expect(executed.ok).toBe(true);
if (executed.ok)
expect(executed.value.evidence.parameters).toEqual({
session_id: started.value.session_id,
command: "dr",
inferior_tty: inferiorTty,
launch_provenance: {
caller_selected_path: callerSelectedPath,
resolved_path: resolvedPath,
},
});
if (executed.ok)
expect(executed.value.evidence.limitations).toContain(
"Launch provenance records the original and resolved startup paths; it does not establish the current target after unrestricted debugger commands.",
);
},
);
it.skipIf(process.platform === "win32")(
"keeps queued Rizin commands serialized when a waiting request is cancelled",
async () => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-queue-cancel-"));
const provider = join(directory, "fake-rizin-queue-cancel.mjs");
const overlapPath = join(directory, "overlap");
await writeFile(
provider,
`#!/usr/bin/env node
process.stdout.write("\\0");
let input = "";
let firstActive = false;
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n"); if (boundary < 0) break;
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
if (line === "first") firstActive = true;
if (line === "third" && firstActive) import("node:fs/promises").then((fs) => fs.writeFile(${JSON.stringify(overlapPath)}, "overlap"));
if (line.startsWith("!echo ")) {
const marker = line.slice(6);
if (firstActive) setTimeout(() => { firstActive = false; process.stdout.write(marker + "\\0"); }, 100);
else process.stdout.write(marker + "\\0");
}
}
});
`,
);
await chmod(provider, 0o700);
const { manager, sessionId } = await startRizinWithProvider(provider);
if (sessionId === undefined) return;
const first = manager.execute(sessionId, "first");
const controller = new AbortController();
const second = manager.execute(sessionId, "second", controller.signal);
await new Promise((resolveDelay) => setTimeout(resolveDelay, 20));
controller.abort();
const third = manager.execute(sessionId, "third");
expect((await second).ok).toBe(false);
expect((await first).ok).toBe(true);
expect((await third).ok).toBe(true);
await expect(readFile(overlapPath, "utf8")).rejects.toThrow();
},
);
it.skipIf(process.platform === "win32")(
"preserves a truncated single Rizin frame that exceeds the protocol limit",
async () => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-frame-overflow-"));
const provider = join(directory, "fake-rizin-frame-overflow.mjs");
await writeFile(
provider,
`#!/usr/bin/env node
process.stdout.write("\\0");
let input = "";
let sent = false;
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n"); if (boundary < 0) break;
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
if (!line.startsWith("!echo ") && !sent) {
sent = true;
process.stdout.write("z".repeat(16 * 1024 * 1024 + 32) + "\\0");
}
}
});
`,
);
await chmod(provider, 0o700);
const { manager, sessionId } = await startRizinWithProvider(provider);
if (sessionId === undefined) return;
const result = await manager.execute(sessionId, "px");
expect(result.ok, result.ok ? "" : result.error.message).toBe(true);
if (result.ok) {
expect(
Buffer.byteLength(result.value.result.output, "utf8"),
).toBeLessThanOrEqual(16 * 1024 * 1024);
expect(result.value.result).toMatchObject({
output_truncated: true,
completion_status: "unknown",
});
expect(result.value.evidence.parameters).toMatchObject({
session_id: sessionId,
command: "px",
inferior_tty: expect.any(String),
});
}
expect(manager.status(sessionId)).toBeDefined();
},
);
it.skipIf(process.platform === "win32")(
"returns bounded partial Rizin output with unknown completion after overflow",
async () => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-output-overflow-"));
const provider = join(directory, "fake-rizin-output-overflow.mjs");
await writeFile(
provider,
`#!/usr/bin/env node
process.stdout.write("\\0");
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n"); if (boundary < 0) break;
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
if (line.startsWith("!echo ")) process.stdout.write(line.slice(6) + "\\0");
else if (line === "olj") process.stdout.write(JSON.stringify([{ fd: 12, raised: true, uri: "ptrace://" + process.ppid }]) + "\\0");
else if (line === "px") process.stdout.write("x".repeat(10 * 1024 * 1024) + "\\0" + "y".repeat(10 * 1024 * 1024) + "\\0");
else process.stdout.write("\\0");
}
});
`,
);
await chmod(provider, 0o700);
const { manager, sessionId } = await startRizinWithProvider(provider);
if (sessionId === undefined) return;
const result = await manager.execute(sessionId, "px");
expect(result.ok, result.ok ? "" : result.error.message).toBe(true);
if (result.ok) {
expect(
Buffer.byteLength(result.value.result.output, "utf8"),
).toBeLessThanOrEqual(16 * 1024 * 1024);
expect(result.value.result).toMatchObject({
output_truncated: true,
completion_status: "unknown",
});
}
expect(manager.status(sessionId)).toBeDefined();
},
);
it.skipIf(process.platform === "win32")(
"waits for the Rizin process to exit when command correlation times out",
async () => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-command-timeout-"));
const provider = join(directory, "fake-rizin-command-timeout.mjs");
await writeFile(
provider,
`#!/usr/bin/env node
await import("node:fs/promises").then((fs) => fs.writeFile(${JSON.stringify(join(directory ?? "", "pid"))}, String(process.pid)));
process.stdout.write("\\0");
process.stdin.setEncoding("utf8");
process.stdin.on("data", () => process.stdout.write(Buffer.from([0xff, 0])));
`,
);
await chmod(provider, 0o700);
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: provider },
{ frameTimeoutMs: 40 },
);
managers.push(manager);
const started = await manager.start({
path: "/tmp/fixture.bin",
inferior_tty: await rizinTestInferiorTty(),
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(started.value.session_id, "dr");
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.value.result).toMatchObject({
output: "�",
output_truncated: true,
completion_status: "unknown",
output_invalid_utf8: true,
});
expect(result.value.evidence.limitations).toContain(
"Collected command frames contained invalid UTF-8 bytes; decoded text may contain replacement characters.",
);
}
await expectOwnedProcessExited(
await readFile(join(directory, "pid"), "utf8"),
);
expect(manager.status(started.value.session_id)?.state).toBe("closed");
},
);
it.skipIf(process.platform === "win32")(
"cancels a running Rizin command and retains its closed status",
async () => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-command-cancel-"));
const provider = join(directory, "fake-rizin-command-cancel.mjs");
await writeFile(
provider,
`#!/usr/bin/env node
process.stdout.write("\\0");
let input = "";
let stalled = false;
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n"); if (boundary < 0) break;
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
if (line === "slow") {
stalled = true;
process.stdout.write(Buffer.from([0xff, 0]));
}
else if (line.startsWith("!echo ") && !stalled) process.stdout.write(line.slice(6) + "\\n\\0");
}
});
`,
);
await chmod(provider, 0o700);
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: provider },
{ frameTimeoutMs: 5_000 },
);
managers.push(manager);
const callerSelectedPath = "./cancelled/../fixture.bin";
const resolvedPath = resolve(callerSelectedPath);
const started = await manager.start({
path: callerSelectedPath,
inferior_tty: await rizinTestInferiorTty(),
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const controller = new AbortController();
setTimeout(() => controller.abort(), 50);
const result = await manager.execute(
started.value.session_id,
"slow",
controller.signal,
);
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error._tag).toBe("AnalysisCancelledError");
expect(result.error.partialObservation).toMatchObject({
normalized_result: { output_invalid_utf8: true },
limitations: expect.arrayContaining([
"Collected command frames contained invalid UTF-8 bytes; decoded text may contain replacement characters.",
]),
parameters: {
launch_provenance: {
caller_selected_path: callerSelectedPath,
resolved_path: resolvedPath,
},
},
});
}
expect(manager.status(started.value.session_id)?.state).toBe("closed");
},
);
it.skipIf(process.platform === "win32")(
"reports bounded Rizin stderr retention in session status",
async () => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-diagnostic-limit-"));
const provider = join(directory, "fake-rizin-diagnostic-limit.mjs");
await writeFile(
provider,
`#!/usr/bin/env node
process.stderr.write("x".repeat(100000));
process.stdout.write("\\0");
process.stdin.resume();
`,
);
await chmod(provider, 0o700);
const manager = createRizinTestManager({
REA_RIZIN_COMMAND: provider,
});
managers.push(manager);
const started = await manager.start({
path: "/tmp/fixture.bin",
inferior_tty: await rizinTestInferiorTty(),
});
expect(started.ok).toBe(true);
if (!started.ok) return;
await new Promise((resolveDelay) => setTimeout(resolveDelay, 50));
expect(
manager.status(started.value.session_id)?.diagnostics_truncated,
).toBe(true);
},
);
it.skipIf(process.platform === "win32")(
"returns cancellation when Rizin startup is cancelled after spawn",
async () => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-start-cancel-"));
const provider = join(directory, "fake-rizin-start-cancel.mjs");
await writeFile(
provider,
`#!/usr/bin/env node\nprocess.stdin.resume();\nsetInterval(() => {}, 1000);\n`,
);
await chmod(provider, 0o700);
const manager = createRizinTestManager({
REA_RIZIN_COMMAND: provider,
});
managers.push(manager);
const controller = new AbortController();
setTimeout(() => controller.abort(), 50);
const started = await manager.start(
{ path: "/tmp/fixture.bin", inferior_tty: await rizinTestInferiorTty() },
controller.signal,
);
expect(started.ok).toBe(false);
if (!started.ok) expect(started.error._tag).toBe("AnalysisCancelledError");
},
);
it.skipIf(process.platform === "win32")(
"converts a Rizin stdin pipe failure into a provider session error",
async () => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-stdin-error-"));
const provider = join(directory, "fake-rizin-stdin-error.mjs");
await writeFile(
provider,
`#!/usr/bin/env node
process.stdout.write("\\0");
setTimeout(() => import("node:fs").then((fs) => fs.closeSync(0)), 40);
setInterval(() => {}, 1000);
`,
);
await chmod(provider, 0o700);
const manager = createRizinTestManager({
REA_RIZIN_COMMAND: provider,
});
managers.push(manager);
const started = await manager.start({
path: "/tmp/fixture.bin",
inferior_tty: await rizinTestInferiorTty(),
});
expect(started.ok).toBe(true);
if (!started.ok) return;
await new Promise((resolveDelay) => setTimeout(resolveDelay, 80));
const result = await manager.execute(started.value.session_id, "dr");
expect(result.ok).toBe(false);
expect(manager.status(started.value.session_id)?.state).toBe("closed");
},
);
it.skipIf(process.platform === "win32")(
"preserves Rizin process-exit reason and partial command output",
async () => {
directory = await mkdtemp(join(tmpdir(), "rea-rizin-command-exit-"));
const provider = join(directory, "fake-rizin-command-exit.mjs");
const writerPidPath = join(directory, "writer.pid");
await writeFile(
provider,
`#!/usr/bin/env node
import { spawn } from "node:child_process";
import { writeFileSync } from "node:fs";
process.stdout.write("\\0");
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const boundary = input.indexOf("\\n");
if (boundary < 0) break;
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
if (line === "exit-now") {
const writer = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: "inherit" });
writeFileSync(${JSON.stringify(writerPidPath)}, String(writer.pid));
process.stdout.write(Buffer.concat([Buffer.from("partial-before-exit\\0second-partial\\0"), Buffer.from([0xff, 0])]), () => process.exit(7));
}
}
});
`,
);
await chmod(provider, 0o700);
let writerObserved = false;
const manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: provider },
{
stopProcess: async () => {
const writerPid = Number(await readFile(writerPidPath, "utf8"));
try {
process.kill(writerPid, 0);
writerObserved = true;
} catch {
writerObserved = false;
}
return {
status: "incomplete",
reason: "owned output writer is still active",
};
},
},
);
managers.push(manager);
const callerSelectedPath = "./exit/../fixture.bin";
const resolvedPath = resolve(callerSelectedPath);
const started = await manager.start({
path: callerSelectedPath,
inferior_tty: await rizinTestInferiorTty(),
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const exited = await manager.execute(started.value.session_id, "exit-now");
expect(exited.ok).toBe(false);
expect(writerObserved).toBe(true);
if (!exited.ok) {
expect(exited.error.cleanup).toEqual({
reason: "owned output writer is still active",
resources: [started.value.session_id],
});
expect(exited.error.partialObservation).toMatchObject({
normalized_result: {
output: ["partial-before-exit", "second-partial", "�"].join("\n"),
completion_status: "unknown",
output_invalid_utf8: true,
},
parameters: {
command: "exit-now",
session_id: started.value.session_id,
launch_provenance: {
caller_selected_path: callerSelectedPath,
resolved_path: resolvedPath,
},
},
});
const partialEvidence = evidenceSchema.parse(
exited.error.partialObservation,
);
expect(partialEvidence.limitations.join(" ")).toContain(
"Rizin exited before the command-completion marker; retained frame output is partial and command completion is unknown.",
);
}
const writerPid = Number(await readFile(writerPidPath, "utf8"));
process.kill(writerPid, "SIGKILL");
},
);
@@ -0,0 +1,648 @@
import { execFileSync, spawn as spawnChild } from "node:child_process";
import {
chmod,
mkdtemp,
readFile,
realpath,
rm,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { spawn } from "@lydell/node-pty";
import { afterEach, expect, it, vi } from "vitest";
import {
assertRizinProcessStartTimeStable,
parseRizinProcStartTime,
RizinDebugSessionManager,
} from "../../../src/rizin/RizinDebugSessionManager.js";
import { evidenceSchema } from "../../../src/domain/evidence.js";
import { TOOL_EFFECTS } from "../../../src/contracts/toolEffects.js";
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
import {
createRizinTestManager,
rizinTestInferiorTty,
} from "./RizinTestInferiorTty.js";
import { createInjectedProcess } from "./RizinDebugSessionCoverage.fixtures.js";
let terminal: ReturnType<typeof spawn> | undefined;
let manager: RizinDebugSessionManager | undefined;
let testDirectory: string | undefined;
let inferiorPid: number | undefined;
let providerPid: number | undefined;
let providerWatchdogPid: number | undefined;
const rizinBinary = findRizinBinary();
afterEach(async () => {
await manager?.closeAll().catch(() => undefined);
manager = undefined;
if (providerPid !== undefined && testDirectory !== undefined) {
try {
const commandLine = await readFile(
`/proc/${providerPid}/cmdline`,
"utf8",
);
if (commandLine.includes(testDirectory))
process.kill(providerPid, "SIGKILL");
} catch {
// The owned fake provider may already have exited.
}
}
providerPid = undefined;
if (providerWatchdogPid !== undefined) {
try {
process.kill(providerWatchdogPid, "SIGTERM");
} catch {
// The watchdog may already have completed.
}
}
providerWatchdogPid = undefined;
terminal?.kill();
terminal = undefined;
let ownedPid = inferiorPid;
if (ownedPid === undefined && testDirectory !== undefined) {
try {
ownedPid = Number(
await readFile(join(testDirectory, "target.pid"), "utf8"),
);
} catch {
// The target may not have started before the test failed.
}
}
if (
ownedPid !== undefined &&
Number.isSafeInteger(ownedPid) &&
ownedPid > 0
) {
try {
const commandLine = await readFile(`/proc/${ownedPid}/cmdline`, "utf8");
if (testDirectory !== undefined && commandLine.includes(testDirectory))
process.kill(ownedPid, "SIGKILL");
} catch {
// The test target may already have exited.
}
}
inferiorPid = undefined;
if (testDirectory !== undefined)
await rm(testDirectory, { recursive: true, force: true });
testDirectory = undefined;
});
it("requires an explicit inferior TTY before spawning Rizin", async () => {
let spawned = false;
const manager = new RizinDebugSessionManager(
{ REA_RIZIN_COMMAND: "rizin" },
{
spawnProcess: async () => {
spawned = true;
throw new Error("must not spawn");
},
},
);
const result = await manager.start({ path: "/tmp/fixture.bin" } as never);
expect(result.ok).toBe(false);
expect(spawned).toBe(false);
});
it.skipIf(process.platform === "win32")(
"fails the protocol when a NUL delimiter does not advance the frame parser",
async () => {
const injected = createInjectedProcess({
startup: (control) => control.output(Buffer.from([0, 0])),
});
manager = createRizinTestManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{ spawnProcess: injected.spawnProcess },
);
const originalIndexOf = Buffer.prototype.indexOf;
let forcedNonAdvancingBoundary = false;
const indexOf = vi
.spyOn(Buffer.prototype, "indexOf")
.mockImplementation(function (this: Buffer, value, byteOffset, encoding) {
if (
this.length === 2 &&
this[0] === 0 &&
this[1] === 0 &&
byteOffset === 1
) {
forcedNonAdvancingBoundary = true;
return 0;
}
return originalIndexOf.call(this, value, byteOffset, encoding);
});
try {
const started = await manager.start({
path: "/tmp/injected",
inferior_tty: await rizinTestInferiorTty(),
});
expect(forcedNonAdvancingBoundary).toBe(true);
expect(started.ok).toBe(false);
if (!started.ok)
expect(started.error.message).toContain(
"frame parser failed to advance past a NUL delimiter",
);
} finally {
indexOf.mockRestore();
}
},
);
it("declares that Rizin close can resume target code and mutate target state", () => {
expect(TOOL_EFFECTS.close_rizin_debug_session).toMatchObject({
mutatesTarget: true,
executesForeignCode: true,
});
});
it.skipIf(process.platform !== "linux").each([
{ name: "empty inferior list", response: "[]", closeSucceeds: true },
{ name: "malformed JSON", response: "not-json", closeSucceeds: false },
{ name: "non-array JSON", response: "{}", closeSucceeds: false },
{
name: "valid non-ptrace descriptor",
response: '[{"raised":true,"fd":3,"uri":"file:///tmp/target"}]',
closeSucceeds: true,
},
{
name: "malformed descriptor row",
response: "[null]",
closeSucceeds: false,
},
{
name: "inactive ptrace row",
response: '[{"raised":false,"fd":3,"uri":"ptrace://1"}]',
closeSucceeds: false,
},
{
name: "malformed ptrace URI",
response: '[{"raised":true,"fd":3,"uri":"ptrace://bad"}]',
closeSucceeds: false,
},
{
name: "multiple ptrace rows",
response:
'[{"raised":true,"fd":3,"uri":"ptrace://1"},{"raised":true,"fd":4,"uri":"ptrace://2"}]',
closeSucceeds: false,
},
])(
"validates Rizin `olj` close response: $name",
async ({ response, closeSucceeds }) => {
const tty = await rizinTestInferiorTty();
testDirectory = await mkdtemp(join(tmpdir(), "rea-rizin-olj-"));
const provider = join(testDirectory, "fake-rizin.cjs");
await writeFile(
provider,
`#!/usr/bin/env node
process.stdout.write("\\0");
let oljCalls = 0;
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const end = input.indexOf("\\n");
if (end < 0) break;
const line = input.slice(0, end); input = input.slice(end + 1);
if (line === "olj") process.stdout.write((++oljCalls === 1 ? ${JSON.stringify(response)} : "[]") + "\\0");
else if (line === "e dbg.exitkills") process.stdout.write("false\\0");
else if (line.startsWith("!echo ")) process.stdout.write(line.slice(6) + "\\0");
}
});
`,
);
execFileSync(process.execPath, ["--check", provider]);
await chmod(provider, 0o700);
manager = new RizinDebugSessionManager({
...process.env,
REA_RIZIN_COMMAND: provider,
});
const started = await manager.start({
path: "/tmp/fake-target",
inferior_tty: tty,
});
expect(started.ok).toBe(true);
if (!started.ok) return;
const closed = await manager.close(started.value.session_id);
expect(closed.ok).toBe(closeSucceeds);
if (!closeSucceeds) {
expect(manager.status(started.value.session_id)?.state).toBe("closed");
await manager.closeAll();
}
},
);
it.skipIf(process.platform !== "linux").each([
{
name: "same descriptor remains listed after detach",
afterDetach: (pid: number) =>
`[{"raised":true,"fd":3,"uri":"ptrace://${pid}"}]`,
},
{
name: "same inferior remains listed under a different FD",
afterDetach: (pid: number) =>
`[{"raised":true,"fd":4,"uri":"ptrace://${pid}"}]`,
},
{
name: "an unexpected ptrace inferior remains listed",
afterDetach: () => '[{"raised":true,"fd":4,"uri":"ptrace://999999999"}]',
},
])(
"retains ownership when o- readback finds $name",
async ({ afterDetach }) => {
const sessionId = await startFakeInferiorSession({ afterDetach });
await expectCloseRejectedAndReleased(sessionId);
},
);
it.skipIf(process.platform !== "linux")(
"detaches a verified fake inferior before stopping the Rizin debugger",
async () => {
const sessionId = await startFakeInferiorSession();
const closed = await manager!.close(sessionId);
expect(closed.ok).toBe(true);
if (!closed.ok) return;
expect(manager!.status(sessionId)).toBeUndefined();
expect(inferiorPid).toBeDefined();
expect(() => process.kill(inferiorPid!, 0)).not.toThrow();
const stat = await readFile(`/proc/${inferiorPid!}/stat`, "utf8");
const commandEnd = stat.lastIndexOf(") ");
expect(commandEnd).toBeGreaterThan(0);
expect(stat.slice(commandEnd + 2).trimStart()[0]).not.toBe("Z");
},
);
it.skipIf(process.platform !== "linux")(
"refuses detach when Rizin reports dbg.exitkills=true",
async () => {
const sessionId = await startFakeInferiorSession({ exitKills: "true" });
await expectCloseRejectedAndReleased(sessionId);
},
);
it.skipIf(process.platform !== "linux")(
"refuses detach when the inferior stderr is not routed to the selected TTY",
async () => {
const sessionId = await startFakeInferiorSession({
stderrPath: "/dev/null",
});
await expectCloseRejectedAndReleased(sessionId);
},
);
it.skipIf(process.platform !== "linux")(
"retains ownership when the ptrace PID has no proc identity",
async () => {
const sessionId = await startFakeInferiorSession({
launchTarget: false,
initialRows: '[{"raised":true,"fd":3,"uri":"ptrace://999999999"}]',
startupWatchdogMs: 2_000,
});
await expectCloseRejectedAndReleased(sessionId);
},
4_000,
);
it("parses Rizin's Linux proc stat start time and rejects malformed identity data", () => {
const fields = Array.from({ length: 20 }, (_, index) => String(index + 1));
expect(
parseRizinProcStartTime(`123 (target ) name) ${fields.join(" ")}`),
).toBe("20");
expect(() => parseRizinProcStartTime("malformed stat contents")).toThrow(
"Inferior process identity is malformed",
);
expect(() => parseRizinProcStartTime("123 (target) short")).toThrow(
"Inferior process start time could not be verified",
);
expect(() => assertRizinProcessStartTimeStable("11", "12")).toThrow(
"disappeared or was reused",
);
expect(() => assertRizinProcessStartTimeStable("11", "11")).not.toThrow();
});
it.skipIf(process.platform !== "linux")(
"retains ownership when cleanup cannot read Rizin stdin",
async () => {
const injected = createInjectedProcess({ stdin: "null" });
manager = new RizinDebugSessionManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{
spawnProcess: injected.spawnProcess,
stopProcess: async (session) => {
try {
await session.detachInferior?.();
} catch {
// This fixture verifies the manager's fail-closed read path only.
}
return { status: "incomplete", reason: "unreachable" };
},
},
);
const started = await manager.start({
path: "/tmp/fake-target",
inferior_tty: await rizinTestInferiorTty(),
});
expect(started.ok).toBe(true);
if (!started.ok) return;
expect((await manager.close(started.value.session_id)).ok).toBe(false);
expect(manager.status(started.value.session_id)?.state).toBe("closed");
},
);
it.skipIf(process.platform !== "linux")(
"retains ownership when an internal Rizin frame is truncated",
async () => {
const sessionId = await startFakeInferiorSession({
truncateCleanupFrame: true,
maxCommandOutputBytes: 1_024,
});
expect((await manager!.close(sessionId)).ok).toBe(false);
expect(manager!.status(sessionId)?.state).toBe("closed");
await expect(manager!.closeAll()).rejects.toThrow("did not stop cleanly");
},
);
it.skipIf(process.platform !== "linux")(
"retains a verified active inferior after public command output truncation makes protocol state ambiguous",
async () => {
const sessionId = await startFakeInferiorSession({
overflowPxCommand: true,
maxCommandOutputBytes: 1_024,
});
let watchdog: ReturnType<typeof setTimeout> | undefined;
const completed = await Promise.race([
manager!.execute(sessionId, "px"),
new Promise<never>((_, reject) => {
watchdog = setTimeout(
() => reject(new Error("detach watchdog expired")),
3_000,
);
}),
])
.catch(async (error: unknown) => {
if (providerPid !== undefined) {
try {
process.kill(providerPid, "SIGKILL");
} catch {
// The watchdog may race with provider exit.
}
}
// The mutated path can leave commandTail permanently held. Prevent cleanup
// from awaiting that same tail; afterEach still kills both child processes.
manager = undefined;
throw error;
})
.finally(() => {
if (watchdog !== undefined) clearTimeout(watchdog);
});
expect(completed.ok).toBe(false);
if (completed.ok) return;
expect(completed.error.cleanupIncomplete).toBe(true);
expect(completed.error.cleanupResources).toEqual([sessionId]);
const evidence = evidenceSchema.parse(completed.error.partialObservation);
expect(evidence.normalized_result).toMatchObject({
output_truncated: true,
});
expect(evidence.limitations.join(" ")).toContain(
"The owned debugger session remains retained because cleanup could not be verified",
);
expect(manager!.status(sessionId)?.state).toBe("closed");
},
);
it.skipIf(
process.platform !== "linux" ||
rizinBinary === undefined ||
!rizinAvailable(rizinBinary),
)(
"routes the inferior to the selected TTY and verifies detach with Rizin 0.7.4 protocol",
async () => {
let terminalOutput = "";
terminal = spawn("sh", ["-c", "tty; exec sleep 60"], {
name: "xterm",
cols: 80,
rows: 24,
encoding: "utf8",
});
const ttyPath = await new Promise<string>((resolve, reject) => {
const timer = setTimeout(
() => reject(new Error("TTY path not printed")),
2_000,
);
terminal!.onData((data) => {
terminalOutput += data;
const match = /\/dev\/pts\/\d+/u.exec(terminalOutput);
if (match) {
clearTimeout(timer);
resolve(match[0]);
}
});
});
const tty = await realpath(ttyPath);
testDirectory = await mkdtemp(join(tmpdir(), "rea-rizin-tty-"));
const wrapper = join(testDirectory, "rizin-with-long-lived-inferior.sh");
const pidPath = join(testDirectory, "target.pid");
const releasePath = join(testDirectory, "emit-output");
const target = join(testDirectory, "target.py");
await writeFile(
target,
`import os, sys, time\nopen(${JSON.stringify(pidPath)}, "w").write(str(os.getpid()))\nwhile not os.path.exists(${JSON.stringify(releasePath)}): time.sleep(0.02)\nprint("REA_RIZIN_STDOUT_MARKER", flush=True)\nprint("REA_RIZIN_STDERR_MARKER", file=sys.stderr, flush=True)\ntime.sleep(60)\n`,
);
await writeFile(
wrapper,
`#!/bin/sh\nexec ${shellQuote(rizinBinary!)} -R arg1=${target} "$@"\n`,
);
await chmod(wrapper, 0o700);
manager = new RizinDebugSessionManager({ REA_RIZIN_COMMAND: wrapper });
const started = await manager.start({
path: "/usr/bin/python3",
inferior_tty: tty,
});
expect(started.ok, started.ok ? "" : started.error.message).toBe(true);
if (!started.ok) return;
const closing = manager.close(started.value.session_id);
expect((await manager.execute(started.value.session_id, "dr")).ok).toBe(
false,
);
const closed = await closing;
expect(closed.ok, closed.ok ? "" : closed.error.message).toBe(true);
const deadline = Date.now() + 5_000;
let pidText = "";
while (Date.now() < deadline) {
try {
pidText = await readFile(pidPath, "utf8");
break;
} catch {
await new Promise((resolveDelay) => setTimeout(resolveDelay, 50));
}
}
inferiorPid = Number(pidText);
expect(Number.isSafeInteger(inferiorPid) && inferiorPid > 0).toBe(true);
expect(() => process.kill(inferiorPid!, 0)).not.toThrow();
await writeFile(releasePath, "release after close");
const outputDeadline = Date.now() + 3_000;
while (
Date.now() < outputDeadline &&
(!terminalOutput.includes("REA_RIZIN_STDOUT_MARKER") ||
!terminalOutput.includes("REA_RIZIN_STDERR_MARKER"))
)
await new Promise((resolveDelay) => setTimeout(resolveDelay, 25));
expect(terminalOutput).toContain("REA_RIZIN_STDOUT_MARKER");
expect(terminalOutput).toContain("REA_RIZIN_STDERR_MARKER");
expect(() => process.kill(inferiorPid!, 0)).not.toThrow();
},
);
function findRizinBinary(): string | undefined {
try {
return execFileSync("which", ["rizin"], { encoding: "utf8" }).trim();
} catch {
return undefined;
}
}
function rizinAvailable(binary: string): boolean {
try {
return execFileSync(binary, ["-v"], { encoding: "utf8" }).includes("0.7.4");
} catch {
return false;
}
}
function shellQuote(value: string): string {
return `'${value.replaceAll("'", `'\\''`)}'`;
}
async function startFakeInferiorSession(
options: {
readonly launchTarget?: boolean;
readonly initialRows?: string;
readonly afterDetach?: (pid: number) => string;
readonly exitKills?: string;
readonly stderrPath?: string;
readonly truncateOlj?: boolean;
readonly truncateCleanupFrame?: boolean;
readonly overflowPxCommand?: boolean;
readonly startupWatchdogMs?: number;
readonly maxCommandOutputBytes?: number;
} = {},
): Promise<string> {
const tty = await realpath(await rizinTestInferiorTty());
testDirectory = await mkdtemp(join(tmpdir(), "rea-rizin-protocol-"));
const targetPath = join(testDirectory, "inferior.mjs");
const pidPath = join(testDirectory, "target.pid");
const provider = join(testDirectory, "fake-rizin.cjs");
const launchTarget = options.launchTarget ?? true;
await writeFile(targetPath, "setInterval(() => {}, 1000);\n");
const initialRows = options.initialRows ?? null;
const afterDetach = options.afterDetach ?? (() => "[]");
const stderrPath = options.stderrPath ?? tty;
await writeFile(
provider,
`#!/usr/bin/env node
const fs = require("node:fs");
const { spawn } = require("node:child_process");
process.stdout.write("\\0");
${launchTarget ? `const ttyFlags = fs.constants.O_WRONLY | fs.constants.O_NOCTTY | fs.constants.O_NONBLOCK; const stdoutFd = fs.openSync(${JSON.stringify(tty)}, ttyFlags); const stderrFd = fs.openSync(${JSON.stringify(stderrPath)}, ttyFlags); const target = spawn(process.execPath, [${JSON.stringify(targetPath)}], { detached: true, stdio: ["ignore", stdoutFd, stderrFd] }); fs.closeSync(stdoutFd); fs.closeSync(stderrFd); target.unref(); const inferiorPid = target.pid; fs.writeFileSync(${JSON.stringify(pidPath)}, String(inferiorPid));` : "const inferiorPid = 999999999;"}
const initialRows = ${JSON.stringify(initialRows)} ?? JSON.stringify([{ raised: true, fd: 3, uri: "ptrace://" + inferiorPid }]);
const afterDetach = ${JSON.stringify(afterDetach(inferiorPid ?? 999999999))};
const exitKills = ${JSON.stringify(options.exitKills ?? "false")};
const truncateOlj = ${JSON.stringify(options.truncateOlj ?? false)};
const truncateCleanupFrame = ${JSON.stringify(options.truncateCleanupFrame ?? false)};
const overflowPxCommand = ${JSON.stringify(options.overflowPxCommand ?? false)};
let oljCalls = 0;
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
input += chunk;
for (;;) {
const end = input.indexOf("\\n");
if (end < 0) break;
const line = input.slice(0, end); input = input.slice(end + 1);
if (line === "olj") {
oljCalls += 1;
if (truncateOlj && oljCalls === 1) process.stdout.write("x".repeat(16 * 1024 * 1024 + 1) + "\\0");
else process.stdout.write((oljCalls === 1 ? initialRows : oljCalls === 2 ? afterDetach : "[]") + "\\0");
}
else if (overflowPxCommand && line === "px") process.stdout.write("x".repeat(2_048) + "\\0");
else if (line === "e dbg.exitkills") process.stdout.write(exitKills + "\\0");
else if (line.startsWith("!echo ")) process.stdout.write((truncateCleanupFrame ? "x".repeat(2_048) : "") + line.slice(6) + "\\0");
}
});
`,
);
await chmod(provider, 0o700);
let providerStderr = "";
manager = new RizinDebugSessionManager(
{ ...process.env, REA_RIZIN_COMMAND: provider },
{
spawnProcess: async (spawnOptions) => {
const launched = await spawnOwnedProviderProcess(spawnOptions);
providerPid = launched.process.pid;
if (options.startupWatchdogMs !== undefined) {
const watchdog = spawnChild(
process.execPath,
[
"-e",
`const fs = require("node:fs"); const provider = Number(process.argv[1]); const directory = process.argv[2]; const targetFile = process.argv[3]; const delay = Number(process.argv[4]); setTimeout(() => { let target; try { target = Number(fs.readFileSync(targetFile, "utf8")); } catch {} for (const pid of [provider, target]) { if (!Number.isSafeInteger(pid) || pid <= 0) continue; try { const commandLine = fs.readFileSync("/proc/" + pid + "/cmdline", "utf8"); if (commandLine.includes(directory)) process.kill(pid, "SIGKILL"); } catch {} } }, delay);`,
String(launched.process.pid),
testDirectory!,
join(testDirectory!, "target.pid"),
String(options.startupWatchdogMs),
],
{ detached: true, stdio: "ignore" },
);
providerWatchdogPid = watchdog.pid;
watchdog.unref();
}
launched.process.stderr?.on("data", (chunk) => {
providerStderr += Buffer.from(chunk).toString("utf8");
});
return launched;
},
...(options.maxCommandOutputBytes === undefined
? {}
: { maxCommandOutputBytes: options.maxCommandOutputBytes }),
},
);
const started = await manager.start({
path: "/tmp/fake-target",
inferior_tty: tty,
});
expect(
started.ok,
started.ok ? "" : `${started.error.message} ${providerStderr}`,
).toBe(true);
if (!started.ok) throw started.error;
if (launchTarget) {
let pidText: string | undefined;
const deadline = Date.now() + 2_000;
while (pidText === undefined && Date.now() < deadline) {
try {
pidText = await readFile(pidPath, "utf8");
} catch {
await new Promise((resolveDelay) => setTimeout(resolveDelay, 10));
}
}
const parsedInferiorPid =
pidText === undefined ? Number.NaN : Number(pidText);
if (!Number.isSafeInteger(parsedInferiorPid) || parsedInferiorPid <= 0)
throw new Error("The test inferior did not publish a valid PID.");
inferiorPid = parsedInferiorPid;
}
return started.value.session_id;
}
async function expectCloseRejectedAndReleased(
sessionId: string,
): Promise<void> {
expect((await manager!.close(sessionId)).ok).toBe(false);
expect(manager!.status(sessionId)?.state).toBe("closed");
await manager!.closeAll();
expect(manager!.status(sessionId)).toBeUndefined();
}
@@ -0,0 +1,73 @@
import { afterAll } from "vitest";
import { spawn } from "@lydell/node-pty";
import { RizinDebugSessionManager } from "../../../src/rizin/RizinDebugSessionManager.js";
import { stopOwnedDebuggerProcess } from "../../../src/process/ownedDebuggerSession.js";
let ttyPathPromise: Promise<string> | undefined;
let terminal: ReturnType<typeof spawn> | undefined;
export const rizinTestInferiorTty = (): Promise<string> => {
if (process.platform === "win32")
return Promise.reject(
new Error("The Rizin test TTY requires a POSIX host."),
);
ttyPathPromise ??= new Promise<string>((resolve, reject) => {
terminal = spawn("sh", ["-c", "tty; exec sleep 600"], {
name: "xterm",
cols: 80,
rows: 24,
encoding: "utf8",
});
let output = "";
const timer = setTimeout(
() => reject(new Error("test TTY path timeout")),
2_000,
);
terminal.onData((chunk) => {
output += chunk;
const pattern =
process.platform === "darwin"
? /\/dev\/ttys[0-9a-z]+/u
: /\/dev\/pts\/\d+/u;
const match = pattern.exec(output);
if (match !== null) {
clearTimeout(timer);
resolve(match[0]);
}
});
});
return ttyPathPromise;
};
afterAll(() => terminal?.kill());
/** These fixture processes do not launch or attach an inferior. */
export const stopFakeNoInferior = async (
session: Parameters<typeof stopOwnedDebuggerProcess>[0],
debuggerName: string,
options?: Parameters<typeof stopOwnedDebuggerProcess>[2],
) =>
stopOwnedDebuggerProcess(
{
...session,
inferiorStateUnknown: () => false,
detachInferior: async () => ({ status: "no-inferior" }),
},
debuggerName,
options,
);
export const createRizinTestManager = (
environment: Readonly<NodeJS.ProcessEnv> = process.env,
options: ConstructorParameters<typeof RizinDebugSessionManager>[1] = {},
): RizinDebugSessionManager =>
new RizinDebugSessionManager(
{ ...process.env, ...environment },
{
// These fake-provider tests model Linux protocol behavior independently of
// the host running the suite. Real-provider coverage checks the host platform.
platform: "linux",
stopProcess: stopFakeNoInferior,
...options,
},
);

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