refactor(test): colocate pure-domain tests and reduce test debt (#471)

* refactor(test): colocate pure-domain tests and reduce test debt

Move focused immutable domain/contracts/adapter tests from
tests/composition/** beside their production owners under src/** as
colocated *.test.ts/*.fixture.ts, and relocate persistence-shaped
composition tests under tests/boundary/filesystem/**. Update import
paths, the Vitest project topology (shared worker context for pure
domain/contracts and recording-port service projects), the test
migration ledger, testing docs, and AGENTS.md to match.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* docs: remove test migration ledger

The cutover is complete and the ledger is no longer referenced anywhere
in source, scripts, or the docs gate. Drop the standalone artifact.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* docs: clean up stale migration artifacts

Remove empty directories left by the test migration and replace the
"final cutover" language in docs/testing.md with standing PR guidance
that no longer references the completed migration.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix: repair CI failures from schema, knip, and stale generated artifacts

Three root causes fixed:

1. catalog-schemas.mjs: valuesAt only traversed anyOf from Zod's
   toJSONSchema, not oneOf. The webScreenshotDiffSchema change to a
   discriminated union produces oneOf, so the product catalog generator
   could not derive the web_screenshot_diff schema version. Add oneOf
   traversal.

2. conformancePackage.ts: the test rewrite removed the only imports of
   ScenarioManifest, ReplayPlan, ShimPlan, and ExpectedEvidence, making
   them unused exports that knip flags. Remove the dead type aliases.

3. Regenerate stale artifacts (product catalog, MCP tool catalog, skill
   metadata, conformance manifest) that drifted from the source changes.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
morluto
2026-08-10 14:57:44 +08:00
committed by GitHub
co-authored by Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
parent 344b9b6dff
commit e91c8c39c2
302 changed files with 6822 additions and 5781 deletions
@@ -1,183 +0,0 @@
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({
status: "enabled",
target: {
access: "launch-or-attach",
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",
}),
);
});
});
describe("browser scenario policy states", () => {
it("parses each legal browser-scenario access state", () => {
const launch = parseConfig({
REA_BROWSER_SCENARIO_ENABLED: "true",
REA_BROWSER_SCENARIO_EXECUTABLE_ROOTS_JSON: '["/opt/chromium"]',
REA_BROWSER_SCENARIO_ALLOWED_ORIGINS_JSON: '["https://app.example.test"]',
});
expect(launch).toMatchObject({
ok: true,
value: {
browserScenarioPolicy: {
status: "enabled",
target: { access: "launch" },
},
},
});
const attach = parseConfig({
REA_BROWSER_SCENARIO_ENABLED: "true",
REA_BROWSER_SCENARIO_CDP_ENDPOINTS_JSON: '["http://127.0.0.1:9222"]',
REA_BROWSER_SCENARIO_ALLOWED_ORIGINS_JSON: '["https://app.example.test"]',
});
expect(attach).toMatchObject({
ok: true,
value: {
browserScenarioPolicy: {
status: "enabled",
target: { access: "attach" },
},
},
});
});
it("rejects enabled browser scenarios without an origin or access path", () => {
expect(
parseConfig({
REA_BROWSER_SCENARIO_ENABLED: "true",
REA_BROWSER_SCENARIO_EXECUTABLE_ROOTS_JSON: '["/opt/chromium"]',
}).ok,
).toBe(false);
expect(
parseConfig({
REA_BROWSER_SCENARIO_ENABLED: "true",
REA_BROWSER_SCENARIO_ALLOWED_ORIGINS_JSON:
'["https://app.example.test"]',
}).ok,
).toBe(false);
});
it("drops inactive browser-scenario settings from the parsed policy", () => {
expect(
parseConfig({
REA_BROWSER_SCENARIO_EXECUTABLE_ROOTS_JSON: '["/ignored/chromium"]',
REA_BROWSER_SCENARIO_CDP_ENDPOINTS_JSON: '["http://127.0.0.1:9222"]',
REA_BROWSER_SCENARIO_ALLOWED_ORIGINS_JSON:
'["https://ignored.example.test"]',
REA_BROWSER_SCENARIO_ALLOWED_ENV_JSON: '["IGNORED_SECRET"]',
}),
).toMatchObject({
ok: true,
value: { browserScenarioPolicy: { status: "disabled" } },
});
});
});
describe("browser runtime input scopes", () => {
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,
);
});
});
@@ -1,20 +0,0 @@
import { describe, expect, it } from "vitest";
import { parseConfig } from "../../../src/config.js";
describe("capability flags", () => {
it("rejects values outside the exact true/false boundary", () => {
const result = parseConfig({
REA_PROCESS_CAPTURE_ENABLED: "typo",
REA_BROWSER_OBSERVE_ENABLED: "typo",
REA_BROWSER_SCENARIO_ENABLED: "typo",
REA_ELECTRON_OBSERVE_ENABLED: "typo",
REA_ELECTRON_AUTOMATE_ENABLED: "typo",
REA_V8_INSPECTOR_OBSERVE_ENABLED: "typo",
REA_JAVASCRIPT_REPLAY_ENABLED: "typo",
REA_MANAGED_RUNTIME_ENABLED: "typo",
});
expect(result.ok).toBe(false);
});
});
@@ -1,68 +0,0 @@
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",
}),
]);
});
});
@@ -1,520 +0,0 @@
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.browserObservationPolicy).toEqual({
status: "disabled",
});
expect(result.value.browserScenarioPolicy).toEqual({
status: "disabled",
});
expect(result.value.electronObservationPolicy).toEqual({
status: "disabled",
});
expect(result.value.electronAutomationPolicy).toEqual({
status: "disabled",
});
expect(result.value.v8InspectorObservationPolicy).toEqual({
status: "disabled",
});
expect(result.value.javascriptReplayPolicy).toEqual({
status: "disabled",
});
expect(result.value.managedRuntimePolicy).toEqual({
status: "disabled",
});
}
});
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,
});
});
});
describe("active Electron permission configuration", () => {
it("builds a separately granted, no-network Electron automation ceiling", () => {
const result = parseConfig({
REA_ELECTRON_AUTOMATE_ENABLED: "true",
REA_ELECTRON_AUTOMATE_AUTO_GRANT: "false",
REA_ELECTRON_AUTOMATE_EXECUTABLE_ROOTS_JSON: '["/opt/electron"]',
REA_ELECTRON_AUTOMATE_APPLICATION_ROOTS_JSON: '["/tmp/apps"]',
});
if (!result.ok) throw result.error;
expect(result.value.electronAutomationPolicy).toEqual({
status: "enabled",
executableRoots: ["/opt/electron"],
applicationRoots: ["/tmp/apps"],
});
expect(result.value.permissionCeilings).toContainEqual({
capability: "electron_automate",
roots: ["/tmp/apps"],
executables: ["/opt/electron"],
environment_names: [],
network: "external",
mount: false,
});
expect(result.value.administratorPermissionGrants).not.toContainEqual(
expect.objectContaining({ capability: "electron_automate" }),
);
const granted = parseConfig({
REA_ELECTRON_AUTOMATE_ENABLED: "true",
REA_ELECTRON_AUTOMATE_AUTO_GRANT: "true",
REA_ELECTRON_AUTOMATE_EXECUTABLE_ROOTS_JSON: '["/opt/electron"]',
REA_ELECTRON_AUTOMATE_APPLICATION_ROOTS_JSON: '["/tmp/apps"]',
});
if (!granted.ok) throw granted.error;
expect(granted.value.administratorPermissionGrants).toContainEqual(
expect.objectContaining({
capability: "electron_automate",
lifetime: "administrator",
}),
);
});
it("rejects relative active Electron roots", () => {
expect(
parseConfig({
REA_ELECTRON_AUTOMATE_APPLICATION_ROOTS_JSON: '["relative/apps"]',
}).ok,
).toBe(false);
expect(
parseConfig({
REA_ELECTRON_AUTOMATE_EXECUTABLE_ROOTS_JSON: '["relative/bin"]',
}).ok,
).toBe(false);
});
it("requires both root sets only for enabled Electron automation", () => {
expect(
parseConfig({
REA_ELECTRON_AUTOMATE_ENABLED: "true",
REA_ELECTRON_AUTOMATE_APPLICATION_ROOTS_JSON: '["/tmp/apps"]',
}).ok,
).toBe(false);
expect(
parseConfig({
REA_ELECTRON_AUTOMATE_ENABLED: "true",
REA_ELECTRON_AUTOMATE_EXECUTABLE_ROOTS_JSON: '["/opt/electron"]',
}).ok,
).toBe(false);
expect(
parseConfig({
REA_ELECTRON_AUTOMATE_EXECUTABLE_ROOTS_JSON: '["/ignored/bin"]',
REA_ELECTRON_AUTOMATE_APPLICATION_ROOTS_JSON: '["/ignored/app"]',
}),
).toMatchObject({
ok: true,
value: { electronAutomationPolicy: { status: "disabled" } },
});
});
});
describe("runtime permission configuration", () => {
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.javascriptReplayPolicy).toMatchObject({
status: "enabled",
roots: ["/tmp/extracted-modules"],
nodePath: "/opt/node/bin/node",
});
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("requires a source root when JavaScript replay is enabled", () => {
expect(
parseConfig({ REA_JAVASCRIPT_REPLAY_ENABLED: "true" }),
).toMatchObject({ ok: false });
});
it("does not retain dormant JavaScript replay authority", () => {
const result = parseConfig({
REA_JAVASCRIPT_REPLAY_ENABLED: "false",
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.javascriptReplayPolicy).toEqual({
status: "disabled",
});
});
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({
status: "enabled",
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("requires a non-empty root set only for enabled managed runtime correlation", () => {
const enabled = parseConfig({ REA_MANAGED_RUNTIME_ENABLED: "true" });
expect(enabled.ok).toBe(false);
if (!enabled.ok)
expect(enabled.error.message).toContain("at least one absolute root");
expect(
parseConfig({
REA_MANAGED_RUNTIME_ROOTS_JSON: '["/ignored/while-disabled"]',
REA_MANAGED_RUNTIME_EXECUTABLE_PATH: "/ignored/dotnet",
}),
).toMatchObject({
ok: true,
value: { managedRuntimePolicy: { status: "disabled" } },
});
});
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: {
status: "disabled",
},
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);
},
);
});
@@ -1,4 +1,4 @@
import { chmod, rm, writeFile } from "node:fs/promises";
import { chmod, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -23,18 +23,13 @@ import {
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 directory = await createTestTempDirectory("rea-direct-provider-");
const targetPath = join(directory, "fixture.hop");
await writeFile(targetPath, "fixture");
vi.stubEnv("HOPPER_LAUNCHER_PATH", process.execPath);
@@ -61,7 +56,7 @@ describe("direct analysis snapshot permissions", () => {
});
it("replays a cache hit with snapshot read authority only", async () => {
directory = await createTestTempDirectory("rea-direct-snapshot-");
const directory = await createTestTempDirectory("rea-direct-snapshot-");
const snapshotPath = join(directory, "analysis.json");
const launcherPath = join(directory, "hopper-launcher");
await writeFile(launcherPath, "fixture Hopper launcher");
@@ -1,153 +0,0 @@
import { describe, expect, it } from "vitest";
import { parseConfig } from "../../../src/config.js";
describe("passive browser observation policy", () => {
it("requires both endpoint and origin scopes when enabled", () => {
expect(
parseConfig({
REA_BROWSER_OBSERVE_ENABLED: "true",
REA_BROWSER_ALLOWED_ORIGINS_JSON: '["https://app.example.test"]',
}).ok,
).toBe(false);
expect(
parseConfig({
REA_BROWSER_OBSERVE_ENABLED: "true",
REA_BROWSER_CDP_ENDPOINTS_JSON: '["http://127.0.0.1:9222"]',
}).ok,
).toBe(false);
});
it("parses one enabled policy and drops inactive settings", () => {
expect(
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"]',
}),
).toMatchObject({
ok: true,
value: {
browserObservationPolicy: {
status: "enabled",
cdpEndpoints: ["http://127.0.0.1:9222"],
allowedOrigins: ["https://app.example.test"],
},
},
});
expect(
parseConfig({
REA_BROWSER_CDP_ENDPOINTS_JSON: '["http://127.0.0.1:9222"]',
REA_BROWSER_ALLOWED_ORIGINS_JSON: '["https://ignored.example.test"]',
}),
).toMatchObject({
ok: true,
value: { browserObservationPolicy: { status: "disabled" } },
});
});
});
describe("passive Electron observation policy", () => {
it("requires both endpoint and file-root scopes when enabled", () => {
expect(
parseConfig({
REA_ELECTRON_OBSERVE_ENABLED: "true",
REA_ELECTRON_FILE_ROOTS_JSON: '["/tmp/electron-app"]',
}).ok,
).toBe(false);
expect(
parseConfig({
REA_ELECTRON_OBSERVE_ENABLED: "true",
REA_ELECTRON_CDP_ENDPOINTS_JSON: '["http://127.0.0.1:9223"]',
}).ok,
).toBe(false);
});
it("parses one enabled policy and drops inactive settings", () => {
expect(
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"]',
}),
).toMatchObject({
ok: true,
value: {
electronObservationPolicy: {
status: "enabled",
cdpEndpoints: ["http://127.0.0.1:9223"],
fileRoots: ["/tmp/electron-app"],
},
},
});
expect(
parseConfig({
REA_ELECTRON_CDP_ENDPOINTS_JSON: '["http://127.0.0.1:9223"]',
REA_ELECTRON_FILE_ROOTS_JSON: '["/ignored/electron-app"]',
}),
).toMatchObject({
ok: true,
value: { electronObservationPolicy: { status: "disabled" } },
});
});
});
describe("passive V8 Inspector observation policy", () => {
const endpoint = {
REA_V8_INSPECTOR_OBSERVE_ENABLED: "true",
REA_V8_INSPECTOR_ENDPOINTS_JSON: '["http://127.0.0.1:9229"]',
} as const;
it("requires an endpoint and at least one target-location scope", () => {
expect(
parseConfig({
REA_V8_INSPECTOR_OBSERVE_ENABLED: "true",
REA_V8_INSPECTOR_FILE_ROOTS_JSON: '["/tmp/node-app"]',
}).ok,
).toBe(false);
expect(parseConfig(endpoint).ok).toBe(false);
});
it.each([
["files", { REA_V8_INSPECTOR_FILE_ROOTS_JSON: '["/tmp/node-app"]' }],
[
"origins",
{
REA_V8_INSPECTOR_ALLOWED_ORIGINS_JSON:
'["https://renderer.example.test"]',
},
],
[
"files-and-origins",
{
REA_V8_INSPECTOR_FILE_ROOTS_JSON: '["/tmp/node-app"]',
REA_V8_INSPECTOR_ALLOWED_ORIGINS_JSON:
'["https://renderer.example.test"]',
},
],
] as const)("parses the %s location variant", (scope, environment) => {
expect(parseConfig({ ...endpoint, ...environment })).toMatchObject({
ok: true,
value: {
v8InspectorObservationPolicy: {
status: "enabled",
locations: { scope },
},
},
});
});
it("drops inactive endpoint and location settings", () => {
expect(
parseConfig({
REA_V8_INSPECTOR_ENDPOINTS_JSON: '["http://127.0.0.1:9229"]',
REA_V8_INSPECTOR_FILE_ROOTS_JSON: '["/ignored/node-app"]',
REA_V8_INSPECTOR_ALLOWED_ORIGINS_JSON:
'["https://ignored.example.test"]',
}),
).toMatchObject({
ok: true,
value: { v8InspectorObservationPolicy: { status: "disabled" } },
});
});
});
@@ -37,11 +37,11 @@ describe("permission authority", () => {
operation_identity: "read:inside-ceiling",
},
"read",
{ elicitationSupported: true },
{ remediation: "elicit" },
);
expect(inside).toMatchObject({
ok: false,
error: { elicitationSupported: true, restartRequired: false },
error: { remediation: "elicit" },
});
const outside = await authority.value.createConnectionAuthority().authorize(
@@ -50,11 +50,11 @@ describe("permission authority", () => {
operation_identity: "read:outside-ceiling",
},
"read",
{ elicitationSupported: true },
{ remediation: "elicit" },
);
expect(outside).toMatchObject({
ok: false,
error: { elicitationSupported: false, restartRequired: true },
error: { remediation: "restart" },
});
});
@@ -1,283 +0,0 @@
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"]);
});
});
@@ -1,43 +0,0 @@
import { describe, expect, it } from "vitest";
import { parseConfig } from "../../../src/config.js";
describe("process capture configuration", () => {
it("parses all authority required by enabled capture", () => {
const result = parseConfig({
REA_PROCESS_CAPTURE_ENABLED: "true",
REA_PROCESS_EXECUTABLE_ROOTS_JSON: '["/opt/tools"]',
REA_PROCESS_WORKING_ROOTS_JSON: '["/tmp/work"]',
REA_PROCESS_ALLOWED_ENV_JSON: '["TOKEN"]',
REA_PROCESS_ALLOW_EXTERNAL_NETWORK: "true",
});
if (!result.ok) throw result.error;
expect(result.value.processExecutionPolicy).toEqual({
status: "enabled",
executableRoots: ["/opt/tools"],
workingRoots: ["/tmp/work"],
allowedEnvironment: ["TOKEN"],
networkAccess: "external",
});
});
it("requires both authority roots when capture is enabled", () => {
expect(parseConfig({ REA_PROCESS_CAPTURE_ENABLED: "true" })).toMatchObject({
ok: false,
});
});
it("does not retain dormant process-capture authority", () => {
const result = parseConfig({
REA_PROCESS_CAPTURE_ENABLED: "false",
REA_PROCESS_EXECUTABLE_ROOTS_JSON: '["/opt/tools"]',
REA_PROCESS_WORKING_ROOTS_JSON: '["/tmp/work"]',
REA_PROCESS_ALLOWED_ENV_JSON: '["TOKEN"]',
REA_PROCESS_ALLOW_EXTERNAL_NETWORK: "true",
});
if (!result.ok) throw result.error;
expect(result.value.processExecutionPolicy).toEqual({
status: "disabled",
});
});
});
@@ -1,155 +0,0 @@
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: [] },
});
});
});
@@ -1,275 +0,0 @@
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();
});
it("does not rewrite an equivalent configuration with reordered environment keys", async () => {
directory = await createTestTempDirectory("rea-setup-");
const configPath = join(directory, "mcp.json");
await writeFile(
configPath,
`${JSON.stringify({
mcpServers: {
rea: {
env: {
JAVA_HOME: "/usr/lib/jvm/jdk-21",
GHIDRA_INSTALL_DIR: "/opt/ghidra",
},
args: ["-y", pinnedPackage, "mcp"],
command: "npx",
},
},
})}\n`,
);
expect(
await configureJsonClient(
{ name: "cursor", configPath },
{
GHIDRA_INSTALL_DIR: "/opt/ghidra",
JAVA_HOME: "/usr/lib/jvm/jdk-21",
},
),
).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();
},
);
});
@@ -1,59 +0,0 @@
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");
});
});
@@ -1,78 +0,0 @@
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"');
});
});