test: overhaul deterministic suite architecture

This commit is contained in:
morluto
2026-07-29 22:00:38 +00:00
parent 7f2348619a
commit 513d9b1555
371 changed files with 30879 additions and 24389 deletions
@@ -0,0 +1,107 @@
import { describe, expect, it } from "vitest";
import {
classifyResource,
detectPackageFormat,
hasValidSignature,
isConfigurationResource,
isManifestResource,
packageManifestSchema,
resourcesByType,
totalResourceSize,
type PackageManifest,
type DigitalSignature,
} from "../../../src/domain/packageAnalysis.js";
describe("package analysis", () => {
it("detects package format from extension", () => {
expect(detectPackageFormat("app.msix")).toBe("msix");
expect(detectPackageFormat("installer.msi")).toBe("msi");
expect(detectPackageFormat("app.appx")).toBe("appx");
expect(detectPackageFormat("app.zip")).toBeNull();
});
it("identifies manifest resources", () => {
expect(isManifestResource("AppXManifest.xml")).toBe(true);
expect(isManifestResource("resources.pri")).toBe(false);
});
it("identifies configuration resources", () => {
expect(isConfigurationResource("settings.xml")).toBe(true);
expect(isConfigurationResource("config.json")).toBe(true);
expect(isConfigurationResource("app.exe")).toBe(false);
});
it("classifies resources by path", () => {
expect(classifyResource("AppXManifest.xml")).toBe("manifest");
expect(classifyResource("icon.png")).toBe("icon");
expect(classifyResource("settings.xml")).toBe("configuration");
expect(classifyResource("cert.cer")).toBe("certificate");
expect(classifyResource("app.exe")).toBe("executable");
expect(classifyResource("lib.dll")).toBe("library");
expect(classifyResource("data.bin")).toBe("other");
});
const validManifest: PackageManifest = {
format: "msix",
name: "TestApp",
publisher: "CN=TestPublisher",
version: "1.0.0.0",
architecture: "x64",
resources: [
{
path: "AppXManifest.xml",
type: "manifest",
size: 1000,
digest: "a".repeat(64),
},
{ path: "icon.png", type: "icon", size: 5000, digest: "b".repeat(64) },
{
path: "app.exe",
type: "executable",
size: 50000,
digest: "c".repeat(64),
},
],
signature: {
is_signed: true,
signer_subject: "CN=TestPublisher",
certificate_thumbprint: "abc123",
is_valid: true,
is_timestamped: true,
timestamp_signer: "CN=Timestamp",
},
is_framework: false,
dependencies: ["Microsoft.VCLibs.14.00"],
capabilities: ["internetClient", "localNetwork"],
};
it("validates a well-formed manifest", () => {
const result = packageManifestSchema.safeParse(validManifest);
expect(result.success).toBe(true);
});
it("filters resources by type", () => {
const icons = resourcesByType(validManifest, "icon");
expect(icons).toHaveLength(1);
expect(icons[0]!.path).toBe("icon.png");
});
it("computes total resource size", () => {
expect(totalResourceSize(validManifest)).toBe(56000);
});
it("checks valid signature", () => {
expect(hasValidSignature(validManifest)).toBe(true);
const unsigned: PackageManifest = {
...validManifest,
signature: { ...validManifest.signature, is_valid: false },
};
expect(hasValidSignature(unsigned)).toBe(false);
});
it("uses DigitalSignature type", () => {
const sig: DigitalSignature = validManifest.signature;
expect(sig.is_signed).toBe(true);
});
});
@@ -0,0 +1,244 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
import type { BinarySession } from "../../../src/application/BinarySession.js";
import { createServer } from "../../../src/server/createServer.js";
import {
JAVASCRIPT_APPLICATION_VERSION_COMPARISON_EXAMPLE,
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE,
JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE,
SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE,
} from "../../../src/contracts/javascriptApplicationWorkflowExamples.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { observed } from "../../fixtures/analysisExecution.js";
interface TestHarness {
readonly client: Client;
readonly session: BinarySession;
readonly resourceListChanges: () => number;
readonly close: () => Promise<void>;
}
async function createTestHarness(): Promise<TestHarness> {
const session = composeBinarySessionFromFactory(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const server = createServer(session, session);
const client = new Client({
name: "application-workflow-test",
version: "1",
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
let resourceListChanges = 0;
client.setNotificationHandler("notifications/resources/list_changed", () => {
resourceListChanges += 1;
});
await server.connect(serverTransport);
await client.connect(clientTransport);
return {
client,
session,
resourceListChanges: () => resourceListChanges,
close: async () => {
await client.close();
await server.close();
await session.close();
},
};
}
async function runInlineEvidenceScenarios(
client: Client,
session: BinarySession,
): Promise<void> {
const traced = await client.callTool({
name: "trace_application_feature",
arguments: JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE,
});
expect(traced.isError).not.toBe(true);
expect(traced.structuredContent).toMatchObject({
result: {
schema_version: 1,
coverage: { status: expect.any(String) },
},
});
const compared = await client.callTool({
name: "compare_application_versions",
arguments: {
...JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE,
unknown_registry_approved: true,
},
});
expect(compared.isError).not.toBe(true);
expect(compared.structuredContent).toMatchObject({
result: {
schema_version: 1,
summary: { unknown: expect.any(Number) },
coverage: { status: expect.any(String) },
},
});
const sourceCompared = await client.callTool({
name: "compare_source_to_bundle",
arguments: {
reference: SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE.reference,
application: JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application,
},
});
expect(sourceCompared.isError).not.toBe(true);
expect(sourceCompared.structuredContent).toMatchObject({
result: {
schema_version: 1,
reference: {
root_sha256: SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE.reference.root_sha256,
},
scoring: { algorithm: "rea-source-to-bundle-signals/v1" },
},
});
expect(session.exportEvidenceBundle().records.length).toBeGreaterThan(2);
}
async function runEvidenceIdScenarios(harness: TestHarness): Promise<void> {
await new Promise<void>((resolve) => setImmediate(resolve));
const notificationsBeforeIdReuse = harness.resourceListChanges();
const tracedById = await harness.client.callTool({
name: "trace_application_feature",
arguments: {
...JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
application_evidence_id:
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application.evidence_id,
},
});
expect(tracedById.isError).not.toBe(true);
await new Promise<void>((resolve) => setImmediate(resolve));
expect(harness.resourceListChanges()).toBe(notificationsBeforeIdReuse);
const comparedById = await harness.client.callTool({
name: "compare_application_versions",
arguments: {
...JAVASCRIPT_APPLICATION_VERSION_COMPARISON_EXAMPLE,
left_evidence_id:
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.left.evidence_id,
right_evidence_id:
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.right.evidence_id,
},
});
expect(comparedById).toMatchObject({
structuredContent: {
result: {
evidence_links: expect.arrayContaining([
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.left.evidence_id,
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.right.evidence_id,
]),
},
},
});
const sourceComparedById = await harness.client.callTool({
name: "compare_source_to_bundle",
arguments: {
...SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE,
application_evidence_id:
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application.evidence_id,
},
});
expect(sourceComparedById.isError).not.toBe(true);
}
async function assertRejectedEvidenceReferences(
client: Client,
session: BinarySession,
): Promise<void> {
const missing = await client.callTool({
name: "trace_application_feature",
arguments: JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
});
expect(missing).toMatchObject({
isError: true,
structuredContent: {
error: { details: { reason: "missing" } },
},
});
const wrongOperation = createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
{ operation: "inventory_artifact", parameters: {}, result: {} },
);
const wrongPredicate = createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
{
predicateType: "fixture.application/v1",
operation: "analyze_javascript_application",
parameters: {},
result: {},
},
);
expect(session.recordEvidence(wrongOperation).ok).toBe(true);
expect(session.recordEvidence(wrongPredicate).ok).toBe(true);
for (const [record, reason] of [
[wrongOperation, "wrong_operation"],
[wrongPredicate, "wrong_predicate"],
] as const) {
const rejected = await client.callTool({
name: "trace_application_feature",
arguments: {
...JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
application_evidence_id: record.evidence_id,
},
});
expect(rejected).toMatchObject({
isError: true,
structuredContent: { error: { details: { reason } } },
});
}
}
async function assertRejectedInlineEvidence(client: Client): Promise<void> {
const duplicateNative = await client.callTool({
name: "trace_application_feature",
arguments: {
...JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE,
native_observations: [
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application,
],
native_observation_evidence_ids: [
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application.evidence_id,
],
},
});
expect(duplicateNative.isError).toBe(true);
const spoofed = await client.callTool({
name: "trace_application_feature",
arguments: {
...JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE,
application: {
...JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application,
provider: { id: "spoofed", name: "spoofed", version: "1" },
},
},
});
expect(spoofed.isError).toBe(true);
}
describe("application workflow MCP parity", () => {
it("traces and compares authenticated graph Evidence in the session", async () => {
const harness = await createTestHarness();
try {
await runInlineEvidenceScenarios(harness.client, harness.session);
await runEvidenceIdScenarios(harness);
await assertRejectedEvidenceReferences(harness.client, harness.session);
await assertRejectedInlineEvidence(harness.client);
} finally {
await harness.close();
}
});
});
@@ -0,0 +1,142 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
import { copyFile, mkdir, rm } from "node:fs/promises";
import { join, resolve } from "node:path";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
import { analyzeJavaScriptApplication } from "../../../src/application/JavaScriptApplicationService.js";
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascriptApplicationAnalysis.js";
import { permissionAuthorityForRoot } from "../../fixtures/permissionAuthority.js";
describe("application workflow MCP parity", () => {
it("compares exact parser export shapes through full Evidence and session IDs", async () => {
const root = await createTestTempDirectory("rea-export-shape-mcp-");
const leftRoot = join(root, "left");
const rightRoot = join(root, "right");
await Promise.all([mkdir(leftRoot), mkdir(rightRoot)]);
await Promise.all([
copyFile(
resolve("tests/fixtures/replay/parser.mjs"),
join(leftRoot, "parser.mjs"),
),
copyFile(
resolve("tests/fixtures/replay/parser-v2.mjs"),
join(rightRoot, "parser.mjs"),
),
]);
const authority = await permissionAuthorityForRoot(
root,
["investigation_input"],
["investigation_input"],
);
const [left, right] = await Promise.all([
analyzeJavaScriptApplication(authority, {
input_path: leftRoot,
approved: true,
}),
analyzeJavaScriptApplication(authority, {
input_path: rightRoot,
approved: true,
}),
]);
if (!left.ok) throw left.error;
if (!right.ok) throw right.error;
const session = composeBinarySessionFromFactory(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const server = createServer(session, session);
const client = new Client({ name: "export-shape-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const selectors = {
left_module_path: "parser.mjs",
left_export_name: "default",
right_module_path: "parser.mjs",
right_export_name: "default",
};
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const full = await client.callTool({
name: "compare_javascript_export_shapes",
arguments: { left: left.value, right: right.value, ...selectors },
});
expect(full.isError).not.toBe(true);
expect(full.structuredContent).toMatchObject({
result: {
summary: { added: 1, removed: 0, changed: 0, unknown: 0 },
changes: [
{
status: "added",
path: "/depth",
right: { availability: "literal", value: 1 },
},
],
},
});
expect(session.exportEvidenceBundle().records).toEqual(
expect.arrayContaining([
expect.objectContaining({
operation: "compare_javascript_export_shapes",
predicate_type: "rea.javascript-export-shape-comparison/v1",
}),
]),
);
const byId = await client.callTool({
name: "compare_javascript_export_shapes",
arguments: {
left_evidence_id: left.value.evidence_id,
right_evidence_id: right.value.evidence_id,
...selectors,
},
});
expect(byId.isError).not.toBe(true);
expect(byId.structuredContent).toMatchObject({
result: {
evidence_links: [left.value.evidence_id, right.value.evidence_id],
changes: [expect.objectContaining({ path: "/depth" })],
},
});
const analyzed = javascriptApplicationAnalysisResultSchema.parse(
left.value.normalized_result,
);
if (analyzed.schema_version !== 2)
throw new TypeError("Expected semantic application Evidence");
const seed = analyzed.semantic_graph.relations[0]?.source_node_id;
if (seed === undefined)
throw new TypeError("Expected at least one semantic relation");
const semantic = await client.callTool({
name: "trace_javascript_semantics",
arguments: {
application: left.value,
query: {
seed: { kind: "semantic-node", node_id: seed },
direction: "forward-influence",
include_ambiguous_dynamic_edges: true,
},
},
});
expect(semantic.isError).not.toBe(true);
expect(semantic.structuredContent).toMatchObject({
result: {
schema_version: 1,
source_evidence_id: left.value.evidence_id,
source_graph_id: analyzed.semantic_graph.graph_id,
summary: { retained_seed_matches: 1 },
},
});
} finally {
await client.close();
await server.close();
await session.close();
await rm(root, { recursive: true, force: true });
}
});
});
@@ -0,0 +1,277 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { createHash } from "node:crypto";
import { readFile, realpath } from "node:fs/promises";
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
import type { BinarySession } from "../../../src/application/BinarySession.js";
import { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
import { controlledReplayOutputSchema } from "../../../src/domain/javascriptReplay.js";
import { nodeCharacterizationPreparationOutputSchema } from "../../../src/domain/nodeRuntimeCharacterization.js";
import { createPermissionPolicy } from "../../../src/domain/permissionPolicy.js";
import { createServer } from "../../../src/server/createServer.js";
import { observed } from "../../fixtures/analysisExecution.js";
function createReplayPolicy(root: string) {
return {
enabled: true,
roots: [root],
nodePath: process.execPath,
bubblewrapPath: process.execPath,
systemdRunPath: process.execPath,
systemctlPath: process.execPath,
shellPath: process.execPath,
};
}
function createReplayAuthority(policy: ReturnType<typeof createReplayPolicy>) {
const ceiling = {
capability: "javascript_replay" as const,
roots: policy.roots,
executables: [
policy.nodePath,
policy.bubblewrapPath,
policy.systemdRunPath,
policy.systemctlPath,
policy.shellPath,
],
environment_names: [],
network: "none" as const,
mount: true,
};
return new PermissionAuthority(
createPermissionPolicy(
[ceiling],
[
{
...ceiling,
grant_id: "administrator:javascript_replay",
lifetime: "administrator",
operation_identity: null,
expires_at: null,
},
],
),
);
}
function createReplayScenario(root: string) {
const policy = createReplayPolicy(root);
const session = composeBinarySessionFromFactory(() => ({
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const server = createServer(session, session, {
permissionAuthority: createReplayAuthority(policy),
javascriptReplayPolicy: policy,
javascriptReplayHost: {
readSource: async (path) => ({
canonicalPath: await realpath(path),
bytes: await readFile(path),
}),
identifyExecutable: async (path) => ({
path,
version: "fixture",
sha256: "1".repeat(64),
}),
identifyWorker: async () => ({
path: "/fixture/worker.js",
version: "fixture-worker-1",
sha256: "2".repeat(64),
}),
identifyRuntimeClosure: async (path) => [
{
sourcePath: path,
destinationPath: "/runtime/node",
sha256: "1".repeat(64),
},
],
seccompDigest: () => "3".repeat(64),
probe: async () => undefined,
},
javascriptReplayRunner: {
execute: async (prepared) => ({
schema_version: 1,
plan_digest: prepared.publicPlan.plan_digest,
outcomes: [
{
case_id: "heading",
outcome: "return",
value: { type: "heading", text: "Title" },
input_sha256:
prepared.publicPlan.cases[0]?.sha256 ?? "0".repeat(64),
output_sha256: "2".repeat(64),
truncated: false,
},
],
stderr: "",
termination: "completed",
cleanup: { state: "complete", residual_resources: [] },
limitations: ["fixture runner"],
reproducer: null,
}),
},
});
const client = new Client({ name: "replay-parity-test", version: "1" });
return { client, server, session };
}
function createReplayInput(root: string) {
return {
mode: "plan",
left: {
modules: [
{
alias: "parser",
path: resolve(root, "parser.mjs"),
format: "esm",
role: "module",
dependencies: {},
},
],
entry_alias: "parser",
entry_export: "default",
},
cases: [{ case_id: "heading", arguments: ["# Title"] }],
approved: false,
};
}
async function executeReplayScenario(
client: Client,
session: BinarySession,
root: string,
) {
const input = createReplayInput(root);
const planned = await client.callTool({
name: "run_controlled_replay",
arguments: input,
});
expect(planned.isError).not.toBe(true);
const digest = controlledReplayOutputSchema.parse(planned.structuredContent)
.plan?.plan_digest;
expect(digest).toMatch(/^[a-f0-9]{64}$/u);
const executed = await client.callTool({
name: "run_controlled_replay",
arguments: {
...input,
mode: "execute",
approved: true,
plan_digest: digest,
},
});
expect(executed.isError).not.toBe(true);
expect(executed.structuredContent).toMatchObject({
phase: "execute",
evidence: {
authority: "controlled-replay",
provider: { id: "rea-javascript-replay" },
},
});
expect(session.exportEvidenceBundle().records).toEqual(
expect.arrayContaining([
expect.objectContaining({ authority: "controlled-replay" }),
]),
);
}
async function createCharacterizationInput(root: string) {
const factoryPath = resolve(root, "sanitizer.factory.txt");
const factoryBytes = await readFile(factoryPath);
const factorySha256 = createHash("sha256").update(factoryBytes).digest("hex");
return {
preparation_approved: true,
selected_alias: "bundle",
expected_effect: "pure",
instrumentation: {
artifact_path: factoryPath,
artifact_sha256: factorySha256,
selection: {
byte_start: 0,
byte_end: factoryBytes.byteLength,
selected_sha256: factorySha256,
export_name: "selected",
},
},
replay: {
mode: "plan",
left: {
modules: [
{
alias: "bundle",
path: factoryPath,
format: "commonjs-factory",
role: "module",
dependencies: {},
},
],
entry_alias: "bundle",
entry_export: "selected",
},
cases: [{ case_id: "heading", arguments: ["# Title"] }],
approved: false,
},
};
}
async function executeCharacterizationScenario(
client: Client,
session: BinarySession,
root: string,
) {
const input = await createCharacterizationInput(root);
const plan = await client.callTool({
name: "prepare_node_characterization",
arguments: input,
});
expect(plan.isError).not.toBe(true);
const approvedPlan = nodeCharacterizationPreparationOutputSchema.parse(
plan.structuredContent,
).plan;
const characterized = await client.callTool({
name: "execute_node_characterization",
arguments: {
execution_approved: true,
approved_plan_sha256: approvedPlan.plan_sha256,
preparation: input,
},
});
expect(characterized.isError).not.toBe(true);
expect(characterized.structuredContent).toMatchObject({
phase: "execution",
evidence: {
authority: "controlled-replay",
provider: { id: "rea-node-characterization" },
},
});
expect(session.exportEvidenceBundle().records).toEqual(
expect.arrayContaining([
expect.objectContaining({
predicate_type: "rea.javascript-export-transformation/v1",
}),
expect.objectContaining({
predicate_type: "rea.runtime-characterization/v1",
}),
]),
);
}
describe("application workflow MCP parity", () => {
it("plans and executes the same controlled replay contract", async () => {
const root = resolve("tests/fixtures/replay");
const { client, server, session } = createReplayScenario(root);
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
await executeReplayScenario(client, session, root);
await executeCharacterizationScenario(client, session, root);
} finally {
await client.close();
await server.close();
await session.close();
}
});
});
@@ -0,0 +1,418 @@
import { execFile } from "node:child_process";
import { copyFile, mkdir, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
import { afterEach, describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
JAVASCRIPT_APPLICATION_VERSION_COMPARISON_EXAMPLE,
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE,
JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE,
SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE,
} from "../../../src/contracts/javascriptApplicationWorkflowExamples.js";
import {
createEvidenceBundle,
serializeEvidenceBundle,
} from "../../../src/domain/evidenceBundle.js";
import { analyzeJavaScriptApplication } from "../../../src/application/JavaScriptApplicationService.js";
import { permissionAuthorityForRoot } from "../../fixtures/permissionAuthority.js";
import { REPLAY_MACHINE_RUN_EXAMPLE } from "../../../src/contracts/replayMachineExample.js";
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascriptApplicationAnalysis.js";
const execute = promisify(execFile);
const temporary: string[] = [];
afterEach(async () => {
await Promise.all(
temporary
.splice(0)
.map(async (path) => rm(path, { recursive: true, force: true })),
);
});
describe("application workflow CLI parity", () => {
it("accepts inline trace JSON and file-backed comparison JSON", async () => {
const traced = await runCli([
"trace-application-feature",
JSON.stringify(JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE),
"--json",
]);
expect(traced).toMatchObject({
operation: "trace_application_feature",
normalized_result: { schema_version: 1 },
});
const root = await createTestTempDirectory("rea-application-cli-");
temporary.push(root);
const comparisonPath = join(root, "comparison.json");
await writeFile(
comparisonPath,
JSON.stringify(JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE),
);
const compared = await runCli([
"compare-application-versions",
comparisonPath,
"--json",
]);
expect(compared).toMatchObject({
operation: "compare_application_versions",
normalized_result: {
schema_version: 1,
summary: { unknown: expect.any(Number) },
},
});
const sourceCompared = await runCli([
"compare-source-to-bundle",
JSON.stringify({
reference: SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE.reference,
application: JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application,
}),
"--json",
]);
expect(sourceCompared).toMatchObject({
operation: "compare_source_to_bundle",
normalized_result: { schema_version: 1 },
});
}, 20_000);
it("traces the same authenticated semantic graph through the CLI", async () => {
const root = await createTestTempDirectory("rea-semantic-cli-");
temporary.push(root);
await writeFile(
join(root, "app.js"),
"function add(value) { return value + 1; } add(2);",
);
const authority = await permissionAuthorityForRoot(
root,
["investigation_input"],
["investigation_input"],
);
const analyzed = await analyzeJavaScriptApplication(authority, {
input_path: root,
approved: true,
});
if (!analyzed.ok) throw analyzed.error;
const result = javascriptApplicationAnalysisResultSchema.parse(
analyzed.value.normalized_result,
);
if (result.schema_version !== 2)
throw new TypeError("Expected semantic application Evidence");
const seed = result.semantic_graph.relations[0]?.source_node_id;
if (seed === undefined)
throw new TypeError("Expected at least one semantic relation");
const traced = await runCli([
"trace-javascript-semantics",
JSON.stringify({
application: analyzed.value,
query: {
seed: { kind: "semantic-node", node_id: seed },
direction: "forward-influence",
include_ambiguous_dynamic_edges: true,
},
}),
"--json",
]);
expect(traced).toMatchObject({
operation: "trace_javascript_semantics",
predicate_type: "rea.javascript-semantic-trace/v1",
normalized_result: {
source_evidence_id: analyzed.value.evidence_id,
source_graph_id: result.semantic_graph.graph_id,
},
});
}, 20_000);
});
describe("application workflow CLI Evidence resolution", () => {
it("resolves Evidence IDs from an explicitly authorized bundle", async () => {
const root = await createTestTempDirectory("rea-application-bundle-cli-");
temporary.push(root);
const bundlePath = join(root, "evidence.json");
await writeFile(
bundlePath,
serializeEvidenceBundle(
createEvidenceBundle([
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.left,
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.right,
]),
),
);
const environment = {
REA_EVIDENCE_ROOTS_JSON: JSON.stringify([root]),
};
const traced = await runCli(
[
"trace-application-feature",
JSON.stringify({
...JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
application_evidence_id:
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application
.evidence_id,
}),
"--evidence-bundle",
bundlePath,
"--json",
],
environment,
);
expect(traced).toMatchObject({
operation: "trace_application_feature",
normalized_result: { schema_version: 1 },
});
const compared = await runCli(
[
"compare-application-versions",
JSON.stringify({
...JAVASCRIPT_APPLICATION_VERSION_COMPARISON_EXAMPLE,
left_evidence_id:
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.left
.evidence_id,
right_evidence_id:
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.right
.evidence_id,
}),
"--evidence-bundle",
bundlePath,
"--json",
],
environment,
);
expect(compared).toMatchObject({
operation: "compare_application_versions",
normalized_result: { schema_version: 1 },
});
const missingRecord = await runCli(
[
"trace-application-feature",
JSON.stringify(JAVASCRIPT_FEATURE_TRACE_EXAMPLE),
"--evidence-bundle",
bundlePath,
"--json",
],
environment,
);
expect(missingRecord).toMatchObject({
code: "evidence_integrity_mismatch",
details: { reason: "missing" },
});
const outsideRoot = await createTestTempDirectory(
"rea-outside-bundle-cli-",
);
temporary.push(outsideRoot);
const outsideBundlePath = join(outsideRoot, "evidence.json");
await writeFile(
outsideBundlePath,
serializeEvidenceBundle(createEvidenceBundle([])),
);
const denied = await runCli(
[
"trace-application-feature",
JSON.stringify(JAVASCRIPT_FEATURE_TRACE_EXAMPLE),
"--evidence-bundle",
outsideBundlePath,
"--json",
],
environment,
);
expect(denied).toMatchObject({ code: "permission_required" });
}, 30_000);
});
describe("application workflow CLI export Evidence", () => {
it("compares exact export shapes from an authorized Evidence bundle", async () => {
const root = await createTestTempDirectory("rea-export-shape-cli-");
temporary.push(root);
const leftRoot = join(root, "left");
const rightRoot = join(root, "right");
await Promise.all([mkdir(leftRoot), mkdir(rightRoot)]);
await Promise.all([
copyFile(
join(process.cwd(), "tests/fixtures/replay/parser.mjs"),
join(leftRoot, "parser.mjs"),
),
copyFile(
join(process.cwd(), "tests/fixtures/replay/parser-v2.mjs"),
join(rightRoot, "parser.mjs"),
),
]);
const authority = await permissionAuthorityForRoot(
root,
["investigation_input"],
["investigation_input"],
);
const [left, right] = await Promise.all([
analyzeJavaScriptApplication(authority, {
input_path: leftRoot,
approved: true,
}),
analyzeJavaScriptApplication(authority, {
input_path: rightRoot,
approved: true,
}),
]);
if (!left.ok) throw left.error;
if (!right.ok) throw right.error;
const bundlePath = join(root, "evidence.json");
await writeFile(
bundlePath,
serializeEvidenceBundle(createEvidenceBundle([left.value, right.value])),
);
const compared = await runCli(
[
"compare-javascript-export-shapes",
JSON.stringify({
left_evidence_id: left.value.evidence_id,
right_evidence_id: right.value.evidence_id,
left_module_path: "parser.mjs",
left_export_name: "default",
right_module_path: "parser.mjs",
right_export_name: "default",
}),
"--evidence-bundle",
bundlePath,
"--json",
],
{ REA_EVIDENCE_ROOTS_JSON: JSON.stringify([root]) },
);
expect(compared).toMatchObject({
operation: "compare_javascript_export_shapes",
predicate_type: "rea.javascript-export-shape-comparison/v1",
normalized_result: {
summary: { added: 1, removed: 0, changed: 0, unknown: 0 },
changes: [
{
status: "added",
path: "/depth",
right: { availability: "literal", value: 1 },
},
],
},
});
}, 20_000);
});
describe("application workflow CLI validation and replay", () => {
it("returns safe actionable JSON validation details", async () => {
const malformed = await runCli([
"trace-application-feature",
"{not-json",
"--json",
]);
expect(malformed).toMatchObject({
code: "invalid_request",
retryable: true,
details: {
issues: [{ path: [], reason: "invalid_format", expected: "JSON" }],
},
});
expect(JSON.stringify(malformed)).not.toContain("not-json");
const missing = await runCli(["trace-application-feature", "{}", "--json"]);
expect(missing).toMatchObject({
code: "invalid_request",
details: {
issues: expect.arrayContaining([
expect.objectContaining({
path: ["seed"],
reason: "missing_argument",
}),
]),
},
});
}, 20_000);
it("runs a replay machine from inline and file-backed JSON", async () => {
const input = REPLAY_MACHINE_RUN_EXAMPLE;
const inline = await runCli([
"run-replay-machine",
JSON.stringify(input),
"--json",
]);
expect(inline).toMatchObject({
schema_version: 1,
final_state: "complete",
decisions: [{ outcome: "matched" }],
transition_journal: [
{ captured_aliases: [{ name: "token", sensitive: true }] },
],
});
expect(JSON.stringify(inline)).not.toContain("opaque");
const root = await createTestTempDirectory("rea-replay-machine-cli-");
temporary.push(root);
const inputPath = join(root, "run.json");
await writeFile(inputPath, JSON.stringify(input));
const fileBacked = await runCli([
"run-replay-machine",
inputPath,
"--json",
]);
expect(fileBacked).toEqual(inline);
const invalid = await runCli([
"run-replay-machine",
JSON.stringify({
machine: input.machine,
events: [
{
protocol: "http",
connection: "not_applicable",
at_ms: 0,
method: null,
path: "/callback",
headers: {},
body: "private-cli-body",
},
],
}),
"--json",
]);
expect(invalid).toMatchObject({
code: "invalid_request",
details: {
issues: expect.arrayContaining([
expect.objectContaining({
path: ["events", 0, "method"],
}),
]),
},
});
expect(JSON.stringify(invalid)).not.toContain("private-cli-body");
}, 20_000);
});
const runCli = async (
arguments_: readonly string[],
environment: Readonly<Record<string, string>> = {},
): Promise<unknown> => {
try {
const { stdout } = await execute(
process.execPath,
["scripts/rea.mjs", ...arguments_],
{
cwd: process.cwd(),
env: { ...process.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,115 @@
import { execFile } from "node:child_process";
import { copyFile, mkdir, rm } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
import { afterEach, describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { writeVersionedJavaScriptApplicationFixtures } from "../../fixtures/javascriptArtifactApplication.js";
const execute = promisify(execFile);
describe("local application workflow verifier", () => {
const temporary: string[] = [];
afterEach(async () => {
await Promise.all(
temporary
.splice(0)
.map(async (path) => rm(path, { recursive: true, force: true })),
);
});
it("reports bounded two-version and trace claims without source text", async () => {
const root = await createTestTempDirectory("rea-application-verifier-");
temporary.push(root);
const fixtures = await writeVersionedJavaScriptApplicationFixtures(root);
const { stdout } = await execute(
process.execPath,
[
"scripts/verify-local-application-workflows.mjs",
"--left",
fixtures.left,
"--right",
fixtures.right,
"--seed-kind",
"module",
"--seed-value",
"stable",
],
{ cwd: process.cwd(), maxBuffer: 16 * 1_024 * 1_024 },
);
const result = JSON.parse(stdout);
expect(result).toMatchObject({
verified: true,
summary: {
added: expect.any(Number),
removed: expect.any(Number),
changed: expect.any(Number),
unknown: expect.any(Number),
},
matching: {
exact_module_source_digest: expect.any(Number),
structural_fingerprint: expect.any(Number),
},
coverage: { status: expect.any(String) },
trace: { summary: { matched_seeds: expect.any(Number) } },
});
expect(stdout).not.toContain("stableValue");
}, 20_000);
it("verifies the source-owned parser depth return-shape addition", async () => {
const root = await createTestTempDirectory("rea-shape-verifier-");
temporary.push(root);
const left = join(root, "left");
const right = join(root, "right");
await Promise.all([mkdir(left), mkdir(right)]);
await Promise.all([
copyFile(
join(process.cwd(), "tests/fixtures/replay/parser.mjs"),
join(left, "parser.mjs"),
),
copyFile(
join(process.cwd(), "tests/fixtures/replay/parser-v2.mjs"),
join(right, "parser.mjs"),
),
]);
const { stdout } = await execute(
process.execPath,
[
"scripts/verify-local-application-workflows.mjs",
"--left",
left,
"--right",
right,
"--left-module-path",
"parser.mjs",
"--left-export-name",
"default",
"--right-module-path",
"parser.mjs",
"--right-export-name",
"default",
],
{ cwd: process.cwd(), maxBuffer: 16 * 1_024 * 1_024 },
);
const result = JSON.parse(stdout);
expect(result.export_shape_comparison).toMatchObject({
summary: { added: 1, removed: 0, changed: 0, unknown: 0 },
changes: [
{
status: "added",
path: "/depth",
right: { availability: "literal", value: 1 },
},
],
runtime_validation: {
recommended_tool: "run_controlled_replay",
automatically_started: false,
},
});
expect(stdout).not.toContain("value.slice");
}, 20_000);
});
@@ -0,0 +1,293 @@
import { rm } from "node:fs/promises";
import { afterEach, describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { analyzeJavaScriptApplication } from "../../../src/application/JavaScriptApplicationService.js";
import { compareApplicationVersionsEvidence } from "../../../src/application/JavaScriptApplicationWorkflowService.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { applicationVersionComparisonResultSchema } from "../../../src/domain/javascriptApplicationVersionComparisonSchemas.js";
import { compareJavaScriptApplicationVersions } from "../../../src/domain/javascriptApplicationVersionComparison.js";
import { createJavaScriptApplicationGraph } from "../../../src/domain/javascriptApplicationGraph.js";
import { traceApplicationFeature } from "../../../src/domain/javascriptFeatureTrace.js";
import { applicationFeatureTraceResultSchema } from "../../../src/domain/javascriptFeatureTraceSchemas.js";
import {
APPLICATION_GRAPH_DIGESTS,
buildSyntheticJavaScriptApplicationGraph,
} from "../../fixtures/javascriptApplicationGraph.js";
import { writeVersionedJavaScriptApplicationFixtures } from "../../fixtures/javascriptArtifactApplication.js";
import { permissionAuthorityForRoot } from "../../fixtures/permissionAuthority.js";
const temporary: string[] = [];
afterEach(async () => {
await Promise.all(
temporary
.splice(0)
.map(async (path) => rm(path, { recursive: true, force: true })),
);
});
describe("JavaScript application workflows", () => {
it("traces a contextBridge API through IPC into linked native evidence", () => {
const graph = buildSyntheticJavaScriptApplicationGraph();
const nativeEvidence = createEvidence(
{
path: "/tmp/synthetic.node",
sha256: APPLICATION_GRAPH_DIGESTS.nativeAddon,
format: "elf",
architecture: "x86_64",
},
{ id: "ghidra", name: "Ghidra", version: "fixture" },
{
operation: "analyze_function",
parameters: { address: "openProject" },
result: { name: "openProject", address: "0x1000" },
limitations: ["Synthetic native provider observation."],
},
);
const result = traceApplicationFeature({
sourceEvidenceId: `ev_${"a".repeat(64)}`,
graph,
nativeEvidence: [nativeEvidence],
seed: {
kind: "api",
value: "desktopApi",
match: "exact",
case_sensitive: false,
},
direction: "outgoing",
limits: traceLimits(),
});
expect(() =>
applicationFeatureTraceResultSchema.parse(result),
).not.toThrow();
expect(result.summary).toMatchObject({
matched_seeds: 1,
native_handoffs: 1,
});
expect(result.native_handoffs).toContainEqual(
expect.objectContaining({
artifact_sha256: APPLICATION_GRAPH_DIGESTS.nativeAddon,
status: "evidence-linked",
evidence_ids: [nativeEvidence.evidence_id],
requested_exports: expect.arrayContaining(["openProject"]),
}),
);
expect(result.paths).toEqual(
expect.arrayContaining([
expect.objectContaining({ end_kind: "native-export" }),
]),
);
expect(
result.graph?.edges.some(
({ evidence }) =>
evidence.authority === "static-relationship-inference" &&
evidence.state === "inferred",
),
).toBe(true);
});
it("keeps no-match and bounded frontiers explicit", () => {
const graph = buildSyntheticJavaScriptApplicationGraph();
const noMatch = traceApplicationFeature({
sourceEvidenceId: `ev_${"a".repeat(64)}`,
graph,
nativeEvidence: [],
seed: {
kind: "route",
value: "/missing",
match: "exact",
case_sensitive: false,
},
direction: "both",
limits: traceLimits(),
});
expect(noMatch).toMatchObject({
graph: null,
coverage: { status: "no-match" },
summary: { matched_seeds: 0 },
});
const bounded = traceApplicationFeature({
sourceEvidenceId: `ev_${"a".repeat(64)}`,
graph,
nativeEvidence: [],
seed: {
kind: "api",
value: "desktopApi",
match: "exact",
case_sensitive: false,
},
direction: "outgoing",
limits: { ...traceLimits(), max_depth: 1 },
});
expect(bounded.coverage).toMatchObject({ status: "truncated" });
expect(bounded.coverage.omitted_nodes).toBeGreaterThan(0);
expect(bounded.summary.native_handoffs).toBe(0);
});
});
describe("JavaScript application comparison workflows", () => {
it("matches rechunked modules by exact source and minified modules by structural fingerprint", async () => {
const root = await createTestTempDirectory("rea-application-versions-");
temporary.push(root);
const fixtures = await writeVersionedJavaScriptApplicationFixtures(root);
const [left, right] = await Promise.all([
analyzeFixture(fixtures.left, true),
analyzeFixture(fixtures.right, true),
]);
const compared = compareApplicationVersionsEvidence({ left, right });
if (!compared.ok) throw compared.error;
const result = applicationVersionComparisonResultSchema.parse(
compared.value.normalized_result,
);
const modules = result.items.filter(
({ node_kind: kind }) => kind === "javascript-module",
);
expect(modules).toEqual(
expect.arrayContaining([
expect.objectContaining({
match: expect.objectContaining({
status: "matched",
basis: "exact-module-source-digest",
confidence: "exact",
}),
}),
expect.objectContaining({
status: "changed",
match: expect.objectContaining({
status: "matched",
basis: "structural-fingerprint",
confidence: "medium",
}),
}),
]),
);
expect(result.matching.ambiguous).toBeGreaterThanOrEqual(4);
expect(modules.filter(({ match }) => match.status === "ambiguous")).toEqual(
expect.arrayContaining([expect.objectContaining({ status: "unknown" })]),
);
expect(result.summary.added).toBeGreaterThan(0);
expect(result.summary.removed).toBeGreaterThan(0);
expect(result.graph.edges).toEqual(
expect.arrayContaining([
expect.objectContaining({
relation: "changed_from",
evidence: expect.objectContaining({
authority: "cross-version-comparison",
state: "inferred",
}),
}),
]),
);
expect(result.limitations.join(" ")).toMatch(
/module ordinals|fuzzy pairing/u,
);
});
it("pairs source-map originals without promoting the match to exact", async () => {
const root = await createTestTempDirectory("rea-source-map-versions-");
temporary.push(root);
const fixtures = await writeVersionedJavaScriptApplicationFixtures(root);
const [left, right] = await Promise.all([
analyzeFixture(fixtures.left, true),
analyzeFixture(fixtures.right, true),
]);
const compared = compareApplicationVersionsEvidence({ left, right });
if (!compared.ok) throw compared.error;
const result = applicationVersionComparisonResultSchema.parse(
compared.value.normalized_result,
);
expect(result.items).toContainEqual(
expect.objectContaining({
node_kind: "source-module",
status: "changed",
match: expect.objectContaining({
basis: "source-map-identity",
confidence: "high",
}),
}),
);
});
it("keeps incomplete one-sided absence unknown and reports output truncation", () => {
const complete = buildSyntheticJavaScriptApplicationGraph();
const rootNode = complete.nodes.find(({ node_id: id }) =>
complete.root_node_ids.includes(id),
);
if (rootNode === undefined) throw new Error("Synthetic graph root missing");
const partial = createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
schema_version: 1,
root_node_ids: [rootNode.node_id],
nodes: [rootNode],
edges: [],
coverage: {
status: "partial",
truncated: true,
omitted_count: complete.nodes.length - 1,
limits: [{ name: "fixture_nodes", value: 1, unit: "items" }],
},
limitations: ["Synthetic partial graph."],
});
const input = {
left: {
evidenceId: `ev_${"a".repeat(64)}`,
rootArtifactSha256: APPLICATION_GRAPH_DIGESTS.package,
graph: complete,
},
right: {
evidenceId: `ev_${"b".repeat(64)}`,
rootArtifactSha256: APPLICATION_GRAPH_DIGESTS.package,
graph: partial,
},
leftNativeEvidence: [],
rightNativeEvidence: [],
limits: {
max_comparison_items: 1,
max_candidate_nodes: 1,
max_graph_nodes: 20,
max_graph_edges: 20,
},
};
const first = compareJavaScriptApplicationVersions(input);
const second = compareJavaScriptApplicationVersions(input);
expect(first.comparison_id).toBe(second.comparison_id);
expect(first.coverage).toMatchObject({
status: "truncated",
right_graph_status: "partial",
});
expect(first.coverage.omitted_comparison_items).toBeGreaterThan(0);
expect(first.summary.removed).toBe(0);
expect(first.summary.unknown).toBeGreaterThan(0);
});
});
const traceLimits = () => ({
max_seed_matches: 25,
max_depth: 12,
max_nodes: 2_000,
max_edges: 4_000,
max_paths: 100,
});
const analyzeFixture = async (root: string, sourceMaps = false) => {
const authority = await permissionAuthorityForRoot(
root,
["investigation_input"],
["investigation_input"],
);
const result = await analyzeJavaScriptApplication(authority, {
input_path: root,
approved: true,
source_map_read_approved: sourceMaps,
});
if (!result.ok) throw result.error;
return result.value;
};
@@ -0,0 +1,128 @@
import { describe, expect, it } from "vitest";
import {
classifyMobileResource,
detectMobileFormat,
detectPlatform,
getAllArchitectures,
hasInternetPermission,
mobileArtifactManifestSchema,
nativeLibsByArchitecture,
type MobileArtifactManifest,
type AndroidManifest,
type SigningInfo,
type NativeLibrary,
type MobileResource,
} from "../../../src/domain/mobileApplicationInvestigation.js";
describe("mobile application investigation", () => {
it("detects mobile format from extension", () => {
expect(detectMobileFormat("app.apk")).toBe("apk");
expect(detectMobileFormat("app.aab")).toBe("aab");
expect(detectMobileFormat("app.ipa")).toBe("ipa");
expect(detectMobileFormat("classes.dex")).toBe("dex");
expect(detectMobileFormat("lib.so")).toBe("native_lib");
expect(detectMobileFormat("readme.txt")).toBeNull();
});
it("detects platform from format", () => {
expect(detectPlatform("apk")).toBe("android");
expect(detectPlatform("aab")).toBe("android");
expect(detectPlatform("dex")).toBe("android");
expect(detectPlatform("ipa")).toBe("ios");
expect(detectPlatform("native_lib")).toBe("cross_platform");
});
it("classifies resources by path", () => {
expect(classifyMobileResource("res/layout/main.xml")).toBe("layout");
expect(classifyMobileResource("res/drawable/icon.png")).toBe("drawable");
expect(classifyMobileResource("assets/data.json")).toBe("asset");
expect(classifyMobileResource("AndroidManifest.xml")).toBe("manifest");
expect(classifyMobileResource("app.entitlements")).toBe("entitlements");
expect(classifyMobileResource("lib/arm64-v8a/libnative.so")).toBe(
"native_lib",
);
expect(classifyMobileResource("unknown.xyz")).toBe("other");
});
const androidManifest: AndroidManifest = {
package_name: "com.example.app",
version_name: "1.0.0",
version_code: 1,
min_sdk: 21,
target_sdk: 34,
permissions: ["android.permission.INTERNET", "android.permission.CAMERA"],
activities: ["MainActivity"],
services: ["BackgroundService"],
receivers: [],
providers: [],
};
const signing: SigningInfo = {
is_signed: true,
signer_identity: "CN=TestSigner",
certificate_fingerprint: "abc123",
signature_scheme: "v2",
is_debuggable: false,
};
const nativeLibs: NativeLibrary[] = [
{
path: "lib/arm64-v8a/libnative.so",
architecture: "arm64-v8a",
size: 100000,
digest: "a".repeat(64),
},
{
path: "lib/armeabi-v7a/libnative.so",
architecture: "armeabi-v7a",
size: 90000,
digest: "b".repeat(64),
},
];
const resources: MobileResource[] = [
{ path: "res/layout/main.xml", type: "layout", size: 1000 },
{ path: "res/drawable/icon.png", type: "drawable", size: 5000 },
];
const validManifest: MobileArtifactManifest = {
format: "apk",
platform: "android",
app_name: "TestApp",
android_manifest: androidManifest,
ios_manifest: null,
signing,
resources,
native_libraries: nativeLibs,
total_size: 5000000,
architectures: ["arm64-v8a", "armeabi-v7a"],
};
it("validates a well-formed manifest", () => {
const result = mobileArtifactManifestSchema.safeParse(validManifest);
expect(result.success).toBe(true);
});
it("filters native libs by architecture", () => {
const arm64 = nativeLibsByArchitecture(validManifest, "arm64-v8a");
expect(arm64).toHaveLength(1);
expect(arm64[0]!.architecture).toBe("arm64-v8a");
});
it("checks internet permission", () => {
expect(hasInternetPermission(validManifest)).toBe(true);
const noInternet: MobileArtifactManifest = {
...validManifest,
android_manifest: { ...androidManifest, permissions: [] },
};
expect(hasInternetPermission(noInternet)).toBe(false);
});
it("gets all architectures", () => {
const archs = getAllArchitectures(validManifest);
expect(archs).toHaveLength(2);
expect(archs).toContain("arm64-v8a");
expect(archs).toContain("armeabi-v7a");
});
});
@@ -0,0 +1,107 @@
import { readFile } from "node:fs/promises";
import { describe, expect, it } from "vitest";
import { packageHopperEnvironment } from "../../../scripts/verify-package-environment.mjs";
describe("package installation workflows", () => {
it("runs package E2E without the retired native rebuild script", async () => {
const continuousIntegration = await readFile(
new URL("../../../.github/workflows/ci.yml", import.meta.url),
"utf8",
);
const realHopperLinux = await readFile(
new URL(
"../../../.github/workflows/real-hopper-linux.yml",
import.meta.url,
),
"utf8",
);
const realHopperMac = await readFile(
new URL("../../../.github/workflows/real-hopper.yml", import.meta.url),
"utf8",
);
expect(continuousIntegration).toContain("os: [ubuntu-latest, macos-14]");
expect(continuousIntegration).toContain("npm run verify:package");
expect(continuousIntegration).toContain("name: Static checks");
expect(continuousIntegration).toContain("npm run check:ci");
expect(continuousIntegration).toContain("shard: [1/4, 2/4, 3/4, 4/4]");
expect(continuousIntegration).toContain("name: Build package");
expect(continuousIntegration).toContain("npm run build:cached");
expect(continuousIntegration).toContain("name: rea-dist");
expect(continuousIntegration).toContain("npm run test:ci:shard:run");
expect(continuousIntegration).toContain("needs: [changes, test-shard]");
expect(continuousIntegration).toContain("if-no-files-found: error");
expect(continuousIntegration).toContain("overwrite: true");
expect(continuousIntegration).toContain(
"code: ${{ steps.package.outputs.required }}",
);
expect(continuousIntegration).toContain("CODE_REQUIRED:");
expect(continuousIntegration).toContain(
'test "${CODE_REQUIRED}" != "true" || test "${SHARD_RESULT}" = "success"',
);
expect(continuousIntegration).toContain("npm run test:ci:merge");
expect(continuousIntegration).toContain("needs: changes");
expect(continuousIntegration).toContain(
"cancel-in-progress: ${{ github.event_name == 'pull_request' }}",
);
for (const workflow of [
continuousIntegration,
realHopperLinux,
realHopperMac,
])
expect(workflow).not.toContain("npm run rebuild:native");
for (const workflow of [realHopperLinux, realHopperMac])
expect(workflow).toContain("npm install --global --ignore-scripts");
for (const workflow of [realHopperLinux, realHopperMac])
expect(workflow).toContain(
"REA_HOPPER_CONFORMANCE_MANIFEST_PATH: ${{ github.workspace }}/build/conformance/manifest.json",
);
expect(realHopperLinux).not.toContain("HOPPER_TARGET_PATH");
expect(realHopperLinux).not.toContain("HOPPER_SECOND_TARGET_PATH");
expect(realHopperLinux).not.toContain("first_target");
expect(realHopperLinux).not.toContain("second_target");
});
it("verifies the package before publish and runs published canaries outside the checkout", async () => {
const release = await readFile(
new URL("../../../.github/workflows/release.yml", import.meta.url),
"utf8",
);
const canary = await readFile(
new URL("../../../scripts/verify-published-package.mjs", import.meta.url),
"utf8",
);
expect(release.indexOf("npm run verify:package")).toBeLessThan(
release.indexOf("npm publish --access public"),
);
expect(release).toContain('verification_root="$(mktemp -d)"');
expect(release).toContain('cd "${verification_root}"');
expect(release).not.toContain('npm run verify:published -- "${version}"');
expect(canary).toContain('mkdtemp(join(tmpdir(), "rea-published-canary-")');
expect(canary).toContain("cwd: canaryRoot");
});
it("uses direct Node ownership on macOS and Windows", () => {
const root = "/tmp/rea-package";
const expected = {
HOPPER_LAUNCHER_PATH: process.execPath,
HOPPER_LOADER_ARGS_JSON: JSON.stringify([
`${root}/tests/fixtures/fakeLauncher.mjs`,
]),
};
expect(packageHopperEnvironment(root, "darwin")).toEqual(expected);
expect(packageHopperEnvironment(root, "win32")).toEqual(expected);
expect(packageHopperEnvironment(root, "linux")).toEqual({
HOPPER_LAUNCHER_PATH: "/bin/sh",
HOPPER_LOADER_ARGS_JSON: JSON.stringify([
"-c",
'node_path=$1; shift; "$node_path" "$@"',
"rea-package-hopper",
process.execPath,
`${root}/tests/fixtures/fakeLauncher.mjs`,
]),
});
});
});
@@ -0,0 +1,194 @@
import { describe, expect, it } from "vitest";
import { runSetup } from "../../../src/application/Setup.js";
import { FakeSetupHost, options } from "./setupTestSupport.js";
describe("setup workflow", () => {
it("omits an aligned managed skill from an otherwise empty plan", async () => {
const host = new FakeSetupHost();
host.hopper = "/Applications/Hopper";
host.skill = "unchanged";
const result = await runSetup(options(false), host);
expect(result.status).toBe("ready");
expect(result.plannedActions).toEqual([]);
expect(result.appliedActions).toEqual([]);
expect(host.skillInstalls).toBe(0);
});
it("installs missing Linux demo dependencies for existing Hopper", async () => {
const host = new FakeSetupHost("linux");
host.distribution = {
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
};
host.hopper = "/opt/hopper/bin/Hopper";
host.linuxDemoRuntimeMissing = true;
const result = await runSetup(
{ ...options(false), structured: false },
host,
() => Promise.resolve(true),
);
expect(result.status).toBe("ready");
expect(host.hopperInstalls).toBe(1);
expect(result.plannedActions.map(({ kind }) => kind)).toContain(
"install_hopper",
);
});
it("does not reinstall Hopper for an unsupported configured path", async () => {
const host = new FakeSetupHost("linux");
host.distribution = {
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
};
host.hopper = "/custom/Hopper";
host.unsupportedHopperVersion = true;
const result = await runSetup(
{ ...options(false), structured: false },
host,
() => Promise.resolve(true),
);
expect(result.status).toBe("needs_human");
expect(host.hopperInstalls).toBe(0);
expect(result.plannedActions.map(({ kind }) => kind)).not.toContain(
"install_hopper",
);
});
it("reports a failed Hopper installation without configuring clients", async () => {
const host = new FakeSetupHost();
host.hopperInstallSucceeds = false;
host.clients = [{ name: "cursor", configPath: "/cursor.json" }];
const result = await runSetup(options(true, true), host);
expect(result.status).toBe("needs_human");
expect(result.code).toBe("download_failed");
expect(result.remediation).toBe("Download failed.");
expect(host.configurations).toBe(0);
});
it("blocks malformed client configuration before Hopper or file mutation", async () => {
const host = new FakeSetupHost();
host.clients = [
{ name: "codex", displayName: "Codex", configPath: "/codex.toml" },
];
host.clientInspections.set("codex", {
status: "invalid",
remediation: "Repair the existing TOML.",
});
const result = await runSetup(options(true, true), host);
expect(result.status).toBe("needs_human");
expect(result.remediation).toBe("Codex: Repair the existing TOML.");
expect(host.hopperInstalls).toBe(0);
expect(host.configurations).toBe(0);
expect(host.skillInstalls).toBe(0);
});
it("blocks malformed configuration before unrelated writes with an existing provider", async () => {
const host = new FakeSetupHost();
host.hopper = "/Applications/Hopper";
host.clients = [
{
name: "claude_desktop",
displayName: "Claude Desktop",
configPath: "/claude.json",
},
{ name: "cursor", displayName: "Cursor", configPath: "/cursor.json" },
];
host.clientInspections.set("claude_desktop", {
status: "invalid",
remediation: "Repair the existing JSON.",
});
const result = await runSetup(options(true), host);
expect(result.status).toBe("needs_human");
expect(result.remediation).toBe(
"Claude Desktop: Repair the existing JSON.",
);
expect(host.configurations).toBe(0);
expect(host.skillInstalls).toBe(0);
});
it("plans a client update when Hopper installation changes its desired environment", async () => {
const host = new FakeSetupHost();
host.clients = [
{ name: "codex", displayName: "Codex", configPath: "/codex.toml" },
];
host.clientInspections.set("codex", { status: "already_current" });
const result = await runSetup(options(false), host);
expect(
result.plannedActions.map(({ id, operation }) => ({
id,
operation,
})),
).toContainEqual({
id: "configure_client:codex",
operation: "update",
});
expect(host.configurations).toBe(0);
});
});
describe("setup workflow action selection", () => {
it("executes only actions selected by the interactive adapter", async () => {
const host = new FakeSetupHost();
host.hopper = "/Applications/Hopper";
host.clients = [
{ name: "codex", displayName: "Codex", configPath: "/codex.toml" },
{ name: "cursor", displayName: "Cursor", configPath: "/cursor.json" },
];
const result = await runSetup(
{ ...options(false), structured: false },
host,
() =>
Promise.resolve({
approved: true,
selectedActionIds: ["configure_client:codex"],
}),
);
expect(result.plannedActions.map(({ id }) => id)).toEqual([
"configure_client:codex",
]);
expect(result.clients).toEqual({ codex: { status: "configured" } });
expect(host.configurations).toBe(1);
expect(host.skillInstalls).toBe(0);
});
it.each([
[
"path",
"Agent configuration path could not be safely verified. Check its permissions and, if it is a symbolic link, verify that the link resolves to a regular file owned by the current user, then rerun setup.",
],
[
"backup",
"Agent configuration could not be backed up, so no change was made. Check file permissions, then rerun setup.",
],
[
"write",
"Agent configuration could not be updated. Check file permissions, then rerun setup.",
],
[
"readback",
"Agent configuration could not be verified after writing. Repair the configuration file or restore its `.rea.backup`, then rerun setup.",
],
] as const)("explains %s configuration recovery", async (reason, message) => {
const host = new FakeSetupHost();
host.hopper = "/Applications/Hopper";
host.clients = [{ name: "internal_client_key", configPath: "/agent.json" }];
host.clientResults.set("internal_client_key", { status: "failed", reason });
const result = await runSetup(options(true), host);
expect(result.status).toBe("needs_human");
expect(result.remediation).toBe(message);
expect(result.remediation).not.toContain("internal_client_key");
});
});
@@ -0,0 +1,32 @@
import { describe, expect, it } from "vitest";
import {
setupInstallFailure,
type HopperInstallFailureReason,
} from "../../../src/application/SetupInstallFailure.js";
describe("setup installer failure projection", () => {
it.each([
["unsupported_host", "unsupported_host"],
["download", "download_failed"],
["release_metadata", "download_failed"],
["integrity", "integrity_mismatch"],
[
"authorization_or_package_manager",
"authorization_or_package_manager_failed",
],
["launcher_missing", "launcher_missing"],
["runtime_dependencies", "runtime_dependency_unavailable"],
["unsupported_hopper_build", "unsupported_hopper_build"],
["cancelled", "setup_cancelled"],
["destination_exists", "destination_exists"],
["mount", "mount_failed"],
["bundle", "bundle_invalid"],
["copy", "copy_failed"],
] as const)("maps %s to %s", (reason, code) => {
const result = setupInstallFailure(reason as HopperInstallFailureReason);
expect(result).toMatchObject({ status: "failed", code });
if (result.status === "failed")
expect(result.remediation.length).toBeGreaterThan(20);
});
});
@@ -0,0 +1,353 @@
import {
copyFile,
lstat,
mkdir,
readFile,
realpath,
rm,
symlink,
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 {
configureTomlClient,
detectClients,
} from "../../../src/application/Setup.js";
import {
runUninstall,
systemUninstallHost,
type UninstallFileSystem,
} from "../../../src/application/Uninstall.js";
const roots: string[] = [];
afterEach(async () => {
await Promise.all(
roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
);
});
describe("agent lifecycle", () => {
it("detects every supported client and skips absent clients", async () => {
const home = await createTestTempDirectory("rea-detect-");
roots.push(home);
for (const marker of [
".claude",
"Library/Application Support/Claude",
".codex",
".cursor",
".gemini",
".codeium/windsurf",
".devin",
])
await mkdir(join(home, marker), { recursive: true });
const detected = await detectClients(home);
expect(detected.map(({ name }) => name)).toEqual([
"claude_code",
"claude_desktop",
"codex",
"cursor",
"gemini_cli",
"windsurf",
"devin",
]);
expect(
detected.find(({ name }) => name === "claude_code")?.configPath,
).toBe(join(home, ".claude.json"));
expect(detected.find(({ name }) => name === "devin")?.format).toBe(
"unsupported",
);
const emptyHome = await createTestTempDirectory("rea-empty-");
roots.push(emptyHome);
expect(await detectClients(emptyHome)).toEqual([]);
});
it("preserves unrelated Codex TOML and supports an installed command", async () => {
const home = await createTestTempDirectory("rea-toml-");
roots.push(home);
const configPath = join(home, ".codex/config.toml");
await mkdir(dirname(configPath), { recursive: true });
await writeFile(
configPath,
'model = "gpt-5"\n[mcp_servers.other]\ncommand = "other"\n',
);
expect(
await configureTomlClient(
{ name: "codex", configPath, format: "toml" },
{
HOPPER_LAUNCHER_PATH: "/Hopper Path",
GHIDRA_INSTALL_DIR: "/opt/ghidra",
JAVA_HOME: "/opt/jdk-21",
},
["rea", "mcp"],
),
).toMatchObject({ status: "configured" });
const configured = await readFile(configPath, "utf8");
expect(configured).toContain('model = "gpt-5"');
expect(configured).toContain("[mcp_servers.rea]");
expect(configured).toContain('command = "rea"');
expect(configured).toContain("startup_timeout_sec = 30");
expect(configured).toContain('GHIDRA_INSTALL_DIR = "/opt/ghidra"');
expect(configured).toContain('JAVA_HOME = "/opt/jdk-21"');
expect(
await configureTomlClient(
{ name: "codex", configPath, format: "toml" },
{
HOPPER_LAUNCHER_PATH: "/Hopper Path",
GHIDRA_INSTALL_DIR: "/opt/ghidra",
JAVA_HOME: "/opt/jdk-21",
},
["rea", "mcp"],
),
).toEqual({ status: "unchanged" });
});
it("updates a symlink target without replacing the TOML config symlink", async () => {
const home = await createTestTempDirectory("rea-toml-symlink-");
roots.push(home);
const configPath = join(home, ".codex/config.toml");
const targetPath = join(home, "managed-config.toml");
const original = 'model = "gpt-5"\n';
await mkdir(dirname(configPath), { recursive: true });
await writeFile(targetPath, original);
await symlink(targetPath, configPath);
expect(
await configureTomlClient(
{ name: "codex", configPath, format: "toml" },
undefined,
["rea", "mcp"],
),
).toMatchObject({ status: "configured" });
expect((await lstat(configPath)).isSymbolicLink()).toBe(true);
expect(await readFile(`${configPath}.rea.backup`, "utf8")).toBe(original);
expect(await readFile(targetPath, "utf8")).toContain("[mcp_servers.rea]");
});
it("fails before mutation when a TOML config symlink is dangling", async () => {
const home = await createTestTempDirectory("rea-toml-symlink-");
roots.push(home);
const configPath = join(home, ".codex/config.toml");
await mkdir(dirname(configPath), { recursive: true });
await symlink(join(home, "missing-config.toml"), configPath);
expect(
await configureTomlClient({ name: "codex", configPath, format: "toml" }),
).toEqual({ status: "failed", reason: "path" });
expect((await lstat(configPath)).isSymbolicLink()).toBe(true);
await expect(
readFile(`${configPath}.rea.backup`, "utf8"),
).rejects.toThrow();
});
});
describe("agent lifecycle removal", () => {
it("uninstalls only owned entries and refuses purge symlinks", async () => {
const home = await createTestTempDirectory("rea-uninstall-");
roots.push(home);
const cursor = join(home, ".cursor/mcp.json");
const skill = join(
home,
".agents/skills/reverse-engineer-anything/SKILL.md",
);
await mkdir(dirname(cursor), { recursive: true });
await mkdir(dirname(skill), { recursive: true });
await writeFile(
cursor,
JSON.stringify({
mcpServers: {
rea: { command: "/isolated prefix/bin/rea", args: ["mcp"] },
other: { command: "other" },
},
}),
);
await writeFile(skill, "managed");
await mkdir(join(home, ".rea"), { recursive: true });
await import("node:fs/promises").then(({ symlink }) =>
symlink(home, join(home, ".rea/cache")),
);
const first = await runUninstall(true, systemUninstallHost(home));
expect(first.status).toBe("complete");
expect(JSON.parse(await readFile(cursor, "utf8"))).toEqual({
mcpServers: { other: { command: "other" } },
});
await expect(readFile(skill, "utf8")).rejects.toThrow();
expect(first.items).toContainEqual(
expect.objectContaining({
name: "cache",
status: "retained",
detail:
"REA did not remove this item because its managed path is a symbolic link. Verify the link target before removing it manually.",
}),
);
expect((await runUninstall(true, systemUninstallHost(home))).status).toBe(
"complete",
);
});
it("removes an owned entry through a symlink without replacing it", async () => {
const home = await createTestTempDirectory("rea-uninstall-symlink-");
roots.push(home);
const configPath = join(home, ".cursor/mcp.json");
const targetPath = join(home, "managed-mcp.json");
const original = JSON.stringify({
mcpServers: {
rea: { command: "rea", args: ["mcp"] },
other: { command: "other" },
},
});
await mkdir(dirname(configPath), { recursive: true });
await writeFile(targetPath, original);
await symlink(targetPath, configPath);
expect((await runUninstall(false, systemUninstallHost(home))).status).toBe(
"complete",
);
expect((await lstat(configPath)).isSymbolicLink()).toBe(true);
expect(await readFile(`${configPath}.rea.backup`, "utf8")).toBe(original);
expect(JSON.parse(await readFile(targetPath, "utf8"))).toEqual({
mcpServers: { other: { command: "other" } },
});
});
it("fails before mutation when an uninstall config symlink is dangling", async () => {
const home = await createTestTempDirectory("rea-uninstall-symlink-");
roots.push(home);
const configPath = join(home, ".cursor/mcp.json");
await mkdir(dirname(configPath), { recursive: true });
await symlink(join(home, "missing-mcp.json"), configPath);
const result = await runUninstall(false, systemUninstallHost(home));
expect(result.status).toBe("failed");
expect(result.items).toContainEqual({
name: "cursor",
status: "failed",
detail:
"Configuration path could not be safely verified. Check its permissions and, if it is a symbolic link, verify that the link resolves to a regular file owned by the current user, then rerun uninstall.",
});
expect((await lstat(configPath)).isSymbolicLink()).toBe(true);
await expect(
readFile(`${configPath}.rea.backup`, "utf8"),
).rejects.toThrow();
});
it("fails closed on malformed client configuration", async () => {
const home = await createTestTempDirectory("rea-uninstall-bad-");
roots.push(home);
const config = join(home, ".cursor/mcp.json");
await mkdir(dirname(config), { recursive: true });
await writeFile(config, "not-json");
const result = await runUninstall(false, systemUninstallHost(home));
expect(result.status).toBe("failed");
expect(result.items).toContainEqual(
expect.objectContaining({
name: "cursor",
status: "failed",
detail:
"Configuration is not valid JSON and was not changed. Repair it, then rerun uninstall.",
}),
);
expect(await readFile(config, "utf8")).toBe("not-json");
});
});
describe("agent lifecycle failure reporting", () => {
it.each([
[
"read",
"Configuration could not be read. Check file permissions, then rerun uninstall.",
],
[
"backup",
"Configuration could not be backed up, so no change was made. Check file permissions, then rerun uninstall.",
],
[
"update",
"Configuration could not be updated. The original was restored and its `.rea.backup` was retained. Repair the configuration or restore the backup, then rerun uninstall.",
],
[
"restore",
"Configuration could not be updated or restored. Restore its `.rea.backup` manually, then rerun uninstall.",
],
] as const)(
"reports an actionable client %s failure",
async (failure, detail) => {
const { home, config } = await uninstallFixture();
let writes = 0;
const fileSystem: UninstallFileSystem = {
...testFileSystem,
readText: (path) =>
failure === "read" && path === config
? Promise.reject(new Error("SECRET read failure"))
: readFile(path, "utf8"),
copy: (source, destination) =>
failure === "backup"
? Promise.reject(new Error("SECRET backup failure"))
: copyFile(source, destination),
writeText: async (path, contents) => {
writes += 1;
if ((failure === "update" && writes === 1) || failure === "restore")
throw new Error("SECRET write failure");
await writeFile(path, contents);
},
};
const result = await runUninstall(
false,
systemUninstallHost(home, fileSystem),
);
expect(result.status).toBe("failed");
expect(result.items).toContainEqual(
expect.objectContaining({ name: "cursor", status: "failed", detail }),
);
expect(JSON.stringify(result)).not.toContain("SECRET");
},
);
it("reports a managed-path removal failure", async () => {
const home = await createTestTempDirectory("rea-uninstall-remove-");
roots.push(home);
const skillRoot = join(home, ".agents/skills/reverse-engineer-anything");
await mkdir(skillRoot, { recursive: true });
const result = await runUninstall(
false,
systemUninstallHost(home, {
...testFileSystem,
remove: () => Promise.reject(new Error("SECRET removal failure")),
}),
);
expect(result.items).toContainEqual({
name: "skill",
status: "failed",
detail:
"This item could not be removed. Check file permissions, then rerun uninstall.",
});
expect(JSON.stringify(result)).not.toContain("SECRET");
});
});
const testFileSystem: UninstallFileSystem = {
readText: (path) => readFile(path, "utf8"),
copy: (source, destination) => copyFile(source, destination),
writeText: (path, contents) => writeFile(path, contents),
stat: (path) => lstat(path),
realpath: (path) => realpath(path),
remove: (path) => rm(path, { recursive: true }),
};
const uninstallFixture = async (): Promise<{
readonly home: string;
readonly config: string;
}> => {
const home = await createTestTempDirectory("rea-uninstall-failure-");
roots.push(home);
const config = join(home, ".cursor/mcp.json");
await mkdir(dirname(config), { recursive: true });
await writeFile(
config,
JSON.stringify({ mcpServers: { rea: { command: "rea", args: ["mcp"] } } }),
);
return { home, config };
};
@@ -0,0 +1,244 @@
import { describe, expect, it } from "vitest";
import {
registrationPermissionEnvironment,
runSetup,
type SetupProgressEvent,
} from "../../../src/application/Setup.js";
import { FakeSetupHost, options } from "./setupTestSupport.js";
describe("setup workflow", () => {
it("propagates only the explicit non-secret investigation root policy", () => {
expect(
registrationPermissionEnvironment({
REA_INVESTIGATION_INPUT_ROOTS_JSON: '["/approved/apps"]',
AUTHORIZATION: "secret",
}),
).toEqual({
REA_INVESTIGATION_INPUT_ROOTS_JSON: '["/approved/apps"]',
});
expect(registrationPermissionEnvironment({})).toEqual({});
});
it("returns a complete plan without mutation", async () => {
const host = new FakeSetupHost();
host.clients = [{ name: "cursor", configPath: "/cursor.json" }];
const result = await runSetup(options(false), host);
expect(result.status).toBe("needs_confirmation");
expect(result.plannedActions.map(({ kind }) => kind)).toEqual([
"install_hopper",
"configure_client",
"install_skill",
]);
expect(host.hopperInstalls).toBe(0);
expect(host.configurations).toBe(0);
expect(result.remediation).toBe(
"Review the setup plan, then rerun interactively or with --yes.",
);
});
it("reports ready after an accepted Linux plan installs healthy Hopper", async () => {
const host = new FakeSetupHost("linux");
host.distribution = {
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
};
const result = await runSetup(
{ ...options(false), structured: false },
host,
() => Promise.resolve(true),
);
expect(result.status).toBe("ready");
expect(result.appliedActions).toEqual([
"installed_hopper",
"installed_skill",
]);
expect(host.hopperInstalls).toBe(1);
expect(result.remediation).toBeUndefined();
});
it("requires first-run activation after installing Hopper on macOS", async () => {
const host = new FakeSetupHost();
const result = await runSetup(
{ ...options(false), structured: false },
host,
() => Promise.resolve(true),
);
expect(result.status).toBe("needs_human");
expect(result.remediation).toContain("choose its demo mode");
});
it("declines an interactive plan without mutation", async () => {
const host = new FakeSetupHost();
const result = await runSetup(
{ ...options(false), structured: false },
host,
() => Promise.resolve(false),
);
expect(result.status).toBe("planned");
expect(result.appliedActions).toEqual([]);
expect(host.hopperInstalls).toBe(0);
expect(host.doctorCalls).toBe(1);
});
it("treats an empty interactive selection as cancellation", async () => {
const host = new FakeSetupHost();
host.clients = [{ name: "codex", configPath: "/codex.toml" }];
const result = await runSetup(
{ ...options(false), structured: false },
host,
() => Promise.resolve({ approved: false, selectedActionIds: [] }),
);
expect(result.status).toBe("planned");
expect(result.plannedActions).toEqual([]);
expect(result.appliedActions).toEqual([]);
expect(host.configurations).toBe(0);
expect(host.skillInstalls).toBe(0);
expect(host.hopperInstalls).toBe(0);
expect(host.doctorCalls).toBe(1);
});
it("requires the Hopper flag for unattended setup", async () => {
const host = new FakeSetupHost();
const result = await runSetup(options(true), host);
expect(result.status).toBe("needs_human");
expect(host.hopperInstalls).toBe(0);
expect(result.appliedActions).toEqual(["installed_skill"]);
expect(result.remediation).toContain("--install-hopper");
expect(result.remediation).toBe(
"Hopper is optional for non-Hopper providers. Rerun with --yes --install-hopper for deep native analysis.",
);
});
it("installs Hopper when unattended authorization is explicit", async () => {
const host = new FakeSetupHost("linux");
host.distribution = {
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
};
const result = await runSetup(options(true, true), host);
expect(result.appliedActions).toEqual([
"installed_hopper",
"installed_skill",
]);
expect(host.hopperInstalls).toBe(1);
expect(result.status).toBe("ready");
expect(result.remediation).toBeUndefined();
});
it("reuses existing Hopper and configures detected clients", async () => {
const host = new FakeSetupHost();
host.hopper = "/Applications/Hopper";
host.clients = [
{ name: "claude", configPath: "/claude.json" },
{ name: "cursor", configPath: "/cursor.json" },
];
const result = await runSetup(options(true), host);
expect(result.status).toBe("ready");
expect(result.appliedActions).toEqual([
"configured_claude",
"configured_cursor",
"installed_skill",
]);
expect(host.hopperInstalls).toBe(0);
});
});
describe("setup workflow lifecycle and provider planning", () => {
it("reports append-only lifecycle progress for each selected action", async () => {
const host = new FakeSetupHost();
host.hopper = "/Applications/Hopper";
host.clients = [
{
name: "codex",
displayName: "Codex",
configPath: "/codex.toml",
},
];
const progress: SetupProgressEvent[] = [];
await runSetup(
{ ...options(true), onProgress: (event) => progress.push(event) },
host,
);
expect(progress).toEqual([
{ actionId: "configure_client:codex", label: "Codex", state: "started" },
{
actionId: "configure_client:codex",
label: "Codex",
state: "completed",
},
{
actionId: "install_skill",
label: "REA reverse-engineering skill",
state: "started",
},
{
actionId: "install_skill",
label: "REA reverse-engineering skill",
state: "completed",
},
]);
});
it("plans and propagates BYO Ghidra without installing software", async () => {
const host = new FakeSetupHost("linux");
host.distribution = {
id: "ubuntu",
versionId: "24.04",
packageFamily: "deb",
supported: true,
};
host.ghidra = "/opt/ghidra_12.1.2_PUBLIC";
host.javaHome = "/usr/lib/jvm/jdk-21";
host.doctorHealthy = true;
host.skill = "unchanged";
host.clients = [{ name: "cursor", configPath: "/cursor.json" }];
const plan = await runSetup(options(false), host);
expect(plan.plannedActions.map(({ kind }) => kind)).toEqual([
"configure_client",
]);
expect(plan.plannedActions[0]?.detail).toContain(
"GHIDRA_INSTALL_DIR=/opt/ghidra_12.1.2_PUBLIC",
);
expect(plan.plannedActions[0]?.detail).toContain(
"JAVA_HOME=/usr/lib/jvm/jdk-21",
);
expect(host.hopperInstalls).toBe(0);
expect(host.configurations).toBe(0);
const applied = await runSetup(options(true), host);
expect(applied.status).toBe("ready");
expect(host.hopperInstalls).toBe(0);
expect(host.configuredProviderEnvironments).toContainEqual({
GHIDRA_INSTALL_DIR: "/opt/ghidra_12.1.2_PUBLIC",
JAVA_HOME: "/usr/lib/jvm/jdk-21",
});
});
it("reinstalls existing Hopper when explicitly requested", async () => {
const host = new FakeSetupHost();
host.hopper = "/Applications/Hopper";
host.skill = "unchanged";
host.clients = [{ name: "codex", configPath: "/codex.toml" }];
host.clientResults.set("codex", { status: "unchanged" });
const result = await runSetup(options(true, true), host);
expect(result.plannedActions.map(({ kind }) => kind)).toEqual([
"install_hopper",
"configure_client",
]);
expect(result.appliedActions).toEqual(["installed_hopper"]);
expect(host.hopperInstalls).toBe(1);
expect(host.hopperReplaceRequests).toEqual([true]);
expect(host.configurations).toBe(0);
expect(host.checkedHopperPaths).toEqual(["/manual/Hopper"]);
});
});
@@ -0,0 +1,139 @@
import { describe, expect, it } from "vitest";
import { runSetup } from "../../../src/application/Setup.js";
import { FakeSetupHost, options } from "./setupTestSupport.js";
describe("setup workflow", () => {
it("records every detected client outcome after an earlier failure", async () => {
const host = new FakeSetupHost();
host.hopper = "/Applications/Hopper";
host.clients = [
{ name: "first", configPath: "/first.json" },
{ name: "second", configPath: "/second.json" },
{ name: "third", configPath: "/third.json" },
];
host.clientResults.set("first", { status: "failed", reason: "write" });
host.clientResults.set("second", { status: "configured" });
host.clientResults.set("third", { status: "failed", reason: "readback" });
const result = await runSetup(options(true), host);
expect(host.configurations).toBe(3);
expect(result.clients).toEqual({
first: { status: "failed", reason: "write" },
second: { status: "configured" },
third: { status: "failed", reason: "readback" },
});
expect(result.appliedActions).toEqual(["configured_second"]);
expect(result.status).toBe("needs_human");
expect(result.remediation).toContain("could not be updated");
});
it("explains skill installation recovery", async () => {
const host = new FakeSetupHost();
host.hopper = "/Applications/Hopper";
host.skill = "failed";
const result = await runSetup(options(true), host);
expect(result.status).toBe("needs_human");
expect(result.remediation).toBe(
"REA analysis skill could not be installed or verified. Check permissions for `~/.agents/skills`, then rerun setup.",
);
});
it("delegates remaining unhealthy checks to doctor remediation", async () => {
const host = new FakeSetupHost();
host.hopper = "/Applications/Hopper";
host.doctorHealthy = false;
const result = await runSetup(options(true), host);
expect(result.remediation).toBe(
"Run rea doctor and apply each reported remediation.",
);
});
it("uses requested readiness scope without hiding environment drift", async () => {
const host = new FakeSetupHost();
host.hopper = "/Applications/Hopper";
host.doctorHealthy = false;
host.scopedDoctorHealthy = true;
const readinessScope = {
clients: ["codex"],
providers: [] as string[],
skill: true,
};
const result = await runSetup(
{
...options(true),
proposeHopper: false,
installSkill: false,
readinessScope,
},
host,
);
expect(result).toMatchObject({
status: "ready",
doctor: { healthy: true, environment_healthy: false },
});
expect(host.doctorScopes).toEqual(expect.arrayContaining([readinessScope]));
});
it("explains unsupported Node and macOS recovery", async () => {
const platformHost = new FakeSetupHost("win32");
expect((await runSetup(options(true), platformHost)).remediation).toBe(
"REA supports Hopper on macOS and selected 64-bit Linux distributions.",
);
const nodeHost = new FakeSetupHost();
nodeHost.nodeVersion = "20.0.0";
expect((await runSetup(options(true), nodeHost)).remediation).toBe(
"Install Node.js 22.19+ or 24.11+ and rerun setup.",
);
const macHost = new FakeSetupHost();
macHost.version = "11.7";
expect((await runSetup(options(true), macHost)).remediation).toBe(
"Upgrade to macOS 12 or newer.",
);
});
it("rejects unsupported hosts before mutation", async () => {
const host = new FakeSetupHost("linux");
host.distribution = {
id: "debian",
versionId: "13",
packageFamily: "deb",
supported: false,
};
const result = await runSetup(options(true, true), host);
expect(result.status).toBe("needs_human");
expect(host.hopperInstalls).toBe(0);
expect(result.remediation).toBe(
"Automated Hopper setup supports Ubuntu 24.04+, Fedora 41+, and 64-bit Arch Linux; configure an existing supported provider instead.",
);
});
it("configures BYO Ghidra on Linux outside Hopper's installer matrix", async () => {
const host = new FakeSetupHost("linux");
host.distribution = {
id: "debian",
versionId: "13",
packageFamily: "deb",
supported: false,
};
host.ghidra = "/opt/ghidra_12.1.2_PUBLIC";
host.javaHome = "/usr/lib/jvm/jdk-21";
host.doctorHealthy = true;
host.skill = "unchanged";
host.clients = [{ name: "codex", configPath: "/codex.toml" }];
const result = await runSetup(options(true), host);
expect(result.status).toBe("ready");
expect(host.hopperInstalls).toBe(0);
expect(host.configuredProviderEnvironments).toContainEqual({
GHIDRA_INSTALL_DIR: "/opt/ghidra_12.1.2_PUBLIC",
JAVA_HOME: "/usr/lib/jvm/jdk-21",
});
});
});
+170
View File
@@ -0,0 +1,170 @@
import {
type ClientConfigurationInspection,
type ClientConfigurationResult,
type SetupClient,
type SetupHost,
type SetupOptions,
type SetupHopperInstallResult,
type SetupProviderEnvironment,
} from "../../../src/application/Setup.js";
import type {
DoctorCheck,
DoctorReport,
DoctorScope,
} from "../../../src/application/Doctor.js";
import type { LinuxDistribution } from "../../../src/application/LinuxHopper.js";
export class FakeSetupHost implements SetupHost {
readonly platform: NodeJS.Platform;
nodeVersion = "25.1.0";
version: string | undefined = "14.5";
distribution: LinuxDistribution | undefined;
hopper: string | undefined;
ghidra: string | undefined;
javaHome: string | undefined;
hopperInstallSucceeds = true;
skill: "installed" | "unchanged" | "failed" = "installed";
clients: readonly SetupClient[] = [];
clientResults = new Map<string, ClientConfigurationResult>();
clientInspections = new Map<string, ClientConfigurationInspection>();
hopperInstalls = 0;
hopperReplaceRequests: boolean[] = [];
configurations = 0;
skillInstalls = 0;
doctorCalls = 0;
doctorScopes: Array<DoctorScope | undefined> = [];
checkedHopperPaths: Array<string | undefined> = [];
configuredProviderEnvironments: SetupProviderEnvironment[] = [];
doctorHealthy: boolean | undefined;
scopedDoctorHealthy: boolean | undefined;
linuxDemoRuntimeMissing = false;
unsupportedHopperVersion = false;
constructor(platform: NodeJS.Platform = "darwin") {
this.platform = platform;
}
macosVersion = (): Promise<string | undefined> =>
Promise.resolve(this.version);
linuxDistribution = (): Promise<LinuxDistribution | undefined> =>
Promise.resolve(this.distribution);
hopperPath = (): Promise<string | undefined> => Promise.resolve(this.hopper);
providerEnvironment = (): Promise<SetupProviderEnvironment> =>
Promise.resolve({
...(this.hopper === undefined
? {}
: { HOPPER_LAUNCHER_PATH: this.hopper }),
...(this.ghidra === undefined ? {} : { GHIDRA_INSTALL_DIR: this.ghidra }),
...(this.javaHome === undefined ? {} : { JAVA_HOME: this.javaHome }),
});
installHopper = (
replaceExisting: boolean,
): Promise<SetupHopperInstallResult> => {
this.hopperInstalls += 1;
this.hopperReplaceRequests.push(replaceExisting);
this.linuxDemoRuntimeMissing = false;
if (this.hopperInstallSucceeds) {
this.hopper = "/manual/Hopper";
return Promise.resolve({
status: "installed",
launcherPath: this.hopper,
});
}
return Promise.resolve({
status: "failed",
code: "download_failed",
remediation: "Download failed.",
});
};
detectedClients = (): Promise<readonly SetupClient[]> =>
Promise.resolve(this.clients);
configureClient = (
client: SetupClient,
providerEnvironment: SetupProviderEnvironment,
): Promise<ClientConfigurationResult> => {
this.configurations += 1;
this.configuredProviderEnvironments.push(providerEnvironment);
return Promise.resolve(
this.clientResults.get(client.name) ?? { status: "configured" },
);
};
clientNeedsConfigure = (
client: SetupClient,
providerEnvironment: SetupProviderEnvironment,
): Promise<boolean> => {
this.checkedHopperPaths.push(providerEnvironment.HOPPER_LAUNCHER_PATH);
return Promise.resolve(
this.clientResults.get(client.name)?.status !== "unchanged",
);
};
inspectClientConfiguration = (
client: SetupClient,
): Promise<ClientConfigurationInspection> =>
Promise.resolve(
this.clientInspections.get(client.name) ?? { status: "update" },
);
skillNeedsInstall = (): Promise<boolean> =>
Promise.resolve(this.skill !== "unchanged");
installSkill = (): Promise<"installed" | "unchanged" | "failed"> => {
this.skillInstalls += 1;
return Promise.resolve(this.skill);
};
doctor = (scope?: DoctorScope): Promise<DoctorReport> => {
this.doctorCalls += 1;
this.doctorScopes.push(scope);
const checks: DoctorCheck[] = [
...(this.linuxDemoRuntimeMissing
? ([
{
name: "hopper-demo-runtime",
ok: false,
classification: "missing_dependency",
},
] as const)
: []),
...(this.unsupportedHopperVersion
? ([
{
name: "hopper-version",
ok: false,
classification: "config_drift",
detail: this.hopper ?? "",
},
] as const)
: []),
];
const environmentHealthy =
this.doctorHealthy ??
(this.hopper !== undefined &&
!this.linuxDemoRuntimeMissing &&
!this.unsupportedHopperVersion);
const healthy =
scope === undefined
? environmentHealthy
: (this.scopedDoctorHealthy ?? environmentHealthy);
return Promise.resolve({
healthy,
environment_healthy: environmentHealthy,
scope: {
mode: scope === undefined ? "audit-wide" : "explicit",
clients: scope?.clients ?? [],
providers: scope?.providers ?? [],
skill: scope?.skill === true,
target: null,
},
scope_checks: checks,
informational_checks: [],
...(this.hopper === undefined ? {} : { hopperPath: this.hopper }),
checks,
});
};
}
export const options = (
approved: boolean,
installHopper = false,
): SetupOptions => ({
approved,
installHopper,
structured: true,
});
+201
View File
@@ -0,0 +1,201 @@
import { describe, expect, it } from "vitest";
import {
detectNpmInstallation,
runUpgrade,
type UpgradeHost,
type UpgradeOutput,
type NpmInstallationHost,
} from "../../../src/application/Upgrade.js";
class FakeUpgradeHost implements UpgradeHost {
latest: string | undefined = "0.6.0";
installationResult: { readonly prefix: string } | undefined = {
prefix: "/fixture",
};
installSucceeds = true;
installs = 0;
output: UpgradeOutput | undefined;
syncResult: boolean | undefined = true;
syncs = 0;
latestVersion = (): Promise<string | undefined> =>
Promise.resolve(this.latest);
installation = (): Promise<{ readonly prefix: string } | undefined> =>
Promise.resolve(this.installationResult);
installLatest = (
_installation: { readonly prefix: string },
output: UpgradeOutput,
): Promise<boolean> => {
this.installs += 1;
this.output = output;
return Promise.resolve(this.installSucceeds);
};
syncAgentIntegration = (
_output: UpgradeOutput,
): Promise<boolean | undefined> => {
this.syncs += 1;
return Promise.resolve(this.syncResult);
};
}
describe("CLI upgrade", () => {
it("reports an already-current release without mutation", async () => {
const host = new FakeUpgradeHost();
expect(await runUpgrade("0.6.0", host)).toEqual({
status: "current",
currentVersion: "0.6.0",
latestVersion: "0.6.0",
installMethod: "npm",
});
expect(host.installs).toBe(0);
});
it("upgrades an outdated global npm installation", async () => {
const host = new FakeUpgradeHost();
expect(await runUpgrade("0.5.0", host)).toEqual({
status: "upgraded",
previousVersion: "0.5.0",
latestVersion: "0.6.0",
versionCheck: "available",
installMethod: "npm",
command: "npm install --global rea-agents@latest",
integrationSync: "setup_invoked",
clientRestartRequired: true,
remediation:
"The updated setup journey was opened to align registrations and the skill. Restart clients whose approved registration changed.",
});
expect(host.installs).toBe(1);
expect(host.syncs).toBe(1);
});
it("does not mutate when the registry check is unavailable", async () => {
const host = new FakeUpgradeHost();
host.latest = undefined;
expect(await runUpgrade("0.5.0", host)).toMatchObject({
status: "failed",
latestVersion: null,
reason: "version-check",
});
expect(host.installs).toBe(0);
});
it.each([
["1.10.0", "1.9.0"],
["1.0.0", "1.0.0-rc.1"],
])(
"does not downgrade installed version %s to registry version %s",
async (currentVersion, latestVersion) => {
const host = new FakeUpgradeHost();
host.latest = latestVersion;
expect(await runUpgrade(currentVersion, host)).toEqual({
status: "current",
currentVersion,
latestVersion,
installMethod: "npm",
});
expect(host.installs).toBe(0);
},
);
it("upgrades a prerelease when the final release is available", async () => {
const host = new FakeUpgradeHost();
host.latest = "1.0.0";
expect(await runUpgrade("1.0.0-rc.1", host)).toMatchObject({
status: "upgraded",
previousVersion: "1.0.0-rc.1",
latestVersion: "1.0.0",
});
expect(host.installs).toBe(1);
});
it("rejects invalid registry version metadata without mutation", async () => {
const host = new FakeUpgradeHost();
host.latest = "latest";
expect(await runUpgrade("1.0.0", host)).toMatchObject({
status: "failed",
currentVersion: "1.0.0",
latestVersion: "latest",
reason: "version-check",
});
expect(host.installs).toBe(0);
});
it("preserves stdout for an explicitly structured CLI response", async () => {
const host = new FakeUpgradeHost();
host.syncResult = undefined;
expect(await runUpgrade("0.5.0", host, "structured")).toMatchObject({
status: "upgraded",
integrationSync: "deferred",
remediation:
"Run rea setup --all-detected to align registrations and the skill, then restart clients that may retain an older MCP server.",
});
expect(host.output).toBe("structured");
});
it("refuses to mutate an unrelated installation", async () => {
const host = new FakeUpgradeHost();
host.installationResult = undefined;
expect(await runUpgrade("0.5.0", host)).toMatchObject({
status: "failed",
reason: "unknown-install-method",
remediation:
"Update manually with: npm install --global rea-agents@latest",
});
expect(host.installs).toBe(0);
});
it("reports npm installation failure", async () => {
const host = new FakeUpgradeHost();
host.installSucceeds = false;
expect(await runUpgrade("0.5.0", host)).toMatchObject({
status: "failed",
reason: "install",
remediation:
"REA could not update through npm. Check npm registry access and global install permissions, then run: npm install --global rea-agents@latest",
});
expect(host.installs).toBe(1);
});
});
describe("npm installation detection", () => {
const host = (root: string, prefix = "/usr/local"): NpmInstallationHost => ({
canonicalPath: (path) => Promise.resolve(path),
globalRoot: () => Promise.resolve(root),
globalPrefix: () => Promise.resolve(prefix),
});
it("returns the prefix for the global package that owns the running CLI", async () => {
await expect(
detectNpmInstallation(
"/usr/local/lib/node_modules/rea-agents",
host("/usr/local/lib/node_modules"),
),
).resolves.toEqual({ prefix: "/usr/local" });
});
it("infers the prefix used by the curl installer's custom npm layout", async () => {
await expect(
detectNpmInstallation(
"/home/user/.local/lib/node_modules/rea-agents",
host("/usr/local/lib/node_modules"),
),
).resolves.toEqual({ prefix: "/home/user/.local" });
});
it("rejects a source checkout when a different global copy exists", async () => {
await expect(
detectNpmInstallation("/work/rea", host("/usr/local/lib/node_modules")),
).resolves.toBeUndefined();
});
});