feat: expand cross-platform investigation workflows

This commit is contained in:
morluto
2026-07-20 08:08:39 +00:00
parent b537ebfa34
commit dffc81c865
672 changed files with 13013 additions and 2302 deletions
+111
View File
@@ -0,0 +1,111 @@
import { mkdtemp, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
TextReader,
Uint8ArrayReader,
Uint8ArrayWriter,
ZipWriter,
} from "@zip.js/zip.js";
import { describe, expect, it } from "vitest";
import { projectAndroidApplicationEvidence } from "../src/application/AndroidApplicationService.js";
import { runProviderAnalysis } from "../src/application/DirectAnalysis.js";
import { androidApplicationProjectionResultSchema } from "../src/domain/androidApplication.js";
import { parseEvidence } from "../src/domain/evidence.js";
describe("Android application projection", () => {
it("projects deterministic APK components and explicit bridge hypotheses", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-android-"));
const path = join(root, "Fixture.apk");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add(
"AndroidManifest.xml",
new Uint8ArrayReader(Uint8Array.from([3, 0, 8, 0])),
);
await writer.add(
"classes.dex",
new Uint8ArrayReader(
Uint8Array.from([0x64, 0x65, 0x78, 0x0a, 0x30, 0x33, 0x35, 0]),
),
);
await writer.add(
"lib/arm64-v8a/libreactnativejni.so",
new Uint8ArrayReader(
Uint8Array.from([0x7f, 0x45, 0x4c, 0x46, 2, 1, 1, 0]),
),
);
await writer.add("assets/index.js", new TextReader("bridge();"));
await writer.add("META-INF/FIXTURE.RSA", new TextReader("opaque signing"));
await writeFile(path, await writer.close());
const inventory = parseEvidence(
await runProviderAnalysis(path, "inventory_artifact", {
node_limit: 500,
occurrence_limit: 500,
edge_limit: 500,
}),
);
const first = projectAndroidApplicationEvidence({
inventory_evidence: [inventory],
limits: { max_components: 100 },
});
const second = projectAndroidApplicationEvidence({
inventory_evidence: [inventory],
limits: { max_components: 100 },
});
expect(first.ok).toBe(true);
expect(second.ok).toBe(true);
if (!first.ok || !second.ok) return;
const left = androidApplicationProjectionResultSchema.parse(
first.value.normalized_result,
);
const right = androidApplicationProjectionResultSchema.parse(
second.value.normalized_result,
);
expect(left).toEqual(right);
expect(left).toMatchObject({
root_format: "apk",
coverage: {
status: "complete-within-inventory",
inventory_complete: true,
omitted_components: 0,
},
});
expect(left.components.manifests).toHaveLength(1);
expect(left.components.dex).toHaveLength(1);
expect(left.components.native_libraries).toHaveLength(1);
expect(left.components.javascript).toHaveLength(1);
expect(left.components.signing).toHaveLength(1);
expect(left.runtime_families).toEqual(
expect.arrayContaining([
"dalvik-art",
"javascript",
"native",
"react-native",
]),
);
expect(left.bridge_candidates).toEqual([
expect.objectContaining({ basis: "react-native-convention" }),
]);
expect(JSON.stringify(left)).not.toContain("opaque signing");
});
it("rejects non-APK inventory Evidence", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-android-invalid-"));
const path = join(root, "fixture.zip");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("one.js", new TextReader("one"));
await writeFile(path, await writer.close());
const inventory = parseEvidence(
await runProviderAnalysis(path, "inventory_artifact", {}),
);
expect(
projectAndroidApplicationEvidence({ inventory_evidence: [inventory] }),
).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
});
});
});
+114
View File
@@ -0,0 +1,114 @@
import { mkdtemp, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
TextReader,
Uint8ArrayReader,
Uint8ArrayWriter,
ZipWriter,
} from "@zip.js/zip.js";
import { describe, expect, it } from "vitest";
import { projectAppleApplicationEvidence } from "../src/application/AppleApplicationService.js";
import { runProviderAnalysis } from "../src/application/DirectAnalysis.js";
import { appleApplicationProjectionResultSchema } from "../src/domain/appleApplication.js";
import { parseEvidence } from "../src/domain/evidence.js";
describe("Apple application projection", () => {
it("projects deterministic IPA components and bridge hypotheses from exact inventory Evidence", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-apple-"));
const path = join(root, "Fixture.ipa");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("Payload/Fixture.app/", undefined, { directory: true });
await writer.add(
"Payload/Fixture.app/Info.plist",
new TextReader("<plist><dict/></plist>"),
);
await writer.add(
"Payload/Fixture.app/Fixture",
new Uint8ArrayReader(
Uint8Array.from([0xcf, 0xfa, 0xed, 0xfe, 0x0c, 0, 0, 1]),
),
);
await writer.add(
"Payload/Fixture.app/Frameworks/React.framework/React",
new Uint8ArrayReader(
Uint8Array.from([0xcf, 0xfa, 0xed, 0xfe, 0x0c, 0, 0, 1]),
),
);
await writer.add(
"Payload/Fixture.app/main.js",
new TextReader("bridge.call();"),
);
await writer.add(
"Payload/Fixture.app/embedded.mobileprovision",
new TextReader("opaque signing bytes"),
);
await writeFile(path, await writer.close());
const inventory = parseEvidence(
await runProviderAnalysis(path, "inventory_artifact", {
node_limit: 500,
occurrence_limit: 500,
edge_limit: 500,
}),
);
const first = projectAppleApplicationEvidence({
inventory_evidence: [inventory],
limits: { max_components: 100 },
});
const second = projectAppleApplicationEvidence({
inventory_evidence: [inventory],
limits: { max_components: 100 },
});
expect(first.ok).toBe(true);
expect(second.ok).toBe(true);
if (!first.ok || !second.ok) return;
const left = appleApplicationProjectionResultSchema.parse(
first.value.normalized_result,
);
const right = appleApplicationProjectionResultSchema.parse(
second.value.normalized_result,
);
expect(left).toEqual(right);
expect(left).toMatchObject({
root_format: "ipa",
application_roots: ["Payload/Fixture.app"],
coverage: {
status: "complete-within-inventory",
inventory_complete: true,
omitted_components: 0,
},
});
expect(left.components.bundle_metadata).toHaveLength(1);
expect(left.components.executables.length).toBeGreaterThanOrEqual(2);
expect(left.components.frameworks).toHaveLength(1);
expect(left.components.javascript).toHaveLength(1);
expect(left.components.signing).toHaveLength(1);
expect(left.runtime_families).toEqual(
expect.arrayContaining(["javascript", "native", "react-native"]),
);
expect(left.bridge_candidates).toEqual([
expect.objectContaining({ basis: "react-native-convention" }),
]);
expect(JSON.stringify(left)).not.toContain("opaque signing bytes");
});
it("rejects non-IPA Evidence and reports projection truncation", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-apple-invalid-"));
const path = join(root, "fixture.zip");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("one.js", new TextReader("one"));
await writeFile(path, await writer.close());
const inventory = parseEvidence(
await runProviderAnalysis(path, "inventory_artifact", {}),
);
expect(
projectAppleApplicationEvidence({ inventory_evidence: [inventory] }),
).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
});
});
});
+36
View File
@@ -83,6 +83,42 @@ describe("application workflow CLI parity", () => {
]),
},
});
const missingAppleInventory = await runCli([
"project-apple-application-graph",
"{}",
"--json",
]);
expect(missingAppleInventory).toMatchObject({
code: "invalid_request",
remediation: {
action: "Correct the listed arguments and retry.",
},
});
const missingAndroidInventory = await runCli([
"project-android-application-graph",
"{}",
"--json",
]);
expect(missingAndroidInventory).toMatchObject({
code: "invalid_request",
remediation: {
action: "Correct the listed arguments and retry.",
},
});
const missingRuntimeInventory = await runCli([
"identify-runtime",
"{}",
"--json",
]);
expect(missingRuntimeInventory).toMatchObject({
code: "invalid_request",
remediation: {
action: "Correct the listed arguments and retry.",
},
});
}, 20_000);
});
+99 -1
View File
@@ -340,6 +340,46 @@ describe("artifact graph MCP integration", () => {
expect(inventoryResult.result).toMatchObject({
manifest: { root_format: "ipa" },
});
const projected = await client.callTool({
name: "project_apple_application_graph",
arguments: {
inventory_evidence_ids: [evidence.evidence_id],
limits: { max_components: 100 },
},
});
expect(projected.isError).not.toBe(true);
const projection = compactResult(projected.structuredContent);
expect(projection.result).toMatchObject({
root_format: "ipa",
source_evidence_ids: [evidence.evidence_id],
components: { javascript: [expect.objectContaining({})] },
});
expect(session.evidenceById(projection.evidence_id)).toMatchObject({
operation: "project_apple_application_graph",
provider: { id: "rea-apple-application" },
});
const identified = await client.callTool({
name: "identify_runtime",
arguments: { inventory_evidence_ids: [evidence.evidence_id] },
});
expect(identified.isError).not.toBe(true);
const runtimeIdentification = compactResult(identified.structuredContent);
expect(runtimeIdentification.result).toMatchObject({
root_format: "ipa",
runtimes: expect.arrayContaining([
expect.objectContaining({
family: "apple",
inspection: "available",
provider_id: "rea-apple-application",
}),
]),
});
expect(
session.evidenceById(runtimeIdentification.evidence_id),
).toMatchObject({
operation: "identify_runtime",
provider: { id: "rea-runtime-identification" },
});
const openedChanged = await client.callTool({
name: "open_binary",
arguments: { path: changedArchive },
@@ -380,7 +420,7 @@ describe("artifact graph MCP integration", () => {
const envelope = z
.object({ result: evidenceBundleSchema })
.parse(exported.structuredContent);
expect(envelope.result.records).toHaveLength(4);
expect(envelope.result.records).toHaveLength(6);
expect(envelope.result.artifacts).toContainEqual({
digest: { sha256: evidence.subject?.digest.sha256 },
format: "ipa",
@@ -394,6 +434,64 @@ describe("artifact graph MCP integration", () => {
]);
}
});
it("projects authenticated APK inventory through the Android MCP workflow", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-android-mcp-"));
const archive = join(root, "Fixture.apk");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("AndroidManifest.xml", new TextReader("manifest"));
await writer.add("classes.dex", new TextReader("dex\n035\0"));
await writeFile(archive, await writer.close());
const session = new BinarySession(new ArtifactProvider());
const server = createServer(session, session);
const client = new Client({ name: "android-artifact-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
await client.callTool({
name: "open_binary",
arguments: { path: archive },
});
const inventory = compactResult(
(
await client.callTool({
name: "inventory_artifact",
arguments: {},
})
).structuredContent,
);
const projected = await client.callTool({
name: "project_android_application_graph",
arguments: {
inventory_evidence_ids: [inventory.evidence_id],
limits: { max_components: 100 },
},
});
expect(projected.isError).not.toBe(true);
const projection = compactResult(projected.structuredContent);
expect(projection.result).toMatchObject({
root_format: "apk",
source_evidence_ids: [inventory.evidence_id],
components: {
manifests: [expect.objectContaining({})],
dex: [expect.objectContaining({})],
},
});
expect(session.evidenceById(projection.evidence_id)).toMatchObject({
operation: "project_android_application_graph",
provider: { id: "rea-android-application" },
});
} finally {
await Promise.allSettled([
client.close(),
server.close(),
session.close(),
]);
}
});
});
const compactResult = (value: unknown) =>
+81
View File
@@ -179,6 +179,46 @@ describe("artifact graph provider", () => {
});
});
it("classifies mobile and managed runtime artifacts without executing them", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-mobile-artifacts-"));
const apkPath = join(root, "fixture.apk");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add(
"AndroidManifest.xml",
new TextReader("binary manifest placeholder"),
);
await writer.add("resources.arsc", new TextReader("resources"));
await writer.add(
"classes.dex",
new TextReader("dex\n035\0fixture bytecode"),
);
await writer.add(
"assets/Fixture.class",
new TextReader("\xca\xfe\xba\xbeclass bytes"),
);
await writer.add("assets/module.wasm", new TextReader("\0asm\u0001\0\0\0"));
await writeFile(apkPath, await writer.close());
const result = await inventory(target(apkPath, "apk"));
const formats = result.nodes.items.map(({ format }) => format);
expect(formats).toEqual(
expect.arrayContaining([
"android-manifest",
"android-resources",
"dex",
"jvm-class",
"webassembly",
]),
);
expect(result.nodes.items).toEqual(
expect.arrayContaining([
expect.objectContaining({ kind: "package-metadata" }),
expect.objectContaining({ kind: "bytecode", format: "dex" }),
expect.objectContaining({ kind: "bytecode", format: "jvm-class" }),
]),
);
});
it("rejects unsafe, colliding, and over-ratio entries", async () => {
expect(() => normalizeArtifactPath("../escape", limits())).toThrow(
/normalized/u,
@@ -301,6 +341,47 @@ describe("artifact graph provider", () => {
);
});
it("requires both caller approval and operator policy before DMG extraction", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-dmg-extract-policy-"));
const path = join(root, "fixture.dmg");
await writeFile(path, "not mounted");
const targetValue = target(path, "dmg");
const occurrenceId = `occ_${"0".repeat(64)}`;
const outputRoot = join(root, "output");
const withoutApproval = await new ArtifactProvider(true)
.createClient(targetValue)
.execute(
"extract_artifact",
artifactExtractionInputSchema.parse({
approved: true,
output_root: outputRoot,
occurrence_ids: [occurrenceId],
}),
);
expect(withoutApproval).toMatchObject({
ok: false,
error: { _tag: "ArtifactOperationError", reason: "unavailable" },
});
const disabledByPolicy = await new ArtifactProvider()
.createClient(targetValue)
.execute(
"extract_artifact",
artifactExtractionInputSchema.parse({
approved: true,
native_mount_approved: true,
output_root: outputRoot,
occurrence_ids: [occurrenceId],
}),
);
expect(disabledByPolicy).toMatchObject({
ok: false,
error: { _tag: "ArtifactOperationError", reason: "unavailable" },
});
await expect(access(outputRoot)).rejects.toThrow();
});
it("paginates wide graphs without changing manifest identity", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-wide-"));
await Promise.all(
+5 -5
View File
@@ -21,11 +21,11 @@ describe("authorized artifact inventory", () => {
try {
const path = join(root, "artifact.js");
await writeFile(path, "export const value = 1;\n");
const inventory = await scanAuthorizedArtifactInventory(
path,
[join(root, "missing"), root],
LIMITS,
);
const inventory = await scanAuthorizedArtifactInventory({
inputPath: path,
roots: [join(root, "missing"), root],
limits: LIMITS,
});
expect(inventory.manifest.root_format).toBe("javascript-bundle");
} finally {
await rm(root, { recursive: true, force: true });
+8
View File
@@ -118,6 +118,14 @@ describe("Hopper bridge truthfulness", () => {
);
});
it("rejects analysis queries while Hopper background analysis is active", () => {
expect(bridgeSource).toContain(
"class AnalysisInProgressError(RuntimeError)",
);
expect(bridgeSource).toContain("raise AnalysisInProgressError(");
expect(bridgeSource).toContain('return "analysis_in_progress"');
});
it("returns deterministic addresses for direct procedure relationships", () => {
expect(bridgeSource).toContain(
"_hex(item.getEntryPoint()) for item in procedure.getAllCallerProcedures()",
+39 -15
View File
@@ -16,24 +16,32 @@ afterEach(async () => {
await Promise.all(browsers.splice(0).map(async (browser) => browser.close()));
});
const startBrowserContext = async (): Promise<{
readonly browser: FakeCdpBrowser;
readonly environment: NodeJS.ProcessEnv;
}> => {
const browser = await startFakeCdpBrowser({
sessionTimeline: "same_origin",
webMcpTools: true,
sensitiveShapes: true,
});
browsers.push(browser);
return {
browser,
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]),
},
};
};
describe("browser CLI parity", () => {
it(
"returns the same Evidence v2 discovery and inspection contracts",
"returns matching discovery, inspection, and comparison 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 { browser, environment } = await startBrowserContext();
const listed = await runCli(
["list-browser-targets", browser.endpoint, "--approved", "--json"],
environment,
@@ -97,6 +105,14 @@ describe("browser CLI parity", () => {
},
},
});
},
INTEGRATION_TEST_TIMEOUT_MS,
);
it(
"returns bundle, session, and WebMCP contracts",
async () => {
const { browser, environment } = await startBrowserContext();
const analyzed = await runCli(
[
"analyze-web-bundle",
@@ -158,6 +174,14 @@ describe("browser CLI parity", () => {
},
},
});
},
INTEGRATION_TEST_TIMEOUT_MS,
);
it(
"returns screenshot, visual comparison, and policy contracts",
async () => {
const { browser, environment } = await startBrowserContext();
const screenshot = await runCli(
[
"capture-web-screenshot",
+3 -2
View File
@@ -33,11 +33,11 @@ const comparison = (
name: process
? "REA deterministic process harness"
: "REA artifact comparison",
version: operation === "compare_process_captures" ? "3" : "1",
version: operation === "compare_process_captures" ? "4" : "1",
},
{
predicateType: process
? "rea.process-comparison/v3"
? "rea.process-comparison/v4"
: "rea.artifact-comparison/v1",
operation,
parameters: {},
@@ -64,6 +64,7 @@ const processResult = (
exit: overrides.exit ?? "unchanged",
filesystem: "unchanged",
protocol: "unchanged",
replay_transition: "unchanged",
process: "unchanged",
shim: overrides.shim ?? "unchanged",
first_divergence:
+15 -1
View File
@@ -10,7 +10,11 @@ import {
readProjectPermissionStore,
writeProjectPermissionStore,
} from "../src/application/ProjectPermissionStore.js";
import { approvePolicyRevocation } from "../src/cliPolicyCommands.js";
import {
approvePolicyRevocation,
policyCapabilitySchema,
} from "../src/cliPolicyCommands.js";
import { PERMISSION_CAPABILITIES } from "../src/domain/permissionPolicy.js";
const execute = promisify(execFile);
const roots: string[] = [];
@@ -22,6 +26,16 @@ afterEach(async () => {
});
describe("policy revocation approval", () => {
it("accepts every capability from the canonical permission inventory", () => {
expect(policyCapabilitySchema.options).toEqual(PERMISSION_CAPABILITIES);
expect(policyCapabilitySchema.parse("javascript_replay")).toBe(
"javascript_replay",
);
expect(policyCapabilitySchema.parse("managed_runtime")).toBe(
"managed_runtime",
);
});
it("accepts --yes without invoking the interactive prompt", async () => {
const confirm = vi.fn<() => Promise<boolean>>();
+10
View File
@@ -93,6 +93,16 @@ describe("runtime configuration", () => {
);
});
it("parses an optional absolute BYO jadx path", () => {
expect(
parseConfig({ REA_JADX_CMD_PATH: "/opt/jadx/bin/jadx" }),
).toMatchObject({
ok: true,
value: { jadxCmdPath: "/opt/jadx/bin/jadx" },
});
expect(parseConfig({ REA_JADX_CMD_PATH: "relative/jadx" }).ok).toBe(false);
});
it("builds a separate Electron endpoint and file-root ceiling", () => {
const result = parseConfig({
REA_ELECTRON_OBSERVE_ENABLED: "true",
+13 -1
View File
@@ -11,6 +11,9 @@ import { NATIVE_TOOL_CONTRACTS } from "../src/contracts/nativeToolContracts.js";
import { ARTIFACT_TOOL_CONTRACTS } from "../src/contracts/artifactToolContracts.js";
import { MANAGED_TOOL_CONTRACTS } from "../src/contracts/managedToolContracts.js";
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "../src/contracts/managedWorkflowToolContracts.js";
import { APPLE_APPLICATION_TOOL_CONTRACTS } from "../src/contracts/appleApplicationToolContracts.js";
import { ANDROID_APPLICATION_TOOL_CONTRACTS } from "../src/contracts/androidApplicationToolContracts.js";
import { RUNTIME_IDENTIFICATION_TOOL_CONTRACTS } from "../src/contracts/runtimeIdentificationToolContracts.js";
import { BROWSER_TOOL_CONTRACTS } from "../src/contracts/browserToolContracts.js";
import { ELECTRON_TOOL_CONTRACTS } from "../src/contracts/electronToolContracts.js";
import { APPLICATION_TOOL_CONTRACTS } from "../src/contracts/applicationToolContracts.js";
@@ -93,11 +96,14 @@ describe("tool contract surface", () => {
...ARTIFACT_TOOL_CONTRACTS,
...MANAGED_TOOL_CONTRACTS,
...MANAGED_WORKFLOW_TOOL_CONTRACTS,
...APPLE_APPLICATION_TOOL_CONTRACTS,
...ANDROID_APPLICATION_TOOL_CONTRACTS,
...RUNTIME_IDENTIFICATION_TOOL_CONTRACTS,
...BROWSER_TOOL_CONTRACTS,
...ELECTRON_TOOL_CONTRACTS,
...APPLICATION_TOOL_CONTRACTS,
];
expect(contracts).toHaveLength(77);
expect(contracts).toHaveLength(80);
for (const contract of contracts) {
const inputSchema = contractJsonSchema(contract.inputSchema);
const outputSchema = contractJsonSchema(contract.outputSchema);
@@ -129,6 +135,9 @@ describe("tool contract surface", () => {
...ARTIFACT_TOOL_CONTRACTS,
...MANAGED_TOOL_CONTRACTS,
...MANAGED_WORKFLOW_TOOL_CONTRACTS,
...APPLE_APPLICATION_TOOL_CONTRACTS,
...ANDROID_APPLICATION_TOOL_CONTRACTS,
...RUNTIME_IDENTIFICATION_TOOL_CONTRACTS,
...BROWSER_TOOL_CONTRACTS,
...ELECTRON_TOOL_CONTRACTS,
...APPLICATION_TOOL_CONTRACTS,
@@ -223,6 +232,9 @@ describe("tool contract surface", () => {
...ARTIFACT_TOOL_CONTRACTS,
...MANAGED_TOOL_CONTRACTS,
...MANAGED_WORKFLOW_TOOL_CONTRACTS,
...APPLE_APPLICATION_TOOL_CONTRACTS,
...ANDROID_APPLICATION_TOOL_CONTRACTS,
...RUNTIME_IDENTIFICATION_TOOL_CONTRACTS,
...BROWSER_TOOL_CONTRACTS,
...ELECTRON_TOOL_CONTRACTS,
...APPLICATION_TOOL_CONTRACTS,
+9 -10
View File
@@ -47,14 +47,13 @@ describe("cross-version inventory", () => {
const right = deferred<typeof snapshot>();
const calls: string[] = [];
const controller = new AbortController();
const scanner: VersionInventoryScanner = (...arguments_) => {
const [path, roots, limits, signal, integrity] = arguments_;
calls.push(path);
expect(roots).toEqual([root]);
expect(limits).toBe(LIMITS);
expect(signal).toBe(controller.signal);
expect(integrity).toBe(INTEGRITY);
return path === "left" ? left.promise : right.promise;
const scanner: VersionInventoryScanner = (input) => {
calls.push(input.inputPath);
expect(input.roots).toEqual([root]);
expect(input.limits).toBe(LIMITS);
expect(input.signal).toBe(controller.signal);
expect(input.integrity).toBe(INTEGRITY);
return input.inputPath === "left" ? left.promise : right.promise;
};
const result = scanVersionInventories(
@@ -84,8 +83,8 @@ describe("cross-version inventory", () => {
it("rejects promptly when either parallel scan fails", async () => {
const left = deferred<never>();
const failure = new Error("right scan failed");
const scanner: VersionInventoryScanner = (path) =>
path === "left" ? left.promise : Promise.reject(failure);
const scanner: VersionInventoryScanner = (input) =>
input.inputPath === "left" ? left.promise : Promise.reject(failure);
await expect(
scanVersionInventories(
+65 -59
View File
@@ -59,64 +59,70 @@ describe("direct analysis snapshot permissions", () => {
});
});
it("replays a cache hit with snapshot read authority only", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-direct-snapshot-"));
const snapshotPath = join(directory, "analysis.json");
const launcherPath = join(directory, "hopper-launcher");
await writeFile(launcherPath, "fixture Hopper launcher");
await chmod(launcherPath, 0o755);
const target = await parseBinaryTarget(process.execPath);
if (!target.ok) throw target.error;
const resolved = await resolveHopperAnalysisProfile(target.value, {
launcherPath,
loaderArgsOverride: [],
provider: HOPPER_PROVIDER_IDENTITY,
});
if (!resolved.ok || resolved.value.profile === null)
throw new Error("fixture Hopper profile did not resolve");
const profile = resolved.value.profile;
const workflowProfile = workflowAnalysisProfile(profile);
const evidence = createEvidence(target.value, REA_WORKFLOW_PROVIDER, {
operation: "binary_overview",
parameters: {},
result: { cached: true },
analysisProfile: workflowProfile,
});
const snapshot: AnalysisSnapshot = {
snapshot_version: 2,
target: snapshotTarget(target.value),
binding: snapshotBinding(profile),
entries: [],
evidence_bundle: createEvidenceBundle([evidence]),
};
const policy = {
roots: [directory],
maxBytes: 1024 * 1024,
maxDepth: 64,
maxStringLength: 1024,
maxNodes: 10_000,
};
expect(
(await writeAnalysisSnapshot(snapshot, snapshotPath, false, policy)).ok,
).toBe(true);
const authority = await permissionAuthorityForRoot(
directory,
["snapshot_read", "snapshot_write"],
["snapshot_read"],
);
vi.stubEnv("REA_ANALYSIS_SNAPSHOT_ROOTS_JSON", JSON.stringify([directory]));
vi.stubEnv("HOPPER_LAUNCHER_PATH", launcherPath);
it.each(["binary_overview", "analyze_function"] as const)(
"replays a %s workflow cache hit with snapshot read authority only",
async (operation) => {
directory = await mkdtemp(join(tmpdir(), "rea-direct-snapshot-"));
const snapshotPath = join(directory, "analysis.json");
const launcherPath = join(directory, "hopper-launcher");
await writeFile(launcherPath, "fixture Hopper launcher");
await chmod(launcherPath, 0o755);
const target = await parseBinaryTarget(process.execPath);
if (!target.ok) throw target.error;
const resolved = await resolveHopperAnalysisProfile(target.value, {
launcherPath,
loaderArgsOverride: [],
provider: HOPPER_PROVIDER_IDENTITY,
});
if (!resolved.ok || resolved.value.profile === null)
throw new Error("fixture Hopper profile did not resolve");
const profile = resolved.value.profile;
const workflowProfile = workflowAnalysisProfile(profile);
const evidence = createEvidence(target.value, REA_WORKFLOW_PROVIDER, {
operation,
parameters: {},
result: { cached: true },
analysisProfile: workflowProfile,
});
const snapshot: AnalysisSnapshot = {
snapshot_version: 2,
target: snapshotTarget(target.value),
binding: snapshotBinding(profile),
entries: [],
evidence_bundle: createEvidenceBundle([evidence]),
};
const policy = {
roots: [directory],
maxBytes: 1024 * 1024,
maxDepth: 64,
maxStringLength: 1024,
maxNodes: 10_000,
};
expect(
(await writeAnalysisSnapshot(snapshot, snapshotPath, false, policy)).ok,
).toBe(true);
const authority = await permissionAuthorityForRoot(
directory,
["snapshot_read", "snapshot_write"],
["snapshot_read"],
);
vi.stubEnv(
"REA_ANALYSIS_SNAPSHOT_ROOTS_JSON",
JSON.stringify([directory]),
);
vi.stubEnv("HOPPER_LAUNCHER_PATH", launcherPath);
await expect(
runDirectAnalysis(
process.execPath,
"binary_overview",
{},
{
snapshotPath,
permissionAuthority: authority,
},
),
).resolves.toEqual(evidence);
});
await expect(
runDirectAnalysis(
process.execPath,
operation,
{},
{
snapshotPath,
permissionAuthority: authority,
},
),
).resolves.toEqual(evidence);
},
);
});
+36
View File
@@ -144,6 +144,42 @@ describe("doctor", () => {
});
});
it("reports optional BYO jadx diagnostics only when configured", async () => {
const result = await runDoctor(
undefined,
host({
configuredJadxCmdPath: "/opt/jadx/bin/jadx",
jadxCmdVersion: () => Promise.resolve("1.5.5"),
}),
);
expect(result.healthy).toBe(true);
expect(result.checks).toContainEqual({
name: "jadx",
ok: true,
classification: "healthy",
detail: "/opt/jadx/bin/jadx (1.5.5)",
});
});
it("reports configured jadx drift without installing it", async () => {
const result = await runDoctor(
undefined,
host({
configuredJadxCmdPath: "/missing/jadx",
jadxCmdVersion: () => Promise.resolve(undefined),
}),
);
expect(result.healthy).toBe(false);
expect(result.checks).toContainEqual({
name: "jadx",
ok: false,
classification: "config_drift",
detail: "/missing/jadx",
remediation:
"Unset REA_JADX_CMD_PATH or point it at a runnable jadx executable.",
});
});
it("does not fall back when the configured Hopper launcher is invalid", async () => {
const configuredPath = "/invalid/custom/hopper";
const result = await runDoctor(
+7 -1
View File
@@ -11,6 +11,9 @@ import {
} from "../src/contracts/toolContracts.js";
import { enhancedInputSchemas } from "../src/contracts/enhancedInputs.js";
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "../src/contracts/managedWorkflowToolContracts.js";
import { APPLE_APPLICATION_TOOL_CONTRACTS } from "../src/contracts/appleApplicationToolContracts.js";
import { ANDROID_APPLICATION_TOOL_CONTRACTS } from "../src/contracts/androidApplicationToolContracts.js";
import { RUNTIME_IDENTIFICATION_TOOL_CONTRACTS } from "../src/contracts/runtimeIdentificationToolContracts.js";
import { AnalysisOutputError } from "../src/domain/errors.js";
import { jsonValueSchema, type JsonValue } from "../src/domain/jsonValue.js";
import { err } from "../src/domain/result.js";
@@ -201,7 +204,10 @@ describe("enhanced MCP tools", () => {
expect(listed.tools).toHaveLength(
TOOL_CONTRACTS.length -
SESSION_TOOL_CONTRACTS.length -
MANAGED_WORKFLOW_TOOL_CONTRACTS.length,
MANAGED_WORKFLOW_TOOL_CONTRACTS.length -
APPLE_APPLICATION_TOOL_CONTRACTS.length -
ANDROID_APPLICATION_TOOL_CONTRACTS.length -
RUNTIME_IDENTIFICATION_TOOL_CONTRACTS.length,
);
expect(
listed.tools
+9 -8
View File
@@ -156,8 +156,8 @@ describe("analysis error projection", () => {
cause: secretCause,
},
),
PermissionRequiredError: new PermissionRequiredError(
{
PermissionRequiredError: new PermissionRequiredError({
requested: {
capability: "evidence_read",
roots: ["/workspace/evidence.json"],
executables: [],
@@ -166,11 +166,11 @@ describe("analysis error projection", () => {
mount: false,
operation_identity: "read:evidence",
},
{ environment_names: ["TOKEN_NAME"] },
null,
false,
true,
),
missing: { environment_names: ["TOKEN_NAME"] },
ceiling: null,
elicitationSupported: false,
restartRequired: true,
}),
ReplayPlanStaleError: new ReplayPlanStaleError(
"a".repeat(64),
"b".repeat(64),
@@ -305,6 +305,7 @@ describe("analysis error projection", () => {
...(
[
"remote",
"analysis_in_progress",
"authorization",
"invalid_request",
"bridge_exception",
@@ -312,7 +313,7 @@ describe("analysis error projection", () => {
).map((diagnostic) => new HopperRemoteError(9, "safe", diagnostic)),
];
expect(variants).toHaveLength(38);
expect(variants).toHaveLength(39);
for (const variant of variants) {
const projected = projectAnalysisError(variant);
const parsed = analysisErrorProjectionSchema.safeParse(projected);
+12
View File
@@ -152,6 +152,8 @@ const server = createServer((socket) => {
type: "bridge_exception",
},
});
} else if (request.method === "analysis_in_progress") {
sendAnalysisInProgress(send, request.id);
} else if (request.method === "current_document") {
send({ id: request.id, result: "fixture" });
} else if (enhancedFixtureResult(request.method) !== undefined) {
@@ -194,5 +196,15 @@ const server = createServer((socket) => {
});
});
const sendAnalysisInProgress = (send, id) =>
send({
id,
error: {
code: -32000,
message: "Hopper analysis is still running",
type: "analysis_in_progress",
},
});
server.listen(socketPath);
process.on("SIGTERM", () => server.close());
+17
View File
@@ -1,4 +1,5 @@
import { spawn } from "node:child_process";
import { rm, writeFile } from "node:fs/promises";
const mode = process.argv[2];
@@ -42,6 +43,22 @@ if (mode === "interactive") {
spawn(process.execPath, [process.argv[1], "tree-child"], { stdio: "ignore" });
process.stdout.write("tree-ready\n");
setInterval(() => undefined, 1_000);
} else if (mode === "reexec-child") {
process.stdout.write("reexec-child-ready\n");
setInterval(() => undefined, 1_000);
} else if (mode === "reexec") {
const child = spawn(process.execPath, [process.argv[1], "reexec-child"], {
detached: true,
stdio: "ignore",
});
child.unref();
process.stdout.write("supervisor-exit\n");
await new Promise((resolve) => setTimeout(resolve, 150));
} else if (mode === "filesystem-effects") {
await writeFile("modified.txt", "after");
await rm("deleted.txt");
await writeFile("created.txt", "created");
process.stdout.write("filesystem-effects-ready\n");
} else if (mode === "crash") {
process.stderr.write("intentional-crash\n");
process.exit(23);
+12 -2
View File
@@ -52,8 +52,16 @@ class FixtureLauncher implements GhidraLauncher {
readonly endpointPaths: string[] = [];
readonly tokens: string[] = [];
readonly processes: ChildProcess[] = [];
readonly launched: Promise<void>;
readonly #resolveLaunched: () => void;
constructor(readonly mode: FixtureMode = "success") {}
constructor(readonly mode: FixtureMode = "success") {
let resolveLaunched = (): void => undefined;
this.launched = new Promise<void>((resolve) => {
resolveLaunched = resolve;
});
this.#resolveLaunched = resolveLaunched;
}
async launch(session: GhidraLaunchSession) {
this.runtimeRoots.push(session.runtimeRoot);
@@ -77,6 +85,7 @@ class FixtureLauncher implements GhidraLauncher {
{ stdio: ["ignore", "pipe", "pipe"] },
);
this.processes.push(process_);
this.#resolveLaunched();
return ok({
process: process_,
ownsProcessLifetime: true,
@@ -244,7 +253,8 @@ describe("GhidraClient", () => {
const client = clientFor(launcher, { startupTimeoutMs: 10_000 });
const controller = new AbortController();
const pending = client.start(controller.signal);
setTimeout(() => controller.abort(), 10);
await launcher.launched;
controller.abort();
const result = await pending;
+11
View File
@@ -188,6 +188,17 @@ describe("HopperClient", () => {
});
});
it("preserves the typed unfinished-analysis diagnostic", async () => {
const client = await startClient();
const result = await client.callTool("analysis_in_progress");
expect(result.ok).toBe(false);
if (!result.ok)
expect(result.error).toMatchObject({
_tag: "HopperRemoteError",
diagnosticType: "analysis_in_progress",
});
});
it("cancels and ignores late responses without corrupting the session", async () => {
const client = await startClient();
const controller = new AbortController();
+7 -1
View File
@@ -24,6 +24,9 @@ import {
TOOL_CONTRACTS,
} from "../../src/contracts/toolContracts.js";
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "../../src/contracts/managedWorkflowToolContracts.js";
import { APPLE_APPLICATION_TOOL_CONTRACTS } from "../../src/contracts/appleApplicationToolContracts.js";
import { ANDROID_APPLICATION_TOOL_CONTRACTS } from "../../src/contracts/androidApplicationToolContracts.js";
import { RUNTIME_IDENTIFICATION_TOOL_CONTRACTS } from "../../src/contracts/runtimeIdentificationToolContracts.js";
const resources: Array<{ close(): Promise<void> }> = [];
@@ -460,7 +463,10 @@ describe("full MCP integration with multi-tool sequences", () => {
expect(listed.tools).toHaveLength(
TOOL_CONTRACTS.length -
SESSION_TOOL_CONTRACTS.length -
MANAGED_WORKFLOW_TOOL_CONTRACTS.length,
MANAGED_WORKFLOW_TOOL_CONTRACTS.length -
APPLE_APPLICATION_TOOL_CONTRACTS.length -
ANDROID_APPLICATION_TOOL_CONTRACTS.length -
RUNTIME_IDENTIFICATION_TOOL_CONTRACTS.length,
);
const names = listed.tools.map((t) => t.name);
expect(names).toContain("binary_overview");
+3 -2
View File
@@ -11,9 +11,9 @@ import {
describe("native DMG artifact reader", () => {
it("uses plist attachment metadata and detaches returned devices", async () => {
if (process.platform !== "darwin") return;
const calls: string[][] = [];
const host: NativeDmgHost = {
platform: "darwin",
async run(arguments_) {
const args = [...arguments_];
calls.push(args);
@@ -51,14 +51,15 @@ describe("native DMG artifact reader", () => {
});
it("rejects non-zero results and surfaces detach failure during attach cleanup", async () => {
if (process.platform !== "darwin") return;
await expect(
NativeDmgArtifactReader.create("/tmp/image.dmg", undefined, {
platform: "darwin",
run: () => Promise.resolve({ stdout: "", exitCode: 1 }),
}),
).rejects.toThrow("non-zero exit code");
const host: NativeDmgHost = {
platform: "darwin",
run(arguments_) {
if (arguments_[0] === "detach")
return Promise.reject(new Error("detach failed"));
+5
View File
@@ -26,5 +26,10 @@ describe("package installation workflows", () => {
expect(workflow).not.toContain("npm run rebuild:native");
for (const workflow of [realHopperLinux, realHopperMac])
expect(workflow).toContain("npm install --global --ignore-scripts");
expect(realHopperLinux).toContain("npm run verify:fixtures");
expect(realHopperLinux).toContain("actions/upload-artifact@v4");
expect(realHopperLinux).toContain("actions/download-artifact@v4");
expect(realHopperLinux).toContain("REA_HOPPER_CONFORMANCE_MANIFEST_PATH:");
expect(realHopperLinux).not.toContain("inputs.first_target");
});
});
+475 -1
View File
@@ -57,7 +57,7 @@ const emptyCapture = (): ProcessCapture => {
schema_version: 4,
manifest: {
rea_version: "test",
provider_version: "3",
provider_version: "4",
platform: process.platform,
architecture: process.arch,
pty_backend: "node-pty",
@@ -85,6 +85,7 @@ const emptyCapture = (): ProcessCapture => {
cleanup_outcome: "not_required",
},
process_samples: [],
process_events: [],
filesystem_checkpoints: [
{ name: "before", at_ms: 0, files: [], effects: [], truncated: false },
{
@@ -379,6 +380,7 @@ describe("process capture domain", () => {
interaction_events: [],
exit: { code: 0, signal: null, reason: "exited" as const },
process_samples: [],
process_events: [],
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
shim_events: [],
protocol_events: [],
@@ -422,6 +424,25 @@ describe("process capture domain", () => {
).toThrow("executable_sha256");
});
it("rejects malformed process lifecycle events", () => {
expect(() =>
parseProcessCapture({
...emptyCapture(),
process_events: [
{
sequence: 0,
at_ms: 0,
type: "spawned",
pid: 0,
parent_pid: null,
previous_parent_pid: null,
signal: null,
},
],
}),
).toThrow();
});
it("tells agents and users to recapture unsupported v3 evidence", () => {
const legacy = { ...emptyCapture(), schema_version: 3 };
expect(() => parseProcessCapture(legacy)).toThrow(
@@ -474,6 +495,7 @@ describe("process capture domain", () => {
interaction_events: [],
exit: { code: 0, signal: null, reason: "exited" as const },
process_samples: [],
process_events: [],
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
shim_events: [],
protocol_events: [],
@@ -533,6 +555,7 @@ describe("process capture domain", () => {
interaction_events: [],
exit: { code: 0, signal: null, reason: "exited" as const },
process_samples: [],
process_events: [],
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
shim_events: [],
protocol_events: [],
@@ -576,6 +599,7 @@ describe("process capture domain", () => {
interaction_events: [],
exit: { code: 0, signal: null, reason: "exited" as const },
process_samples: [],
process_events: [],
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
shim_events: [],
protocol_events: [],
@@ -648,6 +672,7 @@ describe("process capture domain", () => {
command: "worker",
},
],
process_events: [],
filesystem_checkpoints: emptyCapture().filesystem_checkpoints,
shim_events: [],
protocol_events: [],
@@ -674,12 +699,63 @@ describe("process capture domain", () => {
command: "worker",
},
],
process_events: [],
};
const comparison = compareProcessCaptures(capture, changed);
expect(comparison.process).toBe("changed");
expect(comparison.status).toBe("changed");
});
it("compares replay transition order independently of wire events and timing", () => {
const left = {
...emptyCapture(),
replay_transitions: [
{
sequence: 0,
at_ms: 10,
protocol_event_sequence: 0,
transition_id: "login",
state_before: "initial",
state_after: "authenticated",
sensitive_aliases: ["token"],
},
],
};
const timingOnly = {
...left,
replay_transitions: [
{
...left.replay_transitions[0]!,
at_ms: 90,
protocol_event_sequence: 7,
},
],
};
expect(compareProcessCaptures(left, timingOnly).replay_transition).toBe(
"unchanged",
);
const wrongSequence = {
...left,
replay_transitions: [
{
...left.replay_transitions[0]!,
transition_id: "skip_login",
state_after: "authenticated",
},
],
};
const comparison = compareProcessCaptures(left, wrongSequence);
expect(comparison).toMatchObject({
status: "changed",
protocol: "unchanged",
replay_transition: "changed",
first_divergence: {
status: "found",
dimension: "replay_transition",
},
});
});
});
describe("process capture adapter", () => {
@@ -813,6 +889,312 @@ describe("process capture adapter", () => {
}
});
it("executes a login, guarded API, acknowledgement, and reconnect machine", async () => {
const transition = (
...[id, from, to, trigger, actions, extra = {}]: readonly [
string,
string,
string,
Record<string, unknown>,
readonly Record<string, unknown>[],
Record<string, unknown>?,
]
) => ({
id,
from,
to,
priority: 10,
trigger,
actions,
max_uses: 1,
...extra,
});
const scenario = parseProcessScenario({
approved: true,
executable: "/bin/sh",
working_directory: "/tmp",
replay: {
machine: {
initial_state: "login",
states: [
{ name: "login" },
{ name: "api" },
{ name: "join" },
{ name: "ack" },
{ name: "reconnect" },
{ name: "subscribed" },
{ name: "done", terminal: true },
],
transitions: [
transition(
"login",
"login",
"api",
{ protocol: "http", method: "POST", path: "/login" },
[{ type: "http_response", status: 204, headers: {}, body: "" }],
{
captures: [
{
variable: "token",
value: { source: "request_json", path: ["token"] },
sensitive: true,
},
],
},
),
transition(
"api",
"api",
"join",
{ protocol: "http", method: "GET", path: "/api" },
[
{
type: "http_response",
status: 200,
headers: {},
body: "ready",
},
],
{
guards: [
{
variable: "token",
value: {
source: "request_header",
name: "authorization",
},
},
],
},
),
transition(
"join",
"join",
"ack",
{ protocol: "websocket_connect", path: "/ws" },
[{ type: "websocket_send", data: '{"ref":"r1"}' }],
{
captures: [
{
variable: "ref",
value: { source: "action_json", path: ["ref"] },
sensitive: true,
},
],
},
),
transition(
"ack",
"ack",
"reconnect",
{ protocol: "websocket_message", path: "/ws" },
[{ type: "disconnect" }],
{
guards: [
{
variable: "ref",
value: { source: "websocket_json", path: ["ack"] },
},
],
},
),
transition(
"reconnect",
"reconnect",
"subscribed",
{ protocol: "websocket_connect", path: "/ws" },
[{ type: "websocket_send", data: "subscribed" }],
),
transition(
"done",
"subscribed",
"done",
{ protocol: "http", method: "GET", path: "/done" },
[
{
type: "http_response",
status: 200,
headers: {},
body: "complete",
},
],
),
],
max_transitions: 6,
},
},
});
const replay = await startLoopbackReplay(scenario);
try {
expect(await fetch(`${replay.httpUrl}/api`)).toMatchObject({
status: 409,
});
expect(replay.events.at(-1)?.outcome).toBe("invalid_state");
expect(
await fetch(`${replay.httpUrl}/login`, {
method: "POST",
body: '{"token":"secret"}',
}),
).toMatchObject({ status: 204 });
expect(
await fetch(`${replay.httpUrl}/api`, {
headers: { authorization: "secret" },
}),
).toMatchObject({ status: 200 });
await new Promise<void>((resolveFlow, rejectFlow) => {
const socket = new WebSocket(replay.websocketUrl);
socket.once("message", (value) => {
expect(value.toString()).toBe('{"ref":"r1"}');
socket.send('{"ack":"r1"}');
});
socket.once("close", () => resolveFlow());
socket.once("error", rejectFlow);
});
await expect(
new Promise<string>((resolveMessage, rejectMessage) => {
const socket = new WebSocket(replay.websocketUrl);
socket.once("message", (value) => {
resolveMessage(value.toString());
socket.close();
});
socket.once("error", rejectMessage);
}),
).resolves.toBe("subscribed");
expect(await (await fetch(`${replay.httpUrl}/done`)).text()).toBe(
"complete",
);
expect(
replay.transitions.map(({ transition_id }) => transition_id),
).toEqual(["login", "api", "join", "ack", "reconnect", "done"]);
expect(JSON.stringify(replay.transitions)).not.toContain("secret");
expect(JSON.stringify(replay.events)).not.toContain("r1");
expect(replay.events.every((event) => "transition_id" in event)).toBe(
true,
);
const baseCapture = emptyCapture();
const replayCapture = {
...baseCapture,
manifest: {
...baseCapture.manifest,
replay_plan: scenario.replay,
replay_plan_sha256: digestProcessCommitment(scenario.replay),
},
protocol_events: replay.events,
replay_transitions: replay.transitions,
};
expect(
parseProcessCapture(replayCapture).replay_transitions,
).toHaveLength(6);
expect(() =>
parseProcessCapture({
...replayCapture,
replay_transitions: replay.transitions.map((entry, index) =>
index === 0 ? { ...entry, sensitive_aliases: [] } : entry,
),
}),
).toThrow(/secret aliases/u);
await new Promise<void>((resolveClose, rejectClose) => {
const socket = new WebSocket(replay.websocketUrl);
socket.once("close", () => resolveClose());
socket.once("error", rejectClose);
});
expect(replay.events.at(-1)?.outcome).toBe("unexpected_reconnect");
} finally {
await replay.close();
}
});
it("rejects a wrong acknowledgement without advancing replay state", async () => {
const scenario = parseProcessScenario({
approved: true,
executable: "/bin/sh",
working_directory: "/tmp",
replay: {
machine: {
initial_state: "login",
states: [
{ name: "login" },
{ name: "join" },
{ name: "ack" },
{ name: "done", terminal: true },
],
transitions: [
{
id: "login",
from: "login",
to: "join",
trigger: { protocol: "http", method: "POST", path: "/login" },
captures: [
{
variable: "token",
value: { source: "request_json", path: ["token"] },
sensitive: true,
},
],
actions: [
{ type: "http_response", status: 204, headers: {}, body: "" },
],
max_uses: 1,
},
{
id: "join",
from: "join",
to: "ack",
trigger: { protocol: "websocket_connect", path: "/ws" },
captures: [
{
variable: "ref",
value: { source: "action_json", path: ["ref"] },
sensitive: false,
},
],
actions: [{ type: "websocket_send", data: '{"ref":"r1"}' }],
max_uses: 1,
},
{
id: "ack",
from: "ack",
to: "done",
trigger: { protocol: "websocket_message", path: "/ws" },
guards: [
{
variable: "ref",
value: { source: "websocket_json", path: ["ack"] },
},
],
actions: [{ type: "disconnect" }],
max_uses: 1,
},
],
max_transitions: 3,
},
},
});
const replay = await startLoopbackReplay(scenario);
try {
await fetch(`${replay.httpUrl}/login`, {
method: "POST",
body: '{"token":"secret"}',
});
await new Promise<void>((resolveClose, rejectClose) => {
const socket = new WebSocket(replay.websocketUrl);
socket.once("message", () => socket.send('{"ack":"wrong"}'));
socket.once("close", () => resolveClose());
socket.once("error", rejectClose);
});
expect(replay.events.at(-1)).toMatchObject({
outcome: "guard_failed",
state_before: "ack",
state_after: "ack",
});
expect(
replay.transitions.map(({ transition_id }) => transition_id),
).toEqual(["login", "join"]);
} finally {
await replay.close();
}
});
it("captures PTY, filesystem, descendants, HTTP replay, and redacts environment", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-harness-test-"));
const script = join(root, "fixture.mjs");
@@ -1114,6 +1496,13 @@ describe("process capture adapter", () => {
expect(output).toContain("resize:100x40");
expect(output).toContain("signal:SIGINT");
expect(result.value.exit.code).toBe(0);
expect(result.value.process_events).toContainEqual(
expect.objectContaining({
type: "signal_dispatched",
pid: 1,
signal: "SIGINT",
}),
);
});
it("dispatches scheduled events before a silent PTY produces output", async () => {
@@ -1189,6 +1578,10 @@ describe("process capture adapter", () => {
expect(
commands.some((command) => command.includes("tree-grandchild")),
).toBe(true);
expect(
result.value.process_events.filter(({ type }) => type === "spawned")
.length,
).toBeGreaterThanOrEqual(3);
expect(JSON.stringify(result.value.process_samples)).not.toContain(
dirname(processFixture),
);
@@ -1196,4 +1589,85 @@ describe("process capture adapter", () => {
expect(stdout).not.toContain(`${processFixture} tree-child`);
expect(stdout).not.toContain(`${processFixture} tree-grandchild`);
}, 20_000);
it("captures re-executed descendants and cleans them after supervisor exit", async () => {
const capability = await probeProcessCaptureCapability();
if (!capability.available) return;
const result = await captureProcessScenario(
parseProcessScenario({
approved: true,
executable: process.execPath,
arguments: [processFixture, "reexec"],
working_directory: dirname(processFixture),
timeout_ms: 2_000,
idle_timeout_ms: 2_000,
}),
{
enabled: true,
executableRoots: [dirname(process.execPath)],
workingRoots: [dirname(processFixture)],
allowedEnvironment: [],
allowExternalNetwork: true,
},
);
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
expect(
result.value.process_samples.some(({ command }) =>
command.includes("reexec-child"),
),
).toBe(true);
expect(result.value.process_events).toEqual(
expect.arrayContaining([
expect.objectContaining({ type: "reparented" }),
expect.objectContaining({ type: "exited", pid: 1 }),
]),
);
const { stdout } = await execFileAsync("ps", ["-axo", "command="]);
expect(stdout).not.toContain(`${processFixture} reexec-child`);
}, 20_000);
it("classifies source-owned file creation, modification, and deletion", async () => {
const capability = await probeProcessCaptureCapability();
if (!capability.available) return;
const root = await mkdtemp(join(tmpdir(), "rea-effects-test-"));
await writeFile(join(root, "modified.txt"), "before");
await writeFile(join(root, "deleted.txt"), "before");
try {
const result = await captureProcessScenario(
parseProcessScenario({
approved: true,
executable: process.execPath,
arguments: [processFixture, "filesystem-effects"],
working_directory: root,
filesystem_roots: [root],
timeout_ms: 2_000,
idle_timeout_ms: 2_000,
}),
{
enabled: true,
executableRoots: [dirname(process.execPath)],
workingRoots: [root],
allowedEnvironment: [],
allowExternalNetwork: true,
},
);
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
expect(
result.value.filesystem_effects.map(({ path, status }) => ({
path: path.slice(path.lastIndexOf(":") + 1),
status,
})),
).toEqual(
expect.arrayContaining([
{ path: "created.txt", status: "created" },
{ path: "deleted.txt", status: "deleted" },
{ path: "modified.txt", status: "modified" },
]),
);
} finally {
await rm(root, { recursive: true, force: true });
}
});
});
+159
View File
@@ -0,0 +1,159 @@
import { describe, expect, it } from "vitest";
import {
runPairedProcessExperiment,
type ProcessCapturePort,
} from "../src/application/ProcessPairedExperiment.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../src/contracts/processCaptureExample.js";
import { parseProcessCapture } from "../src/domain/processCapture.js";
import {
analyzeProcessRepeatability,
bindProcessScenario,
processPairedExperimentSchema,
} from "../src/domain/processPairedExperiment.js";
import { ok } from "../src/domain/result.js";
const experiment = () =>
processPairedExperimentSchema.parse({
approved: true,
shared_scenario: {
approved: true,
executable: "/bin/template",
arguments: ["shared"],
working_directory: "/tmp",
environment: { SHARED: "yes" },
},
authority: {
id: "authority",
executable: "/bin/authority",
environment: { SIDE: "authority" },
},
candidate: {
id: "candidate",
executable: "/bin/candidate",
arguments: ["candidate"],
environment: { SIDE: "candidate" },
},
repeat_count: 3,
freshness_policy: { max_capture_age_ms: 60_000 },
required_dimensions: ["terminal", "exit", "protocol"],
reconstruction_claims: [],
});
const policy = {
enabled: true,
executableRoots: ["/bin"],
workingRoots: ["/tmp"],
allowedEnvironment: ["SHARED", "SIDE"],
allowExternalNetwork: false,
};
describe("paired process experiments", () => {
it("binds only declared side inputs onto the shared observation contract", () => {
const parsed = experiment();
const authority = bindProcessScenario(
parsed.shared_scenario,
parsed.authority,
);
const candidate = bindProcessScenario(
parsed.shared_scenario,
parsed.candidate,
);
expect(authority).toMatchObject({
executable: "/bin/authority",
arguments: ["shared"],
environment: { SHARED: "yes", SIDE: "authority" },
});
expect(candidate).toMatchObject({
executable: "/bin/candidate",
arguments: ["candidate"],
environment: { SHARED: "yes", SIDE: "candidate" },
});
});
it("runs same-side comparisons first and compares stable sides", async () => {
const observedExecutables: string[] = [];
const capture = parseProcessCapture(EMPTY_PROCESS_CAPTURE_EXAMPLE);
const capturePort: ProcessCapturePort = {
capture: (scenario) => {
observedExecutables.push(scenario.executable);
return Promise.resolve(ok(structuredClone(capture)));
},
};
const result = await runPairedProcessExperiment(experiment(), policy, {
capturePort,
now: () => Date.parse("2026-01-01T00:00:01.000Z"),
});
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(observedExecutables).toEqual([
"/bin/authority",
"/bin/authority",
"/bin/authority",
"/bin/candidate",
"/bin/candidate",
"/bin/candidate",
]);
expect(result.value.authority_repeatability.stable).toBe(true);
expect(result.value.candidate_repeatability.stable).toBe(true);
expect(result.value.cross_side?.status).toBe("unchanged");
});
it("blocks cross-side claims when a candidate has a flaky exit", async () => {
const base = parseProcessCapture(EMPTY_PROCESS_CAPTURE_EXAMPLE);
let candidateRun = 0;
const capturePort: ProcessCapturePort = {
capture: (scenario) => {
let capture = structuredClone(base);
if (scenario.executable === "/bin/candidate") {
candidateRun += 1;
if (candidateRun === 2)
capture = {
...capture,
exit: { code: 1, signal: null, reason: "exited" },
};
}
return Promise.resolve(ok(capture));
},
};
const result = await runPairedProcessExperiment(experiment(), policy, {
capturePort,
now: () => Date.parse("2026-01-01T00:00:01.000Z"),
});
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.candidate_repeatability).toMatchObject({
stable: false,
classification: "flaky_exit",
unstable_dimensions: ["exit"],
});
expect(result.value.cross_side).toBeNull();
expect(result.value.cross_side_blocked_reason).toMatch(/unstable/u);
});
it("distinguishes normalized timing variance from semantic output drift", () => {
const base = parseProcessCapture(EMPTY_PROCESS_CAPTURE_EXAMPLE);
const early = {
...base,
frames: [{ sequence: 0, at_ms: 10, data: "ready" }],
};
const late = {
...base,
frames: [{ sequence: 0, at_ms: 20, data: "ready" }],
};
expect(
analyzeProcessRepeatability([early, late], ["terminal"]),
).toMatchObject({
stable: false,
classification: "timing_variance",
unstable_dimensions: ["terminal"],
});
const changed = {
...base,
frames: [{ sequence: 0, at_ms: 20, data: "failed" }],
};
expect(
analyzeProcessRepeatability([early, changed], ["terminal"]),
).toMatchObject({ classification: "nondeterministic_output" });
});
});
+16 -6
View File
@@ -8,12 +8,15 @@ import { z } from "zod";
import { SUPPORTED_CLIENT_DEFINITIONS } from "../src/application/SupportedClients.js";
import {
APPLE_APPLICATION_PROVIDER,
ANDROID_APPLICATION_PROVIDER,
ARTIFACT_GRAPH_PROVIDER,
JAVASCRIPT_APPLICATION_PROVIDER,
JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER,
JAVASCRIPT_RUNTIME_RECONCILIATION_PROVIDER,
MANAGED_STATIC_PROVIDER,
MANAGED_WORKFLOW_PROVIDER,
RUNTIME_IDENTIFICATION_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";
@@ -79,6 +82,9 @@ describe("canonical product catalog", () => {
JAVASCRIPT_APPLICATION_PROVIDER,
JAVASCRIPT_RUNTIME_RECONCILIATION_PROVIDER,
JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER,
APPLE_APPLICATION_PROVIDER,
ANDROID_APPLICATION_PROVIDER,
RUNTIME_IDENTIFICATION_PROVIDER,
]
.map(({ id }) => id)
.sort(),
@@ -183,16 +189,20 @@ describe("canonical product catalog", () => {
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 artifactFamily = catalog.tools.families.find(
({ id }) => id === "artifact",
);
if (artifactFamily === undefined)
throw new TypeError("Missing artifact family");
const drifted = {
...catalog,
tools: {
...catalog.tools,
families: [
{ ...firstFamily, count: firstFamily.count + 1 },
...catalog.tools.families.slice(1),
],
families: catalog.tools.families.map((family) =>
family.id === artifactFamily.id
? { ...family, count: family.count + 1 }
: family,
),
},
setup_clients: [
...catalog.setup_clients,
+6
View File
@@ -14,6 +14,9 @@ import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "../src/contracts/managedWorkflo
import { BROWSER_TOOL_CONTRACTS } from "../src/contracts/browserToolContracts.js";
import { ELECTRON_TOOL_CONTRACTS } from "../src/contracts/electronToolContracts.js";
import { APPLICATION_TOOL_CONTRACTS } from "../src/contracts/applicationToolContracts.js";
import { APPLE_APPLICATION_TOOL_CONTRACTS } from "../src/contracts/appleApplicationToolContracts.js";
import { ANDROID_APPLICATION_TOOL_CONTRACTS } from "../src/contracts/androidApplicationToolContracts.js";
import { RUNTIME_IDENTIFICATION_TOOL_CONTRACTS } from "../src/contracts/runtimeIdentificationToolContracts.js";
import { SUPPORTED_CLIENT_DEFINITIONS } from "../src/application/SupportedClients.js";
const readmes = [
@@ -30,6 +33,9 @@ const expectedToolCounts = [
NATIVE_TOOL_CONTRACTS.length,
ARTIFACT_TOOL_CONTRACTS.length,
MANAGED_TOOL_CONTRACTS.length + MANAGED_WORKFLOW_TOOL_CONTRACTS.length,
APPLE_APPLICATION_TOOL_CONTRACTS.length,
ANDROID_APPLICATION_TOOL_CONTRACTS.length,
RUNTIME_IDENTIFICATION_TOOL_CONTRACTS.length,
BROWSER_TOOL_CONTRACTS.length,
ELECTRON_TOOL_CONTRACTS.length,
APPLICATION_TOOL_CONTRACTS.length,
+232 -45
View File
@@ -20,6 +20,11 @@ describe("real Hopper fixture binding", () => {
primary: { path: join(root ?? "", "c") },
secondary: { path: join(root ?? "", "version-v2") },
large: { path: join(root ?? "", "large") },
versionV1: { path: join(root ?? "", "version-v1") },
versionV2: { path: join(root ?? "", "version-v2") },
objc: { path: join(root ?? "", "objc") },
napi: { path: join(root ?? "", "napi") },
swift: { path: join(root ?? "", "swift") },
largeOracle: {
symbolPrefix: "_rea_page_",
symbolCount: 1_205,
@@ -35,10 +40,49 @@ describe("real Hopper fixture binding", () => {
leafString: "REA_C_LEAF",
globalName: "rea_c_global",
},
versionV1Expectations: {
symbols: ["_rea_version_entry", "_rea_version_leaf"],
strings: ["REA_VERSION_ONE"],
},
versionV2Expectations: {
symbols: ["_rea_version_entry", "_rea_version_leaf", "_rea_added"],
strings: ["REA_VERSION_TWO"],
},
objcExpectations: {
symbols: ["_OBJC_CLASS_$_REAWidget"],
strings: ["REAWidget", "REAWidgetDelegate", "performAction:error:"],
},
napiExpectations: {
symbols: ["_napi_register_module_v1"],
strings: ["reaProbeOne", "reaProbeTwo", "reaProbeThree"],
},
swiftExpectations: {
strings: [
"REA_SWIFT_EXECUTE",
"REAService",
"REARecord",
"REAState",
"REAProtocol",
],
},
compilers: {
c: {
path: "/usr/bin/clang",
version: "clang fixture",
arguments: ["-O0"],
},
},
},
);
});
it("binds manifests that omit the optional swift fixture", async () => {
const manifest = await fixtureManifest({ includeSwift: false });
const targets = await loadRealHopperFixtureTargets(manifest);
expect(targets.swift).toBeUndefined();
expect(targets.swiftExpectations).toBeUndefined();
});
it("rejects digest drift and artifacts escaping the manifest root", async () => {
const manifest = await fixtureManifest();
await writeFile(join(root ?? "", "c"), "changed");
@@ -65,67 +109,210 @@ describe("real Hopper fixture binding", () => {
fixtures: { name: string; artifact: string; artifactSha256: string }[];
};
const primary = parsed.fixtures.find(({ name }) => name === "c");
const secondary = parsed.fixtures.find(({ name }) => name === "version-v2");
if (primary === undefined || secondary === undefined)
const objc = parsed.fixtures.find(({ name }) => name === "objc");
if (primary === undefined || objc === undefined)
throw new Error("Fixture manifest setup failed");
secondary.artifact = primary.artifact;
secondary.artifactSha256 = primary.artifactSha256;
objc.artifact = primary.artifact;
objc.artifactSha256 = primary.artifactSha256;
await writeFile(manifest, JSON.stringify(parsed));
await expect(loadRealHopperFixtureTargets(manifest)).rejects.toThrow(
/distinct artifacts/u,
);
});
it("rejects a missing mandatory fixture", async () => {
const manifest = await fixtureManifest();
const parsed = JSON.parse(await readFile(manifest, "utf8")) as {
fixtures: { name: string }[];
};
parsed.fixtures = parsed.fixtures.filter(({ name }) => name !== "objc");
await writeFile(manifest, JSON.stringify(parsed));
await expect(loadRealHopperFixtureTargets(manifest)).rejects.toThrow(
/Missing fixture objc/u,
);
});
it("rejects malformed expectations (empty record, empty array, non-string)", async () => {
const manifest = await fixtureManifest();
const parsed = JSON.parse(await readFile(manifest, "utf8")) as {
fixtures: {
name: string;
expectations?: Record<string, unknown>;
}[];
};
const napi = parsed.fixtures.find(({ name }) => name === "napi");
if (napi === undefined) throw new Error("Fixture manifest setup failed");
napi.expectations = {};
await writeFile(manifest, JSON.stringify(parsed));
await expect(loadRealHopperFixtureTargets(manifest)).rejects.toThrow(
/Fixture napi expectations must be nonempty/u,
);
napi.expectations = { exports: [] };
await writeFile(manifest, JSON.stringify(parsed));
await expect(loadRealHopperFixtureTargets(manifest)).rejects.toThrow(
/Fixture napi expectation exports must be nonempty/u,
);
napi.expectations = { exports: ["rea_napi_a", ""] };
await writeFile(manifest, JSON.stringify(parsed));
await expect(loadRealHopperFixtureTargets(manifest)).rejects.toThrow(
/Fixture napi expectation exports must be nonempty strings/u,
);
napi.expectations = { exports: ["rea_napi_a", 7] };
await writeFile(manifest, JSON.stringify(parsed));
await expect(loadRealHopperFixtureTargets(manifest)).rejects.toThrow(
/Fixture napi expectation exports must be nonempty strings/u,
);
});
it("rejects a mandatory fixture that omits expectations", async () => {
const manifest = await fixtureManifest();
const parsed = JSON.parse(await readFile(manifest, "utf8")) as {
fixtures: {
name: string;
expectations?: Record<string, unknown>;
}[];
};
const objc = parsed.fixtures.find(({ name }) => name === "objc");
if (objc === undefined) throw new Error("Fixture manifest setup failed");
delete objc.expectations;
await writeFile(manifest, JSON.stringify(parsed));
await expect(loadRealHopperFixtureTargets(manifest)).rejects.toThrow(
/Fixture objc omitted its expectations/u,
);
});
it("rejects missing compiler provenance", async () => {
const manifest = await fixtureManifest();
const parsed = JSON.parse(await readFile(manifest, "utf8")) as {
fixtures: { name: string; compiler?: unknown }[];
};
const objc = parsed.fixtures.find(({ name }) => name === "objc");
if (objc === undefined) throw new Error("Fixture manifest setup failed");
delete objc.compiler;
await writeFile(manifest, JSON.stringify(parsed));
await expect(loadRealHopperFixtureTargets(manifest)).rejects.toThrow(
/compiler provenance/u,
);
});
});
const fixtureManifest = async (): Promise<string> => {
type FixtureSpec = {
readonly name: string;
readonly artifact: string;
readonly expectations?: Record<string, unknown>;
};
const fixtureManifest = async (options?: {
readonly includeSwift?: boolean;
}): Promise<string> => {
root = await mkdtemp(join(tmpdir(), "rea-hopper-fixture-"));
const primary = Buffer.from("primary");
const secondary = Buffer.from("secondary");
await Promise.all([
writeFile(join(root, "c"), primary),
writeFile(join(root, "version-v2"), secondary),
writeFile(join(root, "large"), Buffer.from("large")),
]);
const buffers: Record<string, Buffer> = {
c: Buffer.from("primary"),
"version-v1": Buffer.from("version-v1"),
"version-v2": Buffer.from("secondary"),
objc: Buffer.from("objc"),
napi: Buffer.from("napi"),
large: Buffer.from("large"),
swift: Buffer.from("swift"),
};
await Promise.all(
Object.entries(buffers).map(([name, buffer]) =>
writeFile(join(root ?? "", name), buffer),
),
);
const includeSwift = options?.includeSwift ?? true;
const fixtures: FixtureSpec[] = [
{
name: "c",
artifact: "c",
expectations: {
hopperOracle: {
mainProcedure: "main",
entryProcedure: "rea_entry",
branchProcedure: "rea_branch",
leafProcedure: "rea_leaf",
entryString: "REA_C_ENTRY",
leafString: "REA_C_LEAF",
globalName: "rea_c_global",
},
},
},
{
name: "version-v1",
artifact: "version-v1",
expectations: {
symbols: ["_rea_version_entry", "_rea_version_leaf"],
strings: ["REA_VERSION_ONE"],
},
},
{
name: "version-v2",
artifact: "version-v2",
expectations: {
symbols: ["_rea_version_entry", "_rea_version_leaf", "_rea_added"],
strings: ["REA_VERSION_TWO"],
},
},
{
name: "objc",
artifact: "objc",
expectations: {
symbols: ["_OBJC_CLASS_$_REAWidget"],
strings: ["REAWidget", "REAWidgetDelegate", "performAction:error:"],
},
},
{
name: "napi",
artifact: "napi",
expectations: {
symbols: ["_napi_register_module_v1"],
strings: ["reaProbeOne", "reaProbeTwo", "reaProbeThree"],
},
},
{
name: "large",
artifact: "large",
expectations: {
symbolPrefix: "_rea_page_",
symbolCount: 1_205,
stringPrefix: "REA_PAGE_",
stringCount: 1_205,
},
},
];
if (includeSwift)
fixtures.push({
name: "swift",
artifact: "swift",
expectations: {
strings: [
"REA_SWIFT_EXECUTE",
"REAService",
"REARecord",
"REAState",
"REAProtocol",
],
},
});
const manifest = join(root, "manifest.json");
await writeFile(
manifest,
JSON.stringify({
schemaVersion: 1,
fixtures: [
{
name: "c",
artifact: "c",
artifactSha256: digest(primary),
expectations: {
hopperOracle: {
mainProcedure: "main",
entryProcedure: "rea_entry",
branchProcedure: "rea_branch",
leafProcedure: "rea_leaf",
entryString: "REA_C_ENTRY",
leafString: "REA_C_LEAF",
globalName: "rea_c_global",
},
},
fixtures: fixtures.map((fixture) => ({
...fixture,
artifactSha256: digest(buffers[fixture.artifact] ?? Buffer.from("")),
compiler: {
path: "/usr/bin/clang",
version: "clang fixture",
arguments: ["-O0"],
},
{
name: "version-v2",
artifact: "version-v2",
artifactSha256: digest(secondary),
},
{
name: "large",
artifact: "large",
artifactSha256: digest(Buffer.from("large")),
expectations: {
symbolPrefix: "_rea_page_",
symbolCount: 1_205,
stringPrefix: "REA_PAGE_",
stringCount: 1_205,
},
},
],
})),
}),
);
return manifest;
+104
View File
@@ -4,6 +4,9 @@ import {
analyzeFixtureProcedure,
requireCurrentDocument,
resolveFixtureProcedure,
verifyLanguageFixture,
verifyAbsentFixtureValues,
verifyNamedFixture,
} from "../scripts/lib/real-hopper-semantic.mjs";
const normalize = (value: unknown): unknown => value;
@@ -95,6 +98,107 @@ describe("real Hopper semantic fixture resolution", () => {
),
).rejects.toThrow(/exactly one Hopper procedure/u);
});
it("proves declared symbols, strings, and language semantics", async () => {
const requests: { name: string; arguments: unknown }[] = [];
const client = {
callTool: async (request: { name: string; arguments: unknown }) => {
requests.push(request);
if (request.name === "find_xrefs_to_name")
return { status: "resolved", name: "_rea_entry", xrefs: [] };
if (request.name === "search_strings")
return {
items: [
{ address: "0x1000", value: "REA_ENTRY", value_truncated: false },
],
};
if (request.name === "get_objc_classes")
return { count: 1, classes: [{ name: "REAWidget" }] };
return {};
},
};
await expect(
verifyLanguageFixture({
client,
options: {},
target: { path: "/fixture", sha256: "a".repeat(64) },
expectations: {
symbols: ["_rea_entry"],
strings: ["REA_ENTRY"],
},
operations: ["get_objc_classes"],
semanticExpectations: { get_objc_classes: ["REAWidget"] },
normalizedResult: normalize,
}),
).resolves.toMatchObject({
symbols: ["_rea_entry"],
strings: ["REA_ENTRY"],
semantics: {
get_objc_classes: {
count: 1,
classes: [{ name: "REAWidget" }],
},
},
});
expect(requests.map(({ name }) => name)).toEqual([
"open_binary",
"find_xrefs_to_name",
"search_strings",
"get_objc_classes",
]);
});
it("rejects missing, truncated, and unavailable positive evidence", async () => {
const target = { path: "/fixture", sha256: "a".repeat(64) };
await expect(
verifyNamedFixture({
client: {
callTool: async ({ name }: { name: string }) =>
name === "find_xrefs_to_name"
? { status: "unresolved" }
: { items: [] },
},
options: {},
target,
expectations: { symbols: ["missing"] },
normalizedResult: normalize,
}),
).rejects.toThrow(/expected symbol/u);
await expect(
verifyNamedFixture({
client: {
callTool: async ({ name }: { name: string }) =>
name === "search_strings"
? {
items: [{ value: "TRUNCATED", value_truncated: true }],
}
: {},
},
options: {},
target,
expectations: { strings: ["TRUNCATED"] },
normalizedResult: normalize,
}),
).rejects.toThrow(/expected string/u);
});
it("proves version-specific symbols and strings remain absent", async () => {
await expect(
verifyAbsentFixtureValues({
client: {
callTool: async ({ name }: { name: string }) =>
name === "find_xrefs_to_name"
? { status: "unresolved", name: "_rea_added" }
: { items: [] },
},
options: {},
target: { path: "/v1", sha256: "a".repeat(64) },
symbols: ["_rea_added"],
strings: ["REA_VERSION_TWO"],
normalizedResult: normalize,
}),
).resolves.toBeUndefined();
});
});
const clientWithItems = (items: readonly unknown[]) => ({
+4 -2
View File
@@ -59,6 +59,7 @@ const processResult = (
exit: "unchanged",
filesystem: "unchanged",
protocol: "unchanged",
replay_transition: "unchanged",
process: "unchanged",
shim: "unchanged",
first_divergence:
@@ -89,10 +90,10 @@ const processComparison = (
{
id: "rea-process",
name: "REA deterministic process harness",
version: "3",
version: "4",
},
{
predicateType: "rea.process-comparison/v3",
predicateType: "rea.process-comparison/v4",
operation: "compare_process_captures",
parameters: {
left_evidence_id: left.evidence_id,
@@ -171,6 +172,7 @@ describe("reconstruction verification", () => {
exit: "unchanged",
filesystem: "unchanged",
protocol: "unchanged",
replay_transition: "unchanged",
process: "unchanged",
shim: "unchanged",
first_divergence: {
+151
View File
@@ -0,0 +1,151 @@
import { describe, expect, it } from "vitest";
import { replayMachineSchema } from "../src/domain/replayMachine.js";
const loginMachine = () => ({
initial_state: "waiting_for_login",
states: [
{ name: "waiting_for_login" },
{ name: "waiting_for_api" },
{ name: "complete", terminal: true },
],
transitions: [
{
id: "login",
from: "waiting_for_login",
to: "waiting_for_api",
priority: 10,
trigger: { protocol: "http", method: "POST", path: "/login" },
captures: [
{
variable: "token",
value: { source: "request_json", path: ["token"] },
sensitive: true,
},
],
actions: [{ type: "http_response", status: 204, headers: {}, body: "" }],
max_uses: 1,
},
{
id: "api",
from: "waiting_for_api",
to: "complete",
priority: 10,
trigger: { protocol: "http", method: "GET", path: "/api" },
guards: [
{
variable: "token",
value: { source: "request_header", name: "authorization" },
},
],
actions: [
{
type: "http_response",
status: 200,
headers: {},
body: "done",
},
],
max_uses: 1,
},
],
max_transitions: 2,
});
describe("replay machine", () => {
it("accepts a bounded, reachable, data-only login machine", () => {
expect(replayMachineSchema.parse(loginMachine())).toMatchObject({
initial_state: "waiting_for_login",
max_transitions: 2,
});
});
it.each([
[
"unreachable state",
(machine: ReturnType<typeof loginMachine>) =>
machine.states.push({ name: "orphan", terminal: false }),
"unreachable",
],
[
"ambiguous transition",
(machine: ReturnType<typeof loginMachine>) =>
machine.transitions.push({ ...machine.transitions[0]!, id: "login_2" }),
"ambiguous",
],
[
"outgoing terminal transition",
(machine: ReturnType<typeof loginMachine>) =>
machine.transitions.push({
...machine.transitions[0]!,
id: "restart",
from: "complete",
to: "waiting_for_login",
trigger: { protocol: "http", method: "POST", path: "/restart" },
}),
"terminal",
],
[
"unknown guard variable",
(machine: ReturnType<typeof loginMachine>) => {
machine.transitions[1]!.guards![0]!.variable = "missing";
},
"never captured",
],
[
"missing terminal state",
(machine: ReturnType<typeof loginMachine>) => {
machine.states[2]!.terminal = false;
},
"terminal state",
],
])("rejects %s", (_name, mutate, message) => {
const machine = loginMachine();
mutate(machine);
expect(() => replayMachineSchema.parse(machine)).toThrow(message);
});
it("canonicalizes methods and headers while refusing persisted credential matchers", () => {
const canonical = {
...loginMachine(),
transitions: loginMachine().transitions.map((transition, index) =>
index === 0
? {
...transition,
trigger: {
protocol: "http",
method: "post",
path: "/login",
headers: { "X-Request-ID": "fixture" },
},
}
: transition,
),
};
expect(
replayMachineSchema.parse(canonical).transitions[0]?.trigger,
).toMatchObject({
method: "POST",
headers: { "x-request-id": "fixture" },
});
const credentialMatcher = {
...loginMachine(),
transitions: loginMachine().transitions.map((transition, index) =>
index === 0
? {
...transition,
trigger: {
protocol: "http",
method: "POST",
path: "/login",
headers: { Authorization: "secret" },
},
}
: transition,
),
};
expect(() => replayMachineSchema.parse(credentialMatcher)).toThrow(
/secret alias/u,
);
});
});
+311
View File
@@ -0,0 +1,311 @@
import { describe, expect, it } from "vitest";
import { replayMachineSchema } from "../src/domain/replayMachine.js";
import { ReplayMachineRuntime } from "../src/domain/replayMachineRuntime.js";
const machine = replayMachineSchema.parse({
initial_state: "login",
states: [
{ name: "login" },
{ name: "api" },
{ name: "complete", terminal: true },
],
transitions: [
{
id: "capture_token",
from: "login",
to: "api",
priority: 10,
trigger: { protocol: "http", method: "POST", path: "/login" },
captures: [
{
variable: "token",
value: { source: "request_json", path: ["token"] },
sensitive: true,
},
],
actions: [{ type: "http_response", status: 204, headers: {}, body: "" }],
max_uses: 1,
},
{
id: "authorize_api",
from: "api",
to: "complete",
priority: 10,
trigger: { protocol: "http", method: "GET", path: "/api" },
guards: [
{
variable: "token",
value: { source: "request_header", name: "authorization" },
},
],
actions: [
{ type: "http_response", status: 200, headers: {}, body: "done" },
],
max_uses: 1,
},
],
max_transitions: 2,
});
const event = (
method: string,
path: string,
body = "",
headers: Readonly<Record<string, string>> = {},
) => ({
protocol: "http" as const,
connection: "not_applicable" as const,
at_ms: 0,
method,
path,
body,
headers,
});
describe("replay machine runtime", () => {
it("captures secret values in memory and journals aliases only", () => {
const runtime = new ReplayMachineRuntime(machine);
expect(
runtime.dispatch(event("POST", "/login", '{"token":"secret"}')),
).toMatchObject({
outcome: "matched",
transition: {
transition_id: "capture_token",
sensitive_aliases: ["token"],
},
});
expect(runtime.redact("Bearer secret")).toBe("Bearer <secret:token>");
expect(
runtime.dispatch(event("GET", "/api", "", { authorization: "secret" })),
).toMatchObject({ outcome: "matched" });
expect(JSON.stringify(runtime.timeline)).not.toContain("secret");
expect(runtime.state).toBe("complete");
});
it("classifies wrong-state, guard, capture, and exhaustion failures", () => {
expect(
new ReplayMachineRuntime(machine).dispatch(event("GET", "/api")),
).toMatchObject({ outcome: "invalid_state" });
expect(
new ReplayMachineRuntime(machine).dispatch(event("POST", "/login", "{}")),
).toMatchObject({ outcome: "invalid_capture" });
const runtime = new ReplayMachineRuntime(machine);
runtime.dispatch(event("POST", "/login", '{"token":"secret"}'));
expect(
runtime.dispatch(event("GET", "/api", "", { authorization: "wrong" })),
).toMatchObject({
outcome: "guard_failed",
});
const bounded = new ReplayMachineRuntime(
replayMachineSchema.parse({
initial_state: "active",
states: [{ name: "active" }, { name: "done", terminal: true }],
transitions: [
{
id: "once",
from: "active",
to: "active",
trigger: { protocol: "http", method: "GET", path: "/once" },
actions: [
{ type: "http_response", status: 200, headers: {}, body: "ok" },
],
max_uses: 1,
},
{
id: "finish",
from: "active",
to: "done",
trigger: { protocol: "http", method: "GET", path: "/done" },
actions: [
{ type: "http_response", status: 200, headers: {}, body: "ok" },
],
max_uses: 1,
},
],
max_transitions: 2,
}),
);
expect(bounded.dispatch(event("GET", "/once"))).toMatchObject({
outcome: "matched",
});
expect(bounded.dispatch(event("GET", "/once"))).toMatchObject({
outcome: "transition_exhausted",
});
});
it("matches bounded headers and bodies and distinguishes wrong-state reconnects", () => {
const runtime = new ReplayMachineRuntime(
replayMachineSchema.parse({
initial_state: "connected",
states: [{ name: "connected" }, { name: "done", terminal: true }],
transitions: [
{
id: "finish",
from: "connected",
to: "done",
trigger: {
protocol: "http",
method: "POST",
path: "/finish",
headers: { "content-type": "application/json" },
body: '{"done":true}',
},
actions: [
{ type: "http_response", status: 204, headers: {}, body: "" },
],
max_uses: 1,
},
{
id: "initial_socket",
from: "connected",
to: "connected",
trigger: { protocol: "websocket_connect", path: "/ws" },
actions: [{ type: "disconnect" }],
max_uses: 1,
},
],
max_transitions: 2,
}),
);
expect(runtime.dispatch(event("POST", "/finish", "wrong"))).toMatchObject({
outcome: "unmatched",
});
expect(
runtime.dispatch({
protocol: "websocket_connect",
connection: "initial",
at_ms: 0,
method: null,
path: "/ws",
headers: {},
body: "",
}),
).toMatchObject({ outcome: "matched" });
expect(
runtime.dispatch({
protocol: "websocket_connect",
connection: "reconnect",
at_ms: 0,
method: null,
path: "/ws",
headers: {},
body: "",
}),
).toMatchObject({ outcome: "transition_exhausted" });
expect(
runtime.dispatch(
event("POST", "/finish", '{"done":true}', {
"content-type": "application/json",
}),
),
).toMatchObject({ outcome: "matched" });
expect(
runtime.dispatch({
protocol: "websocket_connect",
connection: "reconnect",
at_ms: 0,
method: null,
path: "/ws",
headers: {},
body: "",
}),
).toMatchObject({ outcome: "unexpected_reconnect" });
});
it("enforces state, connection, message, byte, and duration limits", () => {
const limitedMachine = replayMachineSchema.parse({
initial_state: "active",
states: [
{ name: "active", max_visits: 1 },
{ name: "done", terminal: true },
],
transitions: [
{
id: "loop",
from: "active",
to: "active",
trigger: { protocol: "websocket_message", path: "/ws" },
actions: [{ type: "websocket_send", data: "ack" }],
max_uses: 2,
},
{
id: "finish",
from: "active",
to: "done",
trigger: { protocol: "http", method: "GET", path: "/done" },
actions: [
{ type: "http_response", status: 200, headers: {}, body: "ok" },
],
max_uses: 1,
},
],
max_transitions: 3,
limits: { connections: 1, messages: 1, bytes: 100, duration_ms: 10 },
});
const stateLimited = new ReplayMachineRuntime(limitedMachine);
expect(
stateLimited.dispatch({
protocol: "websocket_message",
connection: "not_applicable",
at_ms: 0,
method: null,
path: "/ws",
headers: {},
body: "one",
}),
).toMatchObject({ outcome: "limit_exhausted" });
const messageLimited = new ReplayMachineRuntime(
replayMachineSchema.parse({
...limitedMachine,
states: limitedMachine.states.map((state) =>
state.name === "active" ? { ...state, max_visits: 3 } : state,
),
}),
);
const message = {
protocol: "websocket_message" as const,
connection: "not_applicable" as const,
at_ms: 0,
method: null,
path: "/ws",
headers: {},
body: "one",
};
expect(messageLimited.dispatch(message)).toMatchObject({
outcome: "matched",
});
expect(messageLimited.dispatch(message)).toMatchObject({
outcome: "limit_exhausted",
});
const durationLimited = new ReplayMachineRuntime(limitedMachine);
expect(
durationLimited.dispatch({ ...event("GET", "/done"), at_ms: 11 }),
).toMatchObject({ outcome: "limit_exhausted" });
const byteLimited = new ReplayMachineRuntime(
replayMachineSchema.parse({
...limitedMachine,
limits: { ...limitedMachine.limits, bytes: 4 },
}),
);
expect(
byteLimited.dispatch(event("GET", "/missing", "12345")),
).toMatchObject({ outcome: "limit_exhausted" });
const connectionLimited = new ReplayMachineRuntime(limitedMachine);
const connect = {
protocol: "websocket_connect" as const,
connection: "initial" as const,
at_ms: 0,
method: null,
path: "/unknown",
headers: {},
body: "",
};
expect(connectionLimited.dispatch(connect)).toMatchObject({
outcome: "unmatched",
});
expect(
connectionLimited.dispatch({ ...connect, connection: "reconnect" }),
).toMatchObject({ outcome: "limit_exhausted" });
});
});
+2 -2
View File
@@ -60,7 +60,7 @@ describe("production stdio runtime", () => {
);
expect(stderr).not.toContain("HOPPER_LOADER_ARGS_JSON");
expect(stderr).not.toContain(fixturePath);
}, 15_000);
}, 30_000);
it("honors the configured kind for an initial database target", async () => {
const transport = new StdioClientTransport({
@@ -87,5 +87,5 @@ describe("production stdio runtime", () => {
await client.close();
await transport.close();
}
}, 15_000);
}, 30_000);
});
+125
View File
@@ -0,0 +1,125 @@
import { mkdtemp, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
TextReader,
Uint8ArrayReader,
Uint8ArrayWriter,
ZipWriter,
} from "@zip.js/zip.js";
import { describe, expect, it } from "vitest";
import { runProviderAnalysis } from "../src/application/DirectAnalysis.js";
import { parseEvidence } from "../src/domain/evidence.js";
import {
identifyRuntimes,
runtimeIdentificationResultSchema,
} from "../src/domain/runtimeIdentification.js";
describe("runtime identification", () => {
it("identifies APK runtime families and exposes missing semantic providers", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-runtime-"));
const path = join(root, "Fixture.apk");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add(
"AndroidManifest.xml",
new Uint8ArrayReader(Uint8Array.from([3, 0, 8, 0, 8, 0, 0, 0])),
);
await writer.add(
"classes.dex",
new Uint8ArrayReader(
Uint8Array.from([...Buffer.from("dex\n035\0"), 0, 0, 0, 0]),
),
);
await writer.add(
"assets/Fixture.class",
new Uint8ArrayReader(
Uint8Array.from([0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 61]),
),
);
await writer.add(
"assets/module.wasm",
new Uint8ArrayReader(Uint8Array.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0])),
);
await writer.add("assets/main.js", new TextReader("bridge.call();"));
await writer.add(
"lib/arm64-v8a/libfixture.so",
new Uint8ArrayReader(
Uint8Array.from([0x7f, 0x45, 0x4c, 0x46, 2, 1, 1, 0]),
),
);
await writeFile(path, await writer.close());
const inventory = parseEvidence(
await runProviderAnalysis(path, "inventory_artifact", {
node_limit: 100,
occurrence_limit: 100,
edge_limit: 100,
}),
);
const first = identifyRuntimes({ inventory_evidence: [inventory] });
const second = identifyRuntimes({ inventory_evidence: [inventory] });
expect(first).toEqual(second);
expect(runtimeIdentificationResultSchema.parse(first)).toMatchObject({
root_format: "apk",
coverage: {
status: "complete-within-inventory",
inventory_complete: true,
omitted_observations: 0,
},
});
expect(first.runtimes.map(({ family }) => family)).toEqual([
"android",
"javascript",
"jvm",
"native",
"webassembly",
]);
expect(first.runtimes).toEqual(
expect.arrayContaining([
expect.objectContaining({
family: "jvm",
inspection: "provider-missing",
provider_id: null,
}),
expect.objectContaining({
family: "webassembly",
inspection: "provider-missing",
provider_id: null,
}),
expect.objectContaining({
family: "javascript",
inspection: "available",
provider_id: "rea-javascript-application",
}),
expect.objectContaining({
family: "native",
inspection: "provider-selection-required",
provider_id: null,
}),
]),
);
});
it("reports bounded runtime-observation truncation", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-runtime-limit-"));
const path = join(root, "Fixture.apk");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("one.js", new TextReader("one"));
await writer.add("two.js", new TextReader("two"));
await writeFile(path, await writer.close());
const inventory = parseEvidence(
await runProviderAnalysis(path, "inventory_artifact", {}),
);
const result = identifyRuntimes({
inventory_evidence: [inventory],
limits: { max_observations: 1 },
});
expect(result.coverage).toMatchObject({
status: "truncated",
omitted_observations: expect.any(Number),
});
expect(result.coverage.omitted_observations).toBeGreaterThan(0);
});
});
+3 -3
View File
@@ -25,10 +25,10 @@ describe("server and catalog identity", () => {
});
expect(PRODUCT_IDENTITY.packageVersion).toBe(packageJson.version);
expect(SDK_IDENTITY.server).toBe("2.0.0-beta.4");
expect(CLI_COMMAND_NAMES).toHaveLength(55);
expect(new Set(CLI_COMMAND_NAMES).size).toBe(55);
expect(CLI_COMMAND_NAMES).toHaveLength(65);
expect(new Set(CLI_COMMAND_NAMES).size).toBe(65);
expect(CATALOG_IDENTITY.counts).toEqual({
cli_commands: 55,
cli_commands: 65,
mcp_tools: TOOL_CONTRACTS.length,
mcp_prompts: 6,
mcp_resources: 2,
+1 -1
View File
@@ -326,7 +326,7 @@ describe("target-free MCP lifecycle", () => {
).isError,
).not.toBe(true);
await mcp.callTool({ name: "close_binary", arguments: {} });
}, 10_000);
}, 20_000);
it("records approved process residuals in the unknown registry", async () => {
if (!(await probeProcessCaptureCapability()).available) return;
+3 -2
View File
@@ -45,6 +45,7 @@ const processComparison = (
exit: terminal === "truncated" ? "truncated" : "unchanged",
filesystem: terminal === "truncated" ? "truncated" : "unchanged",
protocol: terminal === "truncated" ? "truncated" : "unchanged",
replay_transition: terminal === "truncated" ? "truncated" : "unchanged",
process: terminal === "truncated" ? "truncated" : "unchanged",
shim: terminal === "truncated" ? "truncated" : "unchanged",
first_divergence:
@@ -68,10 +69,10 @@ const processComparison = (
{
id: "rea-process",
name: "REA deterministic process harness",
version: "3",
version: "4",
},
{
predicateType: "rea.process-comparison/v3",
predicateType: "rea.process-comparison/v4",
operation: "compare_process_captures",
parameters: {
left_evidence_id: leftCapture.evidence_id,
+81 -2
View File
@@ -88,6 +88,66 @@ describe("web capture diff", () => {
expect(result.dimensions.dom_structure.reason).toContain("incomplete");
});
it("compares accessibility, storage, console errors, routes, and lifecycle", async () => {
const browser = await startFakeCdpBrowser();
browsers.push(browser);
const captured = await new CdpBrowserProvider().inspectPage(
inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
approved: true,
observation_ms: 0,
}),
);
if (!captured.ok) throw captured.error;
const after = structuredClone(captured.value);
const accessibilityNode = after.accessibility.nodes[0];
if (accessibilityNode !== undefined) accessibilityNode.role = "dialog";
after.storage.local_storage_keys.push("new-key");
const consoleEvent = after.console.events[0];
if (consoleEvent !== undefined) consoleEvent.type = "error";
after.target.url = `${browser.allowedOrigin}/changed`;
after.workers.push({
target_id: "worker-added",
type: "worker",
url: `${browser.allowedOrigin}/worker.js`,
origin: browser.allowedOrigin,
attached: true,
opener_target_id: null,
parent_frame_id: null,
});
markSectionsComplete(captured.value, [
"accessibility",
"storage",
"storage_keys",
"console_events",
"frames",
"workers",
]);
markSectionsComplete(after, [
"accessibility",
"storage",
"storage_keys",
"console_events",
"frames",
"workers",
]);
const result = compareWebCaptures(
compareWebCapturesInputSchema.parse({
before: { inspection: captured.value },
after: { inspection: after },
}),
);
expect(result.dimensions.accessibility.status).toBe("changed");
expect(result.dimensions.storage.status).toBe("changed");
expect(result.dimensions.console_errors.status).toBe("changed");
expect(result.dimensions.current_route.status).toBe("changed");
expect(result.dimensions.lifecycle.status).toBe("changed");
});
it("ignores transient request IDs and capture-approval state", async () => {
const browser = await startFakeCdpBrowser();
browsers.push(browser);
@@ -110,8 +170,25 @@ describe("web capture diff", () => {
const script = after.scripts.items[0];
if (script !== undefined && !script.source.included)
script.source.reason = "different approval explanation";
markSectionsComplete(captured.value, ["scripts", "metadata"]);
markSectionsComplete(after, ["scripts", "metadata"]);
const accessibilityNode = after.accessibility.nodes[0];
if (accessibilityNode !== undefined)
accessibilityNode.node_id = "different-cdp-ax-node-id";
const worker = after.workers[0];
if (worker !== undefined) worker.target_id = "different-worker-target-id";
markSectionsComplete(captured.value, [
"scripts",
"metadata",
"accessibility",
"frames",
"workers",
]);
markSectionsComplete(after, [
"scripts",
"metadata",
"accessibility",
"frames",
"workers",
]);
const result = compareWebCaptures(
compareWebCapturesInputSchema.parse({
@@ -122,6 +199,8 @@ describe("web capture diff", () => {
expect(result.dimensions.scripts.status).toBe("unchanged");
expect(result.dimensions.metadata.status).toBe("unchanged");
expect(result.dimensions.accessibility.status).toBe("unchanged");
expect(result.dimensions.lifecycle.status).toBe("unchanged");
expect(result.dimensions.network.status).toBe("unknown");
expect(result.dimensions.network.total_changes).toBe(0);
});