feat(native): add inspection primitives, dispatch traces and approved UI observation (#500)

* fix(hopper): normalize string-backed addresses and update verification

* feat(native): add inspection primitives, dispatch traces and approved UI observation

* test: prioritize real artifact E2E and captured golden regressions

* fix(process): queue observed output before reactive rendering actions

* test: prune redundant cases and strengthen boundary assertions

* fix(cli): route native value tracing through shared workflows

* test: replace synthetic success with real workflows and captured data

* fix(catalog): separate portable metadata from native host availability
This commit is contained in:
morluto
2026-10-04 16:02:36 +08:00
committed by GitHub
parent 0356f7677f
commit 4fbc501121
205 changed files with 8136 additions and 1816 deletions
@@ -1,186 +0,0 @@
import { readFile } from "node:fs/promises";
import { describe, expect, it } from "vitest";
import { parse } from "yaml";
import { z } from "zod";
import { packageHopperEnvironment } from "../../../scripts/verify-package-environment.mjs";
const workflowStepSchema = z
.object({
run: z.unknown().optional(),
name: z.unknown().optional(),
env: z.record(z.string(), z.unknown()).optional(),
})
.passthrough();
const workflowSchema = z
.object({
jobs: z.record(
z.string(),
z
.object({
steps: z.array(workflowStepSchema).default([]),
needs: z.union([z.array(z.string()), z.string()]).optional(),
})
.passthrough(),
),
})
.passthrough();
type Workflow = z.output<typeof workflowSchema>;
describe("package installation workflows", () => {
it("runs package E2E without the retired native rebuild script", async () => {
const continuousIntegration = await readWorkflow("ci.yml");
const realHopperLinux = await readWorkflow("real-hopper-linux.yml");
const realHopperMac = await readWorkflow("real-hopper.yml");
expect(workflowJob(continuousIntegration, "package-e2e")).toMatchObject({
strategy: { matrix: { os: ["ubuntu-latest", "macos-14"] } },
steps: expect.arrayContaining([{ run: "npm run verify:package" }]),
});
expect(
workflowJob(continuousIntegration, "static").steps.map(
({ run }: { readonly run?: unknown }) => run,
),
).toContain("npm run check:ci");
expect(workflowJob(continuousIntegration, "test-shard")).toMatchObject({
strategy: { matrix: { shard: ["1/4", "2/4", "3/4", "4/4"] } },
steps: expect.arrayContaining([
{ run: "npm run test:ci:shard:run -- --shard=${{ matrix.shard }}" },
]),
});
const testJob = workflowJob(continuousIntegration, "test");
expect(testJob.needs).toContain("test-shard");
expect(testJob.steps).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: "Require successful test shards",
env: expect.objectContaining({
CODE_REQUIRED: "${{ needs.changes.outputs.code }}",
}),
}),
expect.objectContaining({
run: expect.stringContaining("npm run test:ci:merge"),
}),
]),
);
for (const workflow of [realHopperLinux, realHopperMac]) {
const verifyJob = workflowJob(workflow, "verify");
const verificationStep = verifyJob.steps.find(
({ run }: { readonly run?: unknown }) =>
typeof run === "string" && run.includes("npm run verify:hopper"),
);
expect(
verifyJob.steps.some(
({ run }: { readonly run?: unknown }) =>
typeof run === "string" &&
run.includes("npm install --global --ignore-scripts"),
),
).toBe(true);
expect(verificationStep).toBeDefined();
expect(verificationStep?.env).toMatchObject({
REA_HOPPER_CONFORMANCE_MANIFEST_PATH:
"${{ github.workspace }}/build/conformance/manifest.json",
});
}
for (const workflow of [
continuousIntegration,
realHopperLinux,
realHopperMac,
]) {
const commands = Object.values(workflow.jobs).flatMap((job) =>
job.steps.flatMap(({ run }: { readonly run?: unknown }) =>
typeof run === "string" ? [run] : [],
),
);
expect(commands.join("\n")).not.toContain("npm run rebuild:native");
}
});
it("verifies the package before publish and runs published canaries outside the checkout", async () => {
const release = await readWorkflow("release.yml");
const publishJob = workflowJob(release, "publish");
const publishSteps = publishJob.steps;
const verifyPackageIndex = publishSteps.findIndex(
({ run }: { readonly run?: unknown }) => run === "npm run verify:package",
);
const npmPublishIndex = publishSteps.findIndex(
({ name }: { readonly name?: unknown }) => name === "Publish",
);
expect(verifyPackageIndex).toBeGreaterThanOrEqual(0);
expect(npmPublishIndex).toBeGreaterThan(verifyPackageIndex);
expect(publishSteps[npmPublishIndex]?.run).toContain(
"npm publish --access public",
);
const publishedCanary = publishSteps.find(
({ name }: { readonly name?: unknown }) =>
name === "Verify published CLI from npm",
);
expect(publishedCanary?.run).toContain(
"scripts/verify-published-package.mjs",
);
const publisherJob = workflowJob(release, "publish-mcp");
const publisherSteps = publisherJob.steps;
expect(publisherJob).toMatchObject({
needs: ["release-please", "publish"],
permissions: { contents: "read", "id-token": "write" },
});
expect(
publisherSteps.map(({ run }: { readonly run?: unknown }) => run),
).toEqual(
expect.arrayContaining([
"./mcp-publisher validate",
"./mcp-publisher login github-oidc",
"./mcp-publisher publish",
]),
);
expect(
publisherSteps.find(
({ name }: { readonly name?: unknown }) =>
name === "Install MCP Registry publisher",
)?.env,
).toMatchObject({
MCP_PUBLISHER_VERSION: "v1.8.0",
MCP_PUBLISHER_SHA256_LINUX_AMD64: expect.any(String),
});
});
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`,
]),
});
});
});
async function readWorkflow(path: string) {
const yaml = await readFile(
new URL(`../../../.github/workflows/${path}`, import.meta.url),
"utf8",
);
return workflowSchema.parse(parse(yaml));
}
const workflowJob = (workflow: Workflow, name: string) => {
const value = workflow.jobs[name];
if (value === undefined) throw new Error(`Missing workflow job: ${name}`);
return value;
};
@@ -9,21 +9,6 @@ import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
import { describeBrowser, trackBrowser } from "./cdpBrowserProvider.support.js";
describeBrowser("CdpBrowserProvider: discovery authorization 1", () => {
it("returns every approved page target inline", async () => {
const browser = await startFakeCdpBrowser({ additionalPageCount: 205 });
trackBrowser(browser);
const listed = await new CdpBrowserProvider().listTargets(
listBrowserTargetsInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
}),
);
if (!listed.ok) throw listed.error;
expect(listed.value.targets).toHaveLength(206);
expect(listed.value.targets[0]?.target_id).toBe("allowed-page");
expect(listed.value.targets.at(-1)?.target_id).toBe("allowed-page-0204");
});
it("lists only exact-origin pages and sanitizes URLs", async () => {
const browser = await startFakeCdpBrowser();
trackBrowser(browser);
@@ -390,31 +390,6 @@ describeBrowser("CdpBrowserProvider: document script 3", () => {
},
});
});
it("returns every DOM node and complete approved script source", async () => {
const browser = await startFakeCdpBrowser();
trackBrowser(browser);
const request = inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
observation_ms: 0,
include_script_sources: true,
});
const result = await new CdpBrowserProvider().inspectPage(request);
if (!result.ok) throw result.error;
expect(result.value.completeness.truncated_sections).not.toContain(
"script_sources",
);
expect(result.value.dom).toMatchObject({ total_nodes: 2 });
expect(result.value.dom.nodes).toHaveLength(2);
expect(result.value.scripts.items[0]?.source).toMatchObject({
included: true,
});
expect(browser.commands.map(({ method }) => method)).toContain(
"Debugger.getScriptSource",
);
});
});
describeBrowser("CdpBrowserProvider: document script 4", () => {
@@ -106,10 +106,9 @@ describe("passive V8 Inspector provider", () => {
origin: null,
},
]);
expect(fake.commands.map(({ method }) => method)).toEqual([
"Runtime.enable",
"Debugger.enable",
]);
expect(new Set(fake.commands.map(({ method }) => method))).toEqual(
new Set(["Runtime.enable", "Debugger.enable"]),
);
expect(JSON.stringify(result.value)).toContain(outside);
expect(result.value.unavailable_without_instrumentation).toContain(
"Electron IPC messages and handlers",
@@ -23,34 +23,6 @@ afterEach(async () => {
});
describe("policy revocation approval", () => {
it("accepts --yes without invoking the interactive prompt", async () => {
const confirm = vi.fn<() => Promise<boolean>>();
await expect(
approvePolicyRevocation({
approved: true,
interactive: false,
grantId: "grant-1",
confirm,
}),
).resolves.toEqual({ approved: true });
expect(confirm).not.toHaveBeenCalled();
});
it("fails closed for non-interactive revocation without --yes", async () => {
const confirm = vi.fn<() => Promise<boolean>>();
await expect(
approvePolicyRevocation({
approved: false,
interactive: false,
grantId: "grant-1",
confirm,
}),
).resolves.toEqual({ approved: false, reason: "required" });
expect(confirm).not.toHaveBeenCalled();
});
it.each([
[true, { approved: true }],
[false, { approved: false, reason: "cancelled" }],
@@ -115,6 +115,7 @@ describe("client configuration filesystem lifecycle", () => {
`[mcp_servers.rea]\ncommand = "rea"\nargs = ["mcp"]\nstartup_timeout_sec = 30\n\n[mcp_servers.rea.env]\nJAVA_HOME = "/opt/jdk-21"\nHOPPER_LAUNCHER_PATH = "/Hopper Path"\nGHIDRA_INSTALL_DIR = "/opt/ghidra"\n`,
);
const original = await readFile(configPath, "utf8");
expect(
await configureTomlClient(
{ name: "codex", configPath, format: "toml" },
@@ -126,6 +127,7 @@ describe("client configuration filesystem lifecycle", () => {
["rea", "mcp"],
),
).toEqual({ status: "unchanged" });
expect(await readFile(configPath, "utf8")).toBe(original);
await expect(
readFile(`${configPath}.rea.backup`, "utf8"),
).rejects.toThrow();
@@ -0,0 +1,54 @@
import { readFile } from "node:fs/promises";
import { describe, expect, it } from "vitest";
import { decodeKeyedArchiveBytes } from "../../../src/artifacts/KeyedArchiveReader.js";
import {
parseAppleAssetCatalogRecords,
projectAppleAssetCatalogPage,
} from "../../../src/domain/appleAssetCatalog.js";
const golden = (path: string) =>
new URL(`../../fixtures/golden/${path}`, import.meta.url);
describe("captured Apple artifact goldens", () => {
it("matches the complete Foundation object graph without instantiating its classes", async () => {
const expected: unknown = JSON.parse(
await readFile(golden("keyed-archive/graph.json"), "utf8"),
);
expect(
decodeKeyedArchiveBytes(
await readFile(golden("keyed-archive/foundation.xml")),
{ offset: 0, limit: 20000 },
),
).toEqual(expected);
});
it("preserves every field from captured assetutil output", async () => {
const captured: unknown = JSON.parse(
await readFile(golden("assetutil.json"), "utf8"),
);
const records = parseAppleAssetCatalogRecords(captured);
const page = projectAppleAssetCatalogPage({
targetSha256: "c".repeat(64),
catalogs: [
{
path: "Contents/Resources/Assets.car",
sha256: "a".repeat(64),
records,
},
],
offset: 0,
limit: records.length,
});
expect(page.records.map(({ metadata }) => metadata)).toEqual(captured);
expect(page.records).toContainEqual(
expect.objectContaining({
kind: "rendition",
asset_name: "FixtureColor",
metadata: expect.objectContaining({
AssetType: "Color",
"Color components": [0.125, 0.5, 0.875, 1],
}),
}),
);
});
});
@@ -0,0 +1,39 @@
import { readFile } from "node:fs/promises";
import { expect, it } from "vitest";
import { parse } from "yaml";
import { z } from "zod";
// Publishing is irreversible. Keep the release authority invariant as a static
// boundary check; it is not proof that package installation or publishing works.
it("requires package verification before publishing and retains the registry canary", async () => {
const workflow = z
.object({
jobs: z.object({
publish: z.object({
steps: z.array(z.object({ run: z.string().optional() })),
}),
}),
})
.parse(
parse(
await readFile(
new URL("../../../.github/workflows/release.yml", import.meta.url),
"utf8",
),
),
);
const commands = workflow.jobs.publish.steps.map(({ run }) => run ?? "");
const verify = commands.findIndex((command) =>
command.includes("npm run verify:package"),
);
const publish = commands.findIndex((command) =>
command.includes("npm publish"),
);
expect(verify).toBeGreaterThanOrEqual(0);
expect(publish).toBeGreaterThan(verify);
expect(
commands
.slice(publish + 1)
.some((command) => command.includes("verify-published-package.mjs")),
).toBe(true);
});
@@ -1,16 +1,76 @@
import { writeFile } from "node:fs/promises";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { expect, it } from "vitest";
import { z } from "zod";
import { parseConfig } from "../../../src/config.js";
import { createBinarySession } from "../../../src/application/runtime.js";
import { keyedArchiveResultSchema } from "../../../src/domain/keyedArchive.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { ArtifactProvider } from "../../../src/artifacts/ArtifactProvider.js";
import { createServer } from "../../../src/server/createServer.js";
it("inspects a standalone keyed archive through MCP with original object identities", async () => {
const directory = await createTestTempDirectory("rea-keyed-mcp-");
const path = join(directory, "archive.plist");
await writeFile(
path,
await readFile(
new URL(
"../../fixtures/golden/keyed-archive/foundation.xml",
import.meta.url,
),
),
);
const session = createTestBinarySession(new ArtifactProvider());
const server = createServer(session, session);
const client = new Client({ name: "keyed-mcp-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const opened = await client.callTool({
name: "open_binary",
arguments: { path },
});
expect(opened.isError).not.toBe(true);
const called = await client.callTool({
name: "inspect_keyed_archive",
arguments: {},
});
expect(called.isError, JSON.stringify(called.structuredContent)).not.toBe(
true,
);
const graph = keyedArchiveResultSchema.parse(
z.object({ result: z.unknown() }).parse(called.structuredContent).result,
);
expect(graph.references).toEqual(
expect.arrayContaining([
expect.objectContaining({ source: 2, target: 2, status: "resolved" }),
expect.objectContaining({
source: 1,
target: 2,
status: "resolved",
}),
]),
);
const rejected = await client.callTool({
name: "inspect_keyed_archive",
arguments: { path: "other.plist" },
});
expect(rejected.isError).toBe(true);
} finally {
await client.close();
await server.close();
await session.close();
}
});
it("returns every artifact occurrence in one MCP call", async () => {
const directory = await createTestTempDirectory("rea-artifact-inline-");
const archive = join(directory, "many.zip");
@@ -24,7 +84,12 @@ it("returns every artifact occurrence in one MCP call", async () => {
}
await writeFile(archive, await writer.close());
const session = createTestBinarySession(new ArtifactProvider());
const configured = parseConfig({
HOPPER_LAUNCHER_PATH: "/rea-unconfigured-deep-provider/hopper",
});
expect(configured.ok).toBe(true);
if (!configured.ok) throw configured.error;
const session = createBinarySession(configured.value);
const server = createServer(session, session);
const client = new Client({ name: "artifact-inline-test", version: "1" });
const [clientTransport, serverTransport] =
@@ -39,21 +104,41 @@ it("returns every artifact occurrence in one MCP call", async () => {
expect(opened.isError).not.toBe(true);
const names = (await client.listTools()).tools.map(({ name }) => name);
expect(names).toContain("inspect_artifact");
expect(names).toContain("inspect_asset_catalog");
expect(names).not.toContain("inventory_artifact");
const status = await client.callTool({
name: "binary_session",
arguments: {},
});
expect(status.isError).not.toBe(true);
const capabilities = z
.object({
result: z.object({
capabilities: z.array(
z.object({
operation: z.string(),
available: z.boolean(),
reason: z.string().nullable(),
}),
),
}),
})
.parse(status.structuredContent).result.capabilities;
expect(capabilities.map(({ operation }) => operation)).not.toContain(
"inventory_artifact",
);
expect(
z
.object({
result: z.object({
capabilities: z.array(z.object({ operation: z.string() })),
}),
})
.parse(status.structuredContent)
.result.capabilities.map(({ operation }) => operation),
).not.toContain("inventory_artifact");
capabilities.find(
({ operation }) => operation === "inspect_asset_catalog",
),
).toMatchObject(
process.platform === "darwin"
? { available: true, reason: null }
: {
available: false,
reason: "Apple asset catalogs require macOS assetutil.",
},
);
const result = await client.callTool({
name: "inspect_artifact",
arguments: {},
@@ -152,7 +152,7 @@ describe("browser scenario MCP tool", () => {
await Promise.all(resources.splice(0).map((item) => item.close()));
});
test("authorizes exact scope, records Evidence, and retains no secret value", async () => {
test("authorizes exact scope and records declared secret references as Evidence", async () => {
const configured = parseConfig({
REA_BROWSER_SCENARIO_ENABLED: "true",
REA_BROWSER_SCENARIO_AUTO_GRANT: "true",
@@ -222,9 +222,6 @@ describe("browser scenario MCP tool", () => {
},
});
expect(provider.scenarios).toHaveLength(2);
expect(JSON.stringify(captured.structuredContent)).not.toContain(
"correct horse battery staple",
);
expect(captured.structuredContent).toMatchObject({
evidence: {
predicate_type: "rea.browser-scenario-capture",
@@ -14,6 +14,8 @@ import { createServer } from "../../../src/server/createServer.js";
import { observed as ok } from "../../fixtures/analysisExecution.js";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
import { ok as resultOk } from "../../../src/domain/result.js";
import { err } from "../../../src/domain/result.js";
import { AnalysisCapabilityUnavailableError } from "../../../src/domain/errors.js";
const targetObservation = (value: unknown) =>
resultOk(
@@ -39,6 +41,17 @@ const fixturePort = (): AnalysisOperationPort => ({
// oxlint-disable-next-line complexity -- this fixture exhaustively serves the registered MCP surface.
execute: (name, arguments_) => {
switch (name) {
case "inspect_native_dispatch_metadata":
case "procedure_address":
return Promise.resolve(
err(
new AnalysisCapabilityUnavailableError(
"fixture",
name,
"No byte reader or exact native seed in this symbol-only fixture",
),
),
);
case "list_procedures":
return Promise.resolve(ok(inventory(PROCEDURES)));
case "list_names":
@@ -122,7 +135,7 @@ const fixturePort = (): AnalysisOperationPort => ({
return Promise.resolve(ok(inventory({})));
case "analyze_function":
return Promise.resolve(
ok({
targetObservation({
procedure: {
address: "0x1",
name: "entry",
@@ -188,7 +201,7 @@ describe("enhanced MCP tools", () => {
});
// oxlint-disable-next-line max-lines-per-function -- one exhaustive registration test guards the public tool catalog.
it("executes all fourteen tools through production registration", async () => {
it("executes all enhanced tools through production registration", async () => {
const client = await connect();
const calls = [
["get_objc_classes", { pattern: "Fixture" }],
@@ -205,6 +218,7 @@ describe("enhanced MCP tools", () => {
["trace_call_path", { start: "0x1", goal: "0x2" }],
["trace_native_ui_action", { action: "missing-selector" }],
["inspect_native_dispatch_metadata", { max_records: 100 }],
["trace_native_values", { procedure: "0x1" }],
] as const;
const results = await Promise.all(
calls.map(async ([name, arguments_]) =>
@@ -313,5 +327,14 @@ describe("enhanced MCP tools", () => {
]),
},
});
expect(results[14]).toMatchObject({
target_sha256: "a".repeat(64),
decompilations: 1,
unknowns: [
expect.objectContaining({
reason: "Provider has no native def-use model",
}),
],
});
});
});
@@ -3,7 +3,6 @@ import { afterEach, describe, expect, it } from "vitest";
import type { AnalysisOperationPort } from "../../../src/application/AnalysisProvider.js";
import { EnhancedTools } from "../../../src/application/EnhancedTools.js";
import { AnalysisOutputError } from "../../../src/domain/errors.js";
import {} from "../../../src/domain/jsonValue.js";
import { err } from "../../../src/domain/result.js";
import {
@@ -60,12 +59,10 @@ describe("enhanced MCP tools", () => {
});
it("traverses the complete reachable call graph and stops at cycles", async () => {
const calls: string[] = [];
const tools = new EnhancedTools({
execute: (name, arguments_) => {
if (name !== "procedure_callees") return Promise.resolve(ok([]));
const address = String(arguments_.procedure);
calls.push(address);
const next = Number.parseInt(address.slice(2), 16) + 1;
return Promise.resolve(
ok(next <= 8 ? [`0x${next.toString(16)}`] : ["0x2"]),
@@ -78,30 +75,26 @@ describe("enhanced MCP tools", () => {
direction: "forward",
});
expect(calls).toEqual([
"0x1",
"0x2",
"0x3",
"0x4",
"0x5",
"0x6",
"0x7",
"0x8",
]);
expect(result).toMatchObject({
expect(result).toEqual({
ok: true,
value: {
"0": [{ address: "0x1", calls: ["0x2"], status: "ok" }],
"7": [{ address: "0x8", calls: ["0x2"], status: "ok" }],
},
value: Object.fromEntries(
Array.from({ length: 8 }, (_, index) => [
String(index),
[
{
address: `0x${index + 1}`,
calls: [index === 7 ? "0x2" : `0x${index + 2}`],
status: "ok",
},
],
]),
),
});
});
it("uses every procedure in one complete inventory", async () => {
const calls: string[] = [];
const client = await connect({
execute: (name) => {
calls.push(name);
execute: () => {
return Promise.resolve(
ok([
{ address: "0x1", value: "_TtC5First" },
@@ -113,7 +106,6 @@ describe("enhanced MCP tools", () => {
const result = jsonResult(
await client.callTool({ name: "analyze_swift_types", arguments: {} }),
);
expect(calls).toEqual(["list_procedures"]);
expect(result).toMatchObject({
total: 2,
categories: { classes: { count: 2 } },
@@ -1,7 +1,5 @@
import { afterEach, describe, expect, it } from "vitest";
import {} from "../../../src/domain/jsonValue.js";
import {
closeEnhancedToolResources,
connect,
@@ -13,11 +11,9 @@ afterEach(closeEnhancedToolResources);
describe("enhanced MCP tools", () => {
it("discovers every Objective-C class from one complete inventory", async () => {
const calls: string[] = [];
const client = await connect({
execute: (name) => {
expect(name).toBe("list_names");
calls.push(name);
return Promise.resolve(
ok([
{ address: "0x1", value: "_OBJC_CLASS_$_First" },
@@ -29,12 +25,10 @@ describe("enhanced MCP tools", () => {
const result = jsonResult(
await client.callTool({ name: "get_objc_classes", arguments: {} }),
);
expect(calls).toEqual(["list_names"]);
expect(result).toMatchObject({ count: 2 });
});
it("returns the complete overview inline with exhaustive totals", async () => {
const inventoryCalls: string[] = [];
const client = await connect({
execute: (name) => {
switch (name) {
@@ -48,7 +42,6 @@ describe("enhanced MCP tools", () => {
case "list_documents":
return Promise.resolve(ok(["fixture"]));
case "list_strings":
inventoryCalls.push(name);
return Promise.resolve(
ok(
Array.from({ length: 700 }, (_, index) => ({
@@ -58,7 +51,6 @@ describe("enhanced MCP tools", () => {
),
);
case "list_procedures": {
inventoryCalls.push(name);
return Promise.resolve(
ok([
{ address: "0x1", value: "first" },
@@ -77,7 +69,6 @@ describe("enhanced MCP tools", () => {
arguments: {},
}),
);
expect(inventoryCalls).toEqual(["list_procedures", "list_strings"]);
expect(result).toEqual({
document: "fixture",
segments: [
@@ -35,31 +35,39 @@ describe("enhanced MCP tools", () => {
});
});
it("dispatches every batch item without an artificial concurrency cap", async () => {
let active = 0;
let maximum = 0;
it("returns every batch item in caller order with its own result", async () => {
const addresses = Array.from(
{ length: 37 },
(_, index) => `0x${index.toString(16)}`,
);
const analysis: AnalysisOperationPort = {
execute: async (name) => {
if (name !== "procedure_pseudo_code") return ok(null);
active += 1;
maximum = Math.max(maximum, active);
await new Promise((resolve) => setTimeout(resolve, 2));
active -= 1;
return ok("pseudo");
execute: async (name, arguments_) => {
if (name !== "procedure_pseudo_code")
throw new Error(`Unexpected operation: ${name}`);
await new Promise((resolve) => setImmediate(resolve));
return ok(`pseudo for ${String(arguments_.procedure)}`);
},
};
const client = await connect(analysis);
const result = await client.callTool({
name: "batch_decompile",
arguments: {
addresses: Array.from(
{ length: 37 },
(_, index) => `0x${String(index)}`,
),
addresses,
},
});
expect(result.isError).not.toBe(true);
expect(maximum).toBe(37);
expect(result.structuredContent).toMatchObject({
result: {
items: addresses.map((address) => ({
address,
status: "ok",
pseudocode: `pseudo for ${address}`,
})),
total: addresses.length,
succeeded: addresses.length,
failed: 0,
},
});
});
it("returns ordered typed batch failures and zero counts for empty input", async () => {
@@ -23,6 +23,17 @@ describe("Ghidra MCP capability routing", () => {
({ name }) => name,
);
expect(availableNames).toContain("set_comment");
const denied = await mcp.callTool({
name: "set_comment",
arguments: { address: "0x1000", comment: "must not mutate" },
});
expect(denied.isError).toBe(true);
expect(denied.structuredContent).toMatchObject({
error: {
code: "capability_unavailable",
category: "unsupported_provider",
},
});
expect(calls).not.toContain("set_comment");
const status = await mcp.callTool({
@@ -157,10 +157,9 @@ describe("JavaScript runtime observation MCP tools", () => {
parameters: expect.any(Object),
},
});
expect(inspector.commands.map(({ method }) => method)).toEqual([
"Runtime.enable",
"Debugger.enable",
]);
expect(new Set(inspector.commands.map(({ method }) => method))).toEqual(
new Set(["Runtime.enable", "Debugger.enable"]),
);
const direct = await observeDirectly(root, inspector, authority);
expect(direct.ok).toBe(true);
if (direct.ok) expect(evidenceId).toBe(direct.value.evidence_id);
+1 -1
View File
@@ -102,7 +102,7 @@ describe("MCP runtime errors", () => {
await nextTurn();
expect(closeCalls).toBe(1);
expect(unregistrations).toEqual(["reload", "shutdown"]);
expect([...unregistrations].sort()).toEqual(["reload", "shutdown"]);
});
it("reports transport startup failure without its cause", async () => {
-1
View File
@@ -120,7 +120,6 @@ describe("runtime permission reload", () => {
runtime.reload();
await expect.poll(() => reads).toBe(2);
expect(reads).toBe(2);
expect(runtime.options.processPolicy?.().status).toBe("enabled");
expect(runtime.options.artifactIntegrityContinueEnabled?.()).toBe(true);
expectOptionalPolicies(runtime.options, {
@@ -15,10 +15,6 @@ describe("MCP startup policy", () => {
expect(MCP_STARTUP_POLICY.firstCatalogBudgetMs).toBeLessThan(
codexTimeoutMs,
);
expect(MCP_STARTUP_POLICY.firstCatalogBudgetMs).toBe(
MCP_STARTUP_POLICY.initializeBudgetMs +
MCP_STARTUP_POLICY.toolsListBudgetMs,
);
expect(MCP_STARTUP_POLICY.doctorDeadlineMs).toBeGreaterThanOrEqual(
codexTimeoutMs,
);
+55 -16
View File
@@ -13,6 +13,9 @@ const VALID_INPUTS: Readonly<
Record<string, Readonly<Record<string, JsonValue>>>
> = {
address_name: {},
inspect_native_instruction: { address: "0x1000" },
resolve_native_call_targets: { address: "0x1000" },
inspect_native_data_type: { type: "/Missing" },
comment: {},
current_address: {},
current_procedure: {},
@@ -124,6 +127,58 @@ const connect = async (analysis: AnalysisOperationPort) => {
const inventory: JsonValue = [];
const outputFor = (name: string): JsonValue => {
if (name === "inspect_native_instruction")
return {
address: "0x1000",
status: "decoded",
procedure: "0x1000",
architecture: "x86:LE:64:default",
mode: "default",
bytes: "c3",
length: 1,
mnemonic: "RET",
raw_disassembly: "RET",
operands: [],
flow: {
kind: "terminal",
conditional: false,
computed: false,
direct_destinations: [],
},
references: [],
limitations: ["Provider decoder observation"],
};
if (name === "resolve_native_call_targets")
return {
call_site: "0x1000",
procedure: "0x1000",
status: "not-call",
mechanism: "unavailable",
targets: [],
limitations: [],
};
if (name === "inspect_native_data_type")
return {
status: "unavailable",
reason: "Type absent",
id: null,
name: null,
kind: "unavailable",
source: "analysis-database",
source_archive: null,
address: null,
size_bytes: null,
alignment_bytes: null,
packing_enabled: null,
referenced_type: null,
array_count: null,
array_stride_bytes: null,
fields: [],
members: [],
total_fields: 0,
truncated: false,
limitations: [],
};
if (["list_procedures", "list_names", "list_strings"].includes(name))
return inventory;
if (["address_name", "comment", "inline_comment"].includes(name)) return null;
@@ -184,22 +239,6 @@ const outputFor = (name: string): JsonValue => {
};
describe("official Hopper proxy tools", () => {
it("lists every official contract", async () => {
const client = await connect({
execute: () => Promise.resolve(ok(null)),
});
const listed = await client.listTools();
const officialNames = new Set<string>(
OFFICIAL_TOOL_CONTRACTS.map(({ name }) => name),
);
expect(
listed.tools
.map(({ name }) => name)
.filter((name) => officialNames.has(name))
.sort(),
).toEqual(OFFICIAL_TOOL_CONTRACTS.map(({ name }) => name).sort());
});
it("executes every handler and projects omitted Python optionals to null", async () => {
const invocations: Invocation[] = [];
const client = await connect({
@@ -284,7 +284,6 @@ describe("process-capture MCP elicitation grants: replay bounds", () => {
if (!isInputRequiredResult(acceptedAfterPrune))
expect(acceptedAfterPrune.ok).toBe(true);
expect(consumedNonces.has("occupied-0")).toBe(false);
expect(consumedNonces.size).toBe(4096);
});
it.each(["result", "throw"] as const)(
"revokes an elicited grant when final authorization ends with %s",
+6 -1
View File
@@ -26,7 +26,12 @@ describe("ordinary MCP progress and cancellation", () => {
);
expect(result.isError).not.toBe(true);
expect(progress).toEqual([0, 1]);
expect(progress[0]).toBe(0);
expect(progress.at(-1)).toBe(1);
progress.forEach((value, index) => {
expect(value).toBeGreaterThanOrEqual(progress[index - 1] ?? 0);
expect(value).toBeLessThanOrEqual(1);
});
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
-7
View File
@@ -70,13 +70,6 @@ describe("guided prompts over MCP", () => {
if (content?.type !== "text") throw new Error("missing prompt text");
expect(content.text).toContain('"feature":"license validation"');
expect(content.text).toContain("`trace_feature`");
expect(content.text).toContain("Use Evidence returned inline");
expect(content.text).toContain("do not fetch a bundle or resource");
const audit = await client.getPrompt({
name: "audit_residual_unknowns",
arguments: { audit_scope: "all active release blockers" },
});
expect(audit.messages[0]?.content.type).toBe("text");
});
it("renders every workflow without executing analysis or accepting extra context", async () => {
@@ -20,16 +20,18 @@ describe("reconstruction coverage MCP", () => {
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const boundaryId = "replacement.cli";
const result = await client.callTool({
name: "evaluate_reconstruction_coverage",
arguments: {
coverage: currentFixtureCoverage(),
boundary_id: "replacement.cli",
coverage: currentFixtureCoverage(boundaryId),
boundary_id: boundaryId,
},
});
expect(result.isError).not.toBe(true);
expect(result.structuredContent).toMatchObject({
status: "ready",
boundary_id: boundaryId,
summary: { reasons: 0 },
});
} finally {
@@ -40,10 +42,14 @@ describe("reconstruction coverage MCP", () => {
});
});
const currentFixtureCoverage = () => {
const currentFixtureCoverage = (boundaryId: string) => {
const coverage = completeReconstructionCoverageData();
return createReconstructionCoverageData({
...coverage,
boundaries: coverage.boundaries.map((boundary) => ({
...boundary,
boundary_id: boundaryId,
})),
verifier_results: coverage.verifier_results.map((result) => ({
...result,
observed_at: new Date().toISOString(),
@@ -238,11 +238,6 @@ describe("live server identity over MCP", () => {
});
const assertLiveIdentity = async (client: Client): Promise<void> => {
const instructions = client.getInstructions();
expect(instructions).toContain(
"Use the tool that directly answers the question",
);
expect(instructions).toContain("Tool results include inline Evidence");
const identity = await client.callTool({
name: "binary_session",
arguments: {},
+39 -26
View File
@@ -89,34 +89,47 @@ it("lets the SDK validate a tool call before invoking its handler", async () =>
expect(invocations).toBe(1);
});
it("preserves interleaved results across concurrent tool calls", async () => {
const invocations: string[] = [];
// Each handler awaits before mutating shared session-scoped state, so a lost
// update or crossed result would corrupt the final ordering.
const appendOrder: string[] = [];
const append = async (name: string) => {
await new Promise((resolve) => setImmediate(resolve));
appendOrder.push(name);
return ok([]);
it("preserves distinct results across concurrent tool calls", async () => {
const payloads = new Map([
["list_procedures", [{ address: "0x1000", value: "fixture_main" }]],
["list_strings", [{ address: "0x2000", value: "fixture text" }]],
["list_names", [{ address: "0x3000", value: "fixture_global" }]],
]);
const pending = new Map<string, () => void>();
let allStarted: () => void = () => {
throw new Error("start gate missing");
};
const started = new Promise<void>((resolve) => {
allStarted = resolve;
});
const client = await connect({
execute: (name) => {
invocations.push(name);
return append(name);
execute: async (name) => {
const payload = payloads.get(name);
if (payload === undefined)
throw new Error(`Unexpected operation: ${name}`);
await new Promise<void>((resolve) => {
pending.set(name, resolve);
if (pending.size === payloads.size) allStarted();
});
return ok(payload);
},
});
const results = await Promise.all([
client.callTool({ name: "list_procedures", arguments: {} }),
client.callTool({ name: "list_segments", arguments: {} }),
client.callTool({ name: "list_strings", arguments: {} }),
]);
expect(results.every((result) => !result.isError)).toBe(true);
expect(invocations).toHaveLength(3);
expect(new Set(invocations).size).toBe(3);
// Every invocation appears exactly once in the shared append log, so no
// concurrent call was dropped or recorded twice.
expect(appendOrder).toHaveLength(3);
expect([...appendOrder].sort()).toEqual([...invocations].sort());
const names = [...payloads.keys()];
const requests = names.map((name) =>
client.callTool({ name, arguments: {} }),
);
await started;
for (const name of [...names].reverse()) {
const release = pending.get(name);
if (release === undefined)
throw new Error("request did not reach provider");
release();
}
const results = await Promise.all(requests);
results.forEach((result, index) => {
expect(result.isError).not.toBe(true);
expect(structured(result)).toMatchObject({
result: payloads.get(names[index] ?? ""),
});
});
});
@@ -43,35 +43,6 @@ const structured = (result: CallToolResult): Record<string, unknown> => {
return Object.fromEntries(Object.entries(result.structuredContent));
};
it("advertises the native function discovery-to-dossier workflow", async () => {
const client = await connect({
execute: () => Promise.resolve(ok(null)),
});
expect(client.getInstructions()).toContain(
"Search or list symbols when discovery is needed",
);
expect(client.getInstructions()).toContain(
"analyze_function provides a function dossier",
);
const tools = new Map(
(await client.listTools()).tools.map((tool) => [tool.name, tool]),
);
expect(tools.get("binary_overview")?.description).toContain(
"Return native-binary metadata",
);
expect(tools.get("analyze_function")?.description).toContain(
"Build a dossier for one native function",
);
expect(tools.get("analyze_function")?.inputSchema.properties).toHaveProperty(
"procedure",
);
expect(tools.get("inspect_native_api")?.description).toContain(
"Analyze a native API boundary in one function",
);
});
it("executes a realistic workflow: list methods, decompile selected, get xrefs", async () => {
const client = await connect({
execute: (name, args) => {
@@ -148,11 +119,6 @@ it("advertises the complete currently available inventory with a session", async
const listed = await client.listTools();
const names = listed.tools.map((t) => t.name);
expect(names).toContain("open_binary");
expect(names).toContain("close_binary");
expect(names).toContain("binary_session");
expect(names).toContain("binary_overview");
expect(names).toContain("batch_decompile");
const status = structured(
await client.callTool({
name: "binary_session",
@@ -4,6 +4,7 @@ import { McpServer } from "@modelcontextprotocol/server";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import { GENERATED_MCP_TOOL_CATALOG } from "../../../src/generatedMcpToolCatalog.js";
import { annotationsFromEffects } from "../../../src/contracts/toolEffects.js";
import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js";
describe("tool registration options", () => {
@@ -34,6 +35,28 @@ describe("tool registration options", () => {
}));
for (const contract of TOOL_CONTRACTS) {
const tool = advertised.find(({ name }) => name === contract.name);
expect(tool, contract.name).toBeDefined();
expect(describesObject(tool?.inputSchema), contract.name).toBe(true);
expect(describesObject(tool?.outputSchema), contract.name).toBe(true);
expect(tool?.title?.trim().length, contract.name).toBeGreaterThan(0);
expect(tool?.description?.trim().length, contract.name).toBeGreaterThan(
0,
);
expect(JSON.stringify(tool?.outputSchema), contract.name).not.toContain(
'"result":{}',
);
expect(tool?.annotations, contract.name).toEqual(
annotationsFromEffects(contract.effects),
);
expect(contract.examples.length, contract.name).toBeGreaterThan(0);
for (const example of contract.examples) {
expect(example.title.trim().length, contract.name).toBeGreaterThan(0);
expect(
contract.inputSchema.safeParse(example.input).success,
`${contract.name}: ${example.title}`,
).toBe(true);
}
expect(tool?.inputSchema.examples, contract.name).toEqual(
contract.examples.map(({ input }) => input),
);
@@ -42,12 +65,6 @@ describe("tool registration options", () => {
contract.name,
).toEqual([]);
}
const analyzeFunction = advertised.find(
({ name }) => name === "analyze_function",
);
expect(analyzeFunction?.inputSchema.properties).toEqual({
procedure: expect.objectContaining({ type: "string" }),
});
expect(advertised).toEqual(
GENERATED_MCP_TOOL_CATALOG.map((tool) => ({
name: tool.name,
@@ -96,3 +113,18 @@ const missingPropertyDescriptions = (
const isObject = (value: unknown): value is Readonly<Record<string, unknown>> =>
typeof value === "object" && value !== null && !Array.isArray(value);
const describesObject = (schema: unknown): boolean => {
if (!isObject(schema)) return false;
return (
schema.type === "object" ||
[schema.oneOf, schema.anyOf].some(
(variants) =>
Array.isArray(variants) &&
variants.length > 0 &&
variants.every(
(variant: unknown) => isObject(variant) && variant.type === "object",
),
)
);
};
@@ -71,6 +71,10 @@ it("does not launch when policy denies capture", async () => {
expect(result.ok).toBe(false);
if (result.ok) throw new Error("expected policy refusal");
expect(result.error).toBeInstanceOf(ProcessCaptureError);
expect(result.error).toMatchObject({
userCategory: "permission_required",
message: "process capture is disabled",
});
});
itWithCaptureCapability(
@@ -245,6 +249,11 @@ itWithCaptureCapability(
expect(output).toContain("input:answer unicode:雪");
expect(output).toContain("resize:100x40");
expect(output).toContain("signal:SIGINT");
const resized = result.value.rendered_frames.find(
({ columns, rows }) => columns === 100 && rows === 40,
);
expect(resized).toBeDefined();
expect(resized?.lines.join("\n")).toContain("input:answer unicode:雪");
expect(result.value.exit.code).toBe(0);
},
);
@@ -21,6 +21,7 @@ const probeResultSchema = z.strictObject({
}),
current_document: z.literal("fixture"),
current_address: z.literal("0x401000"),
strings: z.strictObject({ "0x401234": z.literal("fixture string") }),
session_document_reused: z.literal(true),
shared_document_shutdown: z.strictObject({
shutdown: z.literal(true),
@@ -3,7 +3,7 @@ import { fileURLToPath } from "node:url";
import { afterEach, describe, expect, it } from "vitest";
import { OFFICIAL_TOOL_CONTRACTS } from "../../../../src/contracts/toolContracts.js";
import { HOPPER_PROVIDER_TOOL_CONTRACTS } from "../../../../src/hopper/HopperProvider.js";
import { ok } from "../../../../src/domain/result.js";
import type {
BridgeLauncher,
@@ -123,9 +123,11 @@ describe("HopperClient protocol", () => {
it("routes every established operation through the authenticated bridge", async () => {
const client = await startClient();
const results = await Promise.all(
OFFICIAL_TOOL_CONTRACTS.map(({ name }) => client.callTool(name, {})),
HOPPER_PROVIDER_TOOL_CONTRACTS.map(({ name }) =>
client.callTool(name, {}),
),
);
expect(results).toHaveLength(36);
expect(results).toHaveLength(HOPPER_PROVIDER_TOOL_CONTRACTS.length);
expect(results.every((result) => result.ok)).toBe(true);
});
@@ -12,12 +12,10 @@ import {
describe("native DMG artifact reader", () => {
it("uses plist attachment metadata and detaches returned devices", async () => {
const calls: string[][] = [];
const commandOptions: unknown[] = [];
const host: NativeDmgHost = {
async run(arguments_, _signal, options) {
async run(arguments_) {
const args = [...arguments_];
calls.push(args);
commandOptions.push(options);
if (args[0] !== "attach") return { stdout: "", exitCode: 0 };
const mountRoot = args[args.indexOf("-mountroot") + 1];
if (mountRoot === undefined) throw new Error("missing mount root");
@@ -43,15 +41,13 @@ describe("native DMG artifact reader", () => {
for await (const entry of reader.entries()) entries.push(entry.path);
expect(entries).toContain("image.dmg/Fixture/hello.txt");
const provenance = reader.provenance();
if (provenance[0] !== undefined)
Reflect.set(provenance[0], "tool", "forged");
const first = provenance[0];
if (first === undefined) throw new Error("expected attachment provenance");
Reflect.set(first, "tool", "forged");
expect(reader.provenance()[0]?.tool).toBe("/usr/bin/hdiutil");
await reader.close();
expect(calls).toContainEqual(["verify", "/tmp/image.dmg"]);
expect(calls).toContainEqual(["detach", "/dev/disk-fixture"]);
expect(commandOptions[0]).toBeUndefined();
expect(commandOptions[1]).toBeUndefined();
expect(commandOptions[2]).toEqual({ timeoutMs: 120_000 });
});
it("rejects non-zero results and surfaces detach failure during attach cleanup", async () => {
@@ -84,12 +84,6 @@ describe("Android application projection", () => {
expect.objectContaining({ basis: "react-native-convention" }),
]);
expect(JSON.stringify(left)).not.toContain("opaque signing");
expect(
androidApplicationProjectionResultSchema.safeParse({
...left,
limitations: Array.from({ length: 101 }, () => "x".repeat(4_097)),
}).success,
).toBe(true);
});
it("rejects non-APK inventory Evidence", async () => {
@@ -9,25 +9,18 @@ import {
} from "@zip.js/zip.js";
import { describe, expect, it } from "vitest";
import { fragmentInventoryEvidence } from "../../fixtures/artifactEvidence.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { projectAppleApplicationEvidence } from "../../../src/application/AppleApplicationService.js";
import { runProviderAnalysis } from "../../../src/application/DirectAnalysis.js";
import { appleApplicationProjectionResultSchema } from "../../../src/domain/appleApplication.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
// Sized to prove the claims this projection makes -- multiple inventory pages,
// every component retained, and one bridge candidate per script/native pair --
// and to cross any ceiling a truncation regression would plausibly introduce.
// A fixture of a dozen frameworks and 16 candidates would pass unnoticed
// against a cap at 100, which is the truncation this guards against. The
// original 1_001 frameworks x 101 pages produced 10_201 candidates and cost
// ~6.4s, roughly half the composition lane, to assert the same properties an
// order of magnitude above the plausible-ceiling range.
// Real ZIP entries cross the former component and bridge-candidate limits.
const FRAMEWORK_COUNT = 250;
const SCRIPT_COUNT = 40;
const NATIVE_COUNT = 40;
const INVENTORY_PAGE_COUNT = 3;
async function createCompleteAppleProjection() {
const root = await createTestTempDirectory("rea-apple-complete-");
@@ -59,43 +52,20 @@ async function createCompleteAppleProjection() {
const inventory = parseEvidence(
await runProviderAnalysis(path, "inventory_artifact", {}),
);
const subject = inventory.subject;
expect(subject).not.toBeNull();
if (subject === null)
throw new TypeError("Missing fixture inventory subject");
const inventoryPages = Array.from(
{ length: INVENTORY_PAGE_COUNT },
(_, index) =>
createEvidence(
{
path: subject.local_path,
sha256: subject.digest.sha256,
format: subject.format,
...(subject.architecture === null
? {}
: { architecture: subject.architecture }),
},
inventory.provider,
{
predicateType: inventory.predicate_type,
operation: inventory.operation,
parameters: {
...inventory.parameters,
projection_test_page: index,
},
result: inventory.normalized_result,
},
),
);
const fragments = fragmentInventoryEvidence(inventory, 3);
const result = projectAppleApplicationEvidence({
inventory_evidence: inventoryPages,
inventory_evidence: fragments,
});
expect(result.ok).toBe(true);
if (!result.ok) throw new TypeError("Could not project fixture inventory");
return appleApplicationProjectionResultSchema.parse(
const projection = appleApplicationProjectionResultSchema.parse(
result.value.normalized_result,
);
expect([...projection.source_evidence_ids].sort()).toEqual(
fragments.map(({ evidence_id }) => evidence_id).sort(),
);
return projection;
}
describe("Apple application projection", () => {
@@ -149,33 +119,6 @@ describe("Apple application projection", () => {
second.value.normalized_result,
);
expect(left).toEqual(right);
const longPath = `Payload/${"deep/".repeat(1_000)}Fixture.app`;
expect(
appleApplicationProjectionResultSchema.parse({
...left,
application_roots: [longPath],
}).application_roots,
).toEqual([longPath]);
expect(
appleApplicationProjectionResultSchema.parse({
...left,
limitations: ["x".repeat(5_000)],
}).limitations,
).toEqual(["x".repeat(5_000)]);
const [framework, ...otherFrameworks] = left.components.frameworks;
if (framework === undefined) throw new Error("Expected framework fixture");
expect(
appleApplicationProjectionResultSchema.parse({
...left,
components: {
...left.components,
frameworks: [
{ ...framework, format: "x".repeat(500) },
...otherFrameworks,
],
},
}).components.frameworks[0]?.format,
).toBe("x".repeat(500));
expect(left).toMatchObject({
root_format: "ipa",
application_roots: ["Payload/Fixture.app"],
@@ -224,18 +167,14 @@ describe("Apple application projection", () => {
});
describe("Apple application projection completeness", () => {
it("returns every component, inventory page, and bridge hypothesis", async () => {
it("returns every component and bridge hypothesis from fragments of a real ZIP inventory", async () => {
const projection = await createCompleteAppleProjection();
expect(projection.components.frameworks).toHaveLength(FRAMEWORK_COUNT);
expect(projection.components.bundle_metadata).toHaveLength(FRAMEWORK_COUNT);
expect(projection.components.javascript).toHaveLength(SCRIPT_COUNT);
expect(projection.components.native_libraries).toHaveLength(NATIVE_COUNT);
expect(projection.source_evidence_ids).toHaveLength(INVENTORY_PAGE_COUNT);
// Every inventory page is retained exactly once.
expect(new Set(projection.source_evidence_ids).size).toBe(
projection.source_evidence_ids.length,
);
expect(projection.source_evidence_ids.length).toBeGreaterThan(1);
expect(projection.source_evidence_ids).toHaveLength(3);
expect(new Set(projection.source_evidence_ids).size).toBe(3);
// One candidate per script/native pair. Deriving this catches a pairing
// regression, which the previous literal 10_201 could not.
expect(projection.bridge_candidates).toHaveLength(
@@ -249,12 +188,13 @@ describe("Apple application projection completeness", () => {
expect(projection).not.toHaveProperty("omitted_bridge_candidates");
});
it("infers an application root when the IPA omits directory entries", async () => {
it("retains long ZIP application roots when the IPA omits directory entries", async () => {
const root = await createTestTempDirectory("rea-apple-root-");
const path = join(root, "Fixture.ipa");
const applicationRoot = `Payload/${"LongApp".repeat(750)}.app`;
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add(
"Payload/Fixture.app/Fixture",
`${applicationRoot}/Fixture`,
new Uint8ArrayReader(
Uint8Array.from([0xcf, 0xfa, 0xed, 0xfe, 0x0c, 0, 0, 1]),
),
@@ -274,7 +214,7 @@ describe("Apple application projection completeness", () => {
result.value.normalized_result,
),
).toMatchObject({
application_roots: ["Payload/Fixture.app"],
application_roots: [applicationRoot],
components: { executables: [expect.any(Object)] },
});
});
@@ -3,6 +3,7 @@ import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { fragmentInventoryEvidence } from "../../fixtures/artifactEvidence.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { inventoryArtifact } from "../../../src/application/ArtifactInventory.js";
@@ -39,26 +40,6 @@ const observe = async (path: string) => {
);
};
const evidencePages = (
inventory: Awaited<ReturnType<typeof observe>>,
side: string,
) =>
Array.from({ length: 101 }, (_, index) =>
createEvidence(
{
path: `${side}-${String(index)}`,
sha256: inventory.subject?.digest.sha256 ?? "0".repeat(64),
format: inventory.subject?.format ?? "directory",
},
PROVIDER,
{
operation: "inventory_artifact",
parameters: { page: index, side },
result: jsonValueSchema.parse(inventory.normalized_result),
},
),
);
const changedArtifactComparison = async () => {
const parent = await createTestTempDirectory("rea-artifact-compare-");
const leftPath = join(parent, "left.app");
@@ -113,30 +94,6 @@ describe("artifact comparison", () => {
);
});
it("accepts all reported comparison dimensions", async () => {
const result = (await changedArtifactComparison()).result;
const firstChange = result.changes[0];
if (firstChange === undefined) throw new Error("Expected artifact change");
const dimensions = [
"content",
"kind",
"format",
"size",
"executable",
"relations",
"metadata",
"availability",
"integrity",
] as const;
expect(
artifactComparisonResultSchema.parse({
...result,
changes: [{ ...firstChange, dimensions }, ...result.changes.slice(1)],
}).changes[0]?.dimensions,
).toEqual(dimensions);
});
it("reports incomplete inventory as truncated, never unchanged", async () => {
const root = await createTestTempDirectory("rea-artifact-truncated-");
await writeFile(join(root, "one.txt"), "one");
@@ -220,27 +177,63 @@ describe("artifact comparison completeness", () => {
});
}, 15_000);
it("retains every inventory citation when comparing many evidence pages", async () => {
const parent = await createTestTempDirectory(
"rea-artifact-pages-evidence-",
);
it("assembles real inventory fragments and retains every citation", async () => {
const parent = await createTestTempDirectory("rea-artifact-fragments-");
const leftPath = join(parent, "left.app");
const rightPath = join(parent, "right.app");
await Promise.all([mkdir(leftPath), mkdir(rightPath)]);
await Promise.all([
writeFile(join(leftPath, "main.js"), "left();"),
writeFile(join(rightPath, "main.js"), "right();"),
]);
const leftInventory = await observe(leftPath);
const rightInventory = await observe(rightPath);
const comparison = compareArtifacts(
evidencePages(leftInventory, "left"),
evidencePages(rightInventory, "right"),
// Cross the former 100-citation limit with distinct, real graph members.
const fragmentCount = 101;
await Promise.all(
Array.from({ length: fragmentCount }, async (_, index) => {
await Promise.all([
writeFile(join(leftPath, `file-${index}.js`), `left(${index});`),
writeFile(join(rightPath, `file-${index}.js`), `right(${index});`),
]);
}),
);
expect(comparison.changes[0]?.evidence_links).toHaveLength(202);
});
const left = await observe(leftPath);
const right = await observe(rightPath);
const leftFragments = fragmentInventoryEvidence(left, fragmentCount);
const rightFragments = fragmentInventoryEvidence(right, fragmentCount);
const citations = [...leftFragments, ...rightFragments]
.map(({ evidence_id }) => evidence_id)
.sort();
expect(new Set(citations).size).toBe(fragmentCount * 2);
const comparison = compareArtifacts(leftFragments, rightFragments);
const complete = compareArtifacts(left, right);
expect(
comparison.changes
.filter(({ logical_path }) => logical_path !== ".")
.map(({ logical_path, classification }) => ({
logical_path,
classification,
}))
.sort((left, right) =>
left.logical_path.localeCompare(right.logical_path),
),
).toEqual(
Array.from({ length: fragmentCount }, (_, index) => ({
logical_path: `file-${index}.js`,
classification: "changed",
})).sort((left, right) =>
left.logical_path.localeCompare(right.logical_path),
),
);
expect({
...comparison,
changes: comparison.changes.map((change) => ({
...change,
evidence_links: [...change.evidence_links].sort(),
})),
}).toEqual({
...complete,
changes: complete.changes.map((change) => ({
...change,
evidence_links: citations,
})),
});
}, 15_000);
it("rejects non-inventory and tampered Evidence", async () => {
const root = await createTestTempDirectory("rea-artifact-invalid-");
@@ -514,6 +514,7 @@ describe("typed unavailability without dispatching", () => {
const session = createTestBinarySession(() => client());
expect((await session.execute("binary_overview", {})).ok).toBe(false);
expect(await session.close()).toEqual({ ok: true, value: null });
expect(await session.close()).toEqual({ ok: true, value: null });
});
it("keeps the active client when a switch fails", async () => {
@@ -622,14 +623,14 @@ describe("active client replacement", () => {
clients.push(value);
return value;
});
await session.open(first);
expect((await session.open(first)).ok).toBe(true);
const call = session.execute("procedure_pseudo_code", {});
const switching = session.open(second);
await Promise.resolve();
expect(clients[0]?.closed).toBe(0);
active.resolve(ok(null));
await call;
await switching;
expect((await call).ok).toBe(true);
expect((await switching).ok).toBe(true);
expect(clients[0]?.closed).toBe(1);
});
@@ -744,8 +745,9 @@ describe("cancellation during profile resolution", () => {
clients.push(value);
return value;
});
await session.open(first);
await session.open(second);
expect((await session.open(first)).ok).toBe(true);
expect((await session.open(second)).ok).toBe(false);
expect((await session.execute("address_name", {})).ok).toBe(true);
expect(clients[1]?.closed).toBe(1);
expect(clients[0]?.closed).toBe(1);
expect(clients[2]?.closed).toBe(0);
@@ -770,10 +772,12 @@ describe("cancellation during profile resolution", () => {
return Promise.resolve();
},
}));
await session.open(first);
await session.open(second);
expect((await session.open(first)).ok).toBe(true);
expect((await session.open(second)).ok).toBe(true);
expect(liveClients).toBe(1);
expect(overlapped).toBe(false);
await session.close();
expect(liveClients).toBe(0);
});
it("clears session state while preserving a typed provider cleanup failure", async () => {
@@ -10,28 +10,18 @@ import { analyzeJavaScriptApplicationInputSchema } from "../../../src/domain/jav
import { writeElectronBoundaryFixture } from "../../fixtures/electronBoundaryApplication.js";
describe("static Electron application analysis", () => {
it("accepts an absolute caller path without caller-selected analysis bounds", () => {
it("rejects relative paths and caller-selected analysis bounds", () => {
expect(
analyzeJavaScriptApplicationInputSchema.safeParse({
input_path: "relative/app.asar",
}).success,
).toBe(false);
expect(
analyzeJavaScriptApplicationInputSchema.safeParse({
input_path: "/tmp/app.asar",
}).success,
).toBe(true);
expect(
analyzeJavaScriptApplicationInputSchema.safeParse({
input_path: "/tmp/app.asar",
limits: { max_findings: 200_000 },
}).success,
).toBe(false);
expect(
analyzeJavaScriptApplicationInputSchema.parse({
input_path: "/tmp/app.asar",
}),
).toEqual({ input_path: "/tmp/app.asar", format: "auto" });
});
it("maps windows, preload, contextBridge, IPC, validations, utility, and native boundaries without execution", async () => {
@@ -26,15 +26,6 @@ it("reconstructs package, Electron roles, Webpack/Rspack modules, and cross-laye
expect(Reflect.get(globalThis, "__rea_bundle_executed")).toBeUndefined();
expect(result.input_path).toBe(root);
const longPath = `/${"deep/".repeat(4_000)}application`;
const { electron_summary: summary, ...analysisResult } = result;
expect(
javascriptApplicationAnalysisResultSchema.parse({
...analysisResult,
summary,
input_path: longPath,
}).input_path,
).toBe(longPath);
expect(result.statistics).toMatchObject({
modules: 4,
parse_failures: 0,
@@ -127,7 +118,6 @@ it("produces deterministic ASAR graphs with unpacked native linkage and complete
expect(first.graph).toEqual(second.graph);
expect(first.inventory_graph_sha256).toBe(second.inventory_graph_sha256);
expect(first.graph.graph_id).toBe(second.graph.graph_id);
expect(first.graph.nodes).toEqual(
expect.arrayContaining([
expect.objectContaining({
@@ -56,6 +56,11 @@ it("matches renderer, frame, script bytes, and worker without claiming execution
expect(() =>
javascriptRuntimeReconciliationResultSchema.parse(result),
).not.toThrow();
expect(result.source_map_authority).toMatchObject({
used_for_primary_matching: false,
static_layer_count: 1,
runtime_script_declarations: 0,
});
expect(result.summary).toMatchObject({
runtime_targets: 1,
runtime_frames: 1,
@@ -153,22 +158,6 @@ it("reports a captured digest disagreement instead of accepting a path match", a
expect(script?.candidate_static_nodes).toHaveLength(1);
});
it("keeps source-map declarations outside primary matching authority", async () => {
const fixture = await applicationFixture();
const staticEvidence = await analyzeFixture(fixture);
const runtimeEvidence = electronRuntimeEvidence(fixture, SOURCE);
const result = reconcileJavaScriptRuntime({
static_layers: [{ role: "application", analysis: staticEvidence }],
runtime_observations: [runtimeEvidence],
});
expect(result.source_map_authority).toMatchObject({
used_for_primary_matching: false,
static_layer_count: 1,
runtime_script_declarations: 0,
});
});
it("reconciles active Electron as a partial target-only runtime capture", async () => {
const fixture = await applicationFixture();
const staticEvidence = await analyzeFixture(fixture);
+10
View File
@@ -2,6 +2,16 @@
volatile int rea_ghidra_inventory_global = 7;
enum ReaFixtureState { REA_FIXTURE_IDLE = 0, REA_FIXTURE_READY = 3 };
union ReaFixturePayload { unsigned int word; unsigned char bytes[4]; };
struct ReaFixtureLayout {
enum ReaFixtureState state;
union ReaFixturePayload payload;
struct ReaFixtureLayout *next;
};
volatile struct ReaFixtureLayout rea_ghidra_inventory_layout = {
REA_FIXTURE_READY, {.word = 5}, 0};
__attribute__((noinline, used)) int rea_ghidra_inventory_leaf(int value) {
puts("REA_GHIDRA_LEAF_VALUE");
return value + rea_ghidra_inventory_global;
@@ -0,0 +1,58 @@
#if defined(__APPLE__)
.section __TEXT,__text,regular,pure_instructions
.globl _rea_relative_switch
_rea_relative_switch:
#else
.text
.globl rea_relative_switch
.type rea_relative_switch,%function
rea_relative_switch:
#endif
cmp w0, #3
b.hi Ldefault
mov w8, w0
#if defined(__APPLE__)
adrp x9, Ltable@PAGE
add x9, x9, Ltable@PAGEOFF
#else
adrp x9, Ltable
add x9, x9, :lo12:Ltable
#endif
adr x10, Lcase0
#if REA_ENTRY_BYTES == 2
ldrh w11, [x9, x8, lsl #1]
#else
ldrb w11, [x9, x8]
#endif
add x10, x10, x11, lsl #2
br x10
Lcase0:
mov w0, #100
ret
#if REA_ENTRY_BYTES == 2
.space 1100
#endif
Lcase1:
mov w0, #101
ret
Lcase2:
mov w0, #102
ret
Lcase3:
mov w0, #103
ret
Ldefault:
mov w0, #-1
ret
#if defined(__APPLE__)
.section __TEXT,__const
#else
.section .rodata
#endif
.p2align 1
Ltable:
#if REA_ENTRY_BYTES == 2
.short (Lcase0-Lcase0)/4, (Lcase1-Lcase0)/4, (Lcase2-Lcase0)/4, (Lcase3-Lcase0)/4
#else
.byte (Lcase0-Lcase0)/4, (Lcase1-Lcase0)/4, (Lcase2-Lcase0)/4, (Lcase3-Lcase0)/4
#endif
@@ -0,0 +1 @@
{ "info": { "author": "xcode", "version": 1 } }
@@ -0,0 +1,17 @@
{
"colors": [
{
"idiom": "universal",
"color": {
"color-space": "srgb",
"components": {
"red": "0.125",
"green": "0.500",
"blue": "0.875",
"alpha": "1.000"
}
}
}
],
"info": { "author": "xcode", "version": 1 }
}
+19
View File
@@ -0,0 +1,19 @@
#import <Foundation/Foundation.h>
@protocol ReaDispatchProtocol
- (void)performAction:(id)sender;
@optional
- (int)optionalFixtureValue;
@end
@interface ReaDispatchFixture : NSObject <ReaDispatchProtocol> {
int state;
}
- (void)performAction:(id)sender;
+ (int)fixtureVersion;
@end
@implementation ReaDispatchFixture
- (void)performAction:(id)sender { state += sender == nil ? 1 : 2; }
+ (int)fixtureVersion { return 1; }
@end
int main(void) { return 0; }
+12
View File
@@ -0,0 +1,12 @@
public protocol ReaWitnessFixtureProtocol { func fixtureValue() -> Int }
public struct ReaWitnessFixture: ReaWitnessFixtureProtocol {
public init() {}
public func fixtureValue() -> Int { 17 }
}
@_cdecl("rea_witness_fixture_entry")
public func fixtureEntry() -> Int { ReaWitnessFixture().fixtureValue() }
public class ReaVtableFixture {
public init() {}
public func fixtureValue() -> Int { 23 }
}
@@ -0,0 +1,16 @@
import Foundation
final class ReaArchiveRecord: NSObject, NSCoding {
var link: ReaArchiveRecord?
override init() { super.init() }
required init?(coder: NSCoder) { super.init() }
func encode(with coder: NSCoder) {
coder.encode(link, forKey: "cycle")
coder.encode(Data([0, 1, 2, 255]), forKey: "payload")
coder.encodeConditionalObject(nil, forKey: "conditional")
}
}
let record = ReaArchiveRecord()
record.link = record
let data = try NSKeyedArchiver.archivedData(withRootObject: [record, record] as NSArray, requiringSecureCoding: false)
try data.write(to: URL(fileURLWithPath: CommandLine.arguments[1]))
+21
View File
@@ -0,0 +1,21 @@
import AppKit
let app = NSApplication.shared
app.setActivationPolicy(.accessory)
let window = NSWindow(contentRect: NSRect(x: 120, y: 120, width: 360, height: 180), styleMask: [.titled, .closable], backing: .buffered, defer: false)
window.title = "REA source-owned UI verification"
final class FixtureController: NSObject {
@objc func increment(_ sender: NSButton) { sender.title = "REA fixture incremented" }
}
let controller = FixtureController()
let button = NSButton(frame: NSRect(x: 30, y: 60, width: 280, height: 40))
button.title = "Increment REA fixture"
button.target = controller
button.action = #selector(FixtureController.increment(_:))
window.contentView?.addSubview(button)
window.orderFront(nil)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
let record = "{\"pid\":\(ProcessInfo.processInfo.processIdentifier),\"window_id\":\(window.windowNumber)}\n"
FileHandle.standardOutput.write(Data(record.utf8))
}
app.run()
@@ -1,24 +1,8 @@
import { describe, expect, it } from "vitest";
import {
generateLargeFixture,
LARGE_FIXTURE_COUNT,
sha256,
sourceDigest,
} from "../../../scripts/lib/conformance-fixtures.mjs";
import { sourceDigest } from "../../../scripts/lib/conformance-fixtures.mjs";
describe("source-built conformance fixtures", () => {
it("generates deterministic large-fixture source", () => {
const first = generateLargeFixture();
const second = generateLargeFixture();
expect(first).toBe(second);
expect(first).toContain("rea_inventory_0000");
expect(first).toContain(
`rea_inventory_${String(LARGE_FIXTURE_COUNT - 1).padStart(4, "0")}`,
);
});
it("hashes source manifests independently of input ordering", () => {
const left = [
{ path: "b.c", content: "b" },
@@ -28,6 +12,5 @@ describe("source-built conformance fixtures", () => {
expect(sourceDigest(left)).toBe(sourceDigest(right));
expect(sourceDigest(left)).toMatch(/^[0-9a-f]{64}$/u);
expect(sha256("fixture")).not.toBe(sha256("changed"));
});
});
@@ -96,6 +96,11 @@ describe("conformance CI replay", () => {
expect(result.passed).toBe(1);
expect(result.failed).toBe(0);
expect(result.errored).toBe(0);
expect(result.drift_detected).toBe(false);
expect(
packageReplayResultSchema.safeParse({ ...result, drift_detected: true })
.success,
).toBe(false);
expect(
packageReplayResultSchema.safeParse({ ...result, passed: 0 }).success,
).toBe(false);
@@ -111,21 +116,6 @@ describe("conformance CI replay", () => {
expect(result.passed).toBe(0);
});
it("does not detect drift when expected and actual match", async () => {
const result = await replayConformancePackage(
validPackage,
{},
passingRunner,
);
expect(
packageReplayResultSchema.safeParse({
...result,
drift_detected: true,
}).success,
).toBe(false);
expect(result.drift_detected).toBe(false);
});
it("retains the observed Evidence ID on the first drift", async () => {
const expected = createEvidence(
undefined,
@@ -167,70 +157,82 @@ describe("conformance CI replay", () => {
);
});
it("counts all result types", async () => {
it("counts pass, fail, error and skipped results without losing runner diagnostics", async () => {
const cases = [
{ id: "s1", status: "pass" },
{ id: "s2", status: "fail" },
{ id: "s3", status: "error" },
{ id: "s4", status: "skipped" },
] as const;
const multiPackage = createConformancePackage({
...validPackageInput,
scenarios: [
...validPackage.scenarios,
{
scenario_id: "s2",
name: "Second scenario",
description: "Second",
fixture_path: "tests/conformance/c/fixture2.c",
expected_exit_code: 1,
expected_patterns: [],
},
],
replay_plans: [
...validPackage.replay_plans,
{
scenario_id: "s2",
steps: [
{
step_id: "step1",
action: "run",
arguments: [],
timeout_ms: 1000,
},
],
environment: {},
},
],
expected_evidence: [
...validPackage.expected_evidence,
{
scenario_id: "s2",
envelopes: [],
bundle: null,
required_dimensions: [],
},
],
verifier_contracts: [
...validPackage.verifier_contracts,
{
scenario_id: "s2",
dimensions: [
{ name: "exit_code", required: true, comparison: "exact" },
],
timing_tolerance_ms: 0,
},
],
scenarios: cases.flatMap(({ id }) =>
validPackage.scenarios.map((scenario) => ({
...scenario,
scenario_id: id,
})),
),
replay_plans: cases.flatMap(({ id }) =>
validPackage.replay_plans.map((plan) => ({ ...plan, scenario_id: id })),
),
expected_evidence: cases.flatMap(({ id }) =>
validPackage.expected_evidence.map((evidence) => ({
...evidence,
scenario_id: id,
})),
),
verifier_contracts: cases.flatMap(({ id }) =>
validPackage.verifier_contracts.map((contract) => ({
...contract,
scenario_id: id,
})),
),
});
const result = await replayConformancePackage(
multiPackage,
{},
async (scenarioId) => ({
scenario_id: scenarioId,
status: scenarioId === "s1" ? "pass" : "fail",
exit_code: scenarioId === "s1" ? 0 : 1,
async (scenarioId) => {
const item = cases.find(({ id }) => id === scenarioId);
if (item === undefined)
throw new Error(`Unexpected scenario: ${scenarioId}`);
return {
scenario_id: scenarioId,
status: item.status,
exit_code:
item.status === "pass" ? 0 : item.status === "fail" ? 1 : null,
duration_ms: 10,
output: "",
error:
item.status === "error"
? "fixture runner failed"
: item.status === "skipped"
? "fixture prerequisite unavailable"
: null,
};
},
);
expect(result).toMatchObject({
total_scenarios: cases.length,
passed: 1,
failed: 1,
errored: 1,
skipped: 1,
});
expect(result.scenario_results).toEqual(
cases.map(({ id, status }) => ({
scenario_id: id,
status,
exit_code: status === "pass" ? 0 : status === "fail" ? 1 : null,
duration_ms: 10,
output: "",
error: null,
}),
error:
status === "error"
? "fixture runner failed"
: status === "skipped"
? "fixture prerequisite unavailable"
: null,
})),
);
expect(result.total_scenarios).toBe(2);
expect(result.passed).toBe(1);
expect(result.failed).toBe(1);
});
});
@@ -169,8 +169,7 @@ describe("conformance trust gates", () => {
{ exit_code: 1, stdout: "hello" },
);
expect(result.verdict).toBe("fail");
expect(result.first_divergence).not.toBeNull();
expect(result.first_divergence!.dimension).toBe("exit_code");
expect(result.first_divergence).toMatchObject({ dimension: "exit_code" });
});
it("reports unknown when both dimensions are undefined", () => {
@@ -24,23 +24,23 @@ describe("real Windows Ghidra workflow trust boundary", () => {
verify: {
if: "github.ref == 'refs/heads/main'",
environment: "real-ghidra-windows",
"runs-on": ["self-hosted", "Windows", "x64", "ghidra-12-1-2"],
steps: [
{},
{ uses: "actions/setup-node@v4" },
{ run: "npm ci" },
{
"runs-on": expect.arrayContaining(["self-hosted", "Windows", "x64"]),
steps: expect.arrayContaining([
expect.objectContaining({ uses: "actions/setup-node@v4" }),
expect.objectContaining({ run: "npm ci" }),
expect.objectContaining({
env: { REA_ANALYSIS_PROVIDER: "ghidra" },
run: "npm run verify:ghidra:windows | Tee-Object -FilePath windows-ghidra-proof.log",
},
{
}),
expect.objectContaining({
uses: "actions/upload-artifact@v4",
with: { path: "windows-ghidra-proof.log" },
},
],
with: expect.objectContaining({
path: "windows-ghidra-proof.log",
}),
}),
]),
},
},
});
expect(workflow.jobs.verify.steps).toHaveLength(5);
});
});
@@ -21,14 +21,9 @@ describe("real Hopper complete inline search", () => {
procedures: { count: 205, calls: 1 },
strings: { count: 205, calls: 1 },
});
expect(client.calls).toEqual([
"open_binary",
"search_procedures",
"search_strings",
]);
});
it.each(["duplicate", "wrong-count", "missing"] as const)(
it.each(["duplicate", "missing"] as const)(
"rejects %s positive evidence",
async (fault) => {
await expect(
@@ -46,19 +41,13 @@ describe("real Hopper complete inline search", () => {
);
});
const fixtureClient = (
count: number,
fault?: "duplicate" | "wrong-count" | "missing",
) => {
const calls: string[] = [];
const fixtureClient = (count: number, fault?: "duplicate" | "missing") => {
return {
calls,
callTool: async (request: unknown) => {
const parsed = request as { name: string };
calls.push(parsed.name);
if (parsed.name === "open_binary") return { isError: false };
const procedures = parsed.name === "search_procedures";
const resultCount = fault === "wrong-count" ? count - 1 : count;
const resultCount = count;
const items = Array.from({ length: resultCount }, (_, index) => {
const duplicateIndex = fault === "duplicate" && index === 1 ? 0 : index;
return {
@@ -1,7 +1,6 @@
import { describe, expect, it } from "vitest";
import {
analyzeFixtureProcedure,
requireCurrentDocument,
resolveFixtureProcedure,
} from "../../../../scripts/lib/real-hopper-semantic.mjs";
@@ -9,29 +8,6 @@ import {
const normalize = (value: unknown): unknown => value;
describe("real Hopper semantic fixture resolution", () => {
it("requests assembly when analyzing fixture procedures", async () => {
const requests: unknown[] = [];
const result = await analyzeFixtureProcedure(
{
callTool: async (request: unknown) => {
requests.push(request);
return { dossier: true };
},
},
{},
{ address: "0x1000", name: "rea_entry" },
normalize,
);
expect(result).toEqual({ dossier: true });
expect(requests).toEqual([
{
name: "analyze_function",
arguments: { procedure: "0x1000" },
},
]);
});
it("binds mutations to the active document, not the first listed one", async () => {
await expect(
requireCurrentDocument(
@@ -47,25 +47,19 @@ describe("localized README product facts", () => {
it("keeps both English CLI onboarding paths discoverable", async () => {
const content = await readFile(resolve("README.md"), "utf8");
expect(content).toContain("npx -y rea-agents@latest analyze");
expect(content).toContain("npm install rea-agents` without `--global`");
expect(content).toContain("npm install --global rea-agents");
expect(content).toContain("rea setup");
expect(content).toContain("--install-hopper");
expect(content).toContain("docs/installation.md");
expect(content).toContain("You do not need both");
expect(content).toContain("npx --yes rea-agents@latest setup");
});
it("documents explicit setup freshness and rollback", async () => {
const content = await readFile(resolve("docs/installation.md"), "utf8");
const prose = normalizedProse(content);
expect(prose).toContain("explicit `@latest` request");
expect(prose).toContain(
"npm exec --yes --package=rea-agents@2.4.0 -- rea setup",
);
expect(prose).toContain(
"pin persistent MCP registrations to the exact version",
);
});
it("documents the published MCP Registry installation path", async () => {
+44
View File
@@ -0,0 +1,44 @@
import { artifactInventoryResultSchema } from "../../src/domain/artifactGraph.js";
import { createEvidence, type Evidence } from "../../src/domain/evidence.js";
import { jsonValueSchema } from "../../src/domain/jsonValue.js";
/** Partition a real scan into authenticated partial observations for merge tests. */
export const fragmentInventoryEvidence = (
evidence: Evidence,
count: number,
): readonly Evidence[] => {
const inventory = artifactInventoryResultSchema.parse(
evidence.normalized_result,
);
const subject = evidence.subject;
if (subject === null)
throw new TypeError("Inventory has no artifact subject");
return Array.from({ length: count }, (_, index) =>
createEvidence(
{
path: subject.local_path,
sha256: subject.digest.sha256,
format: subject.format,
},
evidence.provider,
{
operation: "inventory_artifact",
parameters: evidence.parameters,
confidence: "derived",
authority: evidence.authority,
result: jsonValueSchema.parse({
...inventory,
nodes: inventory.nodes.filter(
(_, ordinal) => ordinal % count === index,
),
occurrences: inventory.occurrences.filter(
(_, ordinal) => ordinal % count === index,
),
edges: inventory.edges.filter(
(_, ordinal) => ordinal % count === index,
),
}),
},
),
);
};
+3
View File
@@ -193,6 +193,9 @@ const sessionInfo = ({
"resolve_containing_procedure",
"search_procedures",
"search_strings",
"inspect_native_data_type",
"inspect_native_instruction",
"resolve_native_call_targets",
"analyze_function",
"procedure_assembly",
"procedure_callees",
+68
View File
@@ -0,0 +1,68 @@
# Captured format and protocol fixtures
These are actual tool outputs, not records assembled to match the parser.
`provenance.json` records the capture host, producer versions, source digests
and immutable capture/expectation digests. Compiled binaries and catalogs are
not committed.
## Foundation archive
`keyed-archive/foundation.xml` is the XML representation of a binary archive
written by Foundation `NSKeyedArchiver`, using the source-owned Swift fixture.
`plutil` represents binary UID entries as `CF$UID` dictionaries. The captured
archive has six objects: nil, the root NSArray, one shared custom record,
its four-byte data payload and two class descriptors.
`keyed-archive/graph.json` is the reviewed complete expected graph. The source
establishes two references from the array to object 2, object 2's self-cycle,
its nil conditional reference and the payload `00 01 02 ff`. The reader reports
serialized classes as unknown and does not instantiate them. The synthetic
malformed-reference tests remain separate.
To recapture the input on an approved macOS host:
```sh
capture_root=$(mktemp -d)
xcrun swift -module-cache-path "$capture_root/modules" \
tests/conformance/native/keyed-archive.swift "$capture_root/model.plist"
plutil -convert xml1 -o tests/fixtures/golden/keyed-archive/foundation.xml \
"$capture_root/model.plist"
rm -rf "$capture_root"
```
Review expected graph changes against the source and XML before updating the
expectation or provenance. Tests never rewrite the golden.
## Asset catalog
`assetutil.json` is the unmodified output of `/usr/bin/assetutil --info` for an
actual `actool` catalog. The source colorset defines `FixtureColor` with sRGB
components `[0.125, 0.5, 0.875, 1]`. Preserve private fields and producer metadata
in this fixed input, including its original timestamp; the test checks that the
projection does not discard them.
```sh
capture_root=$(mktemp -d)
xcrun actool tests/conformance/native/Assets.xcassets \
--compile "$capture_root" --platform macosx --minimum-deployment-target 12.0
/usr/bin/assetutil --info "$capture_root/Assets.car" \
> tests/fixtures/golden/assetutil.json
rm -rf "$capture_root"
```
The real E2E lane builds fresh catalogs and compares all their metadata against
the live utility output. It does not compare volatile timestamps or producer
versions against this historical capture.
## MCP JSON-RPC request
`mcp-initialize.json` captures the `initialize` request emitted by the pinned
`@modelcontextprotocol/client` 2.0.0 SDK on 2026-10-04. The client connected to
the actual `scripts/rea.mjs mcp` subprocess and completed `listTools` (122 tools).
The recorder intercepted `transport.send`, serialized the message, and delegated
the unchanged message to the real SDK transport. The committed JSON is formatted
for review; whitespace is not a wire identity claim. No provider was launched.
The decoder expectation separately specifies every field path, JSON value and
observed-versus-inferred status. It is a captured decoder regression, not proof
of a live protocol-capture product workflow.
+34
View File
@@ -0,0 +1,34 @@
[
{
"AssetStorageVersion": "Xcode 26.5 (17F42) via AssetCatalogAgent-AssetRuntime",
"Authoring Tool": "@(#)PROGRAM:CoreThemeDefinition PROJECT:CoreThemeDefinition-653.4 [LAR] [IIO-2784.5.4][LAR] AppleJPEG[1][32] CMPhoto[1][174]]",
"CoreUIVersion": 975,
"DumpToolVersion": 973.1,
"Key Format": [
"kCRThemeAppearanceName",
"kCRThemeLocalizationName",
"kCRThemeElementName",
"kCRThemePartName",
"kCRThemeSizeName",
"kCRThemeIdentifierName",
"kCRThemeLayerName",
"kCRThemeScaleName"
],
"MainVersion": "@(#)PROGRAM:CoreUI PROJECT:CoreUI-975 [LAR]",
"Platform": "macosx",
"PlatformVersion": "12.0",
"SchemaVersion": 2,
"StorageVersion": 17,
"Timestamp": 1791093487
},
{
"AssetType": "Color",
"Color components": [0.125, 0.5, 0.875, 1],
"Colorspace": "srgb",
"Name": "FixtureColor",
"NameIdentifier": 14784,
"Scale": 1,
"SHA1Digest": "267FA6EDABB4F306584AFF0827A9A614B416CA3AC93B262160080910B446C2BA",
"SizeOnDisk": 260
}
]
+83
View File
@@ -0,0 +1,83 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>$archiver</key>
<string>NSKeyedArchiver</string>
<key>$objects</key>
<array>
<string>$null</string>
<dict>
<key>$class</key>
<dict>
<key>CF$UID</key>
<integer>5</integer>
</dict>
<key>NS.objects</key>
<array>
<dict>
<key>CF$UID</key>
<integer>2</integer>
</dict>
<dict>
<key>CF$UID</key>
<integer>2</integer>
</dict>
</array>
</dict>
<dict>
<key>$class</key>
<dict>
<key>CF$UID</key>
<integer>4</integer>
</dict>
<key>conditional</key>
<dict>
<key>CF$UID</key>
<integer>0</integer>
</dict>
<key>cycle</key>
<dict>
<key>CF$UID</key>
<integer>2</integer>
</dict>
<key>payload</key>
<dict>
<key>CF$UID</key>
<integer>3</integer>
</dict>
</dict>
<data>
AAEC/w==
</data>
<dict>
<key>$classes</key>
<array>
<string>main.ReaArchiveRecord</string>
<string>NSObject</string>
</array>
<key>$classname</key>
<string>main.ReaArchiveRecord</string>
</dict>
<dict>
<key>$classes</key>
<array>
<string>NSArray</string>
<string>NSObject</string>
</array>
<key>$classname</key>
<string>NSArray</string>
</dict>
</array>
<key>$top</key>
<dict>
<key>root</key>
<dict>
<key>CF$UID</key>
<integer>1</integer>
</dict>
</dict>
<key>$version</key>
<integer>100000</integer>
</dict>
</plist>
+176
View File
@@ -0,0 +1,176 @@
{
"archive_format": "xml-plist",
"roots": {
"root": {
"CF$UID": 1
}
},
"objects": [
{
"id": 0,
"kind": "nil",
"class_id": null,
"class_name": null,
"status": "nil",
"value": "$null"
},
{
"id": 1,
"kind": "archived-object",
"class_id": 5,
"class_name": "NSArray",
"status": "unknown-class",
"value": {
"$class": {
"CF$UID": 5
},
"NS.objects": [
{
"CF$UID": 2
},
{
"CF$UID": 2
}
]
}
},
{
"id": 2,
"kind": "archived-object",
"class_id": 4,
"class_name": "main.ReaArchiveRecord",
"status": "unknown-class",
"value": {
"$class": {
"CF$UID": 4
},
"conditional": {
"CF$UID": 0
},
"cycle": {
"CF$UID": 2
},
"payload": {
"CF$UID": 3
}
}
},
{
"id": 3,
"kind": "dictionary",
"class_id": null,
"class_name": null,
"status": "observed",
"value": {
"$plist_type": "data",
"base64": "AAEC/w=="
}
},
{
"id": 4,
"kind": "class-descriptor",
"class_id": null,
"class_name": null,
"status": "observed",
"value": {
"$classes": ["main.ReaArchiveRecord", "NSObject"],
"$classname": "main.ReaArchiveRecord"
}
},
{
"id": 5,
"kind": "class-descriptor",
"class_id": null,
"class_name": null,
"status": "observed",
"value": {
"$classes": ["NSArray", "NSObject"],
"$classname": "NSArray"
}
}
],
"references": [
{
"source": null,
"path": ["root"],
"target": 1,
"raw": {
"CF$UID": 1
},
"status": "resolved"
},
{
"source": 1,
"path": ["$class"],
"target": 5,
"raw": {
"CF$UID": 5
},
"status": "resolved"
},
{
"source": 1,
"path": ["NS.objects", 0],
"target": 2,
"raw": {
"CF$UID": 2
},
"status": "resolved"
},
{
"source": 1,
"path": ["NS.objects", 1],
"target": 2,
"raw": {
"CF$UID": 2
},
"status": "resolved"
},
{
"source": 2,
"path": ["$class"],
"target": 4,
"raw": {
"CF$UID": 4
},
"status": "resolved"
},
{
"source": 2,
"path": ["conditional"],
"target": 0,
"raw": {
"CF$UID": 0
},
"status": "nil"
},
{
"source": 2,
"path": ["cycle"],
"target": 2,
"raw": {
"CF$UID": 2
},
"status": "resolved"
},
{
"source": 2,
"path": ["payload"],
"target": 3,
"raw": {
"CF$UID": 3
},
"status": "resolved"
}
],
"total_objects": 6,
"total_references": 8,
"offset": 0,
"next_offset": null,
"truncated": false,
"limitations": [
"Archive classes are never instantiated. Class names and serialized fields are observed; class-specific semantics are unknown.",
"Conditional references serialized as UID 0 cannot be distinguished from ordinary nil references. Missing fields remain absent in the raw serialized value.",
"Root selection selects the named $top entry; object pagination retains original indices and does not recursively expand references."
]
}
+10
View File
@@ -0,0 +1,10 @@
{
"method": "initialize",
"params": {
"protocolVersion": "2025-11-25",
"capabilities": {},
"clientInfo": { "name": "rea-protocol-golden", "version": "1" }
},
"jsonrpc": "2.0",
"id": 0
}
+23
View File
@@ -0,0 +1,23 @@
{
"captured_on": "2026-10-04",
"host": {
"platform": "macOS",
"version": "26.3",
"architecture": "arm64"
},
"producer": {
"xcode": "26.5 (17F42)",
"swift": "6.3.2 (swiftlang-6.3.2.1.108 clang-2100.1.1.101)",
"assetutil_dump_tool_version": 973.1,
"mcp_client": "@modelcontextprotocol/client 2.0.0"
},
"sha256": {
"tests/conformance/native/keyed-archive.swift": "21e315f01bc53c60e05f5c64c2a832afd8dbabe2369f652b96083290ca71df78",
"tests/conformance/native/Assets.xcassets/Contents.json": "67328f1f20917d61b0904d1eeadd3a9af5ebdfeb20bdd8c6f585f97f7192d873",
"tests/conformance/native/Assets.xcassets/FixtureColor.colorset/Contents.json": "26c6400ce2082ddc155175e80130daddded1a863bd68fe441bee413cc2786731",
"tests/fixtures/golden/keyed-archive/foundation.xml": "93c2bf33ad960be6fba6d45c28462c4bda73ff371fe16725d087087f044479ec",
"tests/fixtures/golden/keyed-archive/graph.json": "eaadd9fca83052e81abd0dac797d2423b0bb750bea386f790586273eb3a3172e",
"tests/fixtures/golden/assetutil.json": "ff50e24963447584e3398dddf4b0426274ffd2ea2d3ae6fac8295f449f91feb3",
"tests/fixtures/golden/mcp-initialize.json": "8f590db5143106aa43dfa96123178484d98268874eff7fabbd708c240c5975bc"
}
}
+17
View File
@@ -41,6 +41,21 @@ class FakeDocumentProvider:
return cls.current
class FakeStringSegment:
def getStringsList(self):
return [("fixture string", FakeStringAddress())]
class FakeStringAddress:
def __str__(self):
return "0x401234"
class FakeStringsDocument:
def getSegmentsList(self):
return [FakeStringSegment()]
def load_bridge(path):
namespace = {
"__file__": path,
@@ -66,6 +81,7 @@ def main():
bridge["REA_OWNS_PROCESS_LIFETIME"] = False
bridge["_configure_hopper_api"](FakeDocumentProvider)
bridge["_bind_session_document"]()
strings = bridge["_strings"](FakeStringsDocument())
current = bridge["_dispatch"]("current_document", {})
current_address = bridge["_dispatch"]("current_address", {})
selected = bridge["_session_document"]() is FakeDocumentProvider.current
@@ -115,6 +131,7 @@ def main():
"imported_without_hopper": unavailable,
"current_document": current,
"current_address": current_address,
"strings": strings,
"session_document_reused": selected,
"shared_document_shutdown": retained,
"analysis_guard": analysis_guard,
@@ -38,29 +38,4 @@ describe("curated Windows test lane", () => {
);
expect(missing.filter((path) => path !== undefined)).toEqual([]);
}, 10_000);
it("still covers Windows process ownership, installation, and capability reporting", async () => {
const paths = await curatedPaths();
const owned = paths.filter((path) => path.includes("ProcessOwnership"));
expect(owned.length).toBeGreaterThan(0);
expect(paths).toContain("src/ghidra/GhidraInstallation.test.ts");
expect(paths).toContain(
"tests/conformance/providers/ghidra/windowsCapabilities.test.ts",
);
}, 10_000);
it("excludes suites that need verified Windows native authority", async () => {
const paths = await curatedPaths();
// These require Job Object process ownership and private-runtime DACL
// enforcement, which windows-latest does not provide by design. Adding them
// here turns the lane red without adding real coverage; those claims belong
// behind the real Ghidra Windows workflow instead.
for (const excluded of [
"src/ghidra/GhidraProvider.test.ts",
"tests/boundary/providers/ghidra/ghidraClient.test.ts",
"tests/boundary/process/providerProcess.test.ts",
]) {
expect(paths).not.toContain(excluded);
}
}, 10_000);
});
@@ -1,78 +1,12 @@
import { execFile } from "node:child_process";
import { readdir } from "node:fs/promises";
import { availableParallelism } from "node:os";
import { join, relative, resolve } from "node:path";
import { promisify } from "node:util";
import { describe, expect, it } from "vitest";
import vitestConfiguration from "../../vitest.config.js";
const execute = promisify(execFile);
const EXPECTED_PROJECTS = [
"acceptance",
"adapters",
"boundary",
"composition",
"conformance",
"domain",
"evaluation",
"mcp-boundary",
"process-boundary",
"process-global",
"services",
];
describe("Vitest project configuration", () => {
it("keeps deterministic execution retry-free and parallelism bounded", () => {
expect(vitestConfiguration.test?.coverage?.enabled).toBe(false);
expect(vitestConfiguration.test?.reporters).toEqual(["default"]);
expect(vitestConfiguration.test?.retry).toBe(0);
// Local and CI deliberately share one worker budget so a green local run
// implies the same concurrency CI will exercise.
const expectedWorkers = Math.min(2, availableParallelism());
expect(vitestConfiguration.test?.maxWorkers).toBe(expectedWorkers);
const projects = (vitestConfiguration.test?.projects ?? []).flatMap(
(project) =>
typeof project === "object" && project !== null && "test" in project
? [project.test]
: [],
);
expect(projects).toHaveLength(EXPECTED_PROJECTS.length);
expect(
projects.every(({ maxWorkers }) => maxWorkers === expectedWorkers),
).toBe(true);
expect(projects.map(({ name }) => name).sort()).toEqual(EXPECTED_PROJECTS);
expect(
projects.every(({ name, isolate }) =>
name === "domain" || name === "mcp-boundary" || name === "services"
? isolate === false
: isolate === undefined,
),
).toBe(true);
});
it("serialises only the projects that own host-level state", () => {
const projects = (vitestConfiguration.test?.projects ?? []).flatMap(
(project) =>
typeof project === "object" && project !== null && "test" in project
? [project.test]
: [],
);
const serial = projects
.filter(({ fileParallelism }) => fileParallelism === false)
.map(({ name }) => name)
.sort();
// Acceptance drives the compiled CLI and MCP stdio surfaces;
// process-global inspects the runner configuration itself;
// process-boundary runs real PTY capture scenarios that contend for host
// terminal resources and still schedule some actions by wall clock.
expect(serial).toEqual([
"acceptance",
"process-boundary",
"process-global",
]);
});
it("classifies every deterministic test in exactly one project", async () => {
const { stdout } = await execute(
process.execPath,