test: overhaul deterministic suite architecture

This commit is contained in:
morluto
2026-07-29 22:00:38 +00:00
parent 7f2348619a
commit 513d9b1555
371 changed files with 30879 additions and 24389 deletions
@@ -0,0 +1,113 @@
import { describe, expect, it } from "vitest";
import { parseConfig } from "../../../src/config.js";
describe("browser runtime configuration", () => {
it("builds an exact-origin browser observation ceiling only when enabled", () => {
const result = parseConfig({
REA_BROWSER_OBSERVE_ENABLED: "true",
REA_BROWSER_CDP_ENDPOINTS_JSON: '["http://127.0.0.1:9222"]',
REA_BROWSER_ALLOWED_ORIGINS_JSON:
'["https://app.example.test", "http://127.0.0.1:3000"]',
});
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.permissionCeilings).toContainEqual({
capability: "browser_observe",
roots: [],
executables: [],
environment_names: [],
origins: [
"http://127.0.0.1:9222",
"http://127.0.0.1:3000",
"https://app.example.test",
],
network: "external",
mount: false,
});
expect(result.value.administratorPermissionGrants).toContainEqual(
expect.objectContaining({
capability: "browser_observe",
lifetime: "administrator",
}),
);
});
it("classifies IPv6 browser origins as loopback network scope", () => {
const result = parseConfig({
REA_BROWSER_OBSERVE_ENABLED: "true",
REA_BROWSER_CDP_ENDPOINTS_JSON: '["http://127.0.0.1:9222"]',
REA_BROWSER_ALLOWED_ORIGINS_JSON: '["http://[::1]:3000"]',
});
if (!result.ok) throw result.error;
expect(result.value.permissionCeilings).toContainEqual(
expect.objectContaining({
capability: "browser_observe",
network: "loopback",
}),
);
});
it("requires an explicit grant for exact-scope browser automation", () => {
const environment = {
REA_BROWSER_SCENARIO_ENABLED: "true",
REA_BROWSER_SCENARIO_EXECUTABLE_ROOTS_JSON: '["/opt/chromium"]',
REA_BROWSER_SCENARIO_CDP_ENDPOINTS_JSON: '["http://127.0.0.1:9222"]',
REA_BROWSER_SCENARIO_ALLOWED_ORIGINS_JSON: '["https://app.example.test"]',
REA_BROWSER_SCENARIO_ALLOWED_ENV_JSON: '["REA_TEST_PASSWORD"]',
};
const result = parseConfig(environment);
if (!result.ok) throw result.error;
expect(result.value.browserScenarioPolicy).toEqual({
enabled: true,
executableRoots: ["/opt/chromium"],
cdpEndpoints: ["http://127.0.0.1:9222"],
allowedOrigins: ["https://app.example.test"],
allowedEnvironment: ["REA_TEST_PASSWORD"],
});
expect(result.value.permissionCeilings).toContainEqual({
capability: "browser_automate",
roots: [],
executables: ["/opt/chromium"],
environment_names: ["REA_TEST_PASSWORD"],
origins: ["http://127.0.0.1:9222", "https://app.example.test"],
network: "external",
mount: false,
});
expect(result.value.administratorPermissionGrants).not.toContainEqual(
expect.objectContaining({ capability: "browser_automate" }),
);
const automatic = parseConfig({
...environment,
REA_BROWSER_SCENARIO_AUTO_GRANT: "true",
});
if (!automatic.ok) throw automatic.error;
expect(automatic.value.administratorPermissionGrants).toContainEqual(
expect.objectContaining({
capability: "browser_automate",
lifetime: "administrator",
}),
);
});
it.each([
'["http://localhost:9222"]',
'["http://192.168.1.5:9222"]',
'["https://127.0.0.1:9222"]',
])("rejects unsafe browser CDP endpoint scopes: %s", (encoded) => {
expect(parseConfig({ REA_BROWSER_CDP_ENDPOINTS_JSON: encoded }).ok).toBe(
false,
);
});
it.each([
'["https://*.example.test"]',
'["https://app.example.test/private"]',
'["https://user:pass@app.example.test"]',
'["file:///tmp/application.html"]',
])("rejects non-exact browser origin scopes: %s", (encoded) => {
expect(parseConfig({ REA_BROWSER_ALLOWED_ORIGINS_JSON: encoded }).ok).toBe(
false,
);
});
});
@@ -0,0 +1,68 @@
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
describe("client registration status", () => {
it("distinguishes aligned, stale, missing, and invalid registrations", async () => {
const home = await createTestTempDirectory("rea-registrations-");
await Promise.all([
mkdir(join(home, ".codex")),
mkdir(join(home, ".cursor")),
mkdir(join(home, ".gemini")),
mkdir(join(home, ".claude")),
]);
await writeFile(
join(home, ".codex/config.toml"),
`[mcp_servers.rea]\ncommand = "npx"\nargs = ["-y", "${PRODUCT_IDENTITY.registrationPackageSpecifier}", "mcp"]\nstartup_timeout_sec = 30\n`,
);
await writeFile(
join(home, ".cursor/mcp.json"),
JSON.stringify({
mcpServers: {
rea: { command: "/old/rea", args: ["mcp"], env: { SECRET: "x" } },
},
}),
);
await writeFile(join(home, ".gemini/settings.json"), "not-json");
const statuses = await readClientRegistrationStatuses(home, "/current/rea");
expect(statuses).toEqual(
expect.arrayContaining([
expect.objectContaining({ client: "codex", state: "aligned" }),
expect.objectContaining({
client: "cursor",
state: "stale",
command: ["/old/rea", "mcp"],
}),
expect.objectContaining({ client: "gemini_cli", state: "invalid" }),
expect.objectContaining({ client: "claude_code", state: "missing" }),
]),
);
expect(JSON.stringify(statuses)).not.toContain("SECRET");
});
it("reports an unversioned npx registration as stale", async () => {
const home = await createTestTempDirectory("rea-registrations-");
await mkdir(join(home, ".codex"));
await writeFile(
join(home, ".codex/config.toml"),
'[mcp_servers.rea]\ncommand = "npx"\nargs = ["-y", "rea-agents", "mcp"]\n',
);
const statuses = await readClientRegistrationStatuses(home);
expect(statuses).toEqual([
expect.objectContaining({
client: "codex",
command: ["npx", "-y", "rea-agents", "mcp"],
state: "stale",
}),
]);
});
});
@@ -0,0 +1,408 @@
import { describe, expect, it } from "vitest";
import { parseConfig } from "../../../src/config.js";
describe("runtime configuration", () => {
it("allows target-free startup and defaults to Hopper's documented launcher", () => {
const empty = parseConfig({});
expect(empty.ok).toBe(true);
if (empty.ok) {
expect(empty.value.hopperTargetPath).toBeUndefined();
expect(empty.value.analysisProvider).toBe("auto");
}
const result = parseConfig({ HOPPER_TARGET_PATH: "/usr/bin/true" });
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.value.hopperLauncherPath).toBe(
process.platform === "linux"
? "/opt/hopper/bin/Hopper"
: "/Applications/Hopper Disassembler.app/Contents/MacOS/hopper",
);
expect(result.value.hopperTargetKind).toBe("executable");
expect(result.value.hopperLoaderArgs).toEqual([]);
expect(result.value.logLevel).toBe("info");
expect(result.value.referenceSourcePolicy).toEqual({
roots: [],
secretPatterns: [],
maxBytes: 16 * 1024 * 1024,
maxEntries: 10_000,
maxDepth: 32,
maxPathBytes: 4_096,
});
expect(result.value.browserObservationEnabled).toBe(false);
expect(result.value.browserCdpEndpoints).toEqual([]);
expect(result.value.browserAllowedOrigins).toEqual([]);
expect(result.value.browserScenarioPolicy).toEqual({
enabled: false,
executableRoots: [],
cdpEndpoints: [],
allowedOrigins: [],
allowedEnvironment: [],
});
expect(result.value.electronObservationEnabled).toBe(false);
expect(result.value.electronCdpEndpoints).toEqual([]);
expect(result.value.electronFileRoots).toEqual([]);
expect(result.value.v8InspectorObservationEnabled).toBe(false);
expect(result.value.v8InspectorEndpoints).toEqual([]);
expect(result.value.v8InspectorFileRoots).toEqual([]);
expect(result.value.v8InspectorAllowedOrigins).toEqual([]);
expect(result.value.javascriptReplayPolicy).toMatchObject({
enabled: false,
roots: [],
});
expect(result.value.managedRuntimePolicy).toMatchObject({
enabled: false,
roots: [],
executablePath: "/usr/bin/dotnet",
});
}
});
it("parses one shared provider selector and rejects unstable IDs", () => {
expect(parseConfig({ REA_ANALYSIS_PROVIDER: "ghidra" })).toMatchObject({
ok: true,
value: { analysisProvider: "ghidra" },
});
expect(parseConfig({ REA_ANALYSIS_PROVIDER: "auto" })).toMatchObject({
ok: true,
value: { analysisProvider: "auto" },
});
for (const invalid of ["", "Auto", "ghidra_1", "ghidra "])
expect(parseConfig({ REA_ANALYSIS_PROVIDER: invalid }).ok).toBe(false);
});
it("parses absolute BYO Ghidra and optional Java paths", () => {
expect(
parseConfig({
GHIDRA_INSTALL_DIR: "/opt/ghidra_12.1.2_PUBLIC",
JAVA_HOME: "/usr/lib/jvm/jdk-21",
}),
).toMatchObject({
ok: true,
value: {
ghidraInstallDir: "/opt/ghidra_12.1.2_PUBLIC",
ghidraJavaHome: "/usr/lib/jvm/jdk-21",
},
});
expect(parseConfig({ GHIDRA_INSTALL_DIR: "relative/ghidra" }).ok).toBe(
false,
);
expect(parseConfig({ JAVA_HOME: "relative/jdk" }).ok).toBe(false);
});
it("parses an optional absolute BYO ilspycmd path", () => {
expect(
parseConfig({ REA_ILSPY_CMD_PATH: "/home/user/.dotnet/tools/ilspycmd" }),
).toMatchObject({
ok: true,
value: {
ilspyCmdPath: "/home/user/.dotnet/tools/ilspycmd",
},
});
expect(parseConfig({ REA_ILSPY_CMD_PATH: "relative/ilspycmd" }).ok).toBe(
false,
);
});
});
describe("runtime permission configuration", () => {
it("builds a separate Electron endpoint and file-root ceiling", () => {
const result = parseConfig({
REA_ELECTRON_OBSERVE_ENABLED: "true",
REA_ELECTRON_CDP_ENDPOINTS_JSON: '["http://127.0.0.1:9223"]',
REA_ELECTRON_FILE_ROOTS_JSON: '["/tmp/electron-app"]',
});
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.permissionCeilings).toContainEqual({
capability: "electron_observe",
roots: ["/tmp/electron-app"],
executables: [],
environment_names: [],
origins: ["http://127.0.0.1:9223"],
network: "loopback",
mount: false,
});
});
it("builds a separate V8 Inspector endpoint, root, and origin ceiling", () => {
const result = parseConfig({
REA_V8_INSPECTOR_OBSERVE_ENABLED: "true",
REA_V8_INSPECTOR_ENDPOINTS_JSON: '["http://127.0.0.1:9229"]',
REA_V8_INSPECTOR_FILE_ROOTS_JSON: '["/tmp/node-app"]',
REA_V8_INSPECTOR_ALLOWED_ORIGINS_JSON: '["http://127.0.0.1:3000"]',
});
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.permissionCeilings).toContainEqual({
capability: "v8_inspector_observe",
roots: ["/tmp/node-app"],
executables: [],
environment_names: [],
origins: ["http://127.0.0.1:9229", "http://127.0.0.1:3000"],
network: "loopback",
mount: false,
});
});
it("can configure a process-capture ceiling without an implicit grant", () => {
const result = parseConfig({
REA_PROCESS_CAPTURE_ENABLED: "true",
REA_PROCESS_CAPTURE_AUTO_GRANT: "false",
REA_PROCESS_EXECUTABLE_ROOTS_JSON: '["/opt/tools"]',
REA_PROCESS_WORKING_ROOTS_JSON: '["/tmp/work"]',
});
if (!result.ok) throw result.error;
expect(result.value.permissionCeilings).toContainEqual(
expect.objectContaining({ capability: "process_capture" }),
);
expect(result.value.administratorPermissionGrants).not.toContainEqual(
expect.objectContaining({ capability: "process_capture" }),
);
});
it("preserves the configured process-capture administrator grant by default", () => {
const result = parseConfig({
REA_PROCESS_CAPTURE_ENABLED: "true",
REA_PROCESS_EXECUTABLE_ROOTS_JSON: '["/opt/tools"]',
REA_PROCESS_WORKING_ROOTS_JSON: '["/tmp/work"]',
});
if (!result.ok) throw result.error;
expect(result.value.administratorPermissionGrants).toContainEqual(
expect.objectContaining({
capability: "process_capture",
lifetime: "administrator",
}),
);
});
it("builds a no-network JavaScript replay ceiling only when enabled", () => {
const result = parseConfig({
REA_JAVASCRIPT_REPLAY_ENABLED: "true",
REA_JAVASCRIPT_REPLAY_ROOTS_JSON: '["/tmp/extracted-modules"]',
REA_JAVASCRIPT_REPLAY_NODE_PATH: "/opt/node/bin/node",
});
if (!result.ok) throw result.error;
expect(result.value.permissionCeilings).toContainEqual({
capability: "javascript_replay",
roots: ["/tmp/extracted-modules"],
executables: [
"/opt/node/bin/node",
"/usr/bin/bwrap",
"/usr/bin/systemd-run",
"/usr/bin/systemctl",
"/usr/bin/bash",
],
environment_names: [],
network: "none",
mount: true,
});
expect(result.value.administratorPermissionGrants).toContainEqual(
expect.objectContaining({
capability: "javascript_replay",
lifetime: "administrator",
}),
);
});
it("rejects relative JavaScript replay roots and executables", () => {
expect(
parseConfig({ REA_JAVASCRIPT_REPLAY_ROOTS_JSON: '["relative/module"]' })
.ok,
).toBe(false);
expect(
parseConfig({ REA_JAVASCRIPT_REPLAY_NODE_PATH: "relative/node" }).ok,
).toBe(false);
});
});
describe("runtime target configuration", () => {
it("builds a no-network managed runtime ceiling only when enabled", () => {
const result = parseConfig({
REA_MANAGED_RUNTIME_ENABLED: "true",
REA_MANAGED_RUNTIME_ROOTS_JSON: '["/tmp/managed-targets"]',
REA_MANAGED_RUNTIME_EXECUTABLE_PATH: "/opt/dotnet/dotnet",
});
if (!result.ok) throw result.error;
expect(result.value.managedRuntimePolicy).toEqual({
enabled: true,
roots: ["/tmp/managed-targets"],
executablePath: "/opt/dotnet/dotnet",
});
expect(result.value.permissionCeilings).toContainEqual({
capability: "managed_runtime",
roots: ["/tmp/managed-targets"],
executables: ["/opt/dotnet/dotnet"],
environment_names: [],
network: "none",
mount: false,
});
expect(result.value.administratorPermissionGrants).toContainEqual(
expect.objectContaining({
capability: "managed_runtime",
lifetime: "administrator",
}),
);
});
it("rejects relative managed runtime roots and executables", () => {
expect(
parseConfig({ REA_MANAGED_RUNTIME_ROOTS_JSON: '["relative/assembly"]' })
.ok,
).toBe(false);
expect(
parseConfig({ REA_MANAGED_RUNTIME_EXECUTABLE_PATH: "relative/dotnet" })
.ok,
).toBe(false);
});
it("rejects relative Electron file roots", () => {
expect(
parseConfig({ REA_ELECTRON_FILE_ROOTS_JSON: '["relative/app"]' }).ok,
).toBe(false);
});
it("parses database kind and loader arguments", () => {
expect(
parseConfig({
HOPPER_TARGET_PATH: "/fixture/sample.hop",
HOPPER_TARGET_KIND: "database",
HOPPER_LOADER_ARGS_JSON: '["-l","FAT","--aarch64","-l","Mach-O"]',
}),
).toMatchObject({
ok: true,
value: {
hopperLauncherPath:
process.platform === "linux"
? "/opt/hopper/bin/Hopper"
: "/Applications/Hopper Disassembler.app/Contents/MacOS/hopper",
hopperTargetPath: "/fixture/sample.hop",
hopperTargetKind: "database",
hopperLoaderArgs: ["-l", "FAT", "--aarch64", "-l", "Mach-O"],
logLevel: "info",
artifactNativeMountEnabled: false,
processExecutionPolicy: {
enabled: false,
executableRoots: [],
workingRoots: [],
allowedEnvironment: [],
allowExternalNetwork: false,
},
evidenceFilePolicy: {
roots: [],
maxBytes: 64 * 1024 * 1024,
maxDepth: 64,
maxStringLength: 1024 * 1024,
maxNodes: 1_000_000,
},
investigationInputRoots: [],
analysisSnapshotFilePolicy: {
roots: [],
maxBytes: 64 * 1024 * 1024,
maxDepth: 64,
maxStringLength: 1024 * 1024,
maxNodes: 1_000_000,
},
referenceSourcePolicy: {
roots: [],
secretPatterns: [],
maxBytes: 16 * 1024 * 1024,
maxEntries: 10_000,
maxDepth: 32,
maxPathBytes: 4_096,
},
},
});
});
});
describe("runtime collection configuration", () => {
it.each(["not-json", "{}", '["ok",1]'])(
"rejects invalid loader args: %s",
(encoded) => {
expect(
parseConfig({
HOPPER_TARGET_PATH: "/tmp/a",
HOPPER_LOADER_ARGS_JSON: encoded,
}).ok,
).toBe(false);
},
);
it("reports the configured string-array size limit", () => {
const result = parseConfig({
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify(
Array.from({ length: 129 }, (_, index) => `/input/${String(index)}`),
),
});
expect(result.ok).toBe(false);
if (!result.ok)
expect(result.error.message).toBe(
"REA_INVESTIGATION_INPUT_ROOTS_JSON must encode at most 128 strings",
);
});
it("parses supported log levels and rejects unknown levels", () => {
const configured = parseConfig({ REA_LOG_LEVEL: "debug" });
expect(configured.ok && configured.value.logLevel).toBe("debug");
expect(parseConfig({ REA_LOG_LEVEL: "verbose" }).ok).toBe(false);
});
it("parses reference source policy roots and secret patterns", () => {
const result = parseConfig({
REA_REFERENCE_ROOTS_JSON: '["/approved", "/srv/reference"]',
REA_REFERENCE_SECRET_PATTERNS_JSON: '["*.env", "*.pem", "secrets/"]',
});
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.value.referenceSourcePolicy).toEqual({
roots: ["/approved", "/srv/reference"],
secretPatterns: ["*.env", "*.pem", "secrets/"],
maxBytes: 16 * 1024 * 1024,
maxEntries: 10_000,
maxDepth: 32,
maxPathBytes: 4_096,
});
}
});
it("parses investigation input roots independently from evidence roots", () => {
const result = parseConfig({
REA_EVIDENCE_ROOTS_JSON: '["/evidence"]',
REA_INVESTIGATION_INPUT_ROOTS_JSON: '["/releases", "/builds"]',
});
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.value.evidenceFilePolicy.roots).toEqual(["/evidence"]);
expect(result.value.investigationInputRoots).toEqual([
"/releases",
"/builds",
]);
}
});
it.each(["not-json", "{}", '["/ok", 1]'])(
"rejects invalid investigation input roots: %s",
(encoded) => {
expect(
parseConfig({ REA_INVESTIGATION_INPUT_ROOTS_JSON: encoded }).ok,
).toBe(false);
},
);
it.each(["not-json", "{}", '["/ok", 1]'])(
"rejects invalid reference source roots: %s",
(encoded) => {
expect(parseConfig({ REA_REFERENCE_ROOTS_JSON: encoded }).ok).toBe(false);
},
);
it.each(["not-json", "{}", '["*.ok", 1]'])(
"rejects invalid reference source secret patterns: %s",
(encoded) => {
expect(
parseConfig({ REA_REFERENCE_SECRET_PATTERNS_JSON: encoded }).ok,
).toBe(false);
},
);
});
@@ -0,0 +1,123 @@
import { chmod, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { writeAnalysisSnapshot } from "../../../src/application/AnalysisSnapshotFiles.js";
import { runDirectAnalysis } from "../../../src/application/DirectAnalysis.js";
import type { AnalysisSnapshot } from "../../../src/domain/analysisSnapshot.js";
import {
snapshotBinding,
snapshotTarget,
} from "../../../src/domain/analysisSnapshot.js";
import { parseBinaryTarget } from "../../../src/domain/binaryTarget.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import { permissionAuthorityForRoot } from "../../fixtures/permissionAuthority.js";
import {
REA_WORKFLOW_PROVIDER,
workflowAnalysisProfile,
} from "../../../src/application/InvestigationProviders.js";
import { HOPPER_PROVIDER_IDENTITY } from "../../../src/hopper/HopperProvider.js";
import { resolveHopperAnalysisProfile } from "../../../src/hopper/HopperAnalysisProfile.js";
let directory: string | undefined;
afterEach(async () => {
vi.unstubAllEnvs();
if (directory !== undefined)
await rm(directory, { recursive: true, force: true });
directory = undefined;
});
describe("direct analysis snapshot permissions", () => {
it("forwards the CLI provider selector ahead of the environment preference", async () => {
directory = await createTestTempDirectory("rea-direct-provider-");
const targetPath = join(directory, "fixture.hop");
await writeFile(targetPath, "fixture");
vi.stubEnv("HOPPER_LAUNCHER_PATH", process.execPath);
vi.stubEnv("REA_ANALYSIS_PROVIDER", "environment-provider");
await expect(
runDirectAnalysis(
targetPath,
"binary_overview",
{},
{
providerId: "request-provider",
},
),
).resolves.toMatchObject({
error: "Analysis failed",
code: "capability_unavailable",
details: {
selection_reason: "unknown_provider",
requested_provider_id: "request-provider",
candidate_ids: ["ghidra", "hopper"],
},
});
});
it("replays a cache hit with snapshot read authority only", async () => {
directory = await createTestTempDirectory("rea-direct-snapshot-");
const snapshotPath = join(directory, "analysis.json");
const launcherPath = join(directory, "hopper-launcher");
await writeFile(launcherPath, "fixture Hopper launcher");
await chmod(launcherPath, 0o755);
const target = await parseBinaryTarget(process.execPath);
if (!target.ok) throw target.error;
const resolved = await resolveHopperAnalysisProfile(target.value, {
launcherPath,
loaderArgsOverride: [],
provider: HOPPER_PROVIDER_IDENTITY,
});
if (!resolved.ok || resolved.value.profile === null)
throw new Error("fixture Hopper profile did not resolve");
const profile = resolved.value.profile;
const workflowProfile = workflowAnalysisProfile(profile);
const evidence = createEvidence(target.value, REA_WORKFLOW_PROVIDER, {
operation: "binary_overview",
parameters: {},
result: { cached: true },
analysisProfile: workflowProfile,
});
const snapshot: AnalysisSnapshot = {
snapshot_version: 2,
target: snapshotTarget(target.value),
binding: snapshotBinding(profile),
entries: [],
evidence_bundle: createEvidenceBundle([evidence]),
};
const policy = {
roots: [directory],
maxBytes: 1024 * 1024,
maxDepth: 64,
maxStringLength: 1024,
maxNodes: 10_000,
};
expect(
(await writeAnalysisSnapshot(snapshot, snapshotPath, false, policy)).ok,
).toBe(true);
const authority = await permissionAuthorityForRoot(
directory,
["snapshot_read", "snapshot_write"],
["snapshot_read"],
);
vi.stubEnv("REA_ANALYSIS_SNAPSHOT_ROOTS_JSON", JSON.stringify([directory]));
vi.stubEnv("HOPPER_LAUNCHER_PATH", launcherPath);
await expect(
runDirectAnalysis(
process.execPath,
"binary_overview",
{},
{
snapshotPath,
permissionAuthority: authority,
},
),
).resolves.toEqual(evidence);
});
});
@@ -0,0 +1,350 @@
import { mkdir, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
canonicalizePermissionCeilings,
canonicalizePermissionRequest,
createPermissionAuthority,
type PermissionAuthority,
} from "../../../src/application/PermissionAuthority.js";
import {
createPermissionPolicy,
evaluatePermission,
type PermissionGrant,
type PermissionScope,
} from "../../../src/domain/permissionPolicy.js";
describe("permission authority", () => {
it("distinguishes an elicitable grant from administrator reconfiguration", async () => {
const sandbox = await createTestTempDirectory(
"rea-permission-remediation-",
);
const allowedRoot = join(sandbox, "allowed");
const outsideRoot = join(sandbox, "outside");
await Promise.all([mkdir(allowedRoot), mkdir(outsideRoot)]);
const authority = await createPermissionAuthority([
evidenceScope(allowedRoot),
]);
expect(authority.ok).toBe(true);
if (!authority.ok) return;
const inside = await authority.value.authorize(
{
...evidenceScope(allowedRoot),
operation_identity: "read:inside-ceiling",
},
"read",
{ elicitationSupported: true },
);
expect(inside).toMatchObject({
ok: false,
error: { elicitationSupported: true, restartRequired: false },
});
const outside = await authority.value.createConnectionAuthority().authorize(
{
...evidenceScope(outsideRoot),
operation_identity: "read:outside-ceiling",
},
"read",
{ elicitationSupported: true },
);
expect(outside).toMatchObject({
ok: false,
error: { elicitationSupported: false, restartRequired: true },
});
});
it("accepts canonical aliases but rejects a symlink escape", async () => {
const sandbox = await createTestTempDirectory("rea-permission-");
const root = join(sandbox, "root");
const outside = join(sandbox, "outside");
await Promise.all([mkdir(root), mkdir(outside)]);
await writeFile(join(root, "inside"), "inside");
await writeFile(join(outside, "secret"), "secret");
await symlink(root, join(sandbox, "root-alias"));
await symlink(join(outside, "secret"), join(root, "escape"));
const ceiling = await canonicalizePermissionCeilings([
{
capability: "evidence_read",
roots: [join(sandbox, "root-alias")],
executables: [],
environment_names: [],
network: "none",
mount: false,
},
]);
expect(ceiling.ok).toBe(true);
if (!ceiling.ok) return;
const policy = createPermissionPolicy(ceiling.value, [
{
...ceiling.value[0]!,
grant_id: "administrator:evidence-read",
lifetime: "administrator",
operation_identity: null,
expires_at: null,
},
]);
const inside = await canonicalizePermissionRequest(
{
capability: "evidence_read",
roots: [join(root, "inside")],
executables: [],
environment_names: [],
network: "none",
mount: false,
operation_identity: "read:inside",
},
"read",
);
const escaped = await canonicalizePermissionRequest(
{
capability: "evidence_read",
roots: [join(root, "escape")],
executables: [],
environment_names: [],
network: "none",
mount: false,
operation_identity: "read:escape",
},
"read",
);
expect(inside.ok).toBe(true);
expect(escaped.ok).toBe(true);
if (!inside.ok || !escaped.ok) return;
expect(evaluatePermission(policy, inside.value)).toMatchObject({
allowed: true,
});
expect(evaluatePermission(policy, escaped.value)).toMatchObject({
allowed: false,
reason: "outside_administrator_ceiling",
});
});
it("canonicalizes a new write through its existing parent", async () => {
const sandbox = await createTestTempDirectory("rea-permission-write-");
const result = await canonicalizePermissionRequest(
{
capability: "evidence_write",
roots: [join(sandbox, "new.json")],
executables: [],
environment_names: [],
network: "none",
mount: false,
operation_identity: "write:new.json",
},
"write",
);
expect(result).toMatchObject({ ok: true });
if (result.ok)
expect(result.value.roots).toEqual([join(sandbox, "new.json")]);
});
});
describe("permission authority policy and connection lifecycle", () => {
it("commits a configured policy only after every grant validates", async () => {
const sandbox = await createTestTempDirectory("rea-permission-reload-");
const oldRoot = join(sandbox, "old");
const newRoot = join(sandbox, "new");
const outsideRoot = join(sandbox, "outside");
await Promise.all([mkdir(oldRoot), mkdir(newRoot), mkdir(outsideRoot)]);
const oldScope = evidenceScope(oldRoot);
const newScope = evidenceScope(newRoot);
const authority = await createPermissionAuthority(
[oldScope],
[administratorGrant(oldScope)],
);
expect(authority.ok).toBe(true);
if (!authority.ok) return;
const reloaded = await authority.value.replaceConfiguredPolicy({
ceilings: [newScope],
administratorGrants: [administratorGrant(newScope)],
projectGrants: [
{
...evidenceScope(outsideRoot),
grant_id: "project:outside-ceiling",
lifetime: "project",
operation_identity: null,
expires_at: null,
},
],
});
expect(reloaded.ok).toBe(false);
expect(await canRead(authority.value, oldRoot)).toBe(true);
expect(await canRead(authority.value, newRoot)).toBe(false);
expect(
await authority.value.replaceConfiguredPolicy({
ceilings: [newScope],
administratorGrants: [administratorGrant(newScope)],
projectGrants: [],
}),
).toEqual({ ok: true, value: null });
expect(await canRead(authority.value, oldRoot)).toBe(false);
expect(await canRead(authority.value, newRoot)).toBe(true);
});
it("isolates transient grants and consumption between live connections", async () => {
const sandbox = await createTestTempDirectory("rea-permission-session-");
const scope = evidenceScope(sandbox);
const configured = await createPermissionAuthority([scope]);
expect(configured.ok).toBe(true);
if (!configured.ok) return;
const connectionA = configured.value.createConnectionAuthority();
const connectionB = configured.value.createConnectionAuthority();
const request = {
...scope,
operation_identity: "read:connection-owned",
};
expect(
connectionA.grant({
...request,
grant_id: "session:a",
lifetime: "session",
operation_identity: null,
expires_at: null,
}),
).toMatchObject({ ok: true });
expect(await connectionA.authorize(request, "read")).toMatchObject({
ok: true,
});
expect(await connectionB.authorize(request, "read")).toMatchObject({
ok: false,
});
connectionB.clearSessionGrants();
expect(await connectionA.authorize(request, "read")).toMatchObject({
ok: true,
});
connectionA.clearSessionGrants();
const onceRequest = {
...request,
operation_identity: "read:once-on-a",
};
expect(
connectionA.grant({
...onceRequest,
grant_id: "once:a",
lifetime: "once",
expires_at: null,
}),
).toMatchObject({ ok: true });
expect(
connectionB.grant({
...onceRequest,
grant_id: "once:a",
lifetime: "once",
expires_at: null,
}),
).toMatchObject({ ok: true });
const concurrent = await Promise.all([
connectionA.authorize(onceRequest, "read"),
connectionA.authorize(onceRequest, "read"),
]);
expect(concurrent.filter(({ ok }) => ok)).toHaveLength(1);
expect(await connectionB.authorize(onceRequest, "read")).toMatchObject({
ok: true,
});
});
});
describe("permission authority policy reload", () => {
it("applies configured policy reloads to existing connections", async () => {
const sandbox = await createTestTempDirectory(
"rea-permission-live-reload-",
);
const allowedRoot = join(sandbox, "allowed");
const replacementRoot = join(sandbox, "replacement");
await Promise.all([mkdir(allowedRoot), mkdir(replacementRoot)]);
const configured = await createPermissionAuthority([
evidenceScope(allowedRoot),
]);
expect(configured.ok).toBe(true);
if (!configured.ok) return;
const connection = configured.value.createConnectionAuthority();
expect(
connection.grant({
...evidenceScope(allowedRoot),
grant_id: "session:before-reload",
lifetime: "session",
operation_identity: null,
expires_at: null,
}),
).toMatchObject({ ok: true });
expect(await canRead(connection, allowedRoot)).toBe(true);
const collisionRequest = {
...evidenceScope(allowedRoot),
operation_identity: "read:reload-collision",
};
expect(
connection.grant({
...collisionRequest,
grant_id: "shared-id",
lifetime: "once",
expires_at: null,
}),
).toMatchObject({ ok: true });
expect(await connection.authorize(collisionRequest, "read")).toMatchObject({
ok: true,
});
expect(
await configured.value.replaceAdministratorGrants([
{
...evidenceScope(allowedRoot),
grant_id: "shared-id",
lifetime: "administrator",
operation_identity: null,
expires_at: null,
},
]),
).toEqual({ ok: true, value: null });
expect(await connection.authorize(collisionRequest, "read")).toMatchObject({
ok: true,
});
expect(
await configured.value.reload([evidenceScope(replacementRoot)]),
).toEqual({ ok: true, value: null });
expect(await canRead(connection, allowedRoot)).toBe(false);
});
});
const evidenceScope = (root: string): PermissionScope => ({
capability: "evidence_read",
roots: [root],
executables: [],
environment_names: [],
network: "none",
mount: false,
});
const administratorGrant = (scope: PermissionScope): PermissionGrant => ({
...scope,
grant_id: "administrator:evidence_read",
lifetime: "administrator",
operation_identity: null,
expires_at: null,
});
const canRead = async (
authority: PermissionAuthority,
root: string,
): Promise<boolean> =>
(
await authority.explain(
{
...evidenceScope(root),
operation_identity: `read:${root}`,
},
"read",
)
).ok;
@@ -0,0 +1,283 @@
import { describe, expect, it } from "vitest";
import { win32 } from "node:path";
import {
consumePermission,
clearSessionPermissions,
createPermissionPolicy,
evaluatePermission,
grantPermission,
isPathContained,
reloadPermissionCeilings,
revokePermission,
} from "../../../src/domain/permissionPolicy.js";
describe("permission policy", () => {
it("rejects sibling escapes for both POSIX and Windows path separators", () => {
expect(isPathContained("/allowed", "/secret")).toBe(false);
expect(
isPathContained("C:\\allowed", "C:\\secret", {
relative: win32.relative,
isAbsolute: win32.isAbsolute,
sep: win32.sep,
}),
).toBe(false);
expect(
isPathContained("C:\\allowed", "C:\\allowed\\nested", {
relative: win32.relative,
isAbsolute: win32.isAbsolute,
sep: win32.sep,
}),
).toBe(true);
});
it("never lets a session grant exceed the administrator ceiling", () => {
const policy = createPermissionPolicy([
{
capability: "process_capture",
roots: ["/workspace/project"],
executables: ["/workspace/project/bin/tool"],
environment_names: ["LANG"],
network: "loopback",
mount: false,
},
]);
const granted = grantPermission(policy, {
grant_id: "grant_session_1",
capability: "process_capture",
roots: ["/workspace/project"],
executables: ["/workspace/project/bin/tool"],
environment_names: ["LANG"],
network: "loopback",
mount: false,
lifetime: "session",
operation_identity: null,
expires_at: null,
});
expect(granted.ok).toBe(true);
if (!granted.ok) return;
expect(
evaluatePermission(granted.value, {
capability: "process_capture",
roots: ["/workspace/project/data"],
executables: ["/workspace/project/bin/tool"],
environment_names: ["LANG"],
network: "loopback",
mount: false,
operation_identity: "capture-1",
}),
).toMatchObject({ allowed: true });
expect(
evaluatePermission(granted.value, {
capability: "process_capture",
roots: ["/workspace/project/data"],
executables: ["/workspace/project/bin/tool"],
environment_names: ["LANG", "TOKEN"],
network: "external",
mount: false,
operation_identity: "capture-2",
}),
).toMatchObject({
allowed: false,
reason: "outside_administrator_ceiling",
missing: {
environment_names: ["TOKEN"],
network: "external",
},
});
});
it("authorizes browser observation only for exact declared origins", () => {
const scope = {
capability: "browser_observe" as const,
roots: [],
executables: [],
environment_names: [],
origins: ["http://127.0.0.1:9222", "https://app.example.test"],
network: "external" as const,
mount: false,
};
const granted = grantPermission(createPermissionPolicy([scope]), {
...scope,
grant_id: "browser-session",
lifetime: "session",
operation_identity: null,
expires_at: null,
});
expect(granted.ok).toBe(true);
if (!granted.ok) return;
expect(
evaluatePermission(granted.value, {
...scope,
operation_identity: "inspect:page-1",
}),
).toMatchObject({ allowed: true });
expect(
evaluatePermission(granted.value, {
...scope,
origins: ["http://127.0.0.1:9222", "https://cdn.example.test"],
operation_identity: "inspect:page-2",
}),
).toMatchObject({
allowed: false,
reason: "outside_administrator_ceiling",
missing: { origins: ["https://cdn.example.test"] },
});
});
});
describe("permission policy lifecycle", () => {
it("consumes once grants and applies revocation and ceiling reload immediately", () => {
const ceiling = {
capability: "evidence_write" as const,
roots: ["/workspace/evidence"],
executables: [],
environment_names: [],
network: "none" as const,
mount: false,
};
const granted = grantPermission(createPermissionPolicy([ceiling]), {
...ceiling,
grant_id: "grant_once_1",
lifetime: "once",
operation_identity: "write:report.json",
expires_at: null,
});
expect(granted.ok).toBe(true);
if (!granted.ok) return;
const request = {
...ceiling,
roots: ["/workspace/evidence/report.json"],
operation_identity: "write:report.json",
};
const decision = evaluatePermission(granted.value, request);
expect(decision).toMatchObject({ allowed: true });
if (!decision.allowed) return;
const consumed = consumePermission(granted.value, decision);
expect(evaluatePermission(consumed, request)).toMatchObject({
allowed: false,
reason: "grant_revoked_or_consumed",
});
expect(
evaluatePermission(
revokePermission(granted.value, "grant_once_1"),
request,
),
).toMatchObject({
allowed: false,
reason: "grant_revoked_or_consumed",
});
expect(
evaluatePermission(reloadPermissionCeilings(granted.value, []), request),
).toMatchObject({
allowed: false,
reason: "outside_administrator_ceiling",
});
});
it("reports a missing scope when revoked grants cover a different root", () => {
const ceiling = {
capability: "evidence_write" as const,
roots: ["/workspace"],
executables: [],
environment_names: [],
network: "none" as const,
mount: false,
};
const granted = grantPermission(createPermissionPolicy([ceiling]), {
...ceiling,
roots: ["/workspace/first"],
grant_id: "revoked-other-root",
lifetime: "project",
operation_identity: null,
expires_at: null,
});
expect(granted.ok).toBe(true);
if (!granted.ok) return;
expect(
evaluatePermission(
revokePermission(granted.value, "revoked-other-root"),
{
...ceiling,
roots: ["/workspace/second"],
operation_identity: "write:report.json",
},
),
).toMatchObject({
allowed: false,
reason: "grant_required",
missing: { roots: ["/workspace/second"] },
});
});
it("expires grants, removes session authority on disconnect, and never combines partial grants", () => {
const ceiling = {
capability: "process_capture" as const,
roots: ["/workspace"],
executables: ["/bin/tool"],
environment_names: ["LANG"],
network: "loopback" as const,
mount: false,
};
const base = createPermissionPolicy([ceiling]);
const rootOnly = grantPermission(base, {
...ceiling,
executables: [],
environment_names: [],
network: "none",
grant_id: "root-only",
lifetime: "project",
operation_identity: null,
expires_at: null,
});
expect(rootOnly.ok).toBe(true);
if (!rootOnly.ok) return;
const executableOnly = grantPermission(rootOnly.value, {
...ceiling,
roots: [],
grant_id: "exec-only",
lifetime: "session",
operation_identity: null,
expires_at: "2026-07-14T00:00:00.000Z",
});
expect(executableOnly.ok).toBe(true);
if (!executableOnly.ok) return;
const request = {
...ceiling,
operation_identity: "capture",
};
expect(
evaluatePermission(
executableOnly.value,
request,
new Date("2026-07-13T00:00:00.000Z"),
),
).toMatchObject({ allowed: false, reason: "grant_required" });
const expiring = grantPermission(base, {
...ceiling,
grant_id: "expiring",
lifetime: "session",
operation_identity: null,
expires_at: "2026-07-14T00:00:00.000Z",
});
expect(expiring.ok).toBe(true);
if (!expiring.ok) return;
expect(
evaluatePermission(
expiring.value,
request,
new Date("2026-07-15T00:00:00.000Z"),
),
).toMatchObject({ allowed: false, reason: "grant_expired" });
expect(
clearSessionPermissions(executableOnly.value).grants.map(
({ grant_id }) => grant_id,
),
).toEqual(["root-only"]);
});
});
@@ -0,0 +1,155 @@
import { chmod, stat, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
readProjectPermissionStore,
revokeProjectPermissionGrant,
writeProjectPermissionStore,
} from "../../../src/application/ProjectPermissionStore.js";
describe("project permission store", () => {
it("persists explicit project grants atomically with owner-only permissions", async () => {
const project = await createTestTempDirectory("rea-policy-project-");
const path = join(project, ".rea", "permissions.json");
const grant = {
grant_id: "project:evidence-read",
capability: "evidence_read" as const,
roots: [project],
executables: [],
environment_names: [],
network: "none" as const,
mount: false,
lifetime: "project" as const,
operation_identity: null,
expires_at: null,
};
const written = await writeProjectPermissionStore(path, project, [grant]);
expect(written.ok).toBe(true);
expect((await stat(path)).mode & 0o077).toBe(0);
const loaded = await readProjectPermissionStore(path, project);
expect(loaded).toMatchObject({
ok: true,
value: { grants: [grant] },
});
});
it("rejects stores readable by another user class", async () => {
const project = await createTestTempDirectory("rea-policy-mode-");
const path = join(project, "permissions.json");
const written = await writeProjectPermissionStore(path, project, []);
expect(written.ok).toBe(true);
await chmod(path, 0o644);
expect(await readProjectPermissionStore(path, project)).toMatchObject({
ok: false,
error: { reason: "not_owner_only" },
});
});
it("binds grants to canonical project identity", async () => {
const first = await createTestTempDirectory("rea-policy-first-");
const second = await createTestTempDirectory("rea-policy-second-");
const path = join(first, "permissions.json");
expect((await writeProjectPermissionStore(path, first, [])).ok).toBe(true);
expect(await readProjectPermissionStore(path, second)).toMatchObject({
ok: false,
error: { reason: "invalid" },
});
});
it("rejects a symlink even when its target is owner-only", async () => {
const project = await createTestTempDirectory("rea-policy-symlink-");
const target = join(project, "target.json");
const path = join(project, "permissions.json");
expect((await writeProjectPermissionStore(target, project, [])).ok).toBe(
true,
);
await symlink(target, path);
expect(await readProjectPermissionStore(path, project)).toMatchObject({
ok: false,
error: { reason: "not_owner_only" },
});
});
it("round-trips managed runtime project grants", async () => {
const project = await createTestTempDirectory("rea-policy-managed-");
const path = join(project, "permissions.json");
const grant = {
grant_id: "project:managed-runtime",
capability: "managed_runtime" as const,
roots: [project],
executables: [process.execPath],
environment_names: [],
network: "none" as const,
mount: false,
lifetime: "project" as const,
operation_identity: null,
expires_at: null,
};
expect(
await writeProjectPermissionStore(path, project, [grant]),
).toMatchObject({ ok: true, value: { grants: [grant] } });
expect(await readProjectPermissionStore(path, project)).toMatchObject({
ok: true,
value: { grants: [grant] },
});
});
it("classifies malformed JSON as an invalid store", async () => {
const project = await createTestTempDirectory("rea-policy-invalid-");
const path = join(project, "permissions.json");
await writeFile(path, "{", { mode: 0o600 });
expect(await readProjectPermissionStore(path, project)).toMatchObject({
ok: false,
error: { reason: "invalid" },
});
});
it("serializes concurrent grant revocations without losing an update", async () => {
const project = await createTestTempDirectory("rea-policy-revoke-");
const path = join(project, ".rea", "permissions.json");
const grant = (grantId: string) => ({
grant_id: grantId,
capability: "evidence_read" as const,
roots: [project],
executables: [],
environment_names: [],
network: "none" as const,
mount: false,
lifetime: "project" as const,
operation_identity: null,
expires_at: null,
});
expect(
(
await writeProjectPermissionStore(path, project, [
grant("grant-one"),
grant("grant-two"),
])
).ok,
).toBe(true);
const revoked = await Promise.all([
revokeProjectPermissionGrant(path, project, "grant-one"),
revokeProjectPermissionGrant(path, project, "grant-two"),
]);
expect(revoked).toEqual([
{ ok: true, value: true },
{ ok: true, value: true },
]);
expect(await readProjectPermissionStore(path, project)).toMatchObject({
ok: true,
value: { grants: [] },
});
});
});
@@ -0,0 +1,242 @@
import { lstat, readFile, rm, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { resolveClientConfigTransactionPath } from "../../../src/application/ClientConfigPath.js";
import { configureJsonClient } from "../../../src/application/Setup.js";
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
const pinnedPackage = PRODUCT_IDENTITY.registrationPackageSpecifier;
let directory: string | undefined;
afterEach(async () => {
if (directory !== undefined)
await rm(directory, { recursive: true, force: true });
directory = undefined;
});
describe("JSON client configuration transaction", () => {
it("rejects a symlink target not owned by the current user", async () => {
if (typeof process.getuid !== "function") return;
const currentUid = process.getuid();
let statCalls = 0;
expect(
await resolveClientConfigTransactionPath("/config", {
lstat: () => {
statCalls += 1;
return Promise.resolve({
uid: statCalls === 1 ? currentUid : currentUid + 1,
isFile: () => statCalls > 1,
isSymbolicLink: () => statCalls === 1,
});
},
realpath: () => Promise.resolve("/target"),
}),
).toBeUndefined();
});
it("preserves existing keys, creates a backup, and reads back the MCP entry", async () => {
directory = await createTestTempDirectory("rea-setup-");
const configPath = join(directory, "mcp.json");
const original =
'{"theme":"dark","mcpServers":{"other":{"command":"other"}}}\n';
await writeFile(configPath, original);
const result = await configureJsonClient({ name: "cursor", configPath });
expect(result.status).toBe("configured");
expect(await readFile(`${configPath}.rea.backup`, "utf8")).toBe(original);
expect(JSON.parse(await readFile(configPath, "utf8"))).toMatchObject({
theme: "dark",
mcpServers: {
other: { command: "other" },
rea: {
command: "npx",
args: ["-y", pinnedPackage, "mcp"],
},
},
});
});
it("updates a symlink target without replacing the JSON config symlink", async () => {
directory = await createTestTempDirectory("rea-setup-");
const targetPath = join(directory, "managed.json");
const configPath = join(directory, "mcp.json");
const original = '{"theme":"dark"}\n';
await writeFile(targetPath, original);
await symlink(targetPath, configPath);
expect(
await configureJsonClient({ name: "cursor", configPath }),
).toMatchObject({ status: "configured" });
expect((await lstat(configPath)).isSymbolicLink()).toBe(true);
expect(await readFile(`${configPath}.rea.backup`, "utf8")).toBe(original);
expect(JSON.parse(await readFile(targetPath, "utf8"))).toMatchObject({
theme: "dark",
mcpServers: {
rea: {
command: "npx",
args: ["-y", pinnedPackage, "mcp"],
},
},
});
expect(await configureJsonClient({ name: "cursor", configPath })).toEqual({
status: "unchanged",
});
});
it("fails before mutation when a JSON config symlink is dangling", async () => {
directory = await createTestTempDirectory("rea-setup-");
const configPath = join(directory, "mcp.json");
await symlink(join(directory, "missing.json"), configPath);
expect(await configureJsonClient({ name: "cursor", configPath })).toEqual({
status: "failed",
reason: "path",
});
expect((await lstat(configPath)).isSymbolicLink()).toBe(true);
await expect(
readFile(`${configPath}.rea.backup`, "utf8"),
).rejects.toThrow();
});
it("performs no write or second backup when configuration already matches", async () => {
directory = await createTestTempDirectory("rea-setup-");
const configPath = join(directory, "mcp.json");
await writeFile(
configPath,
`${JSON.stringify({ mcpServers: { rea: { command: "npx", args: ["-y", pinnedPackage, "mcp"] } } })}\n`,
);
expect(await configureJsonClient({ name: "cursor", configPath })).toEqual({
status: "unchanged",
});
await expect(
readFile(`${configPath}.rea.backup`, "utf8"),
).rejects.toThrow();
});
});
describe("JSON client configuration migration and provider paths", () => {
it("migrates an unversioned npx registration and preserves sibling configuration", async () => {
directory = await createTestTempDirectory("rea-setup-");
const configPath = join(directory, "mcp.json");
const original =
'{"theme":"dark","mcpServers":{"rea":{"command":"npx","args":["-y","rea-agents","mcp"]},"other":{"command":"other"}}}\n';
await writeFile(configPath, original);
expect(await configureJsonClient({ name: "cursor", configPath })).toEqual(
expect.objectContaining({ status: "configured" }),
);
expect(JSON.parse(await readFile(configPath, "utf8"))).toEqual({
theme: "dark",
mcpServers: {
rea: {
command: "npx",
args: ["-y", pinnedPackage, "mcp"],
},
other: { command: "other" },
},
});
expect(await readFile(`${configPath}.rea.backup`, "utf8")).toBe(original);
});
it("persists a custom Hopper launcher and remains idempotent", async () => {
directory = await createTestTempDirectory("rea-setup-");
const configPath = join(directory, "mcp.json");
const hopperPath = "/Applications/Hopper v6.app/Contents/MacOS/hopper";
const client = { name: "cursor", configPath };
const original = "{}\n";
await writeFile(configPath, original);
expect(await configureJsonClient(client, hopperPath)).toMatchObject({
status: "configured",
});
expect(JSON.parse(await readFile(configPath, "utf8"))).toMatchObject({
mcpServers: {
rea: {
command: "npx",
args: ["-y", pinnedPackage, "mcp"],
env: { HOPPER_LAUNCHER_PATH: hopperPath },
},
},
});
expect(await configureJsonClient(client, hopperPath)).toEqual({
status: "unchanged",
});
expect(
await configureJsonClient(client, "/opt/hopper/bin/Hopper"),
).toMatchObject({ status: "configured" });
expect(await readFile(`${configPath}.rea.backup`, "utf8")).toBe(original);
});
it("adds exact BYO Ghidra and Java paths without installing dependencies", async () => {
directory = await createTestTempDirectory("rea-setup-");
const configPath = join(directory, "mcp.json");
const client = { name: "cursor", configPath };
const environment = {
GHIDRA_INSTALL_DIR: "/opt/ghidra_12.1.2_PUBLIC",
JAVA_HOME: "/usr/lib/jvm/jdk-21",
};
expect(await configureJsonClient(client, environment)).toMatchObject({
status: "configured",
});
expect(JSON.parse(await readFile(configPath, "utf8"))).toMatchObject({
mcpServers: {
rea: {
env: {
GHIDRA_INSTALL_DIR: environment.GHIDRA_INSTALL_DIR,
JAVA_HOME: environment.JAVA_HOME,
},
},
},
});
expect(await configureJsonClient(client, environment)).toEqual({
status: "unchanged",
});
});
it("refuses malformed existing JSON without overwriting it", async () => {
directory = await createTestTempDirectory("rea-setup-");
const configPath = join(directory, "mcp.json");
await writeFile(configPath, "not-json");
expect(await configureJsonClient({ name: "cursor", configPath })).toEqual({
status: "failed",
reason: "readback",
});
expect(await readFile(configPath, "utf8")).toBe("not-json");
});
it.each(["null", "[]", '"value"'])(
"refuses a non-object JSON root without overwriting %s",
async (original) => {
directory = await createTestTempDirectory("rea-setup-");
const configPath = join(directory, "mcp.json");
await writeFile(configPath, original);
expect(await configureJsonClient({ name: "cursor", configPath })).toEqual(
{ status: "failed", reason: "readback" },
);
expect(await readFile(configPath, "utf8")).toBe(original);
await expect(
readFile(`${configPath}.rea.backup`, "utf8"),
).rejects.toThrow();
},
);
it.each(["null", "[]", '"value"'])(
"preserves a non-object mcpServers value %s",
async (servers) => {
directory = await createTestTempDirectory("rea-setup-");
const configPath = join(directory, "mcp.json");
const original = `{"mcpServers":${servers}}`;
await writeFile(configPath, original);
expect(await configureJsonClient({ name: "cursor", configPath })).toEqual(
{ status: "failed", reason: "readback" },
);
expect(await readFile(configPath, "utf8")).toBe(original);
await expect(
readFile(`${configPath}.rea.backup`, "utf8"),
).rejects.toThrow();
},
);
});
@@ -0,0 +1,59 @@
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
canonicalSkillNeedsInstall,
installCanonicalSkill,
} from "../../../src/application/Setup.js";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
const roots: string[] = [];
afterEach(async () => {
await Promise.all(
roots.splice(0).map((root) => rm(root, { recursive: true })),
);
});
describe("canonical skill transaction", () => {
it("backs up and upgrades a stale managed skill without touching siblings", async () => {
const home = await createTestTempDirectory("rea-skill-test-");
roots.push(home);
const destination = join(
home,
".agents/skills/reverse-engineer-anything/SKILL.md",
);
const sibling = join(home, ".agents/skills/unrelated/SKILL.md");
await mkdir(dirname(destination), { recursive: true });
await mkdir(dirname(sibling), { recursive: true });
await writeFile(destination, "stale managed skill\n");
await writeFile(sibling, "unrelated skill\n");
expect(await canonicalSkillNeedsInstall(home)).toBe(true);
expect(await installCanonicalSkill(home)).toBe("installed");
expect(await readFile(`${destination}.rea.backup`, "utf8")).toBe(
"stale managed skill\n",
);
const installedSkill = await readFile(destination, "utf8");
expect(installedSkill).toContain('version: "23"');
expect(installedSkill).toContain(
"use normal repository tools and do not run REA",
);
expect(installedSkill).toContain(
`tool_count: ${String(TOOL_CONTRACTS.length)}`,
);
expect(await readFile(sibling, "utf8")).toBe("unrelated skill\n");
expect(
await readFile(
join(
home,
".agents/skills/reverse-engineer-anything/references/javascript-applications.md",
),
"utf8",
),
).toContain("analyze_javascript_application");
expect(await canonicalSkillNeedsInstall(home)).toBe(false);
expect(await installCanonicalSkill(home)).toBe("unchanged");
});
});
@@ -0,0 +1,78 @@
import { describe, expect, it } from "vitest";
import {
runCapabilityStatus,
runProviderStatus,
} from "../../../src/application/DirectAnalysis.js";
import { projectDoctorReport } from "../../../src/application/DoctorProjection.js";
import { runDoctor, type DoctorHost } from "../../../src/application/Doctor.js";
import { CATALOG_IDENTITY } from "../../../src/catalogIdentity.js";
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
const doctorHost = (): DoctorHost => ({
platform: "darwin",
architecture: "x64",
nodeVersion: "24.18.0",
macosVersion: () => Promise.resolve("14.0"),
linuxDistribution: () => Promise.resolve(undefined),
validTarget: () => Promise.resolve(true),
executable: (path) => Promise.resolve(path.includes("Hopper")),
supportedLinuxHopper: () => Promise.resolve(true),
linuxDemoRuntimeCheck: () =>
Promise.resolve({
name: "hopper-demo-runtime",
ok: true,
classification: "healthy",
}),
brewHopperPath: () => Promise.resolve(undefined),
manualHopperPaths: () => Promise.resolve([]),
installedSkillIdentity: () =>
Promise.resolve({
version: PRODUCT_IDENTITY.skillVersion,
toolCount: CATALOG_IDENTITY.counts.mcp_tools,
catalogDigest: CATALOG_IDENTITY.digests.combined_sha256,
}),
});
describe("purpose-specific CLI projections", () => {
it("keeps provider and capability summaries concise with explicit full detail", async () => {
const providers = await runProviderStatus();
const capabilities = await runCapabilityStatus();
const full = await runCapabilityStatus(undefined, "full");
expect(providers).toMatchObject({
open: false,
analysis_provider_candidates: expect.any(Array),
server_identity: { catalog: { counts: expect.any(Object) } },
});
expect(JSON.stringify(providers)).not.toContain('"capabilities"');
expect(JSON.stringify(providers)).not.toContain('"tools"');
expect(capabilities).toMatchObject({
summary: {
total: expect.any(Number),
available: expect.any(Number),
unavailable: expect.any(Number),
},
capabilities: expect.any(Array),
});
expect(JSON.stringify(capabilities)).not.toContain('"effects"');
expect(JSON.stringify(capabilities)).not.toContain('"limits"');
expect(JSON.stringify(full)).toContain('"effects"');
expect(JSON.stringify(full)).toContain('"catalog"');
});
it("omits the catalog tool array only from the default doctor projection", async () => {
const report = await runDoctor(undefined, doctorHost());
const summary = projectDoctorReport(report, "summary");
const full = projectDoctorReport(report, "full");
expect(summary).toMatchObject({
healthy: true,
environment_healthy: true,
failed_scope_checks: [],
informational_drift_count: 0,
});
expect(JSON.stringify(summary)).not.toContain('"tools"');
expect(JSON.stringify(full)).toContain('"tools"');
});
});