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
+387
View File
@@ -0,0 +1,387 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { afterEach, describe, expect, it } from "vitest";
import {
startFakeCdpBrowser,
type FakeCdpBrowser,
} from "../../fixtures/fakeCdpBrowser.js";
const execute = promisify(execFile);
const browsers: FakeCdpBrowser[] = [];
const INTEGRATION_TEST_TIMEOUT_MS = 60_000;
afterEach(async () => {
await Promise.all(browsers.splice(0).map(async (browser) => browser.close()));
});
describe("browser CLI parity", () => {
it(
"returns the same Evidence v2 discovery and inspection contracts",
async () => {
const browser = await startFakeCdpBrowser({
sessionTimeline: "same_origin",
webMcpTools: true,
sensitiveShapes: true,
});
browsers.push(browser);
const environment = {
...process.env,
REA_BROWSER_OBSERVE_ENABLED: "true",
REA_BROWSER_CDP_ENDPOINTS_JSON: JSON.stringify([browser.endpoint]),
REA_BROWSER_ALLOWED_ORIGINS_JSON: JSON.stringify([
browser.allowedOrigin,
]),
};
const listed = await runCli(
["list-browser-targets", browser.endpoint, "--approved", "--json"],
environment,
);
expect(listed).toMatchObject({
operation: "list_browser_targets",
provider: { id: "rea-cdp-browser" },
normalized_result: {
targets: { items: [{ target_id: "allowed-page" }] },
},
});
const inspected = await runCli(
[
"inspect-web-page",
browser.endpoint,
"allowed-page",
"--approved",
"--observation-ms",
"0",
"--include-console-text",
"--console-text-approved",
"--include-json-body-shapes",
"--json-body-schema-approved",
"--include-websocket-shapes",
"--websocket-shape-approved",
"--json",
],
environment,
);
expect(inspected).toMatchObject({
operation: "inspect_web_page",
provider: { id: "rea-cdp-browser" },
normalized_result: {
target: { target_id: "allowed-page" },
network: {
prior_activity_available: false,
requests: [
expect.objectContaining({
body_shapes: expect.objectContaining({ status: "included" }),
}),
],
},
},
});
const inspection = normalizedResult(inspected);
const compared = await runCli(
[
"compare-web-captures",
JSON.stringify({ inspection }),
JSON.stringify({ inspection }),
"--json",
],
environment,
);
expect(compared).toMatchObject({
operation: "compare_web_captures",
normalized_result: {
overall_status: "unknown",
dimensions: {
network: { status: "unknown", total_changes: 0 },
},
},
});
const scenarioCapture = completeScenarioCapture();
const scenarioCompared = await runCli(
[
"compare-web-captures",
JSON.stringify(scenarioCapture),
JSON.stringify(scenarioCapture),
"--normalization-json",
'{"rules":[]}',
"--json",
],
environment,
);
expect(scenarioCompared).toMatchObject({
operation: "compare_web_captures",
normalized_result: {
comparison_kind: "browser_scenario",
overall_status: "unchanged",
alignment: { status: "aligned", aligned_steps: 2 },
},
});
},
INTEGRATION_TEST_TIMEOUT_MS,
);
});
describe("browser CLI capture parity", () => {
it(
"returns the same analysis, session, WebMCP, screenshot, and policy contracts",
async () => {
const browser = await startFakeCdpBrowser({
sessionTimeline: "same_origin",
webMcpTools: true,
sensitiveShapes: true,
});
browsers.push(browser);
const environment = {
...process.env,
REA_BROWSER_OBSERVE_ENABLED: "true",
REA_BROWSER_CDP_ENDPOINTS_JSON: JSON.stringify([browser.endpoint]),
REA_BROWSER_ALLOWED_ORIGINS_JSON: JSON.stringify([
browser.allowedOrigin,
]),
};
const analyzed = await runCli(
[
"analyze-web-bundle",
browser.endpoint,
"allowed-page",
"--approved",
"--source-capture-approved",
"--observation-ms",
"0",
"--json",
],
environment,
);
expect(analyzed).toMatchObject({
operation: "analyze_web_bundle",
normalized_result: {
capture: { scripts_analyzed: 1 },
observations: { source_maps: { status: "not_requested" } },
},
});
const observedSession = await runCli(
[
"observe-web-session",
browser.endpoint,
"allowed-page",
"--approved",
"--observation-ms",
"5",
"--json",
],
environment,
);
expect(observedSession).toMatchObject({
operation: "observe_web_session",
normalized_result: {
window: { end_reason: "window_elapsed" },
timeline: expect.arrayContaining([
expect.objectContaining({ type: "same_origin_reload" }),
]),
},
});
const webMcp = await runCli(
[
"discover-webmcp-tools",
browser.endpoint,
"allowed-page",
"--approved",
"--observation-ms",
"0",
"--json",
],
environment,
);
expect(webMcp).toMatchObject({
operation: "discover_webmcp_tools",
normalized_result: {
tools: {
items: [expect.objectContaining({ name: "search_orders" })],
},
},
});
const screenshot = await runCli(
[
"capture-web-screenshot",
browser.endpoint,
"allowed-page",
"--approved",
"--screenshot-approved",
"--json",
],
environment,
);
const artifact = screenshotArtifact(screenshot);
expect(artifact).toMatchObject({ media_type: "image/png", bytes: 70 });
const visual = await runCli(
[
"compare-web-screenshots",
JSON.stringify(artifact),
JSON.stringify(artifact),
"--json",
],
environment,
);
expect(visual).toMatchObject({
operation: "compare_web_screenshots",
normalized_result: { status: "identical", changed_pixels: 0 },
});
const policy = await runCli(
[
"policy",
"explain",
"browser_observe",
"--origins",
browser.endpoint,
"--origins",
browser.allowedOrigin,
"--network",
"loopback",
"--json",
],
environment,
);
expect(policy).toEqual({
allowed: true,
grant_id: "administrator:browser_observe",
});
},
INTEGRATION_TEST_TIMEOUT_MS,
);
});
describe("browser CLI approval", () => {
it(
"requires explicit approval before opening the CDP endpoint",
async () => {
const browser = await startFakeCdpBrowser();
browsers.push(browser);
const result = await runCli(
["list-browser-targets", browser.endpoint, "--json"],
{
...process.env,
REA_BROWSER_OBSERVE_ENABLED: "true",
REA_BROWSER_CDP_ENDPOINTS_JSON: JSON.stringify([browser.endpoint]),
REA_BROWSER_ALLOWED_ORIGINS_JSON: JSON.stringify([
browser.allowedOrigin,
]),
},
);
expect(result).toMatchObject({
error: "Browser observation failed",
code: "invalid_request",
category: "invalid_input",
});
expect(browser.commands).toHaveLength(0);
},
INTEGRATION_TEST_TIMEOUT_MS,
);
});
const runCli = async (
arguments_: readonly string[],
environment: NodeJS.ProcessEnv,
): Promise<unknown> => {
try {
const { stdout } = await execute(
process.execPath,
["scripts/rea.mjs", ...arguments_],
{
cwd: process.cwd(),
env: environment,
maxBuffer: 16 * 1_024 * 1_024,
},
);
return JSON.parse(stdout);
} catch (cause: unknown) {
if (
typeof cause === "object" &&
cause !== null &&
"stdout" in cause &&
typeof cause.stdout === "string"
)
return JSON.parse(cause.stdout);
throw cause;
}
};
const screenshotArtifact = (value: unknown): Record<string, unknown> => {
if (
!isRecord(value) ||
!isRecord(value.normalized_result) ||
!isRecord(value.normalized_result.artifact)
)
throw new TypeError("Missing CLI screenshot artifact");
return value.normalized_result.artifact;
};
const normalizedResult = (value: unknown): Record<string, unknown> => {
if (!isRecord(value) || !isRecord(value.normalized_result))
throw new TypeError("Missing CLI normalized result");
return value.normalized_result;
};
const completeScenarioCapture = () => {
const url = {
url: "https://app.example.test/",
origin: "https://app.example.test",
query_parameter_names: [],
redacted: false,
};
const completeness = {
status: "complete",
equality_eligible: true,
missing_sections: [],
truncated_sections: [],
};
const artifacts = {
screenshot: { state: "not_requested" },
dom: { state: "not_requested" },
accessibility: { state: "not_requested" },
url: { state: "captured", value: url },
history: { state: "not_requested" },
storage: { state: "not_requested" },
};
const step = (stepIndex: number, stepId: string, action: string) => ({
step_index: stepIndex,
step_id: stepId,
action,
status: "completed",
elapsed_ms: stepIndex,
before_url: url,
after_url: url,
error: null,
event_sequence_start: 1,
event_sequence_end: 0,
artifacts,
completeness,
});
return {
schema_version: 1,
browser: {
mode: "connect",
process_ownership: "external",
cleanup: "disconnected-external",
product: "Chromium",
version: "149",
},
scenario: {
start_origin: "https://app.example.test",
allowed_origins: ["https://app.example.test"],
action_count: 1,
secret_references: [],
},
duration_ms: 1,
steps: [
step(0, "scenario_start", "scenario_start"),
step(1, "open-settings", "click"),
],
events: { retained: 0, dropped: 0, items: [] },
completeness,
limitations: [],
};
};
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
+53
View File
@@ -0,0 +1,53 @@
import { afterEach, describe, expect, it } from "vitest";
import {
isCliOperationFailure,
logCliCommand,
} from "../../../src/cliLogging.js";
import { silentLogger } from "../../../src/logger.js";
const originalExitCode = process.exitCode;
afterEach(() => {
process.exitCode = originalExitCode;
});
describe("CLI operation status", () => {
it.each([
["typed error", { error: "Analysis failed", category: "timeout" }],
["unhealthy diagnostic", { healthy: false, checks: [] }],
["failed status", { status: "failed" }],
["confirmation requirement", { status: "needs_confirmation" }],
["human remediation", { status: "needs_human" }],
["unapplied plan", { status: "planned" }],
])("classifies %s as failure", (_label, value) => {
expect(isCliOperationFailure(value)).toBe(true);
});
it.each([
["ready setup", { status: "ready" }],
["complete uninstall", { status: "complete" }],
["current version", { status: "current" }],
["completed upgrade", { status: "upgraded" }],
["healthy diagnostics", { healthy: true, checks: [] }],
["bounded evidence", { evidence: [{ truncated: true }] }],
])("keeps %s successful", (_label, value) => {
expect(isCliOperationFailure(value)).toBe(false);
});
it("sets a nonzero process status without replacing structured output", async () => {
const output = {
error: "Analysis failed",
category: "integrity_mismatch",
message: "Artifact integrity check failed.",
details: { logical_path: "main.js" },
};
await expect(
logCliCommand(silentLogger, "inventory-artifact", () =>
Promise.resolve(output),
),
).resolves.toBe(output);
expect(process.exitCode).toBe(1);
});
});
+236
View File
@@ -0,0 +1,236 @@
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { createPackageWithOptions } from "@electron/asar";
import { describe, expect, it } from "vitest";
import { fixtureTest } from "../../support/fixtures.js";
import {
renderCliOutputArgumentError,
sanitizeCliOutput,
validateCliOutputArguments,
} from "../../../src/cliOutput.js";
const CLI_INTEGRATION_TIMEOUT_MS = 60_000;
const CLI_VARIANT_TIMEOUT_MS = 120_000;
describe("CLI output argument and sanitization boundary", () => {
it("rejects token windows that would corrupt structured output", () => {
for (const format of ["json", "jsonl", "yaml"] as const) {
const validation = validateCliOutputArguments([
"providers",
"--token-limit",
"5",
"--format",
format,
]);
expect(validation).toMatchObject({
ok: false,
format,
code: "UNSUPPORTED_OUTPUT_COMBINATION",
});
if (!validation.ok) {
const rendered = renderCliOutputArgumentError(validation);
expect(rendered).not.toContain("[truncated:");
if (format === "json" || format === "jsonl")
expect(JSON.parse(rendered)).toMatchObject({
ok: false,
error: { code: "UNSUPPORTED_OUTPUT_COMBINATION" },
});
else
expect(rendered).toMatch(
/^ok: false\nerror:\n code: UNSUPPORTED_OUTPUT_COMBINATION\n/u,
);
}
}
expect(
validateCliOutputArguments([
"providers",
"--token-limit",
"5",
"--format",
"toon",
]),
).toEqual({ ok: true });
expect(
validateCliOutputArguments(["providers", "--token-count", "--json"]),
).toEqual({ ok: true });
});
fixtureTest(
"fails before emitting a truncated JSON document",
async ({ cli }) => {
const result = await cli.run({
arguments: ["providers", "--token-limit", "5", "--json"],
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
ok: false,
error: { code: "UNSUPPORTED_OUTPUT_COMBINATION" },
});
},
CLI_INTEGRATION_TIMEOUT_MS,
);
it("preserves normal output and sanitizes text and JSON validation errors", () => {
expect(sanitizeCliOutput("result: ok\n")).toBe("result: ok\n");
expect(sanitizeCliOutput("result: VALIDATION_ERROR\n")).toBe(
"result: VALIDATION_ERROR\n",
);
const raw =
'code: VALIDATION_ERROR\nmessage: "raw Zod details"\nfieldErrors: SECRET\n';
expect(sanitizeCliOutput(raw)).toBe(
'code: VALIDATION_ERROR\nmessage: "REA could not read the command arguments. Run `rea --help`, correct the arguments, then try again."\n',
);
expect(
JSON.parse(
sanitizeCliOutput(
JSON.stringify({
code: "VALIDATION_ERROR",
message: "raw Zod details",
fieldErrors: [{ code: "invalid_type" }],
}),
),
),
).toEqual({
code: "VALIDATION_ERROR",
message:
"REA could not read the command arguments. Run `rea --help`, correct the arguments, then try again.",
});
expect(
JSON.parse(
sanitizeCliOutput(
JSON.stringify({
ok: false,
error: {
code: "VALIDATION_ERROR",
message: "raw Zod details",
fieldErrors: [{ code: "invalid_type" }],
},
meta: { command: "analyze" },
}),
),
),
).toEqual({
ok: false,
error: {
code: "VALIDATION_ERROR",
message:
"REA could not read the command arguments. Run `rea --help`, correct the arguments, then try again.",
},
meta: { command: "analyze" },
});
});
});
describe("compiled CLI output boundary", () => {
fixtureTest(
"sanitizes a real missing-argument dispatcher failure",
async ({ cli }) => {
const ordinary = await cli.run({ arguments: ["analyze"] });
expect(ordinary).toMatchObject({
exitCode: 1,
stdout:
'code: VALIDATION_ERROR\nmessage: "REA could not read the command arguments. Run `rea --help`, correct the arguments, then try again."\n',
});
const json = await cli.run({
arguments: ["--full-output", "--json", "analyze"],
});
expect(json).toMatchObject({
exitCode: 1,
stdout: expect.not.stringContaining("fieldErrors"),
});
const yaml = await cli.run({
arguments: ["--full-output", "analyze"],
});
expect(yaml).toMatchObject({
exitCode: 1,
stdout:
'ok: false\nerror:\n code: VALIDATION_ERROR\n message: "REA could not read the command arguments. Run `rea --help`, correct the arguments, then try again."\n',
});
},
CLI_INTEGRATION_TIMEOUT_MS,
);
fixtureTest(
"preserves artifact diagnostics in ordinary and full JSON output",
async ({ cli, workspace }) => {
const source = workspace.path("source");
await mkdir(source);
await writeFile(join(source, "main.js"), "console.log('ok');\n");
const archive = workspace.path("fixture.asar");
await createPackageWithOptions(source, archive, { unpack: "*.js" });
await writeFile(join(`${archive}.unpacked`, "main.js"), "changed();\n");
for (const flags of [["--json"], ["--full-output", "--json"]]) {
const result = await cli.run({
arguments: [...flags, "inventory-artifact", archive],
});
expect(result.exitCode).toBe(1);
const output = JSON.stringify(result.json);
expect(output).toContain('"logical_path":"main.js"');
expect(output).toMatch(/"declared_sha256":"[a-f0-9]{64}"/u);
expect(output).toMatch(/"calculated_sha256":"[a-f0-9]{64}"/u);
expect(output).toContain('"unpacked":true');
}
},
CLI_INTEGRATION_TIMEOUT_MS,
);
fixtureTest(
"keeps operation failure status independent of output controls",
async ({ cli }) => {
const variants = [
["--format", "toon"],
["--format", "json"],
["--format", "yaml"],
["--format", "md"],
["--format", "jsonl"],
["--full-output", "--json"],
["--filter-output", "category", "--json"],
["--token-limit", "5", "--json"],
["--token-count", "--json"],
];
for (const flags of variants) {
const result = await cli.run({
arguments: [
...flags,
"investigate-versions",
"/tmp/left",
"/tmp/right",
"/tmp/workspace.json",
],
});
expect(result).toMatchObject({
exitCode: 1,
stdout: expect.any(String),
});
}
},
CLI_VARIANT_TIMEOUT_MS,
);
fixtureTest(
"keeps failure logs out of structured stdout",
async ({ cli }) => {
const result = await cli.run({
arguments: [
"--json",
"investigate-versions",
"/tmp/left",
"/tmp/right",
"/tmp/workspace.json",
],
environment: { REA_LOG_LEVEL: "error" },
});
expect(result).toMatchObject({
exitCode: 1,
stderr: expect.stringContaining('"status":"error"'),
});
expect(result.json).toMatchObject({ error: "ApprovalRequired" });
},
CLI_INTEGRATION_TIMEOUT_MS,
);
});
@@ -0,0 +1,156 @@
import { execFile } from "node:child_process";
import { readFile, rm } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
import { afterEach, describe, expect, it, vi } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
readProjectPermissionStore,
writeProjectPermissionStore,
} from "../../../src/application/ProjectPermissionStore.js";
import { approvePolicyRevocation } from "../../../src/cliPolicyCommands.js";
const execute = promisify(execFile);
const roots: string[] = [];
afterEach(async () => {
await Promise.all(
roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
);
});
describe("policy revocation approval", () => {
it("accepts --yes without invoking the interactive prompt", async () => {
const confirm = vi.fn<() => Promise<boolean>>();
await expect(
approvePolicyRevocation({
approved: true,
interactive: false,
grantId: "grant-1",
confirm,
}),
).resolves.toEqual({ approved: true });
expect(confirm).not.toHaveBeenCalled();
});
it("fails closed for non-interactive revocation without --yes", async () => {
const confirm = vi.fn<() => Promise<boolean>>();
await expect(
approvePolicyRevocation({
approved: false,
interactive: false,
grantId: "grant-1",
confirm,
}),
).resolves.toEqual({ approved: false, reason: "required" });
expect(confirm).not.toHaveBeenCalled();
});
it.each([
[true, { approved: true }],
[false, { approved: false, reason: "cancelled" }],
] as const)(
"uses the interactive decision %s",
async (decision, expected) => {
const confirm = vi.fn(() => Promise.resolve(decision));
await expect(
approvePolicyRevocation({
approved: false,
interactive: true,
grantId: "grant-1",
confirm,
}),
).resolves.toEqual(expected);
expect(confirm).toHaveBeenCalledWith("grant-1");
},
);
it("keeps the packaged project store unchanged until --yes is supplied", async () => {
const project = await createTestTempDirectory("rea-policy-cli-");
roots.push(project);
const store = join(project, ".rea", "permissions.json");
const grant = {
grant_id: "project:revoke-me",
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(store, project, [grant]),
).toMatchObject({
ok: true,
value: { grants: [grant] },
});
const before = await readFile(store);
const environment = {
...process.env,
REA_PERMISSION_PROJECT_ROOT: project,
REA_PERMISSION_PROJECT_STORE: store,
};
const denied = await runCli(
["policy", "revoke", grant.grant_id, "--json"],
environment,
);
expect(denied.status).toBe(1);
expect(denied.output).toEqual({
error:
"Policy revoke requires confirmation. Rerun interactively or with --yes.",
grant_id: grant.grant_id,
});
expect(await readFile(store)).toEqual(before);
const approved = await runCli(
["policy", "revoke", grant.grant_id, "--yes", "--json"],
environment,
);
expect(approved).toEqual({
status: 0,
output: {
revoked: grant.grant_id,
reload: "Send SIGHUP to the REA MCP process",
},
});
expect(await readProjectPermissionStore(store, project)).toMatchObject({
ok: true,
value: { grants: [] },
});
}, 40_000);
});
const runCli = async (
arguments_: readonly string[],
environment: NodeJS.ProcessEnv,
): Promise<{ readonly status: number; readonly output: unknown }> => {
try {
const { stdout } = await execute(
process.execPath,
["scripts/rea.mjs", ...arguments_],
{ cwd: process.cwd(), env: environment },
);
return { status: 0, output: JSON.parse(stdout) };
} catch (cause: unknown) {
if (
typeof cause === "object" &&
cause !== null &&
"code" in cause &&
typeof cause.code === "number" &&
"stdout" in cause &&
typeof cause.stdout === "string"
)
return { status: cause.code, output: JSON.parse(cause.stdout) };
throw cause;
}
};
+399
View File
@@ -0,0 +1,399 @@
import { execFile } from "node:child_process";
import { rm } from "node:fs/promises";
import { promisify } from "node:util";
import { spawn } from "@lydell/node-pty";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const execute = promisify(execFile);
const decisionMarker = "REA_SETUP_DECISION:";
const actions = [
{
id: "configure_client:codex",
kind: "configure_client",
label: "Codex",
target: "/isolated/.codex/config.toml",
detail: "Add the REA MCP registration for Codex.",
external: false,
operation: "create",
},
{
id: "install_skill",
kind: "install_skill",
label: "REA reverse-engineering skill",
target: "/isolated/.agents/skills/reverse-engineering/SKILL.md",
detail: "Install the bundled reverse-engineering skill.",
external: false,
operation: "install",
},
{
id: "install_hopper",
kind: "install_hopper",
label: "Hopper deep-analysis provider",
target: "/isolated/Applications/Hopper Disassembler.app",
detail: "Install the verified Hopper package.",
external: true,
operation: "install",
},
] as const;
describe("interactive setup journey", () => {
it("leads with value, a compact detected-target summary, and durable key help", async () => {
const result = await runJourney([
step("What should REA set up?", "\u0003"),
]);
expect(result.output).toContain(
"Understand local apps and binaries from your coding agent.",
);
expect(result.output).toContain(
"Trace how a feature works with local evidence.",
);
expect(result.output).toContain("Found 1 supported agent");
expect(result.output).toContain("Codex");
expect(result.output).toContain("Hopper deep-analysis provider (provider)");
expect(result.output).toContain(
"Agent integration (MCP + guided workflow)",
);
expect(result.output).toContain(
"Keys: ↑/↓ navigate · Space toggle · Enter confirm · Ctrl-C cancel",
);
expect(result.decision.approved).toBe(false);
});
it("allows deselecting the pre-selected agent integration to opt out", async () => {
const result = await runJourney([step("What should REA set up?", " \r")]);
expect(result.output).toContain(
"Agent integration (MCP + guided workflow)",
);
expect(result.output).not.toContain(
"REA reverse-engineering skill (skill)",
);
expect(result.output).toContain("Hopper deep-analysis provider (provider)");
expect(result.output).not.toContain("Ready to review");
expect(result.output).toContain("Nothing selected. No changes were made.");
expect(result.decision).toEqual({
approved: false,
selectedActionIds: [],
});
});
it("pre-selects agent integration and proceeds to the agent picker on Enter", async () => {
const result = await runJourney([
step("What should REA set up?", "\r"),
step("Which agents should use REA?", "\u0003"),
]);
expect(result.output).toContain("Codex (detected)");
expect(result.output).toContain("Setup cancelled. No changes were made.");
expect(result.decision.approved).toBe(false);
});
it("offers one bundled repair when MCP is aligned but the skill is missing", async () => {
const result = await runJourney(
[step("What should REA set up?", "\r"), step("Apply this change?", "\r")],
false,
actions.filter(({ kind }) => kind !== "configure_client"),
);
expect(result.output).toContain("No agent integrations need configuration");
expect(result.output).toContain(
"Agent integration (MCP + guided workflow)",
);
expect(result.output).not.toContain(
"REA reverse-engineering skill (skill)",
);
expect(result.decision).toEqual({
approved: true,
selectedActionIds: ["install_skill"],
});
});
it("pre-selects all detected agents in the agent picker", async () => {
const result = await runJourney(
[
step("What should REA set up?", "\r"),
step("Which agents should use REA?", "\u0003"),
],
false,
[
actions[0],
{
...actions[0],
id: "configure_client:cursor",
label: "Cursor",
target: "/isolated/.cursor/mcp.json",
},
...actions.slice(1),
],
);
expect(result.output).toContain("Codex (detected)");
expect(result.output).toContain("Cursor (detected)");
expect(result.decision.approved).toBe(false);
});
});
describe("interactive setup selection and confirmation", () => {
it("retains the bundled skill even when all agents are deselected (#399)", async () => {
const result = await runJourney([
step("What should REA set up?", "\r"),
step("Which agents should use REA?", " \r"),
step("Apply this change?", "\r"),
]);
expect(result.output).toContain("Ready to review");
expect(result.output).toContain("INSTALL REA reverse-engineering skill");
expect(result.output).not.toContain("CREATE Codex");
expect(result.decision).toEqual({
approved: true,
selectedActionIds: ["install_skill"],
});
});
it("defaults the final confirmation to Yes, apply", async () => {
const result = await runJourney([
step("What should REA set up?", "\r"),
step("Which agents should use REA?", "\r"),
step("Apply these 2 changes?", "\r"),
]);
expect(result.output).toContain("Ready to review");
expect(result.output).toContain("CREATE Codex");
expect(result.output).toContain("/isolated/.codex/config.toml");
expect(result.output).toContain("INSTALL REA reverse-engineering skill");
expect(result.output).not.toContain(
"INSTALL Hopper deep-analysis provider",
);
expect(result.output).toContain("Yes, apply");
expect(result.decision).toEqual({
approved: true,
selectedActionIds: ["configure_client:codex", "install_skill"],
});
});
it("can still be cancelled at the final confirmation", async () => {
const result = await runJourney([
step("What should REA set up?", "\r"),
step("Which agents should use REA?", "\r"),
step("Apply these 2 changes?", "\u001b[D\r"),
]);
expect(result.output).toContain("Ready to review");
expect(result.output).toContain("Setup cancelled. No changes were made.");
expect(result.decision).toEqual({
approved: false,
selectedActionIds: ["configure_client:codex", "install_skill"],
});
});
it("repairs an aligned agent integration through the bundled option", async () => {
const result = await runJourney(
[step("What should REA set up?", "\r"), step("Apply this change?", "\r")],
false,
actions.filter(({ kind }) => kind !== "configure_client"),
);
expect(result.output).toContain("INSTALL REA reverse-engineering skill");
expect(result.output).toContain(
"Agent integration (MCP + guided workflow)",
);
expect(result.output).not.toContain("CREATE Codex");
expect(result.output).not.toContain(
"INSTALL Hopper deep-analysis provider",
);
expect(result.decision).toEqual({
approved: true,
selectedActionIds: ["install_skill"],
});
});
it("defaults accessible agent integration to Yes and others to No", async () => {
const result = await runJourney(
[
step("Set up Agent integration (MCP + guided workflow)?", "\r"),
step("Set up Hopper deep-analysis provider (provider)?", "\r"),
step("Apply this change?", "\r"),
],
true,
actions.filter(({ kind }) => kind !== "configure_client"),
);
expect(result.output).toContain("Ready to review");
expect(result.output).toContain("INSTALL REA reverse-engineering skill");
expect(result.decision).toEqual({
approved: true,
selectedActionIds: ["install_skill"],
});
});
it("allows accessible opt-out of the pre-selected agent integration", async () => {
const result = await runJourney(
[
step("Set up Agent integration (MCP + guided workflow)?", "\u001b[B\r"),
step("Set up Hopper deep-analysis provider (provider)?", "\r"),
],
true,
);
expect(result.output).toContain("Nothing selected. No changes were made.");
expect(result.decision.selectedActionIds).toEqual([]);
});
});
describe("interactive setup completion", () => {
it("frames completion around the capabilities that are now ready", async () => {
const { stderr } = await execute(
process.execPath,
[
"--input-type=module",
"--eval",
[
'import { renderInteractiveSetupResult } from "./dist/cliSetup.js";',
"renderInteractiveSetupResult({",
' status: "ready",',
" plannedActions: [],",
" appliedActions: [],",
' clients: { codex: { status: "configured" } },',
" doctor: {",
" healthy: true,",
' hopperPath: "/Applications/Hopper",',
" checks: [],",
' providerInspections: [{ id: "ghidra", available: true }],',
' identity: { skill: { state: "aligned" }, registrations: [{ client: "codex", state: "aligned" }] },',
" },",
"});",
].join("\n"),
],
{
cwd: process.cwd(),
env: { ...process.env, NO_COLOR: "1" },
},
);
expect(stderr).toContain("What you can do now");
expect(stderr).toContain("Deep analysis: Hopper and Ghidra");
expect(stderr).toContain("Agent access: Codex");
expect(stderr).toContain("Guided reverse-engineering workflows: installed");
expect(stderr).toContain("CLI: rea analyze /path/to/app");
expect(stderr).toContain(
'Try in Codex: "Explain how a feature works in /path/to/app and show the evidence."',
);
});
});
interface JourneyStep {
readonly prompt: string;
readonly input: string;
}
interface JourneyResult {
readonly output: string;
readonly decision: {
readonly approved: boolean;
readonly selectedActionIds: readonly string[];
};
}
const step = (prompt: string, input: string): JourneyStep => ({
prompt,
input,
});
const runJourney = async (
steps: readonly JourneyStep[],
accessible = false,
journeyActions: readonly object[] = actions,
): Promise<JourneyResult> => {
const isolatedHome = await createTestTempDirectory("rea-cli-setup-test-");
const script = [
'import { confirmInteractiveSetup } from "./dist/cliSetup.js";',
`const actions = ${JSON.stringify(journeyActions)};`,
`const decision = await confirmInteractiveSetup(actions, ${JSON.stringify(accessible)});`,
`process.stdout.write(${JSON.stringify(`\n${decisionMarker}`)} + JSON.stringify(decision) + "\\n");`,
].join("\n");
return new Promise<JourneyResult>((resolvePromise, reject) => {
let output = "";
let nextStep = 0;
let settled = false;
const terminal = spawn(
process.execPath,
["--input-type=module", "--eval", script],
{
cwd: process.cwd(),
env: {
...process.env,
HOME: isolatedHome,
NO_COLOR: "1",
TERM: "xterm-256color",
},
name: "xterm-256color",
cols: 120,
rows: 40,
},
);
const timeout = setTimeout(() => {
terminal.kill();
finish(new Error(`Timed out after output:\n${output}`));
}, 10_000);
terminal.onData((data) => {
output += data;
const pending = steps[nextStep];
if (pending !== undefined && output.includes(pending.prompt)) {
nextStep += 1;
terminal.write(pending.input);
}
});
terminal.onExit(({ exitCode }) => {
if (exitCode !== 0) {
finish(
new Error(`Setup journey exited ${String(exitCode)}:\n${output}`),
);
return;
}
if (nextStep !== steps.length) {
finish(new Error(`Setup journey missed an interaction:\n${output}`));
return;
}
const markerIndex = output.lastIndexOf(decisionMarker);
if (markerIndex === -1) {
finish(new Error(`Setup journey returned no decision:\n${output}`));
return;
}
const serialized = output
.slice(markerIndex + decisionMarker.length)
.split(/\r?\n/u, 1)[0];
if (serialized === undefined) {
finish(
new Error(`Setup journey returned an empty decision:\n${output}`),
);
return;
}
try {
finish(undefined, {
output,
decision: JSON.parse(serialized) as JourneyResult["decision"],
});
} catch (cause: unknown) {
finish(cause instanceof Error ? cause : new Error(String(cause)));
}
});
function finish(error?: Error, result?: JourneyResult): void {
if (settled) return;
settled = true;
clearTimeout(timeout);
void rm(isolatedHome, { recursive: true, force: true }).finally(() => {
if (error !== undefined) reject(error);
else if (result !== undefined) resolvePromise(result);
else reject(new Error("Setup journey completed without a result"));
});
}
});
};
+103
View File
@@ -0,0 +1,103 @@
import { copyFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect } from "vitest";
import { fixtureTest } from "../../support/fixtures.js";
describe("executable dispatcher", () => {
fixtureTest(
"reserves production MCP routing for bare mode arguments",
async ({ processes, workspace }) => {
const scripts = await workspace.mkdir("scripts");
await workspace.mkdir("dist");
await Promise.all([
copyFile("scripts/rea.mjs", join(scripts, "rea.mjs")),
copyFile(
"scripts/package-runner-bootstrap.mjs",
join(scripts, "package-runner-bootstrap.mjs"),
),
workspace.write(
"package.json",
JSON.stringify({ type: "module", version: "1.0.0" }),
),
workspace.write(
"dist/main.js",
'export const runEntrypoint = () => process.stdout.write(JSON.stringify({ adapter: "mcp" }));\n',
),
workspace.write(
"dist/cli.js",
'export const createCli = () => ({ serve: (args) => process.stdout.write(JSON.stringify({ adapter: "cli", args })) });\n',
),
workspace.write(
"dist/cliOutput.js",
"export const sanitizeCliOutput = (output) => output; export const validateCliOutputArguments = () => ({ ok: true }); export const renderCliOutputArgumentError = () => '';\n",
),
workspace.write(
"dist/mcpDoctor.js",
'export const runProductionMcpDoctorCli = (args) => Promise.resolve({ output: JSON.stringify({ adapter: "mcp-doctor", args }), exitCode: 0 });\n',
),
]);
const invoke = async (args: readonly string[]): Promise<unknown> => {
const { exitCode, stdout } = await processes.run(
process.execPath,
[join(scripts, "rea.mjs"), ...args],
{ cwd: workspace.root },
);
expect(exitCode).toBe(0);
return JSON.parse(stdout) as unknown;
};
await expect(invoke(["mcp"])).resolves.toEqual({ adapter: "mcp" });
await expect(invoke(["--mcp"])).resolves.toEqual({ adapter: "mcp" });
await expect(invoke(["mcp", "doctor", "--json"])).resolves.toEqual({
adapter: "mcp-doctor",
args: ["--json"],
});
await expect(invoke(["mcp", "add"])).resolves.toEqual({
adapter: "cli",
args: ["mcp", "add"],
});
await expect(invoke(["--mcp", "extra"])).resolves.toEqual({
adapter: "cli",
args: ["--mcp", "extra"],
});
},
);
fixtureTest(
"explains how to restore a missing compiled runtime",
async ({ processes, workspace }) => {
const scripts = await workspace.mkdir("scripts");
await Promise.all([
copyFile("scripts/rea.mjs", join(scripts, "rea.mjs")),
copyFile(
"scripts/package-runner-bootstrap.mjs",
join(scripts, "package-runner-bootstrap.mjs"),
),
workspace.write(
"package.json",
JSON.stringify({ type: "module", version: "1.0.0" }),
),
]);
for (const args of [["mcp"], ["mcp", "doctor"], ["--help"]]) {
const result = await processes.run(
process.execPath,
[join(scripts, "rea.mjs"), ...args],
{ cwd: workspace.root },
);
expect(result).toMatchObject({
exitCode: 1,
stderr: expect.stringContaining(
"REA's compiled runtime is missing. Run `npm ci` in",
),
});
expect(result).toMatchObject({
stderr: expect.not.stringContaining("ERR_MODULE_NOT_FOUND"),
});
}
},
);
});
+455
View File
@@ -0,0 +1,455 @@
import { describe, expect, it } from "vitest";
import { runDoctor, type DoctorHost } from "../../../src/application/Doctor.js";
import { CATALOG_IDENTITY } from "../../../src/catalogIdentity.js";
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
const host = (overrides: Partial<DoctorHost> = {}): DoctorHost => ({
platform: "darwin",
architecture: "x64",
nodeVersion: "24.18.0",
macosVersion: () => Promise.resolve("12.0"),
linuxDistribution: () => Promise.resolve(undefined),
validTarget: (path) => Promise.resolve(path.includes("Hopper")),
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,
}),
...overrides,
});
describe("doctor", () => {
it("returns exact recovery for every failed diagnostic", async () => {
const result = await runDoctor(
"/missing/app",
host({
nodeVersion: "20.0.0",
macosVersion: () => Promise.resolve("11.7"),
executable: () => Promise.resolve(false),
validTarget: () => Promise.resolve(false),
}),
);
expect(
Object.fromEntries(
result.checks.map(({ name, remediation }) => [name, remediation]),
),
).toEqual({
node: "Install Node.js 22.19+ or 24.11+.",
host: "REA supports macOS 12+, Ubuntu 24.04+, Fedora 41+, 64-bit Arch Linux, and the experimental Windows x64 Ghidra P0 boundary.",
hopper: "Run rea setup to install Hopper, or set HOPPER_LAUNCHER_PATH.",
target: "Supply a readable local app or program path.",
});
});
it.each(["11.7", undefined])(
"rejects unsupported macOS version %s",
async (version) => {
const result = await runDoctor(
undefined,
host({ macosVersion: () => Promise.resolve(version) }),
);
expect(result.checks.find(({ name }) => name === "host")?.ok).toBe(false);
},
);
it("admits only the experimental Windows x64 host boundary", async () => {
const windows = await runDoctor(
undefined,
host({
platform: "win32",
architecture: "x64",
macosVersion: () => Promise.resolve(undefined),
executable: () => Promise.resolve(false),
}),
);
const arm = await runDoctor(
undefined,
host({
platform: "win32",
architecture: "arm64",
macosVersion: () => Promise.resolve(undefined),
executable: () => Promise.resolve(false),
}),
);
expect(windows.checks.find(({ name }) => name === "host")).toMatchObject({
ok: true,
detail: "win32 x64",
});
expect(arm.checks.find(({ name }) => name === "host")).toMatchObject({
ok: false,
detail: "win32 arm64",
});
});
it("detects a manual configured Hopper before Homebrew", async () => {
let brewProbes = 0;
const result = await runDoctor(
undefined,
host({
configuredHopperPath: "/manual/Hopper",
executable: (path) => Promise.resolve(path === "/manual/Hopper"),
brewHopperPath: () => {
brewProbes += 1;
return Promise.resolve(undefined);
},
}),
);
expect(result.hopperPath).toBe("/manual/Hopper");
expect(result.healthy).toBe(true);
expect(brewProbes).toBe(0);
});
it("reports optional BYO ilspycmd diagnostics only when configured", async () => {
const result = await runDoctor(
undefined,
host({
configuredIlspyCmdPath: "/tools/ilspycmd",
ilspyCmdVersion: (path) =>
Promise.resolve(
path === "/tools/ilspycmd" ? "ilspycmd: 9.1.0.7988" : undefined,
),
}),
);
expect(result.healthy).toBe(true);
expect(result.checks).toContainEqual({
name: "ilspycmd",
ok: true,
classification: "healthy",
detail: "/tools/ilspycmd (ilspycmd: 9.1.0.7988)",
});
});
it("reports configured ilspycmd drift without installing it", async () => {
const result = await runDoctor(
undefined,
host({
configuredIlspyCmdPath: "/missing/ilspycmd",
ilspyCmdVersion: () => Promise.resolve(undefined),
}),
);
expect(result.healthy).toBe(false);
expect(result.checks).toContainEqual({
name: "ilspycmd",
ok: false,
classification: "config_drift",
detail: "/missing/ilspycmd",
remediation:
"Unset REA_ILSPY_CMD_PATH or point it at a runnable ilspycmd executable.",
});
});
it("does not fall back when the configured Hopper launcher is invalid", async () => {
const configuredPath = "/invalid/custom/hopper";
const result = await runDoctor(
undefined,
host({ configuredHopperPath: configuredPath }),
);
expect(result.hopperPath).toBeUndefined();
expect(result.healthy).toBe(false);
expect(result.checks.find(({ name }) => name === "hopper")).toEqual({
name: "hopper",
ok: false,
classification: "config_drift",
detail: configuredPath,
remediation:
"Unset or update HOPPER_LAUNCHER_PATH to an executable Hopper launcher.",
});
});
});
describe("doctor installation identity", () => {
it("distinguishes stale skills, path shadowing, and unobservable live state", async () => {
const result = await runDoctor(
undefined,
host({
installationPaths: () =>
Promise.resolve(["/usr/local/bin/rea", "/home/user/bin/rea"]),
installedSkillIdentity: () =>
Promise.resolve({
version: "10",
toolCount: null,
catalogDigest: null,
}),
}),
);
expect(result.identity).toMatchObject({
live_server: { state: "unknown" },
installations: { state: "multiple" },
skill: {
installed_version: "10",
state: "stale",
remediation: "Run rea setup to update the installed REA skill.",
},
});
});
it("reports a missing installed skill as unhealthy", async () => {
const result = await runDoctor(
undefined,
host({ installedSkillIdentity: () => Promise.resolve(undefined) }),
);
expect(result.healthy).toBe(false);
expect(result.identity?.skill).toMatchObject({
state: "missing",
remediation: "Run rea setup to update the installed REA skill.",
});
expect(result.checks).toContainEqual({
name: "skill:identity",
ok: false,
classification: "config_drift",
detail: "Installed REA skill identity is missing.",
remediation: "Run rea setup to update the installed REA skill.",
});
});
it("reports stale client registration paths without claiming live state", async () => {
const result = await runDoctor(
undefined,
host({
clientRegistrations: () =>
Promise.resolve([
{
client: "codex",
config_path: "/home/user/.codex/config.toml",
command: ["/old/rea", "mcp"],
state: "stale",
remediation:
"Run rea setup to refresh this registration, then restart the client.",
},
]),
}),
);
expect(result.healthy).toBe(false);
expect(result.identity).toMatchObject({
live_server: { state: "unknown" },
registrations: [{ client: "codex", state: "stale" }],
});
expect(result.checks).toContainEqual(
expect.objectContaining({
name: "registration:codex",
classification: "config_drift",
}),
);
});
});
describe("doctor scoped readiness", () => {
it("scopes effective readiness to selected clients without hiding drift", async () => {
const registrations = [
{
client: "codex",
config_path: "/home/user/.codex/config.toml",
command: ["/current/rea", "mcp"],
state: "aligned" as const,
remediation: null,
},
{
client: "cursor",
config_path: "/home/user/.cursor/mcp.json",
command: ["/old/rea", "mcp"],
state: "stale" as const,
remediation: "Run rea setup to refresh this registration.",
},
];
const scoped = await runDoctor(
undefined,
host({ clientRegistrations: () => Promise.resolve(registrations) }),
{ clients: ["codex"] },
);
expect(scoped).toMatchObject({
healthy: true,
environment_healthy: false,
scope: { mode: "explicit", clients: ["codex"] },
});
expect(scoped.scope_checks).toContainEqual(
expect.objectContaining({ name: "registration:codex", ok: true }),
);
expect(scoped.informational_checks).toContainEqual(
expect.objectContaining({ name: "registration:cursor", ok: false }),
);
const staleSelected = await runDoctor(
undefined,
host({ clientRegistrations: () => Promise.resolve(registrations) }),
{ clients: ["cursor"] },
);
expect(staleSelected.healthy).toBe(false);
});
it("requires explicitly selected providers instead of any available provider", async () => {
const ghidra = {
id: "ghidra",
configured: true,
available: true,
providerVersion: "12.1.2",
registrationEnvironment: { GHIDRA_INSTALL_DIR: "/tools/ghidra" },
checks: [
{
name: "configuration",
ok: true,
code: null,
detail: "/tools/ghidra",
remediation: null,
classification: "config_drift" as const,
},
],
};
const noHopper = host({
executable: () => Promise.resolve(false),
providerInspections: () => Promise.resolve([ghidra]),
});
const hopper = await runDoctor(undefined, noHopper, {
providers: ["hopper"],
});
expect(hopper).toMatchObject({
healthy: false,
environment_healthy: true,
});
const selectedGhidra = await runDoctor(undefined, noHopper, {
providers: ["ghidra"],
});
expect(selectedGhidra.healthy).toBe(true);
});
});
describe("doctor Linux and Hopper discovery", () => {
it("accepts an officially supported Linux distribution", async () => {
const path = "/home/user/.local/share/rea/hopper/bin/Hopper";
const result = await runDoctor(
undefined,
host({
platform: "linux",
macosVersion: () => Promise.resolve(undefined),
linuxDistribution: () =>
Promise.resolve({
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
}),
configuredHopperPath: path,
executable: (candidate) => Promise.resolve(candidate === path),
}),
);
expect(result.healthy).toBe(true);
expect(result.hopperPath).toBe(path);
});
it("reports missing Linux demo-session dependencies", async () => {
const result = await runDoctor(
undefined,
host({
platform: "linux",
macosVersion: () => Promise.resolve(undefined),
linuxDistribution: () =>
Promise.resolve({
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
}),
linuxDemoRuntimeCheck: () =>
Promise.resolve({
name: "hopper-demo-runtime",
ok: false,
classification: "missing_dependency",
remediation: "Install Xvfb, xauth, Python 3, libX11, and libXtst.",
}),
}),
);
expect(result.healthy).toBe(false);
expect(
result.checks.find(({ name }) => name === "hopper-demo-runtime"),
).toMatchObject({
ok: false,
classification: "missing_dependency",
remediation: expect.stringContaining("xauth"),
});
});
it("explains how to recover from an unsupported configured launcher", async () => {
const path = "/custom/Hopper";
const result = await runDoctor(
undefined,
host({
platform: "linux",
configuredHopperPath: path,
linuxDistribution: () =>
Promise.resolve({
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
}),
executable: (candidate) => Promise.resolve(candidate === path),
supportedLinuxHopper: () => Promise.resolve(false),
}),
);
expect(
result.checks.find(({ name }) => name === "hopper-version")?.remediation,
).toContain("Unset or update HOPPER_LAUNCHER_PATH");
});
it("detects a Homebrew cask installed outside /Applications", async () => {
const path =
"/opt/homebrew/Caskroom/hopper/Hopper Disassembler.app/Contents/MacOS/hopper";
const result = await runDoctor(
undefined,
host({
executable: (candidate) => Promise.resolve(candidate === path),
brewHopperPath: () => Promise.resolve(path),
}),
);
expect(result.hopperPath).toBe(path);
});
it("detects a manually installed Hopper application", async () => {
const path = "/Applications/Hopper v6.app/Contents/MacOS/hopper";
const result = await runDoctor(
undefined,
host({
executable: (candidate) => Promise.resolve(candidate === path),
manualHopperPaths: () => Promise.resolve([path]),
}),
);
expect(result.hopperPath).toBe(path);
});
it("uses shared app target validation when a target is supplied", async () => {
const result = await runDoctor(
"/Applications/Notes.app",
host({
validTarget: (path) =>
Promise.resolve(path === "/Applications/Notes.app"),
}),
);
expect(result.checks.find(({ name }) => name === "target")?.ok).toBe(true);
});
it("rejects a readable Hopper launcher without execute permission", async () => {
const path = "/manual/Hopper";
const result = await runDoctor(
undefined,
host({
configuredHopperPath: path,
validTarget: () => Promise.resolve(true),
executable: () => Promise.resolve(false),
}),
);
expect(result.hopperPath).toBeUndefined();
expect(result.checks.find(({ name }) => name === "hopper")?.ok).toBe(false);
});
});
@@ -0,0 +1,93 @@
import { describe, expect, it } from "vitest";
import { runDoctor, type DoctorHost } from "../../../src/application/Doctor.js";
import { CATALOG_IDENTITY } from "../../../src/catalogIdentity.js";
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
const host = (overrides: Partial<DoctorHost> = {}): DoctorHost => ({
platform: "darwin",
architecture: "x64",
nodeVersion: "24.18.0",
macosVersion: () => Promise.resolve("12.0"),
linuxDistribution: () => Promise.resolve(undefined),
validTarget: (path) => Promise.resolve(path.includes("Hopper")),
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,
}),
...overrides,
});
describe("doctor runtime executable diagnostics", () => {
it("reports a broken shadowed Node candidate without hiding the healthy launcher", async () => {
const result = await runDoctor(
undefined,
host({
runtimeExecutables: () =>
Promise.resolve({
launcher_node: "/healthy/node",
candidates: [
{
tool: "node",
lexical_path: "/healthy/node",
canonical_path: "/healthy/node",
path_index: null,
selection: "rea-launcher",
version: "v24.18.0",
healthy: true,
failure: null,
},
{
tool: "node",
lexical_path: "/opt/homebrew/bin/node",
canonical_path: "/opt/homebrew/Cellar/node/25.2.1/bin/node",
path_index: 2,
selection: "path-shadowed",
version: null,
healthy: false,
failure: {
code: "runtime_dynamic_library_missing",
exit_code: 134,
signal: null,
dependency:
"/opt/homebrew/opt/simdjson/lib/libsimdjson.29.dylib",
stderr: "dyld: Library not loaded",
},
},
],
}),
}),
);
expect(result.healthy).toBe(false);
expect(result.identity?.runtime_executables).toMatchObject({
launcher_node: "/healthy/node",
candidates: [
{ healthy: true, selection: "rea-launcher" },
{
healthy: false,
failure: { code: "runtime_dynamic_library_missing" },
},
],
});
expect(
result.checks.find(({ name }) => name === "node-toolchains"),
).toMatchObject({
ok: false,
classification: "missing_dependency",
remediation: expect.stringContaining("Do not create"),
});
});
});
+276
View File
@@ -0,0 +1,276 @@
import { execFile } from "node:child_process";
import { rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import { promisify } from "node:util";
import { afterEach, describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
startFakeCdpBrowser,
type FakeCdpBrowser,
} from "../../fixtures/fakeCdpBrowser.js";
import { writeElectronBoundaryFixture } from "../../fixtures/electronBoundaryApplication.js";
import { JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE } from "../../../src/contracts/javascriptRuntimeReconciliationExample.js";
const execute = promisify(execFile);
const INTEGRATION_TEST_TIMEOUT_MS = 20_000;
const browsers: FakeCdpBrowser[] = [];
const temporary: string[] = [];
afterEach(async () => {
await Promise.all(browsers.splice(0).map(async (browser) => browser.close()));
await Promise.all(
temporary
.splice(0)
.map(async (path) => rm(path, { recursive: true, force: true })),
);
});
describe("Electron CLI parity", () => {
it(
"returns the same root-confined Electron Evidence contracts",
async () => {
const root = await createTestTempDirectory("rea-electron-cli-");
temporary.push(root);
await writeFile(
join(root, "index.html"),
"<script src='app.js'></script>",
);
await writeFile(join(root, "app.js"), "export const app = true;");
const browser = await startFakeCdpBrowser({
electronFileUrl: pathToFileURL(join(root, "index.html")).href,
});
browsers.push(browser);
const environment = {
...process.env,
REA_ELECTRON_OBSERVE_ENABLED: "true",
REA_ELECTRON_CDP_ENDPOINTS_JSON: JSON.stringify([browser.endpoint]),
REA_ELECTRON_FILE_ROOTS_JSON: JSON.stringify([root]),
};
const listed = await runCli(
["list-electron-targets", browser.endpoint, "--approved", "--json"],
environment,
);
expect(listed).toMatchObject({
operation: "list_electron_targets",
normalized_result: {
targets: { items: [{ target_id: "electron-page" }] },
},
});
const inspected = await runCli(
[
"inspect-electron-page",
browser.endpoint,
"electron-page",
"--approved",
"--observation-ms",
"0",
"--json",
],
environment,
);
expect(inspected).toMatchObject({
operation: "inspect_electron_page",
provider: { id: "rea-cdp-electron" },
normalized_result: {
target: { file_path: join(root, "index.html") },
},
});
},
INTEGRATION_TEST_TIMEOUT_MS,
);
it(
"returns the static JavaScript application Evidence contract",
async () => {
const root = await createTestTempDirectory("rea-electron-static-cli-");
temporary.push(root);
await writeElectronBoundaryFixture(root);
const environment = {
...process.env,
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([root]),
};
const analyzed = await runCli(
["analyze-javascript-application", root, "--approved", "--json"],
environment,
);
expect(analyzed).toMatchObject({
operation: "analyze_javascript_application",
provider: { id: "rea-javascript-application" },
normalized_result: {
input_path: root,
summary: {
browser_windows: 3,
context_bridge_apis: 2,
ipc: { paired_renderer_transmissions: 4 },
},
},
});
},
INTEGRATION_TEST_TIMEOUT_MS,
);
});
describe("Electron CLI artifact behavior", () => {
it(
"keeps artifact format separate from structured output format",
async () => {
const root = await createTestTempDirectory("rea-electron-format-cli-");
temporary.push(root);
await writeElectronBoundaryFixture(root);
const environment = {
...process.env,
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([root]),
};
const analyzed = await runCli(
[
"--format",
"json",
"analyze-javascript-application",
root,
"--approved",
"--artifact-format",
"directory",
],
environment,
);
expect(analyzed).toMatchObject({
operation: "analyze_javascript_application",
normalized_result: { input_path: root, format: "directory" },
});
},
INTEGRATION_TEST_TIMEOUT_MS,
);
it(
"routes generic approved analysis of a directory to static JavaScript",
async () => {
const root = await createTestTempDirectory("rea-electron-routed-cli-");
temporary.push(root);
await writeElectronBoundaryFixture(root);
const environment = {
...process.env,
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([root]),
};
const analyzed = await runCli(
["analyze", root, "--approved", "--json"],
environment,
);
expect(analyzed).toMatchObject({
operation: "analyze_javascript_application",
provider: { id: "rea-javascript-application" },
normalized_result: {
input_path: root,
format: "directory",
summary: { ipc: { paired_renderer_transmissions: 4 } },
},
});
},
INTEGRATION_TEST_TIMEOUT_MS,
);
it(
"requires explicit approval before generic JavaScript analysis",
async () => {
const root = await createTestTempDirectory(
"rea-electron-unapproved-cli-",
);
temporary.push(root);
await writeElectronBoundaryFixture(root);
const environment = {
...process.env,
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([root]),
};
const denied = await runCli(["analyze", root, "--json"], environment);
expect(denied).toMatchObject({
code: "invalid_request",
details: {
operation: "analyze_javascript_application",
issues: [
{
path: ["approved"],
reason: "invalid_value",
expected: [true],
},
],
},
});
expect(denied).not.toHaveProperty("details.candidate_ids");
},
INTEGRATION_TEST_TIMEOUT_MS,
);
});
describe("Electron CLI runtime reconciliation", () => {
it(
"reads a file and returns the derived static/runtime reconciliation contract",
async () => {
const root = await createTestTempDirectory("rea-runtime-cli-");
const inputPath = join(root, "reconciliation.json");
temporary.push(root);
await writeFile(
inputPath,
JSON.stringify(JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE),
);
const reconciled = await runCli(
["reconcile-javascript-runtime", inputPath, "--json"],
process.env,
);
expect(reconciled).toMatchObject({
operation: "reconcile_javascript_runtime",
provider: { id: "rea-javascript-runtime-reconciliation" },
normalized_result: {
schema_version: 1,
summary: { runtime_scripts: 1, matched: 1 },
source_map_authority: { used_for_primary_matching: false },
},
});
const missingPath = join(root, "missing.json");
const missing = await runCli(
["reconcile-javascript-runtime", missingPath, "--json"],
process.env,
);
expect(missing).toMatchObject({
input_path: missingPath,
input_reason: "read-failed",
maximum_input_bytes: 64 * 1_024 * 1_024,
});
},
INTEGRATION_TEST_TIMEOUT_MS,
);
});
const runCli = async (
arguments_: readonly string[],
environment: NodeJS.ProcessEnv,
): Promise<unknown> => {
try {
const { stdout } = await execute(
process.execPath,
["scripts/rea.mjs", ...arguments_],
{ cwd: process.cwd(), env: environment, maxBuffer: 16 * 1_024 * 1_024 },
);
return JSON.parse(stdout);
} catch (cause: unknown) {
if (
typeof cause === "object" &&
cause !== null &&
"stdout" in cause &&
typeof cause.stdout === "string"
)
return JSON.parse(cause.stdout);
throw cause;
}
};
@@ -0,0 +1,149 @@
import { execFile } from "node:child_process";
import { rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import { promisify } from "node:util";
import { afterEach, describe, expect, test } from "vitest";
import { loadConfiguredPermissionAuthority } from "../../../src/application/PermissionConfiguration.js";
import { observeJavaScriptRuntime } from "../../../src/application/JavaScriptRuntimeObservationService.js";
import { V8InspectorProvider } from "../../../src/browser/V8InspectorProvider.js";
import { parseConfig } from "../../../src/config.js";
import { startFakeV8Inspector } from "../../fixtures/fakeV8Inspector.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const execute = promisify(execFile);
const TIMEOUT_MS = 20_000;
describe("JavaScript runtime observation CLI parity", () => {
const resources: Array<{ close(): Promise<unknown> }> = [];
const temporary: string[] = [];
afterEach(async () => {
await Promise.all(resources.splice(0).map((item) => item.close()));
await Promise.all(
temporary
.splice(0)
.map((path) => rm(path, { recursive: true, force: true })),
);
});
test(
"returns the same passive Inspector Evidence contracts",
async () => {
const root = await createTestTempDirectory("rea-v8-cli-");
temporary.push(root);
const entry = join(root, "entry.js");
await writeFile(entry, "export const value = 1;\n");
const inspector = await startFakeV8Inspector({
targetUrl: pathToFileURL(entry).href,
});
resources.push(inspector);
const environment = {
...process.env,
REA_V8_INSPECTOR_OBSERVE_ENABLED: "true",
REA_V8_INSPECTOR_ENDPOINTS_JSON: JSON.stringify([inspector.endpoint]),
REA_V8_INSPECTOR_FILE_ROOTS_JSON: JSON.stringify([root]),
};
const listed = await runCli(
[
"list-javascript-runtime-targets",
inspector.endpoint,
"--approved",
"--json",
],
environment,
);
expect(listed).toMatchObject({
operation: "list_javascript_runtime_targets",
provider: { id: "rea-v8-inspector" },
normalized_result: {
targets: { items: [{ target_id: inspector.targetId }] },
},
});
const observed = await runCli(
[
"observe-javascript-runtime",
inspector.endpoint,
inspector.targetId,
"--runtime-kind",
"node",
"--approved",
"--observation-ms",
"10",
"--json",
],
environment,
);
expect(observed).toMatchObject({
operation: "observe_javascript_runtime",
provider: { id: "rea-v8-inspector" },
normalized_result: {
target: { target_id: inspector.targetId, runtime_kind: "node" },
scripts: {
items: [
expect.objectContaining({
location: { kind: "file", file_path: entry },
}),
],
},
},
});
const config = parseConfig(environment);
if (!config.ok) throw config.error;
const authority = await loadConfiguredPermissionAuthority(config.value);
if (!authority.ok) throw authority.error;
const direct = await observeJavaScriptRuntime(
new V8InspectorProvider(),
authority.value,
{
inspector_endpoint: inspector.endpoint,
allowed_file_roots: [root],
allowed_origins: [],
target_id: inspector.targetId,
runtime_kind: "node",
approved: true,
observation_ms: 10,
limits: {
max_events: 10_000,
max_scripts: 2_000,
max_execution_contexts: 1_000,
max_location_bytes: 16_384,
max_total_metadata_bytes: 4_194_304,
},
},
);
expect(direct.ok).toBe(true);
if (direct.ok)
expect(evidenceIdFrom(observed)).toBe(direct.value.evidence_id);
},
TIMEOUT_MS,
);
});
const runCli = async (
arguments_: readonly string[],
environment: NodeJS.ProcessEnv,
): Promise<unknown> => {
const { stdout } = await execute(
process.execPath,
["scripts/rea.mjs", ...arguments_],
{
cwd: process.cwd(),
env: environment,
maxBuffer: 16 * 1_024 * 1_024,
},
);
return JSON.parse(stdout);
};
const evidenceIdFrom = (value: unknown): string => {
if (typeof value !== "object" || value === null)
throw new TypeError("Missing CLI Evidence");
const id = Reflect.get(value, "evidence_id");
if (typeof id !== "string") throw new TypeError("Missing CLI Evidence ID");
return id;
};
@@ -0,0 +1,153 @@
import { chmod, readFile, writeFile } from "node:fs/promises";
import { delimiter, join } from "node:path";
import { describe, expect, it } from "vitest";
import {
packageRunnerSetupPlan,
runPackageRunnerSetupBootstrap,
} from "../../../scripts/package-runner-bootstrap.mjs";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("package-runner setup bootstrap", () => {
it("reruns bare setup through the current release when npm selected a local package", () => {
expect(
packageRunnerSetupPlan({
args: ["setup", "--client", "codex"],
environment: {
npm_lifecycle_event: "npx",
npm_config_local_prefix: "/work/project",
},
packageRoot: "/work/project/node_modules/rea-agents",
packageName: "rea-agents",
}),
).toEqual({
command: "npm",
args: [
"exec",
"--yes",
"--package=rea-agents@latest",
"--",
"rea",
"setup",
"--client",
"codex",
],
});
});
it("leaves explicit rollback and non-local invocations untouched", () => {
const base = {
args: ["setup"],
packageRoot: "/work/project/node_modules/rea-agents",
packageName: "rea-agents",
} as const;
expect(
packageRunnerSetupPlan({
...base,
environment: {
npm_lifecycle_event: "npx",
npm_config_local_prefix: "/work/project",
npm_config_package: "rea-agents@2.4.0",
},
}),
).toBeUndefined();
expect(
packageRunnerSetupPlan({
...base,
environment: {
npm_lifecycle_event: "npx",
npm_config_local_prefix: "/work/project",
npm_config_package: "rea-agents@^2.4.0",
},
}),
).toEqual(
expect.objectContaining({
args: expect.arrayContaining(["--package=rea-agents@latest"]),
}),
);
expect(
packageRunnerSetupPlan({
...base,
packageRoot: "/root/.npm/_npx/cache/node_modules/rea-agents",
environment: {
npm_lifecycle_event: "npx",
npm_config_local_prefix: "/work/project",
},
}),
).toBeUndefined();
});
it("does not redirect recursively or affect commands other than setup", () => {
const environment = {
npm_lifecycle_event: "npx",
npm_config_local_prefix: "/work/project",
REA_PACKAGE_RUNNER_BOOTSTRAPPED: "1",
};
expect(
packageRunnerSetupPlan({
args: ["setup"],
environment,
packageRoot: "/work/project/node_modules/rea-agents",
packageName: "rea-agents",
}),
).toBeUndefined();
expect(
packageRunnerSetupPlan({
args: ["doctor"],
environment: {
npm_lifecycle_event: "npx",
npm_config_local_prefix: "/work/project",
},
packageRoot: "/work/project/node_modules/rea-agents",
packageName: "rea-agents",
}),
).toBeUndefined();
});
it("forwards setup arguments to npm with a recursion marker", async () => {
const directory = await createTestTempDirectory("rea-bootstrap-");
const npm = join(directory, "npm");
const log = join(directory, "invocation.json");
await writeFile(
npm,
`#!/usr/bin/env node
import { writeFileSync } from "node:fs";
writeFileSync(process.env.REA_BOOTSTRAP_TEST_LOG, JSON.stringify({
args: process.argv.slice(2),
marker: process.env.REA_PACKAGE_RUNNER_BOOTSTRAPPED,
}));
`,
);
await chmod(npm, 0o755);
await expect(
runPackageRunnerSetupBootstrap({
args: ["setup", "--dry-run"],
environment: {
...process.env,
PATH: `${directory}${delimiter}${process.env.PATH ?? ""}`,
REA_BOOTSTRAP_TEST_LOG: log,
npm_lifecycle_event: "npx",
npm_config_local_prefix: "/work/project",
},
packageRoot: "/work/project/node_modules/rea-agents",
packageName: "rea-agents",
}),
).resolves.toBe(0);
await expect(readFile(log, "utf8").then(JSON.parse)).resolves.toEqual({
args: [
"exec",
"--yes",
"--package=rea-agents@latest",
"--",
"rea",
"setup",
"--dry-run",
],
marker: "1",
});
});
});
+192
View File
@@ -0,0 +1,192 @@
import { open, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { afterEach, describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
captureProcessScenarioFile,
compareProcessEvidenceFiles,
projectProcessCliError,
} from "../../../src/application/ProcessCli.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { PROCESS_PROVIDER } from "../../../src/application/ProcessEvidence.js";
const roots: string[] = [];
const execFileAsync = promisify(execFile);
const CLI_INTEGRATION_TIMEOUT_MS = 60_000;
afterEach(async () => {
await Promise.all(
roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
);
});
const fixture = async (): Promise<string> => {
const root = await createTestTempDirectory("rea-process-cli-");
roots.push(root);
return root;
};
describe("process CLI errors", () => {
it(
"exits unsuccessfully without writing failure-shaped evidence",
async () => {
await expect(
execFileAsync(
process.execPath,
["scripts/rea.mjs", "capture-process", "/missing/scenario.json"],
{ cwd: process.cwd() },
),
).rejects.toMatchObject({
code: 1,
stdout: expect.stringContaining("category: invalid_input"),
});
},
CLI_INTEGRATION_TIMEOUT_MS,
);
it("projects unexpected causes without their message or stack", () => {
const projected = projectProcessCliError(
new Error("SECRET internal failure /private/path"),
);
expect(projected).toEqual({
error: "Process command failed",
category: "execution_failure",
message:
"Process command could not complete. Check the input files and run `rea doctor`, then try again.",
});
expect(JSON.stringify(projected)).not.toContain("SECRET");
});
it("projects missing, malformed JSON, and invalid scenario files", async () => {
const root = await fixture();
const malformed = join(root, "malformed.json");
const invalid = join(root, "invalid.json");
await writeFile(malformed, "not-json");
await writeFile(invalid, "{}");
expect(
await captureProcessScenarioFile(join(root, "missing.json")),
).toEqual({
error: "Process command failed",
category: "invalid_input",
message:
"Process input file could not be read. Check that the path exists and is readable.",
});
expect(await captureProcessScenarioFile(malformed)).toEqual({
error: "Process command failed",
category: "invalid_input",
message:
"Process input file is not valid JSON. Repair the file, then try again.",
});
expect(await captureProcessScenarioFile(invalid)).toEqual({
error: "Process command failed",
category: "invalid_input",
message:
"Process scenario is invalid. Check its required fields and limits, then try again.",
});
});
it("reports the exact process-capture policy recovery", async () => {
const root = await fixture();
const scenario = join(root, "scenario.json");
await writeFile(
scenario,
JSON.stringify({
approved: true,
executable: "/bin/sh",
working_directory: "/tmp",
}),
);
expect(await captureProcessScenarioFile(scenario)).toMatchObject({
error: "Process command failed",
code: "permission_required",
category: "permission_required",
message:
"This operation needs additional local permission. Review the requested scope and remediation.",
details: {
capability: "process_capture",
ceiling: null,
},
remediation: {
restart_required: false,
elicitation_supported: false,
},
});
});
it("rejects oversized process input before parsing", async () => {
const root = await fixture();
const path = join(root, "large.json");
const handle = await open(path, "w");
await handle.truncate(64 * 1024 * 1024 + 1);
await handle.close();
expect(await captureProcessScenarioFile(path)).toEqual({
error: "Process command failed",
category: "truncated",
message:
"Process input file is too large. Reduce it below 64 MiB, then try again.",
});
});
it("explains unsupported and unrelated capture evidence", async () => {
const root = await fixture();
const legacy = join(root, "legacy.json");
const unrelated = join(root, "unrelated.json");
await writeFile(
legacy,
JSON.stringify(
createEvidence(undefined, PROCESS_PROVIDER, {
predicateType: "rea.process-capture/v3",
operation: "capture_process_scenario",
parameters: {},
result: {},
}),
),
);
await writeFile(
unrelated,
JSON.stringify(
createEvidence(undefined, PROCESS_PROVIDER, {
predicateType: "unrelated/v1",
operation: "other",
parameters: {},
result: {},
}),
),
);
const legacyResult = await compareProcessEvidenceFiles(legacy, legacy);
expect(legacyResult).toMatchObject({
error: "Process command failed",
category: "invalid_input",
});
expect(JSON.stringify(legacyResult)).toContain(
"Process Capture v3 is unsupported",
);
expect(await compareProcessEvidenceFiles(unrelated, unrelated)).toEqual({
error: "Process command failed",
category: "invalid_input",
message:
"Capture evidence is not from the current process-capture workflow. Create new capture evidence, then try again.",
});
});
it("classifies malformed capture evidence as invalid input", async () => {
const root = await fixture();
const malformed = join(root, "malformed-evidence.json");
await writeFile(malformed, "{}");
expect(await compareProcessEvidenceFiles(malformed, malformed)).toEqual({
error: "Process command failed",
category: "invalid_input",
message:
"Capture evidence is malformed. Create new capture evidence, then try again.",
});
});
});
+303
View File
@@ -0,0 +1,303 @@
import { readFile, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, describe, expect, it } from "vitest";
import { z } from "zod";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { SUPPORTED_CLIENT_DEFINITIONS } from "../../../src/application/SupportedClients.js";
import {
ARTIFACT_GRAPH_PROVIDER,
JAVASCRIPT_APPLICATION_PROVIDER,
JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER,
JAVASCRIPT_RUNTIME_RECONCILIATION_PROVIDER,
MANAGED_STATIC_PROVIDER,
MANAGED_WORKFLOW_PROVIDER,
} from "../../../src/application/InvestigationProviders.js";
import { CDP_BROWSER_PROVIDER_IDENTITY } from "../../../src/browser/CdpBrowserProvider.js";
import { CDP_ELECTRON_PROVIDER_IDENTITY } from "../../../src/browser/CdpElectronProvider.js";
import { PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY } from "../../../src/browser/PlaywrightBrowserScenarioProvider.js";
import { V8_INSPECTOR_PROVIDER_IDENTITY } from "../../../src/browser/V8InspectorProvider.js";
import { CLI_COMMAND_NAMES } from "../../../src/cliCommandNames.js";
import { createCli } from "../../../src/cli.js";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import { analysisSnapshotSchema } from "../../../src/domain/analysisSnapshot.js";
import { investigationWorkspaceSchema } from "../../../src/domain/investigationWorkspace.js";
import {
HOPPER_PROVIDER_IDENTITY,
HOPPER_PROVIDER_TOOL_CONTRACTS,
} from "../../../src/hopper/HopperProvider.js";
import {
GHIDRA_PROVIDER_IDENTITY,
GHIDRA_PROVIDER_TOOL_CONTRACTS,
} from "../../../src/ghidra/GhidraProvider.js";
import { NATIVE_MACOS_PROVIDER_IDENTITY } from "../../../src/native/NativeMacOSProvider.js";
import {
assertDocumentationFacts,
documentationFactIssues,
} from "../../../scripts/lib/docs-facts.mjs";
import { ensureGeneratedFile } from "../../../scripts/lib/generated-file.mjs";
import {
createCliInventory,
cliCommandDescriptionIssues,
cliCommandOptionNames,
createProductCatalog,
providerCatalogDigest,
serializeProductCatalog,
} from "../../../scripts/lib/product-catalog.mjs";
const root = fileURLToPath(new URL("../../..", import.meta.url));
const temporaryRoots: string[] = [];
afterEach(async () => {
await Promise.all(
temporaryRoots
.splice(0)
.map((path) => rm(path, { recursive: true, force: true })),
);
});
describe("canonical product catalog", () => {
it("matches every source-derived checked-in product fact", async () => {
const catalog = await createProductCatalog(root);
expect(catalog.tools.total).toBe(TOOL_CONTRACTS.length);
expect(
catalog.tools.families.reduce((total, family) => total + family.count, 0),
).toBe(TOOL_CONTRACTS.length);
expect(catalog.setup_clients.map(({ id }) => id)).toEqual(
SUPPORTED_CLIENT_DEFINITIONS.map(({ name }) => name),
);
expect(catalog.cli.commands).toHaveLength(CLI_COMMAND_NAMES.length);
expect(catalog.providers.map(({ id }) => id).sort()).toEqual(
[
HOPPER_PROVIDER_IDENTITY,
GHIDRA_PROVIDER_IDENTITY,
NATIVE_MACOS_PROVIDER_IDENTITY,
ARTIFACT_GRAPH_PROVIDER,
MANAGED_STATIC_PROVIDER,
MANAGED_WORKFLOW_PROVIDER,
CDP_BROWSER_PROVIDER_IDENTITY,
PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY,
CDP_ELECTRON_PROVIDER_IDENTITY,
V8_INSPECTOR_PROVIDER_IDENTITY,
JAVASCRIPT_APPLICATION_PROVIDER,
JAVASCRIPT_RUNTIME_RECONCILIATION_PROVIDER,
JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER,
]
.map(({ id }) => id)
.sort(),
);
expect(
catalog.providers.find(({ id }) => id === HOPPER_PROVIDER_IDENTITY.id)
?.capabilities,
).toEqual(HOPPER_PROVIDER_TOOL_CONTRACTS.map(({ name }) => name).sort());
expect(
catalog.providers.find(({ id }) => id === GHIDRA_PROVIDER_IDENTITY.id)
?.capabilities,
).toEqual(GHIDRA_PROVIDER_TOOL_CONTRACTS.map(({ name }) => name).sort());
expect(
catalog.providers.find(
({ id }) => id === CDP_ELECTRON_PROVIDER_IDENTITY.id,
)?.capabilities,
).toEqual(["inspect_electron_page", "list_electron_targets"]);
expect(
catalog.providers.find(
({ id }) => id === JAVASCRIPT_APPLICATION_PROVIDER.id,
)?.capabilities,
).toEqual(["analyze_javascript_application"]);
expect(
catalog.providers.find(
({ id }) => id === JAVASCRIPT_RUNTIME_RECONCILIATION_PROVIDER.id,
)?.capabilities,
).toEqual(["reconcile_javascript_runtime"]);
expect(
catalog.providers.find(
({ id }) => id === JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER.id,
)?.capabilities,
).toEqual([
"build_reconstruction_obligation_ledger",
"commit_reconstruction_coverage",
"compare_application_versions",
"compare_javascript_export_shapes",
"compare_source_to_bundle",
"evaluate_reconstruction_readiness",
"execute_node_characterization",
"prepare_node_characterization",
"query_reconstruction_coverage",
"run_controlled_replay",
"trace_application_feature",
"trace_javascript_semantics",
]);
expect(
catalog.providers.find(({ id }) => id === MANAGED_WORKFLOW_PROVIDER.id)
?.capabilities,
).toEqual([
"compare_managed_members",
"import_managed_reconstruction",
"plan_managed_runtime_correlation",
"project_managed_application_graph",
"verify_managed_native_boundaries",
]);
expect(catalog.runtime_catalog.digests.providers_sha256).toBe(
providerCatalogDigest(catalog.providers),
);
expect(
z.toJSONSchema(analysisSnapshotSchema).properties?.snapshot_version,
).toMatchObject({
const: catalog.schemas.find(({ id }) => id === "analysis_snapshot")
?.version,
});
expect(
z.toJSONSchema(investigationWorkspaceSchema).properties
?.workspace_version,
).toMatchObject({
const: catalog.schemas.find(({ id }) => id === "investigation_workspace")
?.version,
});
expect(
JSON.parse(await readFile("docs/product-catalog.json", "utf8")),
).toEqual(catalog);
expect(await serializeProductCatalog(catalog)).toBe(
await readFile("docs/product-catalog.json", "utf8"),
);
await expect(
assertDocumentationFacts(root, catalog),
).resolves.toBeUndefined();
await expect(documentationFactIssues(root, catalog)).resolves.toEqual([]);
}, 60_000);
});
describe("canonical CLI catalog", () => {
it("uses the same primary command names as the actual Incur router", () => {
const inventory = createCliInventory(createCli());
expect(inventory.primary).toEqual([...CLI_COMMAND_NAMES].sort());
expect(inventory.aliases).toEqual([
{ name: "compare-bundles", target: "compare" },
]);
}, 30_000);
it("describes every primary command argument and option", () => {
expect(cliCommandDescriptionIssues(createCli())).toEqual([]);
});
it("exposes the shared provider selector on every deep-analysis command", () => {
const cli = createCli();
for (const name of [
"analyze",
"inspect",
"decompile",
"xrefs",
"trace",
"function",
"inspect-native-api",
"search",
]) {
expect(cliCommandOptionNames(cli, name)).toContain("provider");
}
});
});
describe("canonical product catalog drift", () => {
it("reports tool-family, setup-client, and schema fact drift", async () => {
const catalog = await createProductCatalog(root);
const firstFamily = catalog.tools.families[0];
if (firstFamily === undefined) throw new TypeError("Missing tool family");
const drifted = {
...catalog,
tools: {
...catalog.tools,
families: [
{ ...firstFamily, count: firstFamily.count + 1 },
...catalog.tools.families.slice(1),
],
},
setup_clients: [
...catalog.setup_clients,
{
id: "future_client",
display_name: "Future Client",
format: "json",
configuration: "managed",
},
],
schemas: catalog.schemas.map((schema) =>
schema.id === "process_capture"
? { ...schema, version: Number(schema.version) + 1 }
: schema,
),
};
const issues = await documentationFactIssues(root, drifted);
expect(issues.some((issue) => issue.includes("tool family counts"))).toBe(
true,
);
expect(issues.some((issue) => issue.includes("Future Client"))).toBe(true);
expect(issues.some((issue) => issue.includes("Process Capture v5"))).toBe(
true,
);
});
it("changes the provider projection digest when provider facts drift", async () => {
const catalog = await createProductCatalog(root);
const firstProvider = catalog.providers[0];
if (firstProvider === undefined) throw new TypeError("Missing provider");
const driftedProviders = [
{ ...firstProvider, name: `${firstProvider.name} drifted` },
...catalog.providers.slice(1),
];
expect(providerCatalogDigest(driftedProviders)).not.toBe(
catalog.runtime_catalog.digests.providers_sha256,
);
});
it("fails check mode without rewriting a stale generated artifact", async () => {
const directory = await createTestTempDirectory("rea-generated-check-");
temporaryRoots.push(directory);
const path = join(directory, "catalog.json");
await writeFile(path, "stale\n", "utf8");
await expect(
ensureGeneratedFile({
path,
source: "current\n",
check: true,
generateCommand: "npm run docs:generate",
}),
).rejects.toThrow("missing or stale");
expect(await readFile(path, "utf8")).toBe("stale\n");
await expect(
ensureGeneratedFile({
path,
source: "current\n",
check: false,
generateCommand: "npm run docs:generate",
}),
).resolves.toEqual({ changed: true });
expect(await readFile(path, "utf8")).toBe("current\n");
});
it("accepts and preserves native generated-file line endings", async () => {
const directory = await createTestTempDirectory("rea-generated-eol-");
temporaryRoots.push(directory);
const path = join(directory, "catalog.json");
await writeFile(path, "current\r\n", "utf8");
await expect(
ensureGeneratedFile({
path,
source: "current\n",
check: true,
generateCommand: "npm run docs:generate",
}),
).resolves.toEqual({ changed: false });
expect(await readFile(path, "utf8")).toBe("current\r\n");
await expect(
ensureGeneratedFile({
path,
source: "updated\n",
check: false,
generateCommand: "npm run docs:generate",
}),
).resolves.toEqual({ changed: true });
expect(await readFile(path, "utf8")).toBe("updated\r\n");
});
});
@@ -0,0 +1,47 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { describe, expect, it } from "vitest";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
const execute = promisify(execFile);
describe("reconstruction obligation ledger CLI parity", () => {
it("builds the same Evidence-backed empty ledger through the CLI", async () => {
const input = {
evidence_bundle: createEvidenceBundle([]),
reviewed_obligations: [],
manifest: {
schema_version: 1,
bindings: [],
contradictions: [],
},
limits: { max_obligations: 100 },
page: { offset: 0, limit: 50 },
};
const { stdout } = await execute(
process.execPath,
[
"scripts/rea.mjs",
"build-reconstruction-obligation-ledger",
JSON.stringify(input),
"--json",
],
{
cwd: process.cwd(),
env: process.env,
maxBuffer: 16 * 1_024 * 1_024,
},
);
expect(JSON.parse(stdout)).toMatchObject({
operation: "build_reconstruction_obligation_ledger",
predicate_type: "rea.reconstruction-obligation-ledger/v1",
normalized_result: {
schema: "ReconstructionObligationLedger",
status: "unknown",
summary: { total: 0 },
},
});
}, 20_000);
});
@@ -0,0 +1,36 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { describe, expect, it } from "vitest";
import { RECONSTRUCTION_READINESS_EXAMPLE } from "../../../src/contracts/reconstructionReadinessExample.js";
const execute = promisify(execFile);
describe("reconstruction readiness CLI parity", () => {
it("emits the same passing report through the public CLI", async () => {
const { stdout } = await execute(
process.execPath,
[
"scripts/rea.mjs",
"evaluate-reconstruction-readiness",
JSON.stringify(RECONSTRUCTION_READINESS_EXAMPLE),
"--json",
],
{
cwd: process.cwd(),
env: process.env,
maxBuffer: 32 * 1_024 * 1_024,
},
);
expect(JSON.parse(stdout)).toMatchObject({
operation: "evaluate_reconstruction_readiness",
predicate_type: "rea.reconstruction-readiness-report/v1",
normalized_result: {
schema: "ReconstructionReadinessReport",
status: "pass",
summary: { passed_required_stages: 9 },
},
});
}, 20_000);
});