Merge remote-tracking branch 'origin/main' into feat/persistent-workspace-investigation-runs

# Conflicts:
#	README.md
#	scripts/verify-package.mjs
#	src/cli.ts
#	src/domain/errors.ts
#	src/server/registerInvestigationTools.ts
#	tests/errors.test.ts
This commit is contained in:
morluto
2026-07-14 04:28:14 +08:00
91 changed files with 4402 additions and 711 deletions
+127
View File
@@ -0,0 +1,127 @@
import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
readAnalysisSnapshot,
writeAnalysisSnapshot,
} from "../src/application/AnalysisSnapshotFiles.js";
import {
createAnalysisSnapshotEntry,
parseAnalysisSnapshot,
snapshotEvidenceForQuery,
type AnalysisSnapshot,
} from "../src/domain/analysisSnapshot.js";
import { createEvidenceBundle } from "../src/domain/evidenceBundle.js";
import { createEvidence } from "../src/domain/evidence.js";
import { createAnalysisExecution } from "../src/application/AnalysisProvider.js";
let directory: string | undefined;
afterEach(async () => {
if (directory !== undefined)
await rm(directory, { recursive: true, force: true });
directory = undefined;
});
describe("analysis snapshots", () => {
it("finds exact CLI evidence for provider-free replay", () => {
const target = {
path: "/tmp/app",
sha256: "b".repeat(64),
kind: "executable",
format: "mach-o",
architecture: "arm64",
loaderArgs: [],
} as const;
const evidence = createEvidence(
target,
{ id: "fixture", name: "Fixture", version: "1" },
{
operation: "analyze_function",
parameters: { procedure: "main" },
result: { summary: "cached" },
},
);
const snapshot: AnalysisSnapshot = {
snapshot_version: 1,
target: {
sha256: target.sha256,
format: target.format,
architecture: target.architecture,
loader_args: [],
},
entries: [],
evidence_bundle: createEvidenceBundle([evidence]),
};
expect(
snapshotEvidenceForQuery(snapshot, {
target,
operation: "analyze_function",
parameters: {
procedure: "main",
},
provider: { id: "fixture", name: "Fixture", version: "1" },
}),
).toEqual(evidence);
expect(
snapshotEvidenceForQuery(snapshot, {
target,
operation: "analyze_function",
parameters: {
procedure: "other",
},
provider: { id: "fixture", name: "Fixture", version: "1" },
}),
).toBeUndefined();
});
it("writes canonical private JSON and rejects a changed query identity", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-analysis-snapshot-"));
const path = join(directory, "analysis.json");
const target: AnalysisSnapshot["target"] = {
sha256: "a".repeat(64),
format: "mach-o",
architecture: "arm64",
loader_args: [],
};
const entry = createAnalysisSnapshotEntry(
target,
"address_name",
{ address: "0x1000" },
createAnalysisExecution("main", {
id: "fixture",
name: "Fixture analysis provider",
version: "1",
}),
);
const snapshot: AnalysisSnapshot = {
snapshot_version: 1,
target,
entries: [entry],
evidence_bundle: createEvidenceBundle([]),
};
const policy = {
roots: [directory],
maxBytes: 1024 * 1024,
maxDepth: 64,
maxStringLength: 1024,
maxNodes: 10_000,
};
const written = await writeAnalysisSnapshot(snapshot, path, false, policy);
expect(written.ok).toBe(true);
expect((await readFile(path, "utf8")).endsWith("\n")).toBe(true);
expect((await stat(path)).mode & 0o777).toBe(0o600);
expect((await readAnalysisSnapshot(path, policy)).ok).toBe(true);
const altered = JSON.parse(await readFile(path, "utf8"));
altered.entries[0].parameters.address = "0x2000";
await writeFile(path, JSON.stringify(altered));
const loaded = await readAnalysisSnapshot(path, policy);
expect(loaded.ok).toBe(false);
if (!loaded.ok) expect(loaded.error._tag).toBe("EvidenceIntegrityError");
expect(() => parseAnalysisSnapshot(altered)).toThrow(/identifier/u);
});
});
+48 -1
View File
@@ -1,8 +1,9 @@
import { mkdtemp, writeFile } from "node:fs/promises";
import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { createPackageWithOptions } from "@electron/asar";
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { describe, expect, it } from "vitest";
import { z } from "zod";
@@ -16,6 +17,52 @@ import { createServer } from "../src/server/createServer.js";
import { observed } from "./fixtures/analysisExecution.js";
describe("artifact graph MCP integration", () => {
it("returns a safe ASAR integrity error without paths or hashes", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-asar-integrity-mcp-"));
const source = join(root, "source");
const original = "console.log('ok');\n";
const changed = "changed();\n";
await mkdir(source);
await writeFile(join(source, "main.js"), original);
const archive = join(root, "fixture.asar");
await createPackageWithOptions(source, archive, { unpack: "*.js" });
await writeFile(join(`${archive}.unpacked`, "main.js"), changed);
const session = new BinarySession(new ArtifactProvider());
const server = createServer(session, session);
const client = new Client({ name: "asar-integrity-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const opened = await client.callTool({
name: "open_binary",
arguments: { path: archive },
});
expect(opened.isError).not.toBe(true);
const result = await client.callTool({
name: "inventory_artifact",
arguments: {},
});
expect(result.isError).toBe(true);
expect(result.structuredContent).toEqual({
error: {
category: "integrity_mismatch",
message:
"Artifact is invalid or has changed. Get a fresh copy and try again.",
},
});
} finally {
await Promise.allSettled([
client.close(),
server.close(),
session.close(),
]);
}
});
it("rejects altered payloads that reuse session Evidence IDs", async () => {
const session = new BinarySession(() => ({
health: () => Promise.resolve(),
+151 -1
View File
@@ -5,7 +5,10 @@ import { afterEach, describe, expect, it } from "vitest";
import { BinarySession } from "../src/application/BinarySession.js";
import type { AnalysisClient } from "../src/application/AnalysisProvider.js";
import type { AnalysisProvider } from "../src/application/AnalysisProvider.js";
import type {
AnalysisProvider,
CapabilityDescriptor,
} from "../src/application/AnalysisProvider.js";
import { HopperStartError } from "../src/domain/errors.js";
import { err } from "../src/domain/result.js";
import { observed as ok } from "./fixtures/analysisExecution.js";
@@ -96,6 +99,97 @@ describe("binary session", () => {
await session.close();
});
it("replays exact immutable calls from a matching provider-neutral snapshot", async () => {
const [first, second] = await targets();
const initialCalls: string[] = [];
const initial = new BinarySession(cacheProvider(initialCalls));
expect((await initial.open(first)).ok).toBe(true);
expect(
(
await initial.execute("address_name", {
address: "0x1000",
document: "first",
})
).ok,
).toBe(true);
const snapshot = initial.exportAnalysisSnapshot();
expect(snapshot.ok).toBe(true);
if (!snapshot.ok) return;
expect(snapshot.value.entries).toHaveLength(1);
await initial.close();
const replayCalls: string[] = [];
const replay = new BinarySession(cacheProvider(replayCalls));
expect(replay.importAnalysisSnapshot(snapshot.value)).toEqual({
ok: true,
value: 1,
});
expect((await replay.open(first)).ok).toBe(true);
const cached = await replay.execute("address_name", {
address: "0x1000",
document: "first",
});
expect(cached.ok).toBe(true);
if (cached.ok)
expect(cached.value.limitations).toContainEqual(
expect.stringContaining("local REA analysis snapshot"),
);
expect(
(
await replay.execute("set_address_name", {
address: "0x1000",
name: "renamed",
document: "first",
})
).ok,
).toBe(true);
expect(
(
await replay.execute("address_name", {
address: "0x1000",
document: "first",
})
).ok,
).toBe(true);
expect(replayCalls).toEqual(["health", "set_address_name", "address_name"]);
expect(replay.exportAnalysisSnapshot().ok).toBe(false);
await replay.close();
const mismatch = new BinarySession(cacheProvider([]));
expect(mismatch.importAnalysisSnapshot(snapshot.value).ok).toBe(true);
const opened = await mismatch.open(second);
expect(opened.ok).toBe(false);
if (!opened.ok) expect(opened.error._tag).toBe("EvidenceIntegrityError");
await mismatch.close();
});
it("does not snapshot reads that depend on the provider cursor", async () => {
const [first] = await targets();
const calls: string[] = [];
const session = new BinarySession(cacheProvider(calls));
expect((await session.open(first)).ok).toBe(true);
expect((await session.execute("address_name", {})).ok).toBe(true);
expect((await session.execute("address_name", {})).ok).toBe(true);
expect(calls).toEqual(["health", "address_name", "address_name"]);
expect(session.exportAnalysisSnapshot()).toMatchObject({
ok: true,
value: { entries: [] },
});
await session.close();
});
it("does not replay operations with filesystem side effects", async () => {
const [first] = await targets();
const calls: string[] = [];
const session = new BinarySession(cacheProvider(calls, true));
expect((await session.open(first)).ok).toBe(true);
const input = { address: "0x1000", document: "first" };
expect((await session.execute("address_name", input)).ok).toBe(true);
expect((await session.execute("address_name", input)).ok).toBe(true);
expect(calls).toEqual(["health", "address_name", "address_name"]);
await session.close();
});
it("returns typed unavailability without dispatching a partial provider", async () => {
const [first] = await targets();
const operations: string[] = [];
@@ -306,6 +400,62 @@ const client = (fail = false): AnalysisClient => ({
close: () => Promise.resolve(),
});
const cacheProvider = (
calls: string[],
mayWriteFilesystem = false,
): AnalysisProvider => {
const identity = {
id: "fixture",
name: "Fixture analysis provider",
version: "1",
} as const;
return {
identity: () => identity,
capabilities: () => [
cacheCapability(identity, "address_name", false, mayWriteFilesystem),
cacheCapability(identity, "set_address_name", true),
],
createClient: () => ({
execute: (operation) => {
calls.push(operation);
return Promise.resolve(ok(operation));
},
close: () => Promise.resolve(),
}),
};
};
const cacheCapability = (
provider: CapabilityDescriptor["provider"],
operation: "address_name" | "set_address_name",
mutatesArtifact: boolean,
mayWriteFilesystem = false,
): CapabilityDescriptor => ({
provider,
operation,
inputContractVersion: 1,
outputContractVersion: 1,
available: true,
reason: null,
pagination: "none",
exhaustive: true,
effects: {
mutatesArtifact,
launchesProcess: false,
mayShowUi: false,
mayAccessNetwork: false,
mayWriteFilesystem,
changesPermissions: false,
requiresRoot: false,
},
limits: {
maxResults: null,
maxPayloadBytes: null,
timeoutMs: null,
},
limitations: [],
});
class TestClient implements AnalysisClient {
closed = 0;
constructor(
+372
View File
@@ -0,0 +1,372 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import { z } from "zod";
const execFileAsync = promisify(execFile);
const bridgePath = fileURLToPath(
new URL("../bridge/hopper_bridge.py", import.meta.url),
);
const probePath = fileURLToPath(
new URL("./fixtures/bridgeRegexProbe.py", import.meta.url),
);
const errorResultSchema = z.object({
action: z.enum(["match", "search"]),
ok: z.literal(false),
type: z.string(),
diagnostic_type: z.string(),
message: z.string(),
});
const matchResultSchema = z.object({
action: z.literal("match"),
ok: z.literal(true),
backtracking_paths: z.number().int().positive(),
matched: z.boolean(),
});
const searchResultSchema = z.object({
action: z.literal("search"),
ok: z.literal(true),
result: z.object({
items: z.array(
z.object({
address: z.string(),
value: z.string(),
value_truncated: z.boolean(),
}),
),
offset: z.number().int().nonnegative(),
limit: z.number().int().positive(),
total: z.number().int().nonnegative(),
next_offset: z.number().int().nonnegative().nullable(),
has_more: z.boolean(),
}),
});
const probeResultSchema = z.union([
errorResultSchema,
matchResultSchema,
searchResultSchema,
]);
type ProbeInput =
| {
readonly action: "match";
readonly pattern: string;
readonly value: string;
readonly case_sensitive?: boolean;
}
| {
readonly action: "search";
readonly items: readonly (readonly [string, string])[];
readonly params: Readonly<Record<string, string | number | boolean>>;
};
const probe = async (input: ProbeInput) => {
const result = await execFileAsync(
"python3",
[probePath, bridgePath, JSON.stringify(input)],
{ timeout: 3_000, maxBuffer: 1024 * 1024 },
);
return probeResultSchema.parse(JSON.parse(result.stdout));
};
const invalidRequest = (action: "match" | "search", message: string) => ({
action,
ok: false,
type: "ValueError",
diagnostic_type: "invalid_request",
message,
});
describe("Hopper bridge regex bounds", () => {
it("accepts useful patterns whose static backtracking budget is bounded", async () => {
await expect(
probe({
action: "match",
pattern: String.raw`^rea_(?:main|helper)_[0-9]{1,3}$`,
value: "REA_helper_42",
}),
).resolves.toEqual({
action: "match",
ok: true,
backtracking_paths: 6,
matched: true,
});
});
it("applies bounded regex matching through deterministic pagination", async () => {
await expect(
probe({
action: "search",
items: [
["0x1000", "REA_main_1"],
["0x2000", "unrelated"],
["0x3000", "rea_helper_42"],
],
params: {
pattern: String.raw`^rea_(?:main|helper)_[0-9]{1,3}$`,
mode: "regex",
case_sensitive: false,
offset: 1,
limit: 1,
},
}),
).resolves.toEqual({
action: "search",
ok: true,
result: {
items: [
{
address: "0x3000",
value: "rea_helper_42",
value_truncated: false,
},
],
offset: 1,
limit: 1,
total: 2,
next_offset: null,
has_more: false,
},
});
});
it.each([
[
"lookaround",
"(?=a)a",
"Regex lookarounds and backreferences are not supported",
],
[
"backreference",
String.raw`(a)\1`,
"Regex lookarounds and backreferences are not supported",
],
[
"nested repeat",
"(a{1,2}){1,2}",
"Nested regex repetitions are not supported",
],
[
"unbounded repeat",
"a+",
"Unbounded or excessive regex repetitions are not supported",
],
[
"excessive repeat",
"a{1001}",
"Unbounded or excessive regex repetitions are not supported",
],
])("rejects unsupported %s constructs", async (_name, pattern, message) => {
await expect(
probe({ action: "match", pattern, value: "aaaa", case_sensitive: true }),
).resolves.toEqual(invalidRequest("match", message));
});
it.each(["(", "a{999999999999999999999999}"])(
"normalizes parser failure %s through the search boundary",
async (pattern) => {
await expect(
probe({
action: "search",
items: [],
params: { pattern, mode: "regex", offset: 0, limit: 1 },
}),
).resolves.toEqual(invalidRequest("search", "Invalid regex pattern"));
},
);
it("accepts the maximum bounded repeat at the exact work budget", async () => {
await expect(
probe({
action: "match",
pattern: "a{1000}",
value: "a".repeat(1_000),
case_sensitive: true,
}),
).resolves.toEqual({
action: "match",
ok: true,
backtracking_paths: 1,
matched: true,
});
});
it("accepts expensive matching just below the cumulative work limit", async () => {
await expect(
probe({
action: "match",
pattern: "(?:a|aa){1,8}b",
value: "a".repeat(115),
case_sensitive: true,
}),
).resolves.toEqual({
action: "match",
ok: true,
backtracking_paths: 510,
matched: false,
});
});
it("rejects ambiguous bounded repetition before Python regex execution", async () => {
await expect(
probe({
action: "match",
pattern: "(a|aa){1,35}b",
value: "a".repeat(35),
case_sensitive: true,
}),
).resolves.toEqual(
invalidRequest(
"match",
"Regex exceeds the 10000-path backtracking budget",
),
);
});
it("rejects excessive combinations across adjacent optional atoms", async () => {
await expect(
probe({
action: "match",
pattern: `${"a?".repeat(14)}b`,
value: "a".repeat(14),
case_sensitive: true,
}),
).resolves.toEqual(
invalidRequest(
"match",
"Regex exceeds the 10000-path backtracking budget",
),
);
});
it("bounds cumulative work before evaluating a costly candidate", async () => {
await expect(
probe({
action: "match",
pattern: "(?:a|aa){1,12}b",
value: "a".repeat(4_096),
case_sensitive: true,
}),
).resolves.toEqual(
invalidRequest(
"match",
"Regex search exceeds the 1000000-unit work budget",
),
);
});
it("applies the regex work budget across the full inventory", async () => {
await expect(
probe({
action: "search",
items: [
["0x1000", "a".repeat(60)],
["0x2000", "a".repeat(60)],
],
params: {
pattern: "(?:a|aa){1,8}b",
mode: "regex",
case_sensitive: true,
offset: 0,
limit: 1,
},
}),
).resolves.toEqual(
invalidRequest(
"search",
"Regex search exceeds the 1000000-unit work budget",
),
);
});
it("rejects oversized regex candidates instead of matching a prefix", async () => {
await expect(
probe({
action: "match",
pattern: "needle",
value: `${"x".repeat(4_096)}needle`,
}),
).resolves.toEqual(
invalidRequest(
"match",
"Regex candidate exceeds the 4096-character safety limit",
),
);
});
it("accepts a regex candidate at the exact character limit", async () => {
await expect(
probe({
action: "match",
pattern: "z$",
value: `${"a".repeat(4_095)}z`,
case_sensitive: true,
}),
).resolves.toEqual({
action: "match",
ok: true,
backtracking_paths: 1,
matched: true,
});
});
it.each([
[256, true],
[257, false],
])("enforces the %i-character pattern boundary", async (length, accepted) => {
const pattern = "a".repeat(length);
const result = await probe({
action: "search",
items: [["0x1000", pattern]],
params: {
pattern,
mode: "regex",
case_sensitive: true,
offset: 0,
limit: 1,
},
});
if (accepted) {
expect(result).toMatchObject({
action: "search",
ok: true,
result: { total: 1 },
});
return;
}
expect(result).toEqual(
invalidRequest(
"search",
"pattern must contain between 1 and 256 characters",
),
);
});
it("keeps literal matching exhaustive while bounding returned text", async () => {
const result = await probe({
action: "search",
items: [["0x1000", `${"x".repeat(4_096)}needle`]],
params: {
pattern: "needle",
mode: "literal",
case_sensitive: true,
offset: 0,
limit: 1,
},
});
expect(result).toMatchObject({
action: "search",
ok: true,
result: {
total: 1,
has_more: false,
items: [{ address: "0x1000", value_truncated: true }],
},
});
if (result.action === "search" && result.ok)
expect(result.result.items[0]?.value).toHaveLength(4_096);
});
});
+34
View File
@@ -72,6 +72,11 @@ describe("Hopper bridge truthfulness", () => {
);
expect(bridgeSource).toContain("MAX_SEARCH_PATTERN_LENGTH = 256");
expect(bridgeSource).toContain("MAX_SEARCH_VALUE_LENGTH = 4096");
expect(bridgeSource).toContain("MAX_REGEX_BACKTRACKING_PATHS = 10000");
expect(bridgeSource).toContain("MAX_REGEX_CANDIDATE_LENGTH = 4096");
expect(bridgeSource).toContain("MAX_REGEX_SEARCH_WORK_UNITS = 1000000");
expect(bridgeSource).toContain("_checked_regex_paths(");
expect(bridgeSource).toContain("_bounded_regex_matcher(");
expect(bridgeSource).toContain('"value_truncated"');
expect(bridgeSource).toContain("page_end = offset + limit");
expect(bridgeSource).toContain("if offset <= total < page_end:");
@@ -91,4 +96,33 @@ describe("Hopper bridge truthfulness", () => {
expect(bridgeSource).toContain('"type": _diagnostic_type(error)');
expect(bridgeSource).not.toContain("traceback.format_exc");
});
it("stops background analysis and closes the session-owned document", () => {
expect(bridgeSource).toContain("def _session_document():");
expect(bridgeSource).toContain("os.path.realpath(REA_TARGET_PATH)");
expect(bridgeSource).toContain("document.getExecutableFilePath()");
expect(bridgeSource).toContain("document.getDatabaseFilePath()");
expect(bridgeSource).toContain("document.backgroundProcessActive()");
expect(bridgeSource).toContain("document.requestBackgroundProcessStop()");
expect(bridgeSource).toContain("document.waitForBackgroundProcessToEnd()");
expect(bridgeSource).toContain("document.closeDocument()");
expect(bridgeSource).toContain(
"document_closed = _session_document() is None",
);
});
it("returns deterministic addresses for direct procedure relationships", () => {
expect(bridgeSource).toContain(
"_hex(item.getEntryPoint()) for item in procedure.getAllCallerProcedures()",
);
expect(bridgeSource).toContain(
"_hex(item.getEntryPoint()) for item in procedure.getAllCalleeProcedures()",
);
expect(bridgeSource).not.toContain(
"_procedure_name(item) for item in procedure.getAllCallerProcedures()",
);
expect(bridgeSource).not.toContain(
"_procedure_name(item) for item in procedure.getAllCalleeProcedures()",
);
});
});
+90
View File
@@ -0,0 +1,90 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { describe, expect, it } from "vitest";
import { sanitizeCliOutput } from "../src/cliOutput.js";
const execFileAsync = promisify(execFile);
describe("CLI output boundary", () => {
it("preserves normal output and sanitizes text and JSON validation errors", () => {
expect(sanitizeCliOutput("result: ok\n")).toBe("result: ok\n");
expect(sanitizeCliOutput("result: VALIDATION_ERROR\n")).toBe(
"result: VALIDATION_ERROR\n",
);
const raw =
'code: VALIDATION_ERROR\nmessage: "raw Zod details"\nfieldErrors: SECRET\n';
expect(sanitizeCliOutput(raw)).toBe(
'code: VALIDATION_ERROR\nmessage: "REA could not read the command arguments. Run `rea --help`, correct the arguments, then try again."\n',
);
expect(
JSON.parse(
sanitizeCliOutput(
JSON.stringify({
code: "VALIDATION_ERROR",
message: "raw Zod details",
fieldErrors: [{ code: "invalid_type" }],
}),
),
),
).toEqual({
code: "VALIDATION_ERROR",
message:
"REA could not read the command arguments. Run `rea --help`, correct the arguments, then try again.",
});
expect(
JSON.parse(
sanitizeCliOutput(
JSON.stringify({
ok: false,
error: {
code: "VALIDATION_ERROR",
message: "raw Zod details",
fieldErrors: [{ code: "invalid_type" }],
},
meta: { command: "analyze" },
}),
),
),
).toEqual({
ok: false,
error: {
code: "VALIDATION_ERROR",
message:
"REA could not read the command arguments. Run `rea --help`, correct the arguments, then try again.",
},
meta: { command: "analyze" },
});
});
it("sanitizes a real missing-argument dispatcher failure", async () => {
await expect(
execFileAsync(process.execPath, ["scripts/rea.mjs", "analyze"], {
cwd: process.cwd(),
}),
).rejects.toMatchObject({
stdout:
'code: VALIDATION_ERROR\nmessage: "REA could not read the command arguments. Run `rea --help`, correct the arguments, then try again."\n',
});
await expect(
execFileAsync(
process.execPath,
["scripts/rea.mjs", "--full-output", "--json", "analyze"],
{ cwd: process.cwd() },
),
).rejects.toMatchObject({
stdout: expect.not.stringContaining("fieldErrors"),
});
await expect(
execFileAsync(
process.execPath,
["scripts/rea.mjs", "--full-output", "analyze"],
{ cwd: process.cwd() },
),
).rejects.toMatchObject({
stdout:
'ok: false\nerror:\n code: VALIDATION_ERROR\n message: "REA could not read the command arguments. Run `rea --help`, correct the arguments, then try again."\n',
});
});
});
+7
View File
@@ -62,6 +62,13 @@ describe("runtime configuration", () => {
maxStringLength: 1024 * 1024,
maxNodes: 1_000_000,
},
analysisSnapshotFilePolicy: {
roots: [],
maxBytes: 64 * 1024 * 1024,
maxDepth: 64,
maxStringLength: 1024 * 1024,
maxNodes: 1_000_000,
},
referenceSourcePolicy: {
roots: [],
secretPatterns: [],
+31
View File
@@ -14,6 +14,19 @@ import {
sessionOutputSchemas,
} from "../src/contracts/toolOutputSchemas.js";
const emptySchemaPaths = (value: unknown, path = "$"): string[] => {
if (Array.isArray(value))
return value.flatMap((item, index) =>
emptySchemaPaths(item, `${path}[${String(index)}]`),
);
if (typeof value !== "object" || value === null) return [];
const entries = Object.entries(value);
if (entries.length === 0) return [path];
return entries.flatMap(([key, item]) =>
emptySchemaPaths(item, `${path}.${key}`),
);
};
describe("tool contract surface", () => {
it("advertises complete typed schemas and annotations for all analysis tools", () => {
const contracts = [
@@ -122,4 +135,22 @@ describe("tool contract surface", () => {
expect(contract.description).toMatch(/[.;]/u);
}
});
it("publishes no unconstrained output-schema holes across all 68 tools", () => {
const contracts = [
...OFFICIAL_TOOL_CONTRACTS,
...ENHANCED_TOOL_CONTRACTS,
...NATIVE_TOOL_CONTRACTS,
...ARTIFACT_TOOL_CONTRACTS,
...SESSION_TOOL_CONTRACTS,
];
expect(contracts).toHaveLength(68);
for (const contract of contracts) {
const schema = z.toJSONSchema(contract.outputSchema, {
target: "draft-07",
unrepresentable: "any",
});
expect(emptySchemaPaths(schema), contract.name).toEqual([]);
}
});
});
+22
View File
@@ -14,6 +14,28 @@ const host = (overrides: Partial<DoctorHost> = {}): DoctorHost => ({
});
describe("doctor", () => {
it("returns exact recovery for every failed diagnostic", async () => {
const result = await runDoctor(
"/missing/app",
host({
nodeVersion: "20.0.0",
macosVersion: () => Promise.resolve("11.7"),
executable: () => Promise.resolve(false),
validTarget: () => Promise.resolve(false),
}),
);
expect(
Object.fromEntries(
result.checks.map(({ name, remediation }) => [name, remediation]),
),
).toEqual({
node: "Install Node.js 22.19+ or 24.11+.",
host: "REA supports macOS 12+, Ubuntu 24.04+, Fedora 41+, and 64-bit Arch Linux.",
hopper: "Run rea setup to install Hopper, or set HOPPER_LAUNCHER_PATH.",
target: "Supply a readable local app or program path.",
});
});
it.each(["11.7", undefined])(
"rejects unsupported macOS version %s",
async (version) => {
+16 -12
View File
@@ -311,9 +311,9 @@ describe("enhanced MCP tools", () => {
address: "0x2",
status: "error",
error: {
tag: "AnalysisOutputError",
message: "Invalid analysis output for decompile: failed",
details: { operation: "decompile", reason: "failed" },
category: "execution_failure",
message:
"Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.",
},
},
],
@@ -352,7 +352,11 @@ describe("enhanced MCP tools", () => {
{
address: "0x1",
status: "error",
error: { tag: "AnalysisOutputError" },
error: {
category: "execution_failure",
message:
"Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.",
},
},
],
},
@@ -551,8 +555,8 @@ describe("enhanced MCP tools", () => {
});
expect(result.isError).toBe(true);
const text = result.content.find((item) => item.type === "text");
expect(text?.type === "text" ? text.text : "").toContain(
"non-advancing pagination offset",
expect(text?.type === "text" ? text.text : "").toBe(
"Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.",
);
});
@@ -598,8 +602,8 @@ describe("enhanced MCP tools", () => {
});
expect(result.isError).toBe(true);
const text = result.content.find((item) => item.type === "text");
expect(text?.type === "text" ? text.text : "").toContain(
"HopperProtocolError",
expect(text?.type === "text" ? text.text : "").toBe(
"Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.",
);
});
@@ -619,8 +623,8 @@ describe("enhanced MCP tools", () => {
});
expect(result.isError).toBe(true);
const text = result.content.find((item) => item.type === "text");
expect(text?.type === "text" ? text.text : "").toContain(
"AnalysisOutputError",
expect(text?.type === "text" ? text.text : "").toBe(
"Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.",
);
});
@@ -655,8 +659,8 @@ describe("enhanced MCP tools", () => {
});
expect(result.isError).toBe(true);
const text = result.content.find((item) => item.type === "text");
expect(text?.type === "text" ? text.text : "").toContain(
"AnalysisOutputError",
expect(text?.type === "text" ? text.text : "").toBe(
"Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.",
);
});
+34 -9
View File
@@ -37,7 +37,7 @@ describe("analysis error projection", () => {
);
});
it("exhaustively projects stable tags without causes or local paths", () => {
it("projects every typed failure without internal details", () => {
const secretCause = new Error("secret-token");
const byTag = {
AnalysisProtocolError: new AnalysisProtocolError("protocol failed"),
@@ -103,17 +103,42 @@ describe("analysis error projection", () => {
} satisfies Readonly<Record<AnalysisErrorTag, AnalysisError>>;
const errors = Object.values(byTag);
const projected = errors.map(projectAnalysisError);
expect(new Set(projected.map(({ tag }) => tag)).size).toBe(errors.length);
expect(projected).toHaveLength(24);
expect(JSON.stringify(projected)).not.toContain("secret-token");
expect(JSON.stringify(projected)).not.toContain("/secret/local/path");
const serialized = JSON.stringify(projected);
for (const hidden of [
"secret-token",
"/secret/local/path",
"fixture",
"overview",
"AnalysisCapabilityUnavailableError",
"main.js",
"declaredSha256",
])
expect(serialized).not.toContain(hidden);
expect(
projected.find(({ tag }) => tag === "HopperTimeoutError"),
).toMatchObject({ details: { timeoutMs: 100 } });
expect(
projected.find(({ tag }) => tag === "ProviderAdapterError"),
projectAnalysisError(byTag.AnalysisCapabilityUnavailableError),
).toMatchObject({
details: { providerId: "fixture", operation: "overview" },
category: "unsupported_provider",
});
expect(
projectAnalysisError(
new ArtifactOperationError("inventory_artifact", "integrity", {
logicalPath: "main.js",
declaredSha256: "a".repeat(64),
calculatedSha256: "b".repeat(64),
unpacked: true,
}),
),
).toMatchObject({
category: "integrity_mismatch",
});
expect(projected.every(({ message }) => message.length > 0)).toBe(true);
expect(
projected.every(({ message }) =>
/try again|run `rea doctor`|current target|when ready|smaller request|smaller artifact|fresh copy|re-import|reduce|inline evidence|configured evidence directory|evidence file|allow overwrite|refresh the current state|reported setting|call open_binary|supported file|review capture policy/u.test(
message,
),
),
).toBe(true);
});
});
+62
View File
@@ -0,0 +1,62 @@
"""Execute REA's bridge regex helpers without starting a Hopper socket."""
import json
from pathlib import Path
import sys
def _load_bridge(path):
source = Path(path).read_text(encoding="utf-8")
prefix, marker, suffix = source.rpartition("\n_run()")
if not marker or suffix.strip():
raise RuntimeError("bridge entrypoint shape changed")
namespace = {"__file__": path}
exec(compile(prefix, path, "exec"), namespace)
return namespace
def _probe(namespace, payload):
action = payload["action"]
try:
if action == "match":
parsed = namespace["sre_parse"].parse(payload["pattern"])
paths, steps = namespace["_validate_regex_node"](parsed)
flags = (
0
if payload.get("case_sensitive", False)
else namespace["re"].IGNORECASE
)
expression = namespace["re"].compile(payload["pattern"], flags)
matcher = namespace["_bounded_regex_matcher"](expression, paths, steps)
matched = matcher(payload["value"])
return {
"action": action,
"ok": True,
"backtracking_paths": paths,
"matched": matched,
}
if action == "search":
inventory = tuple(tuple(item) for item in payload["items"])
namespace["_search_inventory"] = lambda _document, _kind: inventory
return {
"action": action,
"ok": True,
"result": namespace["_search_page"](
object(), "string", payload["params"]
),
}
raise ValueError("unknown probe action")
except Exception as error:
return {
"action": action,
"ok": False,
"type": type(error).__name__,
"diagnostic_type": namespace["_diagnostic_type"](error),
"message": str(error),
}
if __name__ == "__main__":
bridge = _load_bridge(sys.argv[1])
request = json.loads(sys.argv[2])
print(json.dumps(_probe(bridge, request), sort_keys=True))
+8 -1
View File
@@ -126,7 +126,14 @@ const server = createServer((socket) => {
true,
);
} else if (request.method === "shutdown") {
send({ id: request.id, result: { shutdown: true } });
send({
id: request.id,
result: {
shutdown: true,
analysis_stopped: true,
document_closed: true,
},
});
setTimeout(() => server.close(), 2);
} else if (request.method === "hang") {
// Deliberately leave the request pending.
+11 -1
View File
@@ -56,7 +56,17 @@ describe("function comparison MCP integration", () => {
arguments: { domain: "function-comparison" },
});
expect(unknowns.structuredContent).toMatchObject({
result: [expect.objectContaining({ domain: "function-comparison" })],
result: [
expect.objectContaining({
domain: "function-comparison",
recommended_probes: [
expect.objectContaining({
rationale:
"Capture complete dossiers for both functions under the same target context and analysis limits.",
}),
],
}),
],
});
} finally {
await Promise.allSettled([
+97 -6
View File
@@ -6,6 +6,7 @@ import {
readFile,
readdir,
rm,
symlink,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
@@ -64,14 +65,94 @@ describe("curl installer scenarios", () => {
});
it.each([
["unsupported Node", { FAKE_NODE_VERSION: "20.0.0" }, "unsupported"],
["npm failure", { FAKE_NPM_FAIL: "1" }, "npm package installation failed"],
["version mismatch", { FAKE_REA_VERSION: "9.9.9" }, "does not match"],
[
"unsupported Node",
{ FAKE_NODE_VERSION: "20.0.0" },
"REA installation failed: Node.js 20.0.0 is unsupported; use Node.js 22.19+ or 24.11+.\n",
],
[
"npm failure",
{ FAKE_NPM_FAIL: "1" },
"REA installation failed: npm could not install REA. Check registry access and npm permissions, then retry.\n",
],
[
"version mismatch",
{ FAKE_REA_VERSION: "9.9.9" },
"REA installation failed: installed version 9.9.9 does not match 0.3.0.\n",
],
] as const)("fails closed on %s", async (_name, overrides, message) => {
const fixture = await createFixture();
await expect(
runInstaller(fixture, ["--version", "0.3.0"], overrides),
).rejects.toMatchObject({ stderr: expect.stringContaining(message) });
).rejects.toMatchObject({ stderr: message });
});
it.each([
[
"unreadable Node version",
["--version", "0.3.0"],
{ FAKE_NODE_VERSION: "invalid" },
"REA installation failed: the active Node.js version could not be read. Check that node works and is on PATH, then retry.\n",
],
[
"release lookup",
[],
{ FAKE_CURL_FAIL: "1" },
"REA installation failed: the latest REA release could not be resolved. Check network access or pass --version VERSION, then retry.\n",
],
[
"release response",
[],
{ FAKE_CURL_BODY: "not-json" },
"REA installation failed: the release response was invalid. Retry later or pass --version VERSION.\n",
],
[
"release tag",
[],
{ FAKE_CURL_BODY: '{"tag_name":"unrelated-1.0.0"}' },
"REA installation failed: the latest release tag was invalid. Retry later or pass --version VERSION.\n",
],
[
"npm prefix",
["--version", "0.3.0"],
{ FAKE_PLATFORM: "Darwin", FAKE_NPM_PREFIX_FAIL: "1" },
"REA installation failed: the npm global prefix could not be read. Repair the npm configuration, then retry.\n",
],
[
"missing installed command",
["--version", "0.3.0"],
{ FAKE_NPM_SKIP_BINARY: "1" },
"REA installation failed: npm completed without installing the rea command. Check the npm global bin directory and PATH, then retry.\n",
],
[
"unreadable installed version",
["--version", "0.3.0"],
{ FAKE_REA_VERSION_FAIL: "1" },
"REA installation failed: the installed REA version could not be read. Reinstall the requested version, then retry.\n",
],
] as const)(
"reports exact recovery for %s failure",
async (_name, args, overrides, message) => {
const fixture = await createFixture();
await expect(
runInstaller(fixture, args, overrides),
).rejects.toMatchObject({
stderr: message,
});
},
);
it("reports exact recovery when curl is missing", async () => {
const fixture = await createFixture();
await rm(join(fixture.bin, "curl"));
await expect(
runInstaller(fixture, ["--version", "0.3.0"], {
PATH: fixture.bin,
}),
).rejects.toMatchObject({
stderr:
"REA installation failed: curl is required. Install curl, then rerun this installer.\n",
});
});
});
@@ -94,7 +175,7 @@ const createFixture = async (): Promise<InstallerFixture> => {
await Promise.all([mkdir(home), mkdir(bin), mkdir(temporary)]);
await executable(
join(bin, "uname"),
'#!/bin/sh\n[ "$1" = "-m" ] && echo x86_64 || echo Linux\n',
'#!/bin/sh\n[ "$1" = "-m" ] && echo x86_64 || printf \'%s\\n\' "${FAKE_PLATFORM:-Linux}"\n',
);
await executable(
join(bin, "node"),
@@ -106,12 +187,14 @@ if [ "$1" = "-p" ]; then printf '%s\n' "\${FAKE_NODE_VERSION:-24.18.0}"; else ex
join(bin, "npm"),
`#!/bin/sh
printf '%s\n' "$*" >> "$FAKE_NPM_LOG"
[ "$1" = "prefix" ] && { [ "\${FAKE_NPM_PREFIX_FAIL:-}" = "1" ] && exit 1; printf '%s\n' "$FAKE_NPM_PREFIX"; exit 0; }
[ "\${FAKE_NPM_FAIL:-}" = "1" ] && exit 1
prefix="$HOME/.local"
while [ "$#" -gt 0 ]; do
if [ "$1" = "--prefix" ]; then shift; prefix="$1"; fi
shift
done
[ "\${FAKE_NPM_SKIP_BINARY:-}" = "1" ] && exit 0
mkdir -p "$prefix/bin"
cp "$FAKE_REA_SOURCE" "$prefix/bin/rea"
chmod +x "$prefix/bin/rea"
@@ -119,15 +202,22 @@ chmod +x "$prefix/bin/rea"
);
await executable(
join(bin, "curl"),
'#!/bin/sh\nprintf \'{"tag_name":"rea-agents-0.3.0"}\'\n',
`#!/bin/sh
[ "\${FAKE_CURL_FAIL:-}" = "1" ] && exit 1
if [ -n "\${FAKE_CURL_BODY:-}" ]; then printf '%s' "$FAKE_CURL_BODY"; else printf '%s' '{"tag_name":"rea-agents-0.3.0"}'; fi
`,
);
await executable(
join(bin, "rea-source"),
`#!/bin/sh
printf '%s\n' "$*" >> "$FAKE_REA_LOG"
[ "\${FAKE_REA_VERSION_FAIL:-}" = "1" ] && exit 1
[ "$1" = "--version" ] && printf '%s\n' "\${FAKE_REA_VERSION:-0.3.0}"
exit 0
`,
);
for (const command of ["chmod", "cp", "mkdir", "tr"])
await symlink(`/usr/bin/${command}`, join(bin, command));
return { home, bin, temporary, npmLog, reaLog };
};
@@ -150,6 +240,7 @@ const runInstaller = async (
FAKE_NPM_LOG: fixture.npmLog,
FAKE_REA_LOG: fixture.reaLog,
FAKE_REA_SOURCE: join(fixture.bin, "rea-source"),
FAKE_NPM_PREFIX: join(fixture.home, ".npm-global"),
...overrides,
},
});
@@ -23,6 +23,7 @@ describe("configuration parsing integration", () => {
HOPPER_TARGET_KIND: "executable",
HOPPER_LOADER_ARGS_JSON: '["-l","Mach-O","--aarch64"]',
REA_EVIDENCE_ROOTS_JSON: '["/tmp/evidence"]',
REA_ANALYSIS_SNAPSHOT_ROOTS_JSON: '["/tmp/analysis"]',
});
expect(result.ok).toBe(true);
if (!result.ok) throw new Error("unreachable");
@@ -34,6 +35,9 @@ describe("configuration parsing integration", () => {
"--aarch64",
]);
expect(result.value.evidenceFilePolicy.roots).toEqual(["/tmp/evidence"]);
expect(result.value.analysisSnapshotFilePolicy.roots).toEqual([
"/tmp/analysis",
]);
});
it("rejects target kind values outside the enum", () => {
+22 -5
View File
@@ -252,6 +252,11 @@ describe("full MCP integration with multi-tool sequences", () => {
},
});
expect(unavailable.isError).toBe(true);
expect(structured(unavailable)).toMatchObject({
error: {
category: "unsupported_provider",
},
});
expect(received[0]).not.toHaveProperty("unknown_registry_approved");
expect(
structured(
@@ -260,9 +265,15 @@ describe("full MCP integration with multi-tool sequences", () => {
).toMatchObject({
result: [
{
domain: "provider-capability",
domain: "analysis-capability",
question:
"procedure_pseudo_code is unavailable: Decompiler is not installed.",
"The requested analysis is unavailable for the current target.",
recommended_probes: [
{
rationale:
"Choose another analysis or target that can answer this question.",
},
],
},
],
});
@@ -354,7 +365,7 @@ describe("full MCP integration with multi-tool sequences", () => {
expect(names).not.toContain("open_binary");
});
it("propagates remote Hopper errors with structured content", async () => {
it("projects remote failures without provider or bridge details", async () => {
const client = await connect({
execute: () =>
Promise.resolve(err(new HopperRemoteError(-32000, "bridge timeout"))),
@@ -365,8 +376,14 @@ describe("full MCP integration with multi-tool sequences", () => {
arguments: {},
});
expect(result.isError).toBe(true);
expect(text(result)).toContain("HopperRemoteError");
expect(text(result)).toContain("bridge timeout");
expect(structured(result)).toMatchObject({
error: {
category: "execution_failure",
},
});
expect(text(result)).toBe(
"Analysis could not complete. Retry once; if it continues, run `rea doctor`.",
);
});
it("handles concurrent tool calls without corruption", async () => {
+131 -7
View File
@@ -14,7 +14,8 @@ import {
PROCESS_CAPTURE_REFERENCE,
PROCESS_COMPARISON_EVIDENCE,
} from "../src/contracts/investigationExamples.js";
import { parseEvidence } from "../src/domain/evidence.js";
import { createEvidence, parseEvidence } from "../src/domain/evidence.js";
import { jsonObjectSchema, jsonValueSchema } from "../src/domain/jsonValue.js";
import { createServer } from "../src/server/createServer.js";
import { observed } from "./fixtures/analysisExecution.js";
import { readInvestigationWorkspace } from "../src/application/InvestigationWorkspaceStore.js";
@@ -102,7 +103,7 @@ describe("investigation MCP workflows", () => {
unknown_registry_approved: true,
},
});
expect(response.isError).not.toBe(true);
expect(response.isError, JSON.stringify(response)).not.toBe(true);
const evidence = parseEvidence(
z.object({ result: z.unknown() }).parse(response.structuredContent)
.result,
@@ -111,9 +112,14 @@ describe("investigation MCP workflows", () => {
provider: { id: "rea-changed-behavior" },
normalized_result: { behavior_status: "unknown" },
});
expect(session.listUnknowns({ domain: "changed-behavior" })).toHaveLength(
1,
);
expect(
session.listUnknowns({ domain: "changed-behavior" }),
).toMatchObject([
{
question:
"Did both versions behave the same under a complete controlled replay?",
},
]);
} finally {
await close(session, server, client);
}
@@ -148,6 +154,66 @@ describe("investigation MCP workflows", () => {
}
});
it("records a safe unresolved call-path question", async () => {
const { session, server, client } = await connected();
const base = FUNCTION_COMPARISON_EXAMPLE.left;
if (base.subject === null) throw new Error("missing dossier subject");
const dossier = createEvidence(
{
path: base.subject.local_path,
sha256: base.subject.digest.sha256,
format: base.subject.format,
...(base.subject.architecture === null
? {}
: { architecture: base.subject.architecture }),
},
base.provider,
{
predicateType: base.predicate_type,
operation: base.operation,
parameters: base.parameters,
result: jsonValueSchema.parse({
...jsonObjectSchema.parse(base.normalized_result),
callees: {
items: [{ address: "0x2000", name: "next" }],
total: 1,
returned: 1,
truncated: false,
next_offset: null,
},
}),
rawResult: base.raw_result,
confidence: base.confidence,
authority: base.authority,
limitations: base.limitations,
locations: base.locations,
evidenceLinks: base.evidence_links,
},
);
expect(session.recordEvidence(dossier).ok).toBe(true);
try {
const response = await client.callTool({
name: "build_call_path",
arguments: {
...INVESTIGATION_EXAMPLES.build_call_path,
functions: [dossier],
start: { address: "0x1000" },
goal: { address: "0x3000" },
unknown_registry_approved: true,
},
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
expect(session.listUnknowns({ domain: "call-path" })).toMatchObject([
{
question:
"Can the requested call path be established from complete analysis?",
},
]);
} finally {
await close(session, server, client);
}
});
it("records an explicit non-causal static/runtime hypothesis", async () => {
const { session, server, client } = await connected();
for (const evidence of [
@@ -182,6 +248,51 @@ describe("investigation MCP workflows", () => {
}
});
it("records a safe unresolved static/runtime question", async () => {
const { session, server, client } = await connected();
for (const evidence of [
FUNCTION_COMPARISON_EXAMPLE.left,
FUNCTION_COMPARISON_EXAMPLE.right,
FUNCTION_COMPARISON_EVIDENCE,
PROCESS_CAPTURE_REFERENCE,
PROCESS_CAPTURE_RECONSTRUCTION,
PROCESS_COMPARISON_EVIDENCE,
])
expect(session.recordEvidence(evidence).ok).toBe(true);
const mapping =
INVESTIGATION_EXAMPLES.correlate_static_and_runtime.mappings[0];
if (mapping === undefined) throw new Error("missing correlation fixture");
try {
const response = await client.callTool({
name: "correlate_static_and_runtime",
arguments: {
...INVESTIGATION_EXAMPLES.correlate_static_and_runtime,
mappings: [
{
...mapping,
static: {
...mapping.static,
selector: { kind: "function", dimension: "assembly" },
},
},
],
unknown_registry_approved: true,
},
});
expect(response.isError).not.toBe(true);
expect(
session.listUnknowns({ domain: "static-runtime-correlation" }),
).toMatchObject([
{
question:
"Does runtime behavior match the available static analysis?",
},
]);
} finally {
await close(session, server, client);
}
});
it("passes only the finite declared reconstruction specification", async () => {
const { session, server, client } = await connected();
for (const evidence of [
@@ -193,7 +304,10 @@ describe("investigation MCP workflows", () => {
try {
const response = await client.callTool({
name: "verify_reconstruction",
arguments: INVESTIGATION_EXAMPLES.verify_reconstruction,
arguments: {
...INVESTIGATION_EXAMPLES.verify_reconstruction,
unknown_registry_approved: true,
},
});
expect(response.isError).not.toBe(true);
const evidence = parseEvidence(
@@ -243,7 +357,10 @@ describe("investigation MCP workflows", () => {
try {
const response = await client.callTool({
name: "verify_reconstruction",
arguments: INVESTIGATION_EXAMPLES.verify_reconstruction,
arguments: {
...INVESTIGATION_EXAMPLES.verify_reconstruction,
unknown_registry_approved: true,
},
});
expect(response.isError).not.toBe(true);
const evidence = parseEvidence(
@@ -254,6 +371,13 @@ describe("investigation MCP workflows", () => {
status: "unknown",
summary: { unknown: 1 },
});
expect(
session.listUnknowns({ domain: "reconstruction-verification" }),
).toContainEqual(
expect.objectContaining({
question: "Does the reconstruction satisfy every declared claim?",
}),
);
} finally {
await close(session, server, client);
}
+109
View File
@@ -0,0 +1,109 @@
import type { ServeStdioOptions } from "@modelcontextprotocol/server/stdio";
import { describe, expect, it } from "vitest";
import { run, runEntrypoint } from "../src/main.js";
type RuntimeDependencies = NonNullable<Parameters<typeof run>[0]>;
const nextTurn = (): Promise<void> =>
new Promise((resolve) => setImmediate(resolve));
const dependencies = (
serve: RuntimeDependencies["serve"],
output: string[],
shutdown: Array<() => void>,
exitCodes: number[],
): RuntimeDependencies => ({
env: {},
serve,
writeStderr: (text) => output.push(text),
setExitCode: (code) => exitCodes.push(code),
registerShutdown: (handler) => shutdown.push(handler),
});
describe("MCP runtime errors", () => {
it("reports connection loss without the transport cause", async () => {
const output: string[] = [];
const shutdown: Array<() => void> = [];
let options: ServeStdioOptions | undefined;
let closeCalls = 0;
const close = (): Promise<void> => {
closeCalls += 1;
return Promise.resolve();
};
const exitCodes: number[] = [];
expect(
await run(
dependencies(
(_factory, received) => {
options = received;
return { close };
},
output,
shutdown,
exitCodes,
),
),
).toBe(0);
options?.onerror?.(new Error("SECRET transport stack"));
expect(output).toEqual([
"REA lost its MCP client connection. Restart REA from your MCP client.\n",
]);
shutdown[0]?.();
await nextTurn();
expect(closeCalls).toBe(1);
});
it("reports transport startup failure without its cause", async () => {
const output: string[] = [];
expect(
await run(
dependencies(
() => {
throw new Error("SECRET startup stack");
},
output,
[],
[],
),
),
).toBe(1);
expect(output).toEqual([
"REA could not start its MCP connection. Restart REA from your MCP client; run `rea doctor` if it fails again.\n",
]);
});
it("reports shutdown failure and sets a failing exit code", async () => {
const output: string[] = [];
const shutdown: Array<() => void> = [];
const exitCodes: number[] = [];
await run(
dependencies(
() => ({ close: () => Promise.reject(new Error("SECRET close")) }),
output,
shutdown,
exitCodes,
),
);
shutdown[0]?.();
await nextTurn();
expect(exitCodes).toEqual([1]);
expect(output).toEqual([
"REA could not close cleanly. End the REA process before starting it again.\n",
]);
});
it("reports an unexpected entrypoint failure without its cause", async () => {
const output: string[] = [];
const exitCodes: number[] = [];
await runEntrypoint(
() => Promise.reject(new Error("SECRET entrypoint stack")),
(text) => output.push(text),
(code) => exitCodes.push(code),
);
expect(output).toEqual([
"REA could not start. Run `rea doctor`, then restart REA from your MCP client.\n",
]);
expect(exitCodes).toEqual([1]);
});
});
+1 -1
View File
@@ -199,7 +199,7 @@ describe("official Hopper proxy tools", () => {
expect(result.content).toEqual([
{
type: "text",
text: "HopperRemoteError: Hopper request failed (-1): denied",
text: "Analysis could not complete. Retry once; if it continues, run `rea doctor`.",
},
]);
});
+164
View File
@@ -0,0 +1,164 @@
import { mkdtemp, open, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { afterEach, describe, expect, it } from "vitest";
import {
captureProcessScenarioFile,
compareProcessEvidenceFiles,
projectProcessCliError,
} from "../src/application/ProcessCli.js";
import { createEvidence } from "../src/domain/evidence.js";
import { PROCESS_PROVIDER } from "../src/application/ProcessEvidence.js";
const roots: string[] = [];
const execFileAsync = promisify(execFile);
afterEach(async () => {
await Promise.all(
roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
);
});
const fixture = async (): Promise<string> => {
const root = await mkdtemp(join(tmpdir(), "rea-process-cli-"));
roots.push(root);
return root;
};
describe("process CLI errors", () => {
it("exits unsuccessfully without writing failure-shaped evidence", async () => {
await expect(
execFileAsync(
process.execPath,
["scripts/rea.mjs", "capture-process", "/missing/scenario.json"],
{ cwd: process.cwd() },
),
).rejects.toMatchObject({
code: 1,
stdout: expect.stringContaining("PROCESS_COMMAND_FAILED"),
});
});
it("projects unexpected causes without their message or stack", () => {
const projected = projectProcessCliError(
new Error("SECRET internal failure /private/path"),
);
expect(projected).toEqual({
error: "Process command failed",
category: "execution_failure",
message:
"Process command could not complete. Check the input files and run `rea doctor`, then try again.",
});
expect(JSON.stringify(projected)).not.toContain("SECRET");
});
it("projects missing, malformed JSON, and invalid scenario files", async () => {
const root = await fixture();
const malformed = join(root, "malformed.json");
const invalid = join(root, "invalid.json");
await writeFile(malformed, "not-json");
await writeFile(invalid, "{}");
expect(
await captureProcessScenarioFile(join(root, "missing.json")),
).toEqual({
error: "Process command failed",
category: "invalid_input",
message:
"Process input file could not be read. Check that the path exists and is readable.",
});
expect(await captureProcessScenarioFile(malformed)).toEqual({
error: "Process command failed",
category: "invalid_input",
message:
"Process input file is not valid JSON. Repair the file, then try again.",
});
expect(await captureProcessScenarioFile(invalid)).toEqual({
error: "Process command failed",
category: "invalid_input",
message:
"Process scenario is invalid. Check its required fields and limits, then try again.",
});
});
it("reports the exact process-capture policy recovery", async () => {
const root = await fixture();
const scenario = join(root, "scenario.json");
await writeFile(
scenario,
JSON.stringify({
approved: true,
executable: "/bin/sh",
working_directory: "/tmp",
}),
);
expect(await captureProcessScenarioFile(scenario)).toEqual({
error: "Process command failed",
category: "permission_required",
message:
"Process capture is disabled. Set `REA_PROCESS_CAPTURE_ENABLED=true`, configure approved roots, then restart REA.",
});
});
it("rejects oversized process input before parsing", async () => {
const root = await fixture();
const path = join(root, "large.json");
const handle = await open(path, "w");
await handle.truncate(64 * 1024 * 1024 + 1);
await handle.close();
expect(await captureProcessScenarioFile(path)).toEqual({
error: "Process command failed",
category: "truncated",
message:
"Process input file is too large. Reduce it below 64 MiB, then try again.",
});
});
it("explains unsupported and unrelated capture evidence", async () => {
const root = await fixture();
const legacy = join(root, "legacy.json");
const unrelated = join(root, "unrelated.json");
await writeFile(
legacy,
JSON.stringify(
createEvidence(undefined, PROCESS_PROVIDER, {
predicateType: "rea.process-capture/v3",
operation: "capture_process_scenario",
parameters: {},
result: {},
}),
),
);
await writeFile(
unrelated,
JSON.stringify(
createEvidence(undefined, PROCESS_PROVIDER, {
predicateType: "unrelated/v1",
operation: "other",
parameters: {},
result: {},
}),
),
);
const legacyResult = await compareProcessEvidenceFiles(legacy, legacy);
expect(legacyResult).toMatchObject({
error: "Process command failed",
category: "invalid_input",
});
expect(JSON.stringify(legacyResult)).toContain(
"Process Capture v3 is unsupported",
);
expect(await compareProcessEvidenceFiles(unrelated, unrelated)).toEqual({
error: "Process command failed",
category: "invalid_input",
message:
"Capture evidence is not from the current process-capture workflow. Create new capture evidence, then try again.",
});
});
});
+51
View File
@@ -7,6 +7,11 @@ import { add, commit, init } from "isomorphic-git";
import { describe, expect, it } from "vitest";
import { importReferenceSource } from "../src/application/ReferenceSourceImport.js";
import { projectReferenceSourceEntryFailure } from "../src/application/ReferenceSourceImportEntries.js";
import {
projectReferenceSourceImportError,
type ReferenceSourceImportError,
} from "../src/application/ReferenceSourceImportTypes.js";
import { createHistoricalSourceManifest } from "../src/domain/referenceSourceGraph.js";
const limits = {
@@ -43,6 +48,52 @@ const importTree = (root: string, approvedRoot: string, signal?: AbortSignal) =>
});
describe("reference source import", () => {
it("projects entry failures without low-level reader diagnostics", () => {
for (const [kind, code] of [
["directory", "io"],
["symlink", "io"],
["file", "io"],
["file", "cancelled"],
["file", "limit"],
["unknown", "unsupported"],
] as const) {
const message = projectReferenceSourceEntryFailure({
status: "failed",
path: "safe/path",
kind,
code,
message: "SECRET internal diagnostic /private/path",
});
expect(message).not.toContain("SECRET");
expect(message).not.toContain("/private/path");
expect(message).toMatch(/Check|try again|when ready|smaller|supported/u);
}
});
it("projects every import failure without raw parser or policy text", () => {
const expectedCategories = {
cancelled: "cancelled",
"invalid-limits": "invalid_input",
"invalid-root": "invalid_input",
io: "execution_failure",
parse: "execution_failure",
policy: "permission_required",
} as const;
for (const [code, category] of Object.entries(expectedCategories)) {
const projected = projectReferenceSourceImportError({
tag: "reference-source-import",
code: code as ReferenceSourceImportError["code"],
message: "SECRET parser stack and /private/path",
});
expect(projected.category).toBe(category);
expect(projected.message).not.toContain("SECRET");
expect(projected.message).not.toContain("/private/path");
expect(projected.message).toMatch(
/try again|when ready|positive integer|Check that|REA_REFERENCE_ROOTS_JSON/u,
);
}
});
it("is relocation-stable, resolves imports, and excludes secrets before capture", async () => {
const parent = await mkdtemp(join(tmpdir(), "rea-reference-import-"));
try {
+53 -6
View File
@@ -1,4 +1,4 @@
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
@@ -45,6 +45,13 @@ describe("target-free MCP lifecycle", () => {
maxStringLength: 1024,
maxNodes: 10_000,
},
analysisSnapshotFilePolicy: {
roots: [directory],
maxBytes: 1024 * 1024,
maxDepth: 68,
maxStringLength: 1024,
maxNodes: 10_000,
},
});
const mcp = new Client({ name: "session-test", version: "1.0.0" });
const [clientTransport, serverTransport] =
@@ -58,7 +65,9 @@ describe("target-free MCP lifecycle", () => {
arguments: {},
});
expect(before.isError).toBe(true);
expect(text(before)).toContain("NoBinaryOpenError");
expect(text(before)).toBe(
"No app is open. Ask the user which app to investigate, then call open_binary with its local path.",
);
expect((await mcp.listTools()).tools).toHaveLength(68);
const deniedCapture = await mcp.callTool({
name: "capture_process_scenario",
@@ -69,7 +78,14 @@ describe("target-free MCP lifecycle", () => {
},
});
expect(deniedCapture.isError).toBe(true);
expect(text(deniedCapture)).toContain("process capture is disabled");
expect(structured(deniedCapture)).toMatchObject({
error: {
category: "permission_required",
},
});
expect(text(deniedCapture)).toBe(
"Process capture is disabled. Set `REA_PROCESS_CAPTURE_ENABLED=true`, configure approved roots, then restart REA.",
);
expect(
(await mcp.callTool({ name: "open_binary", arguments: { path: first } }))
.isError,
@@ -171,10 +187,42 @@ describe("target-free MCP lifecycle", () => {
expect(
text(await mcp.callTool({ name: "binary_session", arguments: {} })),
).toContain("second.hop");
await mcp.callTool({ name: "close_binary", arguments: {} });
const snapshotPath = join(directory, "analysis.json");
expect(
structured(
await mcp.callTool({
name: "close_binary",
arguments: { snapshot_path: snapshotPath },
}),
).result,
).toMatchObject({ path: snapshotPath, entries: 0 });
expect(JSON.parse(await readFile(snapshotPath, "utf8"))).toMatchObject({
evidence_bundle: { records: [], unknowns: [] },
});
expect(
text(await mcp.callTool({ name: "binary_session", arguments: {} })),
).toContain('"open": false');
expect(
(
await mcp.callTool({
name: "open_binary",
arguments: { path: first, snapshot_path: snapshotPath },
})
).isError,
).toBe(true);
expect(
structured(await mcp.callTool({ name: "list_unknowns", arguments: {} }))
.result,
).toEqual([]);
expect(
(
await mcp.callTool({
name: "open_binary",
arguments: { path: second, snapshot_path: snapshotPath },
})
).isError,
).not.toBe(true);
await mcp.callTool({ name: "close_binary", arguments: {} });
}, 10_000);
it("records approved process residuals in the unknown registry", async () => {
@@ -219,8 +267,7 @@ describe("target-free MCP lifecycle", () => {
),
).result;
expect(listed).toContainEqual({
question:
"network: External network isolation is not enforced by this adapter.",
question: "Was network behavior fully observed during capture?",
domain: "process-network",
});
});
+82 -3
View File
@@ -12,7 +12,7 @@ import type { LinuxDistribution } from "../src/application/LinuxHopper.js";
class FakeSetupHost implements SetupHost {
readonly platform: NodeJS.Platform;
readonly nodeVersion = "25.1.0";
nodeVersion = "25.1.0";
version: string | undefined = "14.5";
distribution: LinuxDistribution | undefined;
hopper: string | undefined;
@@ -22,6 +22,7 @@ class FakeSetupHost implements SetupHost {
clientResults = new Map<string, ClientConfigurationResult>();
hopperInstalls = 0;
configurations = 0;
doctorHealthy: boolean | undefined;
constructor(platform: NodeJS.Platform = "darwin") {
this.platform = platform;
@@ -55,7 +56,7 @@ class FakeSetupHost implements SetupHost {
checks: readonly DoctorCheck[];
}> =>
Promise.resolve({
healthy: this.hopper !== undefined,
healthy: this.doctorHealthy ?? this.hopper !== undefined,
...(this.hopper === undefined ? {} : { hopperPath: this.hopper }),
checks: [],
});
@@ -80,6 +81,9 @@ describe("setup workflow", () => {
]);
expect(host.hopperInstalls).toBe(0);
expect(host.configurations).toBe(0);
expect(result.remediation).toBe(
"Review the setup plan, then rerun interactively or with --yes.",
);
});
it("applies an accepted interactive plan including Hopper", async () => {
@@ -95,6 +99,9 @@ describe("setup workflow", () => {
"installed_skill",
]);
expect(host.hopperInstalls).toBe(1);
expect(result.remediation).toBe(
"Open Hopper, complete its one-time activation, then rerun rea doctor --json.",
);
});
it("declines an interactive plan without mutation", async () => {
@@ -116,6 +123,9 @@ describe("setup workflow", () => {
expect(host.hopperInstalls).toBe(0);
expect(result.appliedActions).toEqual(["installed_skill"]);
expect(result.remediation).toContain("--install-hopper");
expect(result.remediation).toBe(
"Hopper is optional for non-Hopper providers. Rerun with --yes --install-hopper for deep native analysis.",
);
});
it("installs Hopper when unattended authorization is explicit", async () => {
@@ -151,10 +161,76 @@ describe("setup workflow", () => {
host.clients = [{ name: "cursor", configPath: "/cursor.json" }];
const result = await runSetup(options(true, true), host);
expect(result.status).toBe("needs_human");
expect(result.remediation).toContain("failed");
expect(result.remediation).toBe(
"Hopper installation failed; install Hopper manually or rerun setup after resolving the reported system error.",
);
expect(host.configurations).toBe(0);
});
it.each([
[
"backup",
"Agent configuration could not be backed up, so no change was made. Check file permissions, then rerun setup.",
],
[
"write",
"Agent configuration could not be updated. Check file permissions, then rerun setup.",
],
[
"readback",
"Agent configuration could not be verified after writing. Repair the configuration file or restore its `.rea.backup`, then rerun setup.",
],
] as const)("explains %s configuration recovery", async (reason, message) => {
const host = new FakeSetupHost();
host.hopper = "/Applications/Hopper";
host.clients = [{ name: "internal_client_key", configPath: "/agent.json" }];
host.clientResults.set("internal_client_key", { status: "failed", reason });
const result = await runSetup(options(true), host);
expect(result.status).toBe("needs_human");
expect(result.remediation).toBe(message);
expect(result.remediation).not.toContain("internal_client_key");
});
it("explains skill installation recovery", async () => {
const host = new FakeSetupHost();
host.hopper = "/Applications/Hopper";
host.skill = "failed";
const result = await runSetup(options(true), host);
expect(result.status).toBe("needs_human");
expect(result.remediation).toBe(
"REA analysis skill could not be installed or verified. Check permissions for `~/.agents/skills`, then rerun setup.",
);
});
it("delegates remaining unhealthy checks to doctor remediation", async () => {
const host = new FakeSetupHost();
host.hopper = "/Applications/Hopper";
host.doctorHealthy = false;
const result = await runSetup(options(true), host);
expect(result.remediation).toBe(
"Run rea doctor and apply each reported remediation.",
);
});
it("explains unsupported Node and macOS recovery", async () => {
const platformHost = new FakeSetupHost("win32");
expect((await runSetup(options(true), platformHost)).remediation).toBe(
"REA supports Hopper on macOS and selected 64-bit Linux distributions.",
);
const nodeHost = new FakeSetupHost();
nodeHost.nodeVersion = "20.0.0";
expect((await runSetup(options(true), nodeHost)).remediation).toBe(
"Install Node.js 22.19+ or 24.11+ and rerun setup.",
);
const macHost = new FakeSetupHost();
macHost.version = "11.7";
expect((await runSetup(options(true), macHost)).remediation).toBe(
"Upgrade to macOS 12 or newer.",
);
});
it("rejects unsupported hosts before mutation", async () => {
const host = new FakeSetupHost("linux");
host.distribution = {
@@ -166,5 +242,8 @@ describe("setup workflow", () => {
const result = await runSetup(options(true, true), host);
expect(result.status).toBe("needs_human");
expect(host.hopperInstalls).toBe(0);
expect(result.remediation).toBe(
"REA supports Hopper on Ubuntu 24.04+, Fedora 41+, and 64-bit Arch Linux.",
);
});
});
+120 -4
View File
@@ -1,4 +1,12 @@
import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import {
copyFile,
lstat,
mkdtemp,
mkdir,
readFile,
rm,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
@@ -10,6 +18,7 @@ import {
import {
runUninstall,
systemUninstallHost,
type UninstallFileSystem,
} from "../src/application/Uninstall.js";
const roots: string[] = [];
@@ -110,7 +119,12 @@ describe("agent lifecycle", () => {
mcpServers: { other: { command: "other" } },
});
expect(first.items).toContainEqual(
expect.objectContaining({ name: "cache", status: "retained" }),
expect.objectContaining({
name: "cache",
status: "retained",
detail:
"REA did not remove this item because its managed path is a symbolic link. Verify the link target before removing it manually.",
}),
);
expect((await runUninstall(true, systemUninstallHost(home))).status).toBe(
"complete",
@@ -123,9 +137,111 @@ describe("agent lifecycle", () => {
const config = join(home, ".cursor/mcp.json");
await mkdir(dirname(config), { recursive: true });
await writeFile(config, "not-json");
expect((await runUninstall(false, systemUninstallHost(home))).status).toBe(
"failed",
const result = await runUninstall(false, systemUninstallHost(home));
expect(result.status).toBe("failed");
expect(result.items).toContainEqual(
expect.objectContaining({
name: "cursor",
status: "failed",
detail:
"Configuration is not valid JSON and was not changed. Repair it, then rerun uninstall.",
}),
);
expect(await readFile(config, "utf8")).toBe("not-json");
});
it.each([
[
"read",
"Configuration could not be read. Check file permissions, then rerun uninstall.",
],
[
"backup",
"Configuration could not be backed up, so no change was made. Check file permissions, then rerun uninstall.",
],
[
"update",
"Configuration could not be updated. The original was restored and its `.rea.backup` was retained. Repair the configuration or restore the backup, then rerun uninstall.",
],
[
"restore",
"Configuration could not be updated or restored. Restore its `.rea.backup` manually, then rerun uninstall.",
],
] as const)(
"reports an actionable client %s failure",
async (failure, detail) => {
const { home, config } = await uninstallFixture();
let writes = 0;
const fileSystem: UninstallFileSystem = {
...testFileSystem,
readText: (path) =>
failure === "read" && path === config
? Promise.reject(new Error("SECRET read failure"))
: readFile(path, "utf8"),
copy: (source, destination) =>
failure === "backup"
? Promise.reject(new Error("SECRET backup failure"))
: copyFile(source, destination),
writeText: async (path, contents) => {
writes += 1;
if ((failure === "update" && writes === 1) || failure === "restore")
throw new Error("SECRET write failure");
await writeFile(path, contents);
},
};
const result = await runUninstall(
false,
systemUninstallHost(home, fileSystem),
);
expect(result.status).toBe("failed");
expect(result.items).toContainEqual(
expect.objectContaining({ name: "cursor", status: "failed", detail }),
);
expect(JSON.stringify(result)).not.toContain("SECRET");
},
);
it("reports a managed-path removal failure", async () => {
const home = await mkdtemp(join(tmpdir(), "rea-uninstall-remove-"));
roots.push(home);
const skillRoot = join(home, ".agents/skills/rea-analysis");
await mkdir(skillRoot, { recursive: true });
const result = await runUninstall(
false,
systemUninstallHost(home, {
...testFileSystem,
remove: () => Promise.reject(new Error("SECRET removal failure")),
}),
);
expect(result.items).toContainEqual({
name: "skill",
status: "failed",
detail:
"This item could not be removed. Check file permissions, then rerun uninstall.",
});
expect(JSON.stringify(result)).not.toContain("SECRET");
});
});
const testFileSystem: UninstallFileSystem = {
readText: (path) => readFile(path, "utf8"),
copy: (source, destination) => copyFile(source, destination),
writeText: (path, contents) => writeFile(path, contents),
stat: (path) => lstat(path),
remove: (path) => rm(path, { recursive: true }),
};
const uninstallFixture = async (): Promise<{
readonly home: string;
readonly config: string;
}> => {
const home = await mkdtemp(join(tmpdir(), "rea-uninstall-failure-"));
roots.push(home);
const config = join(home, ".cursor/mcp.json");
await mkdir(dirname(config), { recursive: true });
await writeFile(
config,
JSON.stringify({ mcpServers: { rea: { command: "rea", args: ["mcp"] } } }),
);
return { home, config };
};
+8 -1
View File
@@ -26,9 +26,16 @@ describe("tool result projection", () => {
content: [
{
type: "text",
text: "AnalysisOutputError: Analysis output does not match the tool contract",
text: "Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.",
},
],
structuredContent: {
error: {
category: "execution_failure",
message:
"Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.",
},
},
isError: true,
});
});
+2
View File
@@ -98,6 +98,8 @@ describe("CLI upgrade", () => {
expect(await runUpgrade("0.5.0", host)).toMatchObject({
status: "failed",
reason: "install",
remediation:
"REA could not update through npm. Check npm registry access and global install permissions, then run: npm install --global rea-agents@latest",
});
expect(host.installs).toBe(1);
});