Add evidence-backed investigation workflows

This commit is contained in:
morluto
2026-07-12 21:12:18 +00:00
parent 4110a4d717
commit 4ff4c11a00
178 changed files with 26320 additions and 1222 deletions
+174
View File
@@ -0,0 +1,174 @@
import { mkdtemp, mkdir, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { inventoryArtifact } from "../src/application/ArtifactInventory.js";
import {
artifactComparisonResultSchema,
compareArtifacts,
} from "../src/domain/artifactComparison.js";
import { createEvidence } from "../src/domain/evidence.js";
import { jsonValueSchema } from "../src/domain/jsonValue.js";
const LIMITS = {
maxEntries: 1_000,
maxTotalBytes: 1024 * 1024,
maxEntryBytes: 1024 * 1024,
maxCompressionRatio: 100,
maxDepth: 20,
maxPathBytes: 1024,
} as const;
const PROVIDER = {
id: "rea-artifact-graph",
name: "REA artifact graph",
version: "1",
} as const;
const observe = async (
path: string,
page: {
readonly nodeOffset?: number;
readonly nodeLimit?: number;
readonly occurrenceOffset?: number;
readonly edgeOffset?: number;
} = {},
) => {
const inventory = await inventoryArtifact(path, LIMITS, {
nodeOffset: page.nodeOffset ?? 0,
nodeLimit: page.nodeLimit ?? 500,
occurrenceOffset: page.occurrenceOffset ?? 0,
occurrenceLimit: 500,
edgeOffset: page.edgeOffset ?? 0,
edgeLimit: 500,
});
return createEvidence(
{
path,
sha256: inventory.manifest.root_sha256,
format: inventory.manifest.root_format,
},
PROVIDER,
{
operation: "inventory_artifact",
parameters: {},
result: jsonValueSchema.parse(inventory),
confidence: "observed",
authority: "shipped-artifact",
},
);
};
describe("artifact comparison", () => {
it("classifies deterministic path changes and cites both inventories", async () => {
const parent = await mkdtemp(join(tmpdir(), "rea-artifact-compare-"));
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"), "old();"),
writeFile(join(leftPath, "same.txt"), "same"),
writeFile(join(rightPath, "main.js"), "newer();"),
writeFile(join(rightPath, "same.txt"), "same"),
writeFile(join(rightPath, "added.txt"), "added"),
]);
const left = await observe(leftPath);
const right = await observe(rightPath);
const first = compareArtifacts(left, right, 0, 1);
const second = compareArtifacts(left, right, 0, 1);
expect(first).toEqual(second);
expect(artifactComparisonResultSchema.parse(first)).toMatchObject({
status: "changed",
summary: { added: 1, changed: 2, unknown: 0 },
changes: { limit: 1, total: 3, next_offset: 1 },
});
expect(first.changes.items[0]?.evidence_links).toEqual([
left.evidence_id,
right.evidence_id,
]);
const all = compareArtifacts(left, right, 0, 500);
expect(all.changes.items).toEqual(
expect.arrayContaining([
expect.objectContaining({
logical_path: "added.txt",
classification: "added",
}),
expect.objectContaining({
logical_path: "main.js",
classification: "changed",
dimensions: expect.arrayContaining(["content", "size"]),
}),
]),
);
});
it("reports incomplete inventory as truncated, never unchanged", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-artifact-truncated-"));
await writeFile(join(root, "one.txt"), "one");
const incomplete = await observe(root, { nodeLimit: 1 });
const comparison = compareArtifacts(incomplete, incomplete, 0, 100);
expect(comparison).toMatchObject({
status: "truncated",
summary: { unchanged: 0, unknown: 2 },
});
expect(comparison.limitations).toContain(
"Left artifact inventory is incomplete.",
);
});
it("assembles bounded page sets for graphs larger than one page", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-artifact-pages-"));
for (let index = 0; index < 501; index += 1)
await writeFile(
join(root, `file-${String(index).padStart(3, "0")}.txt`),
String(index),
);
const pages = await Promise.all([
observe(root),
observe(root, {
nodeOffset: 500,
occurrenceOffset: 500,
edgeOffset: 500,
}),
]);
expect(compareArtifacts(pages, pages, 0, 100)).toMatchObject({
status: "unchanged",
summary: { unchanged: 502, unknown: 0 },
changes: { total: 0 },
});
});
it("rejects non-inventory and tampered Evidence", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-artifact-invalid-"));
const evidence = await observe(root);
expect(() =>
compareArtifacts(
{ ...evidence, operation: "binary_overview" },
evidence,
0,
10,
),
).toThrow(/identifier/u);
const wrongOperation = createEvidence(undefined, PROVIDER, {
operation: "binary_overview",
parameters: {},
result: evidence.normalized_result,
});
expect(() => compareArtifacts(wrongOperation, evidence, 0, 10)).toThrow(
/inventory_artifact/u,
);
const mismatchedSubject = createEvidence(
{ path: root, sha256: "f".repeat(64), format: "directory" },
PROVIDER,
{
operation: "inventory_artifact",
parameters: {},
result: evidence.normalized_result,
},
);
expect(() => compareArtifacts(mismatchedSubject, evidence, 0, 10)).toThrow(
/root digest/u,
);
});
});
+145
View File
@@ -0,0 +1,145 @@
import { mkdtemp, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { BinarySession } from "../src/application/BinarySession.js";
import { ArtifactProvider } from "../src/artifacts/ArtifactProvider.js";
import { ARTIFACT_COMPARISON_EXAMPLE } from "../src/contracts/artifactComparisonExample.js";
import { evidenceBundleSchema } from "../src/domain/evidenceBundle.js";
import { parseEvidence } from "../src/domain/evidence.js";
import { createServer } from "../src/server/createServer.js";
import { observed } from "./fixtures/analysisExecution.js";
describe("artifact graph MCP integration", () => {
it("rejects comparison Evidence that is not owned by the session", async () => {
const session = new BinarySession(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const server = createServer(session, session);
const client = new Client({
name: "artifact-ownership-test",
version: "1",
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const result = await client.callTool({
name: "compare_artifacts",
arguments: ARTIFACT_COMPARISON_EXAMPLE,
});
expect(result.isError).toBe(true);
expect(session.exportEvidenceBundle().records).toEqual([]);
} finally {
await Promise.allSettled([
client.close(),
server.close(),
session.close(),
]);
}
});
it("opens archives without Hopper, compares them, and exports linked evidence", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-artifact-mcp-"));
const archive = join(directory, "fixture.ipa");
const changedArchive = join(directory, "changed.ipa");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("Payload/Fixture.app/main.js", new TextReader("main();"));
await writeFile(archive, await writer.close());
const changedWriter = new ZipWriter(new Uint8ArrayWriter());
await changedWriter.add(
"Payload/Fixture.app/main.js",
new TextReader("changed();"),
);
await writeFile(changedArchive, await changedWriter.close());
const session = new BinarySession(new ArtifactProvider());
const server = createServer(session, session);
const client = new Client({ name: "artifact-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: archive },
});
expect(opened.isError).not.toBe(true);
const inventory = await client.callTool({
name: "inventory_artifact",
arguments: {},
});
expect(inventory.isError).not.toBe(true);
const evidence = parseEvidence(inventory.structuredContent);
expect(evidence).toMatchObject({
provider: { id: "rea-artifact-graph" },
subject: { format: "ipa" },
normalized_result: {
manifest: { root_format: "ipa" },
},
});
const openedChanged = await client.callTool({
name: "open_binary",
arguments: { path: changedArchive },
});
expect(openedChanged.isError).not.toBe(true);
const changedInventory = await client.callTool({
name: "inventory_artifact",
arguments: {},
});
const changedEvidence = parseEvidence(changedInventory.structuredContent);
const compared = await client.callTool({
name: "compare_artifacts",
arguments: {
left: evidence,
right: changedEvidence,
unknown_registry_approved: true,
},
});
expect(compared.isError).not.toBe(true);
const comparisonEvidence = parseEvidence(
z.object({ result: z.unknown() }).parse(compared.structuredContent)
.result,
);
expect(comparisonEvidence).toMatchObject({
provider: { id: "rea-artifact-comparison" },
evidence_links: [evidence.evidence_id, changedEvidence.evidence_id],
normalized_result: { status: "changed" },
});
const unknowns = await client.callTool({
name: "list_unknowns",
arguments: { domain: "artifact-comparison" },
});
expect(unknowns.structuredContent).toMatchObject({
result: [expect.objectContaining({ domain: "artifact-comparison" })],
});
const exported = await client.callTool({
name: "export_evidence_bundle",
arguments: {},
});
const envelope = z
.object({ result: evidenceBundleSchema })
.parse(exported.structuredContent);
expect(envelope.result.records).toHaveLength(4);
expect(envelope.result.artifacts).toContainEqual({
digest: { sha256: evidence.subject?.digest.sha256 },
format: "ipa",
architecture: null,
});
} finally {
await Promise.allSettled([
client.close(),
server.close(),
session.close(),
]);
}
});
});
+372
View File
@@ -0,0 +1,372 @@
import {
access,
mkdtemp,
mkdir,
readFile,
readdir,
symlink,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createPackage } from "@electron/asar";
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { describe, expect, it } from "vitest";
import { ArtifactProvider } from "../src/artifacts/ArtifactProvider.js";
import { MachOSliceArtifactReader } from "../src/artifacts/MachOSliceArtifactReader.js";
import { runProviderAnalysis } from "../src/application/DirectAnalysis.js";
import {
ArtifactPathRegistry,
normalizeArtifactPath,
} from "../src/artifacts/ArtifactPaths.js";
import {
artifactExtractionInputSchema,
artifactInventoryInputSchema,
} from "../src/contracts/artifactToolContracts.js";
import type { BinaryTarget } from "../src/domain/binaryTarget.js";
import { parseBinaryTarget } from "../src/domain/binaryTarget.js";
import { parseEvidence } from "../src/domain/evidence.js";
import { ok } from "../src/domain/result.js";
import type { NativeCommandRunner } from "../src/native/CommandRunner.js";
import {
artifactExtractionResultSchema,
artifactInventoryResultSchema,
} from "../src/domain/artifactGraph.js";
describe("artifact graph provider", () => {
it("inventories app trees deterministically without following symlinks", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-artifacts-"));
const app = join(root, "Fixture.app");
await mkdir(join(app, "Contents", "Resources"), { recursive: true });
await mkdir(join(app, "Contents", "MacOS"), { recursive: true });
await mkdir(join(app, "Contents", "Frameworks", "Fixture.framework"), {
recursive: true,
});
const machO = Buffer.from([0xcf, 0xfa, 0xed, 0xfe, 0x0c, 0, 0, 1]);
await writeFile(join(app, "Contents", "MacOS", "Fixture"), machO, {
mode: 0o755,
});
await writeFile(
join(app, "Contents", "Frameworks", "Fixture.framework", "Fixture"),
machO,
);
await writeFile(join(app, "Contents", "Resources", "main.js"), "main();\n");
await writeFile(join(app, "Contents", "Resources", "main.js.map"), "{}\n");
await symlink("/etc/passwd", join(app, "Contents", "Resources", "outside"));
const client = new ArtifactProvider().createClient(
target(app, "directory"),
);
const input = artifactInventoryInputSchema.parse({
node_limit: 500,
occurrence_limit: 500,
edge_limit: 500,
});
const first = await client.execute("inventory_artifact", input);
const second = await client.execute("inventory_artifact", input);
expect(first.ok).toBe(true);
expect(second.ok).toBe(true);
if (!first.ok || !second.ok) return;
const left = artifactInventoryResultSchema.parse(first.value.result);
const right = artifactInventoryResultSchema.parse(second.value.result);
expect(left.manifest).toEqual(right.manifest);
expect(left.nodes.items.map(({ kind }) => kind)).toEqual(
expect.arrayContaining([
"executable",
"framework",
"javascript",
"source-map",
]),
);
expect(
left.occurrences.items.find(({ logical_path: path }) =>
path.endsWith("outside"),
),
).toMatchObject({ artifact_id: null, entry_kind: "symlink" });
const script = left.occurrences.items.find(({ logical_path: path }) =>
path.endsWith("main.js"),
);
const sourceMap = left.occurrences.items.find(({ logical_path: path }) =>
path.endsWith("main.js.map"),
);
expect(left.edges.items).toEqual(
expect.arrayContaining([
expect.objectContaining({
relation: "maps-source",
parent_artifact_id: script?.artifact_id,
child_artifact_id: sourceMap?.artifact_id,
}),
]),
);
});
it("streams ZIP and official ASAR inventories within shared limits", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-containers-"));
const zipPath = join(root, "fixture.apk");
const zipWriter = new ZipWriter(new Uint8ArrayWriter());
await zipWriter.add("assets/index.js", new TextReader("export default 1;"));
await zipWriter.add("lib/arm64-v8a/addon.so", new TextReader("native"));
await writeFile(zipPath, await zipWriter.close());
const parsed = await parseBinaryTarget(zipPath);
expect(parsed.ok && parsed.value.format).toBe("apk");
if (!parsed.ok) return;
const zipResult = await inventory(parsed.value);
expect(zipResult.occurrences.total).toBe(3);
expect(zipResult.nodes.items.map(({ kind }) => kind)).toEqual(
expect.arrayContaining(["javascript", "dynamic-library"]),
);
const cliEvidence = parseEvidence(
await runProviderAnalysis(zipPath, "inventory_artifact", {}),
);
expect(cliEvidence).toMatchObject({
operation: "inventory_artifact",
provider: { id: "rea-artifact-graph" },
subject: { format: "apk" },
});
const source = join(root, "asar-source");
await mkdir(source);
await writeFile(join(source, "main.js"), "console.log('ok');\n");
const asarPath = join(root, "app.asar");
await createPackage(source, asarPath);
const asarResult = await inventory(target(asarPath, "asar"));
expect(asarResult.occurrences.items).toEqual(
expect.arrayContaining([
expect.objectContaining({ logical_path: "main.js" }),
]),
);
});
it("rejects unsafe, colliding, and over-ratio entries", async () => {
expect(() => normalizeArtifactPath("../escape", limits())).toThrow(
/normalized/u,
);
const registry = new ArtifactPathRegistry();
registry.add("A.js", "file");
expect(() => registry.add("a.js", "file")).toThrow(/collision/u);
const root = await mkdtemp(join(tmpdir(), "rea-bomb-"));
const zipPath = join(root, "bomb.zip");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("zeros", new TextReader("0".repeat(100_000)));
await writeFile(zipPath, await writer.close());
const client = new ArtifactProvider().createClient(target(zipPath, "zip"));
const result = await client.execute(
"inventory_artifact",
artifactInventoryInputSchema.parse({ max_compression_ratio: 2 }),
);
expect(result).toMatchObject({
ok: false,
error: { _tag: "ArtifactOperationError", reason: "limit" },
});
});
it("extracts only selected occurrences through an exclusively owned output tree", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-extract-"));
const source = join(root, "source");
await mkdir(join(source, "assets"), { recursive: true });
await writeFile(join(source, "assets", "selected.js"), "selected();\n");
await writeFile(join(source, "assets", "ignored.js"), "ignored();\n");
const targetValue = target(source, "directory");
const graph = await inventory(targetValue);
const selected = graph.occurrences.items.find(
({ logical_path: path }) => path === "assets/selected.js",
);
expect(selected).toBeDefined();
if (selected === undefined) return;
const cancelledOutput = join(root, "cancelled-output");
const controller = new AbortController();
controller.abort();
const cancelled = await new ArtifactProvider()
.createClient(targetValue)
.execute(
"extract_artifact",
artifactExtractionInputSchema.parse({
approved: true,
output_root: cancelledOutput,
occurrence_ids: [selected.occurrence_id],
}),
{ signal: controller.signal },
);
expect(cancelled).toMatchObject({
ok: false,
error: { _tag: "ArtifactOperationError", reason: "cancelled" },
});
await expect(access(cancelledOutput)).rejects.toThrow();
const output = join(root, "output");
const result = await new ArtifactProvider()
.createClient(targetValue)
.execute(
"extract_artifact",
artifactExtractionInputSchema.parse({
approved: true,
output_root: output,
occurrence_ids: [selected.occurrence_id],
}),
);
expect(result.ok).toBe(true);
if (!result.ok) return;
const firstExtraction = artifactExtractionResultSchema.parse(
result.value.result,
);
expect(firstExtraction).toMatchObject({
output_root: "$OUTPUT_ROOT",
containment_verified: true,
artifacts: { total: 1 },
extraction_manifest: { output_root_alias: "$OUTPUT_ROOT" },
});
expect(await readFile(join(output, "assets", "selected.js"), "utf8")).toBe(
"selected();\n",
);
await expect(
access(join(output, "assets", "ignored.js")),
).rejects.toThrow();
const relocatedOutput = join(root, "relocated-output");
const relocated = await new ArtifactProvider()
.createClient(targetValue)
.execute(
"extract_artifact",
artifactExtractionInputSchema.parse({
approved: true,
output_root: relocatedOutput,
occurrence_ids: [selected.occurrence_id],
}),
);
expect(relocated.ok).toBe(true);
if (!relocated.ok) return;
expect(
artifactExtractionResultSchema.parse(relocated.value.result)
.extraction_manifest,
).toEqual(firstExtraction.extraction_manifest);
const second = await new ArtifactProvider()
.createClient(targetValue)
.execute(
"extract_artifact",
artifactExtractionInputSchema.parse({
approved: true,
output_root: output,
occurrence_ids: [selected.occurrence_id],
}),
);
expect(second).toMatchObject({
ok: false,
error: { _tag: "ArtifactOperationError", reason: "path" },
});
expect(await readdir(root)).not.toEqual(
expect.arrayContaining([expect.stringMatching(/^\.output\.rea-/u)]),
);
});
it("paginates wide graphs without changing manifest identity", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-wide-"));
await Promise.all(
Array.from({ length: 520 }, async (_, index) =>
writeFile(
join(root, `file-${String(index).padStart(4, "0")}.txt`),
`${index}`,
),
),
);
const client = new ArtifactProvider().createClient(
target(root, "directory"),
);
const first = await client.execute(
"inventory_artifact",
artifactInventoryInputSchema.parse({ occurrence_limit: 500 }),
);
const secondPage = await client.execute(
"inventory_artifact",
artifactInventoryInputSchema.parse({
occurrence_offset: 500,
occurrence_limit: 500,
}),
);
expect(first.ok && secondPage.ok).toBe(true);
if (!first.ok || !secondPage.ok) return;
const left = artifactInventoryResultSchema.parse(first.value.result);
const right = artifactInventoryResultSchema.parse(secondPage.value.result);
expect(left.manifest).toEqual(right.manifest);
expect(left.occurrences).toMatchObject({ total: 521, next_offset: 500 });
expect(right.occurrences).toMatchObject({
offset: 500,
next_offset: null,
});
});
it("uses bounded native lipo metadata for universal slice ranges", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-slices-"));
const binary = join(root, "fat");
await writeFile(binary, Buffer.from("0123456789abcdef"));
const runner: NativeCommandRunner = {
run: () =>
Promise.resolve(
ok({
tool: "lipo",
executable: "/usr/bin/lipo",
executableSha256: "1".repeat(64),
toolVersion: null,
versionReason: "fixture",
arguments: ["-detailed_info", binary],
stdout:
"architecture x86_64\n cputype 16777223\n cpusubtype 3\n offset 0\n size 8\n align 2^2\narchitecture arm64\n cputype 16777228\n cpusubtype 0\n offset 8\n size 8\n align 2^2\n",
stderr: "",
stdoutBytes: 1,
stderrBytes: 0,
stdoutTruncated: false,
stderrTruncated: false,
exitCode: 0,
signal: null,
}),
),
};
const reader = new MachOSliceArtifactReader(binary, runner);
const entries = [];
for await (const entry of reader.entries()) entries.push(entry);
expect(entries).toHaveLength(2);
const secondEntry = entries[1];
expect(secondEntry).toBeDefined();
if (secondEntry === undefined) return;
expect(secondEntry).toMatchObject({
path: "slices/arm64",
byteOffset: 8,
declaredSize: 8,
});
const chunks: Buffer[] = [];
const stream = await reader.open(secondEntry);
for await (const chunk of stream) chunks.push(Buffer.from(chunk));
expect(Buffer.concat(chunks).toString()).toBe("89abcdef");
expect(reader.provenance()).toEqual([
expect.objectContaining({ tool: "lipo", effects: ["read"] }),
]);
});
});
const inventory = async (targetValue: BinaryTarget) => {
const result = await new ArtifactProvider().createClient(targetValue).execute(
"inventory_artifact",
artifactInventoryInputSchema.parse({
node_limit: 500,
occurrence_limit: 500,
edge_limit: 500,
}),
);
if (!result.ok) throw result.error;
return artifactInventoryResultSchema.parse(result.value.result);
};
const target = (
path: string,
format: BinaryTarget["format"] | "directory",
): BinaryTarget => ({
path,
sourcePath: path,
sha256: "0".repeat(64),
kind: format === "directory" ? "executable" : "archive",
format: format === "directory" ? "mach-o" : format,
loaderArgs: [],
});
const limits = () => ({ maxDepth: 20, maxPathBytes: 4_096 });
+114 -17
View File
@@ -7,7 +7,8 @@ import { BinarySession } from "../src/application/BinarySession.js";
import type { AnalysisClient } from "../src/application/AnalysisProvider.js";
import type { AnalysisProvider } from "../src/application/AnalysisProvider.js";
import { HopperStartError } from "../src/domain/errors.js";
import { err, ok } from "../src/domain/result.js";
import { err } from "../src/domain/result.js";
import { observed as ok } from "./fixtures/analysisExecution.js";
let directory: string | undefined;
afterEach(async () => {
@@ -24,9 +25,12 @@ describe("binary session", () => {
identity: () => ({ id: "fixture", name: "Fixture", version: "1" }),
capabilities: () => [
{
operation: "fixture-analysis",
version: 1,
provider: { id: "fixture", name: "Fixture", version: "1" },
operation: "address_name",
inputContractVersion: 1,
outputContractVersion: 1,
available: true,
reason: null,
pagination: "none",
exhaustive: true,
effects: {
@@ -35,7 +39,13 @@ describe("binary session", () => {
mayShowUi: false,
mayAccessNetwork: false,
mayWriteFilesystem: false,
requiresPrivileges: false,
changesPermissions: false,
requiresRoot: false,
},
limits: {
maxResults: null,
maxPayloadBytes: null,
timeoutMs: null,
},
limitations: [],
},
@@ -50,13 +60,94 @@ describe("binary session", () => {
};
const session = new BinarySession(provider);
expect((await session.open(first)).ok).toBe(true);
expect(await session.execute("fixture_operation", {})).toEqual({
expect(await session.execute("address_name", {})).toEqual({
ok: true,
value: "fixture_operation",
value: {
result: "address_name",
rawResult: "address_name",
provider: {
id: "fixture",
name: "Fixture analysis provider",
version: "1",
},
limitations: [],
locations: [],
subject: null,
},
});
expect(provider.identity().id).toBe("fixture");
expect(provider.capabilities()[0]?.operation).toBe("fixture-analysis");
expect(operations).toEqual(["health", "fixture_operation"]);
expect(provider.capabilities()[0]?.operation).toBe("address_name");
expect(session.status()).toMatchObject({
provider: { id: "fixture", name: "Fixture", version: "1" },
capabilities: [
{
operation: "address_name",
available: true,
reason: null,
effects: {
mutates_artifact: false,
launches_process: false,
},
},
],
});
expect(operations).toEqual(["health", "address_name"]);
await session.close();
});
it("returns typed unavailability without dispatching a partial provider", async () => {
const [first] = await targets();
const operations: string[] = [];
const provider: AnalysisProvider = {
identity: () => ({ id: "partial", name: "Partial", version: "1" }),
capabilities: () => [
{
provider: { id: "partial", name: "Partial", version: "1" },
operation: "address_name",
inputContractVersion: 1,
outputContractVersion: 1,
available: false,
reason: "fixture intentionally omits symbol lookup",
pagination: "none",
exhaustive: false,
effects: {
mutatesArtifact: false,
launchesProcess: false,
mayShowUi: false,
mayAccessNetwork: false,
mayWriteFilesystem: false,
changesPermissions: false,
requiresRoot: false,
},
limits: {
maxResults: null,
maxPayloadBytes: null,
timeoutMs: null,
},
limitations: ["No symbol lookup implementation."],
},
],
createClient: () => ({
execute: (operation) => {
operations.push(operation);
return Promise.resolve(ok(operation));
},
close: () => Promise.resolve(),
}),
};
const session = new BinarySession(provider);
expect((await session.open(first)).ok).toBe(true);
const result = await session.execute("address_name", {});
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toMatchObject({
_tag: "AnalysisCapabilityUnavailableError",
providerId: "partial",
operation: "address_name",
reason: "fixture intentionally omits symbol lookup",
});
}
expect(operations).toEqual(["health"]);
await session.close();
});
@@ -105,7 +196,7 @@ describe("binary session", () => {
it("waits for an active call before closing its client during a switch", async () => {
const [first, second] = await targets();
const active = deferred<ReturnType<typeof ok<null>>>();
const active = deferred<ReturnType<typeof ok>>();
const clients: TestClient[] = [];
const session = new BinarySession(() => {
const value = new TestClient(
@@ -117,7 +208,7 @@ describe("binary session", () => {
return value;
});
await session.open(first);
const call = session.execute("long", {});
const call = session.execute("procedure_pseudo_code", {});
const switching = session.open(second);
await Promise.resolve();
expect(clients[0]?.closed).toBe(0);
@@ -129,7 +220,7 @@ describe("binary session", () => {
it("cancels an open queued behind another transition without creating a client", async () => {
const [first, second] = await targets();
const health = deferred<ReturnType<typeof ok<null>>>();
const health = deferred<ReturnType<typeof ok>>();
let created = 0;
const session = new BinarySession(() => {
created += 1;
@@ -143,21 +234,27 @@ describe("binary session", () => {
await opening;
const result = await queued;
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error._tag).toBe("HopperCancelledError");
if (!result.ok) expect(result.error._tag).toBe("AnalysisCancelledError");
expect(created).toBe(1);
});
it("cancels a call while it waits for a transition", async () => {
const [first] = await targets();
const health = deferred<ReturnType<typeof ok<null>>>();
const health = deferred<ReturnType<typeof ok>>();
const session = new BinarySession(() => new TestClient(health.promise));
const opening = session.open(first);
const controller = new AbortController();
const call = session.execute("overview", {}, { signal: controller.signal });
const call = session.execute(
"binary_overview",
{},
{
signal: controller.signal,
},
);
controller.abort();
const result = await call;
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error._tag).toBe("HopperCancelledError");
if (!result.ok) expect(result.error._tag).toBe("AnalysisCancelledError");
health.resolve(ok(null));
await opening;
});
@@ -211,9 +308,9 @@ const client = (fail = false): AnalysisClient => ({
class TestClient implements AnalysisClient {
closed = 0;
constructor(
readonly pendingHealth?: Promise<ReturnType<typeof ok<null>>>,
readonly pendingHealth?: Promise<ReturnType<typeof ok>>,
readonly failHealth = false,
readonly pendingCall?: Promise<ReturnType<typeof ok<null>>>,
readonly pendingCall?: Promise<ReturnType<typeof ok>>,
) {}
execute(name: string) {
if (name === "health")
+31
View File
@@ -73,6 +73,37 @@ describe("executable header parsing", () => {
});
describe("binary target I/O", () => {
it("classifies ZIP profiles and text artifacts without Hopper", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-artifact-target-"));
const zip = join(directory, "fixture.apk");
const script = join(directory, "bundle.js");
await writeFile(zip, Buffer.from([0x50, 0x4b, 0x05, 0x06, 0, 0, 0, 0]));
await writeFile(script, "export default 1;\n");
const archive = await parseBinaryTarget(zip);
const javascript = await parseBinaryTarget(script);
expect(archive.ok && archive.value).toMatchObject({
kind: "archive",
format: "apk",
loaderArgs: [],
});
expect(javascript.ok && javascript.value).toMatchObject({
kind: "artifact",
format: "javascript",
loaderArgs: [],
});
});
it("does not trust a ZIP-family extension without ZIP magic", async () => {
const directory = await mkdtemp(join(tmpdir(), "rea-fake-archive-"));
const path = join(directory, "fake.zip");
await writeFile(path, "not a zip");
const result = await parseBinaryTarget(path);
expect(result).toMatchObject({
ok: false,
error: { _tag: "BinaryTargetError" },
});
});
it("resolves relative Hopper databases and rejects unknown or unreadable paths", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-target-"));
await writeFile(join(directory, "sample.hop"), "database");
+30 -1
View File
@@ -19,7 +19,10 @@ describe("Hopper bridge truthfulness", () => {
it("does not fabricate non-writable and non-executable segment permissions", () => {
expect(bridgeSource).toContain('"writable": None');
expect(bridgeSource).toContain('"executable": None');
expect(bridgeSource).toContain('"permissions": _unavailable(');
expect(bridgeSource).toContain('"readable": None');
expect(bridgeSource).toContain("permission_limitation = _unavailable(");
expect(bridgeSource).toContain('"permissions": permission_limitation');
expect(bridgeSource).toContain('"provenance": "hopper-public-python-api"');
expect(bridgeSource).not.toContain('"writable": False');
expect(bridgeSource).not.toContain('"executable": False');
});
@@ -51,4 +54,30 @@ describe("Hopper bridge truthfulness", () => {
expect(bridgeSource).toContain('_offset(params, "assembly_offset")');
expect(bridgeSource).toContain('params.get("collection_offset", {})');
});
it("projects opaque Hopper locals into an exact provenance-bearing shape", () => {
expect(bridgeSource).toContain("def _procedure_locals(procedure):");
expect(bridgeSource).toContain('"description": str(local)');
expect(bridgeSource).not.toContain(
"_json_safe(procedure.getLocalVariableList())",
);
});
it("bounds search and makes regex an explicitly constrained opt-in", () => {
expect(bridgeSource).toContain('params.get("mode", "literal")');
expect(bridgeSource).toContain("pattern.casefold()");
expect(bridgeSource).toContain("_validate_regex_node(parsed)");
expect(bridgeSource).toContain(
"Nested regex repetitions are not supported",
);
expect(bridgeSource).toContain("MAX_SEARCH_PATTERN_LENGTH = 256");
expect(bridgeSource).toContain("MAX_SEARCH_VALUE_LENGTH = 4096");
expect(bridgeSource).toContain('"value_truncated"');
});
it("caches sorted search inventories and invalidates them after renames", () => {
expect(bridgeSource).toContain("_search_inventory_cache");
expect(bridgeSource).toContain("tuple(sorted(values.items()");
expect(bridgeSource).toContain("_invalidate_search_inventory(document)");
});
});
+205
View File
@@ -0,0 +1,205 @@
import { describe, expect, it } from "vitest";
import {
bundleComparisonResultSchema,
compareBundles,
} from "../src/domain/bundleComparison.js";
import { createEvidence } from "../src/domain/evidence.js";
import { createEvidenceBundle } from "../src/domain/evidenceBundle.js";
import {
createResidualUnknown,
recordUnknownInputSchema,
updateResidualUnknown,
updateUnknownInputSchema,
} from "../src/domain/residualUnknown.js";
const PROVIDER = { id: "fixture", name: "Fixture", version: "1" } as const;
const evidence = (label: string) =>
createEvidence(undefined, PROVIDER, {
operation: "observe",
parameters: { label },
result: { label },
confidence: "derived",
authority: "analyst-inference",
});
describe("bundle comparison", () => {
it("returns unchanged only for equal canonical bundles", () => {
const first = evidence("first");
const second = evidence("second");
const left = createEvidenceBundle([first, second]);
const right = createEvidenceBundle([second, first]);
const result = compareBundles(left, right, [], 0, 100);
expect(bundleComparisonResultSchema.parse(result)).toMatchObject({
status: "unchanged",
summary: {
records_unchanged: 2,
records_added: 0,
records_removed: 0,
unresolved: 0,
},
changes: { total: 0, next_offset: null },
});
expect(result.left_bundle_sha256).toBe(result.right_bundle_sha256);
});
it("classifies explicit pairs and pages stable membership changes", () => {
const oldRecord = evidence("old");
const newRecord = evidence("new");
const removed = evidence("removed");
const added = evidence("added");
const left = createEvidenceBundle([oldRecord, removed]);
const right = createEvidenceBundle([newRecord, added]);
const pairs = [
{
left_evidence_id: oldRecord.evidence_id,
right_evidence_id: newRecord.evidence_id,
},
];
const first = compareBundles(left, right, pairs, 0, 1);
const repeated = compareBundles(left, right, pairs, 0, 1);
expect(first).toEqual(repeated);
expect(first).toMatchObject({
status: "changed",
summary: {
records_added: 1,
records_removed: 1,
records_changed: 1,
},
changes: { total: 3, next_offset: 1 },
});
expect(
compareBundles(left, right, pairs, 1, 500).changes.items,
).toHaveLength(2);
expect(first.limitations).toContain(
"One-sided membership proves only bundle inclusion or omission, not behavioral absence.",
);
});
it("rejects missing and non-bijective explicit pairs", () => {
const leftRecord = evidence("left");
const rightRecord = evidence("right");
const left = createEvidenceBundle([leftRecord]);
const right = createEvidenceBundle([rightRecord]);
expect(() =>
compareBundles(
left,
right,
[
{
left_evidence_id: evidence("missing").evidence_id,
right_evidence_id: rightRecord.evidence_id,
},
],
0,
100,
),
).toThrow(/missing left evidence/u);
expect(() =>
compareBundles(
left,
right,
[
{
left_evidence_id: leftRecord.evidence_id,
right_evidence_id: rightRecord.evidence_id,
},
{
left_evidence_id: leftRecord.evidence_id,
right_evidence_id: rightRecord.evidence_id,
},
],
0,
100,
),
).toThrow(/one-to-one/u);
expect(() =>
compareBundles(
{ ...left, records: [leftRecord, leftRecord] },
right,
[],
0,
100,
),
).toThrow(/duplicate record IDs/u);
});
it("distinguishes advanced and missing unknown histories from equality", () => {
const mutationOne = evidence("mutation-one");
const initial = createResidualUnknown(
recordUnknownInputSchema.parse({
approved: true,
question: "Which branch remains unexplained?",
severity: "high",
domain: "comparison",
supporting_evidence_ids: [],
contradicting_evidence_ids: [],
required_authority: "shipped-artifact",
required_confidence: "observed",
required_environment: null,
recommended_probes: [],
relationships: [],
}),
mutationOne.evidence_id,
null,
);
const mutationTwo = evidence("mutation-two");
const advanced = updateResidualUnknown(
initial,
updateUnknownInputSchema.parse({
approved: true,
unknown_id: initial.unknown_id,
expected_revision: 1,
status: "investigating",
severity: initial.severity,
supporting_evidence_ids: [],
contradicting_evidence_ids: [],
required_authority: initial.required_authority,
required_confidence: initial.required_confidence,
required_environment: null,
recommended_probes: [],
relationships: [],
resolution: null,
}),
mutationTwo.evidence_id,
);
const initialBundle = createEvidenceBundle([mutationOne], [initial]);
const advancedBundle = createEvidenceBundle(
[mutationOne, mutationTwo],
[initial, advanced],
);
expect(
compareBundles(initialBundle, advancedBundle, [], 0, 100),
).toMatchObject({
status: "changed",
summary: { unknowns_advanced: 1, unresolved: 0 },
changes: {
items: [
expect.objectContaining({
entity: "evidence",
classification: "added",
}),
expect.objectContaining({
entity: "residual_unknown",
classification: "history_advanced",
}),
],
},
});
const absent = createEvidenceBundle([]);
const missing = compareBundles(initialBundle, absent, [], 0, 100);
expect(missing).toMatchObject({
status: "unknown",
summary: { unknowns_removed: 1, unresolved: 1 },
});
expect(missing.changes.items).toContainEqual(
expect.objectContaining({
classification: "removed",
conclusion_kind: "unresolved_branch",
limitations: [
"A missing unknown history does not establish resolution.",
],
}),
);
});
});
+134
View File
@@ -0,0 +1,134 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { BinarySession } from "../src/application/BinarySession.js";
import { createEvidence, parseEvidence } from "../src/domain/evidence.js";
import { createEvidenceBundle } from "../src/domain/evidenceBundle.js";
import { createResidualUnknown } from "../src/domain/residualUnknown.js";
import { createServer } from "../src/server/createServer.js";
import { observed } from "./fixtures/analysisExecution.js";
const sourceEvidence = (label: string) =>
createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
{
operation: "observe",
parameters: { label },
result: { label },
confidence: "observed",
authority: "shipped-artifact",
},
);
describe("bundle comparison MCP integration", () => {
it("rejects unknown histories that are not owned by the session", async () => {
const session = new BinarySession(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const leftRecord = sourceEvidence("left-unowned-unknown");
const rightRecord = sourceEvidence("right-unowned-unknown");
expect(session.recordEvidence(leftRecord).ok).toBe(true);
expect(session.recordEvidence(rightRecord).ok).toBe(true);
const unknown = createResidualUnknown(
{
approved: true,
question: "Unowned history?",
severity: "high",
domain: "bundle-comparison-test",
supporting_evidence_ids: [leftRecord.evidence_id],
contradicting_evidence_ids: [],
required_authority: "shipped-artifact",
required_confidence: "observed",
required_environment: null,
recommended_probes: [],
relationships: [],
},
leftRecord.evidence_id,
null,
);
const server = createServer(session, session);
const client = new Client({ name: "bundle-unknown-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const result = await client.callTool({
name: "compare_bundles",
arguments: {
left: createEvidenceBundle([leftRecord], [unknown]),
right: createEvidenceBundle([rightRecord]),
},
});
expect(result.isError).toBe(true);
expect(session.exportEvidenceBundle()).toMatchObject({
records: [leftRecord, rightRecord].sort((left, right) =>
left.evidence_id.localeCompare(right.evidence_id),
),
unknowns: [],
});
} finally {
await Promise.allSettled([
client.close(),
server.close(),
session.close(),
]);
}
});
it("records a digest-anchored comparison linked to every source record", async () => {
const session = new BinarySession(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const leftRecord = sourceEvidence("left");
const rightRecord = sourceEvidence("right");
expect(session.recordEvidence(leftRecord).ok).toBe(true);
expect(session.recordEvidence(rightRecord).ok).toBe(true);
const server = createServer(session, session);
const client = new Client({ name: "bundle-comparison-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const result = await client.callTool({
name: "compare_bundles",
arguments: {
left: createEvidenceBundle([leftRecord]),
right: createEvidenceBundle([rightRecord]),
record_pairs: [
{
left_evidence_id: leftRecord.evidence_id,
right_evidence_id: rightRecord.evidence_id,
},
],
},
});
expect(result.isError).not.toBe(true);
const evidence = parseEvidence(
z.object({ result: z.unknown() }).parse(result.structuredContent)
.result,
);
expect(evidence).toMatchObject({
provider: { id: "rea-bundle-comparison" },
evidence_links: [
leftRecord.evidence_id,
rightRecord.evidence_id,
].sort(),
normalized_result: { status: "changed" },
});
} finally {
await Promise.allSettled([
client.close(),
server.close(),
session.close(),
]);
}
});
});
+180
View File
@@ -0,0 +1,180 @@
import { describe, expect, it } from "vitest";
import { enhancedInputSchemas } from "../src/contracts/enhancedInputs.js";
import {
buildCallPath,
callPathInputSchema,
callPathResultSchema,
} from "../src/domain/callPath.js";
import { createEvidence, type Evidence } from "../src/domain/evidence.js";
import { functionDossierSchema } from "../src/domain/hopperValues.js";
import { jsonValueSchema } from "../src/domain/jsonValue.js";
const bounded = <Item>(items: readonly Item[], complete = true) => ({
items,
total: complete ? items.length : null,
returned: items.length,
truncated: !complete,
next_offset: null,
});
const observe = (
address: string,
callees: readonly string[],
complete = true,
provider = "rea-workflow",
): Evidence => {
const value = functionDossierSchema.parse({
procedure: {
address,
name: `fn_${address.slice(2)}`,
signature: null,
locals: [],
},
pseudocode: {
text: "",
total_chars: 0,
returned_chars: 0,
truncated: false,
next_offset: null,
},
assembly: bounded([]),
comments: bounded([]),
callers: bounded([]),
callees: bounded(
callees.map((callee) => ({
address: callee,
name: `fn_${callee.slice(2)}`,
})),
complete,
),
incoming_references: bounded([]),
outgoing_references: bounded([]),
referenced_strings: bounded([]),
referenced_names: bounded([]),
basic_blocks: bounded([]),
instruction_scan: { scanned: 0, truncated: false },
});
return createEvidence(
{ path: "/tmp/a", sha256: "a".repeat(64), format: "mach-o" },
{ id: provider, name: provider, version: "1" },
{
operation: "analyze_function",
parameters: enhancedInputSchemas.analyze_function.parse({
procedure: address,
include_assembly: false,
}),
result: jsonValueSchema.parse(value),
confidence: "derived",
authority: "shipped-artifact",
},
);
};
const run = (functions: Evidence[], overrides: Record<string, unknown> = {}) =>
buildCallPath(
callPathInputSchema.parse({
functions,
start: { address: "0x1000" },
goal: { address: "0x4000" },
...overrides,
}),
);
describe("call path reconstruction", () => {
it("returns deterministic shortest-first cited paths", () => {
const result = run([
observe("0x1000", ["0x3000", "0x2000"]),
observe("0x2000", ["0x4000"]),
observe("0x3000", ["0x5000"]),
observe("0x5000", ["0x6000"]),
observe("0x6000", ["0x4000"]),
]);
expect(callPathResultSchema.parse(result)).toEqual(result);
expect(result.status).toBe("found");
expect(result.shortest_hops).toBe(2);
expect(
result.paths.items.map((path) =>
path.nodes.map(({ address }) => address),
),
).toEqual([
["0x1000", "0x2000", "0x4000"],
["0x1000", "0x3000", "0x5000", "0x6000", "0x4000"],
]);
expect(
result.paths.items[0]?.edges.every(
(edge) => edge.evidence_links.length > 0,
),
).toBe(true);
});
it("accepts a direct cited edge without a goal dossier", () => {
const result = run([observe("0x1000", ["0x4000"])]);
expect(result).toMatchObject({ status: "found", shortest_hops: 1 });
expect(result.paths.items[0]?.nodes[1]).toMatchObject({
address: "0x4000",
name: null,
});
});
it("only reports not_found for exhaustive closure", () => {
expect(run([observe("0x1000", []), observe("0x4000", [])]).status).toBe(
"not_found",
);
const unknown = run([observe("0x1000", ["0x2000"])]);
expect(unknown.status).toBe("unknown");
expect(unknown.limitations).toContain(
"No analyze_function Evidence covers reachable function 0x2000",
);
});
it("reports incomplete and depth-bounded absence as unknown", () => {
expect(run([observe("0x1000", [], false)]).status).toBe("unknown");
expect(
run([observe("0x1000", ["0x2000"]), observe("0x2000", [])], {
max_depth: 0,
}).status,
).toBe("unknown");
});
it("truncates deterministically at max_paths and paginates retained paths", () => {
const result = run(
[
observe("0x1000", ["0x2000", "0x3000"]),
observe("0x2000", ["0x4000"]),
observe("0x3000", ["0x4000"]),
],
{ max_paths: 1, offset: 0, limit: 1 },
);
expect(result.status).toBe("truncated");
expect(result.paths).toMatchObject({
total: null,
returned: 1,
truncated: true,
lower_bound: 2,
});
expect(result.paths.items[0]?.nodes[1]?.address).toBe("0x2000");
});
it("normalizes hex addresses and rejects duplicates and mixed providers", () => {
expect(
run([observe("0x001000", [])], {
start: { address: "0X00001000" },
}),
).toMatchObject({ status: "not_found", start: "0x1000" });
expect(() =>
run([observe("0x1000", [])], { start: { address: "1000" } }),
).toThrow();
const one = observe("0x1000", []);
expect(() => run([one, one])).toThrow(/Duplicate/u);
expect(() => run([one, observe("0x2000", [], true, "other")])).toThrow(
/providers/u,
);
});
it("requires an observed start function", () => {
expect(() => run([observe("0x2000", [])])).toThrow(
/supplied for start 0x1000/u,
);
});
});
+214
View File
@@ -0,0 +1,214 @@
import { describe, expect, it } from "vitest";
import {
changedBehaviorResultSchema,
findChangedBehavior,
} from "../src/domain/changedBehavior.js";
import { createEvidence, type Evidence } from "../src/domain/evidence.js";
import type { JsonValue } from "../src/domain/jsonValue.js";
const source = (digit: string): Evidence =>
createEvidence(
{
path: `/tmp/source-${digit}`,
sha256: digit.repeat(64),
format: "file",
},
{ id: "fixture", name: "Fixture", version: "1" },
{ operation: "fixture", parameters: {}, result: { digit } },
);
const left = source("1");
const right = source("2");
const comparison = (
operation: "compare_process_captures" | "compare_artifacts",
result: JsonValue,
): Evidence => {
const process = operation === "compare_process_captures";
return createEvidence(
undefined,
{
id: process ? "rea-process" : "rea-artifact-comparison",
name: process
? "REA deterministic process harness"
: "REA artifact comparison",
version: "1",
},
{
predicateType: process
? "rea.process-comparison/v1"
: "rea.artifact-comparison/v1",
operation,
parameters: {},
result,
confidence: "derived",
authority: "analyst-inference",
evidenceLinks: [left.evidence_id, right.evidence_id],
},
);
};
const processResult = (
overrides: Partial<{
status: "unchanged" | "changed" | "unknown" | "truncated";
terminal: "unchanged" | "changed" | "unknown" | "truncated";
exit: "unchanged" | "changed" | "unknown" | "truncated";
}> = {},
): JsonValue => ({
status: overrides.status ?? "unchanged",
terminal: overrides.terminal ?? "unchanged",
exit: overrides.exit ?? "unchanged",
filesystem: "unchanged",
protocol: "unchanged",
process: "unchanged",
limitations: [],
});
const artifactResult = (
pagination: {
readonly offset?: number;
readonly next_offset?: number | null;
} = {},
nestedLinks: string[] = [left.evidence_id, right.evidence_id],
): JsonValue => ({
status: "changed",
left_manifest_id: `agm_${"3".repeat(64)}`,
right_manifest_id: `agm_${"4".repeat(64)}`,
summary: {
unchanged: 0,
added: 0,
removed: 0,
changed: 1,
unknown: 0,
},
changes: {
items: [
{
classification: "changed",
logical_path: "main.js",
dimensions: ["content"],
left_occurrence_id: `occ_${"5".repeat(64)}`,
right_occurrence_id: `occ_${"6".repeat(64)}`,
left_artifact_id: `art_${"7".repeat(64)}`,
right_artifact_id: `art_${"8".repeat(64)}`,
evidence_links: nestedLinks,
},
],
offset: pagination.offset ?? 0,
limit: 100,
total: 1,
next_offset: pagination.next_offset ?? null,
},
limitations: [],
});
describe("changed behavior", () => {
it("classifies runtime changes as observed and cites both observations", () => {
const evidence = comparison(
"compare_process_captures",
processResult({ status: "changed", terminal: "changed" }),
);
const result = findChangedBehavior([evidence], 0, 100);
expect(changedBehaviorResultSchema.parse(result)).toMatchObject({
behavior_status: "observed_changed",
summary: { observed_changes: 1, static_candidates: 0 },
findings: { total: 1, next_offset: null },
});
expect(result.findings.items[0]).toMatchObject({
scope: "runtime",
dimension: "terminal",
classification: "observed_change",
evidence_links: expect.arrayContaining([
evidence.evidence_id,
left.evidence_id,
right.evidence_id,
]),
});
});
it("keeps static differences as candidates, never runtime observations", () => {
const evidence = comparison("compare_artifacts", artifactResult());
const result = findChangedBehavior([evidence], 0, 100);
expect(result).toMatchObject({
behavior_status: "unknown",
summary: { observed_changes: 0, static_candidates: 1 },
});
expect(result.findings.items[0]).toMatchObject({
scope: "static_candidate",
dimension: "artifact:main.js",
classification: "derived_relationship",
});
expect(result.limitations).toContain(
"Static differences are behavior candidates, not runtime observations.",
);
});
it("lets incomplete runtime evidence dominate observed changes", () => {
const changed = comparison(
"compare_process_captures",
processResult({ status: "changed", terminal: "changed" }),
);
const unknown = comparison(
"compare_process_captures",
processResult({ status: "unknown", exit: "unknown" }),
);
const result = findChangedBehavior([changed, unknown], 0, 1);
expect(result).toMatchObject({
behavior_status: "unknown",
findings: { total: 2, limit: 1, next_offset: 1 },
});
expect(findChangedBehavior([changed, unknown], 0, 1)).toEqual(result);
});
it("requires complete artifact comparison pagination", () => {
const paged = comparison(
"compare_artifacts",
artifactResult({ next_offset: 1 }),
);
expect(() => findChangedBehavior([paged], 0, 100)).toThrow(
/complete artifact comparison pagination/u,
);
});
it("rejects bundles, duplicate comparisons, and malformed exact results", () => {
const valid = comparison("compare_process_captures", processResult());
expect(() => findChangedBehavior([valid, valid], 0, 100)).toThrow(
/duplicate comparison Evidence/u,
);
const bundle = createEvidence(
undefined,
{ id: "rea-bundle-comparison", name: "Bundle", version: "1" },
{
predicateType: "rea.bundle-comparison/v1",
operation: "compare_bundles",
parameters: {},
result: {},
confidence: "derived",
authority: "analyst-inference",
evidenceLinks: [left.evidence_id, right.evidence_id],
},
);
expect(() => findChangedBehavior([bundle], 0, 100)).toThrow(
/requires process, artifact, or function/u,
);
const malformed = comparison("compare_process_captures", {
status: "unchanged",
});
expect(() => findChangedBehavior([malformed], 0, 100)).toThrow();
const contradictory = comparison(
"compare_process_captures",
processResult({ status: "unchanged", terminal: "changed" }),
);
expect(() => findChangedBehavior([contradictory], 0, 100)).toThrow(
/contradicts its dimensions/u,
);
const danglingNested = comparison(
"compare_artifacts",
artifactResult({}, [`ev_${"f".repeat(64)}`, right.evidence_id]),
);
expect(() => findChangedBehavior([danglingNested], 0, 100)).toThrow(
/outside its top-level closure/u,
);
});
});
+49
View File
@@ -0,0 +1,49 @@
import { execFile } from "node:child_process";
import { readFile, writeFile } from "node:fs/promises";
import { promisify } from "node:util";
import { afterEach, describe, expect, it } from "vitest";
const exec = promisify(execFile);
const manifestPath = "metadata/completion-manifest.json";
let original: string | undefined;
afterEach(async () => {
if (original !== undefined) await writeFile(manifestPath, original);
original = undefined;
});
describe("generated completion manifest", () => {
it("is deterministic, current, path-independent, and never promotes unknowns", async () => {
await exec(process.execPath, ["scripts/generate-completion-manifest.mjs"]);
const first = await readFile(manifestPath, "utf8");
await exec(process.execPath, ["scripts/generate-completion-manifest.mjs"]);
expect(await readFile(manifestPath, "utf8")).toBe(first);
await expect(
exec(process.execPath, [
"scripts/generate-completion-manifest.mjs",
"--check",
]),
).resolves.toBeDefined();
expect(first).not.toContain(process.cwd());
const manifest = JSON.parse(first) as {
outcomes: { pass: unknown[]; unsupported: unknown[]; unknown: unknown[] };
};
expect(manifest.outcomes.pass).toEqual([]);
expect(manifest.outcomes.unsupported).toHaveLength(1);
expect(manifest.outcomes.unknown).toHaveLength(1);
});
it("check mode detects manual tampering without rewriting it", async () => {
original = await readFile(manifestPath, "utf8");
const tampered = `${original.trimEnd()} `;
await writeFile(manifestPath, tampered);
await expect(
exec(process.execPath, [
"scripts/generate-completion-manifest.mjs",
"--check",
]),
).rejects.toThrow(/stale or tampered/u);
expect(await readFile(manifestPath, "utf8")).toBe(tampered);
});
});
+126
View File
@@ -0,0 +1,126 @@
import { describe, expect, it } from "vitest";
import { BinarySession } from "../src/application/BinarySession.js";
import { CompositeProvider } from "../src/application/CompositeProvider.js";
import type {
AnalysisOperation,
AnalysisProvider,
CapabilityDescriptor,
ProviderIdentity,
} from "../src/application/AnalysisProvider.js";
import { createAnalysisExecution } from "../src/application/AnalysisProvider.js";
import type { BinaryTarget } from "../src/domain/binaryTarget.js";
import { ok } from "../src/domain/result.js";
const target: BinaryTarget = {
path: "/fixture",
kind: "database",
format: "hopper",
sha256: "0".repeat(64),
loaderArgs: [],
};
describe("composite analysis provider", () => {
it("routes disjoint operations and does not start children during health", async () => {
const hopperCalls: string[] = [];
const nativeCalls: string[] = [];
const hopper = provider("hopper", "address_name", hopperCalls);
const native = provider("native", "analyze_function", nativeCalls);
const composite = new CompositeProvider([hopper, native]);
const client = composite.createClient(target);
expect(await client.execute("health", {})).toEqual({
ok: true,
value: {
result: null,
rawResult: null,
provider: {
id: "composite:hopper+native",
name: "REA composite analysis provider",
version: null,
},
limitations: [],
locations: [],
subject: null,
},
});
expect(hopperCalls).toEqual([]);
expect(nativeCalls).toEqual([]);
expect(await client.execute("address_name", {})).toEqual({
ok: true,
value: createAnalysisExecution("hopper:address_name", hopper.identity()),
});
expect(await client.execute("analyze_function", {})).toEqual({
ok: true,
value: createAnalysisExecution(
"native:analyze_function",
native.identity(),
),
});
expect(hopperCalls).toEqual(["address_name"]);
expect(nativeCalls).toEqual(["analyze_function"]);
});
it("publishes exact operation provenance and rejects ambiguous routes", () => {
const hopper = provider("hopper", "address_name", []);
const native = provider("native", "analyze_function", []);
const session = new BinarySession(new CompositeProvider([hopper, native]));
expect(session.providerIdentity("address_name").id).toBe("hopper");
expect(session.providerIdentity("analyze_function").id).toBe("native");
expect(session.providerIdentity("binary_overview").id).toBe("hopper");
expect(session.providerIdentity().id).toBe("composite:hopper+native");
expect(
() =>
new CompositeProvider([
hopper,
provider("duplicate", "address_name", []),
]),
).toThrow(/Multiple providers declare operation address_name/u);
});
});
const provider = (
id: string,
operation: Exclude<AnalysisOperation, "health">,
calls: string[],
): AnalysisProvider => {
const identity: ProviderIdentity = { id, name: id, version: "1" };
return {
identity: () => identity,
capabilities: () => [capability(identity, operation)],
createClient: () => ({
execute: (called) => {
calls.push(called);
return Promise.resolve(
ok(createAnalysisExecution(`${id}:${called}`, identity)),
);
},
close: () => Promise.resolve(),
}),
};
};
const capability = (
providerIdentity: ProviderIdentity,
operation: Exclude<AnalysisOperation, "health">,
): CapabilityDescriptor => ({
provider: providerIdentity,
operation,
inputContractVersion: 1,
outputContractVersion: 1,
available: true,
reason: null,
pagination: "none",
exhaustive: true,
effects: {
mutatesArtifact: false,
launchesProcess: true,
mayShowUi: false,
mayAccessNetwork: false,
mayWriteFilesystem: false,
changesPermissions: false,
requiresRoot: false,
},
limits: { maxResults: null, maxPayloadBytes: 1_000_000, timeoutMs: 5_000 },
limitations: [],
});
+58
View File
@@ -14,6 +14,14 @@ describe("runtime configuration", () => {
expect(result.value.hopperTargetKind).toBe("executable");
expect(result.value.hopperLoaderArgs).toEqual([]);
expect(result.value.logLevel).toBe("info");
expect(result.value.referenceSourcePolicy).toEqual({
roots: [],
secretPatterns: [],
maxBytes: 16 * 1024 * 1024,
maxEntries: 10_000,
maxDepth: 32,
maxPathBytes: 4_096,
});
}
});
@@ -38,6 +46,22 @@ describe("runtime configuration", () => {
executableRoots: [],
workingRoots: [],
allowedEnvironment: [],
allowExternalNetwork: false,
},
evidenceFilePolicy: {
roots: [],
maxBytes: 64 * 1024 * 1024,
maxDepth: 64,
maxStringLength: 1024 * 1024,
maxNodes: 1_000_000,
},
referenceSourcePolicy: {
roots: [],
secretPatterns: [],
maxBytes: 16 * 1024 * 1024,
maxEntries: 10_000,
maxDepth: 32,
maxPathBytes: 4_096,
},
},
});
@@ -60,4 +84,38 @@ describe("runtime configuration", () => {
expect(configured.ok && configured.value.logLevel).toBe("debug");
expect(parseConfig({ REA_LOG_LEVEL: "verbose" }).ok).toBe(false);
});
it("parses reference source policy roots and secret patterns", () => {
const result = parseConfig({
REA_REFERENCE_ROOTS_JSON: '["/approved", "/srv/reference"]',
REA_REFERENCE_SECRET_PATTERNS_JSON: '["*.env", "*.pem", "secrets/"]',
});
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.value.referenceSourcePolicy).toEqual({
roots: ["/approved", "/srv/reference"],
secretPatterns: ["*.env", "*.pem", "secrets/"],
maxBytes: 16 * 1024 * 1024,
maxEntries: 10_000,
maxDepth: 32,
maxPathBytes: 4_096,
});
}
});
it.each(["not-json", "{}", '["/ok", 1]'])(
"rejects invalid reference source roots: %s",
(encoded) => {
expect(parseConfig({ REA_REFERENCE_ROOTS_JSON: encoded }).ok).toBe(false);
},
);
it.each(["not-json", "{}", '["*.ok", 1]'])(
"rejects invalid reference source secret patterns: %s",
(encoded) => {
expect(
parseConfig({ REA_REFERENCE_SECRET_PATTERNS_JSON: encoded }).ok,
).toBe(false);
},
);
});
+51 -4
View File
@@ -6,6 +6,8 @@ import {
OFFICIAL_TOOL_CONTRACTS,
SESSION_TOOL_CONTRACTS,
} from "../src/contracts/toolContracts.js";
import { NATIVE_TOOL_CONTRACTS } from "../src/contracts/nativeToolContracts.js";
import { ARTIFACT_TOOL_CONTRACTS } from "../src/contracts/artifactToolContracts.js";
import {
enhancedOutputSchemas,
officialOutputSchemas,
@@ -14,8 +16,13 @@ import {
describe("tool contract surface", () => {
it("advertises complete typed schemas and annotations for all analysis tools", () => {
const contracts = [...OFFICIAL_TOOL_CONTRACTS, ...ENHANCED_TOOL_CONTRACTS];
expect(contracts).toHaveLength(43);
const contracts = [
...OFFICIAL_TOOL_CONTRACTS,
...ENHANCED_TOOL_CONTRACTS,
...NATIVE_TOOL_CONTRACTS,
...ARTIFACT_TOOL_CONTRACTS,
];
expect(contracts).toHaveLength(50);
for (const contract of contracts) {
const inputSchema = z.toJSONSchema(contract.inputSchema, {
target: "draft-07",
@@ -29,14 +36,21 @@ describe("tool contract surface", () => {
expect(outputSchema.type).toBe("object");
expect(contract.annotations).toMatchObject({
idempotentHint: true,
openWorldHint: false,
});
expect(contract.annotations.openWorldHint).toBe(false);
expect(typeof contract.annotations.readOnlyHint).toBe("boolean");
expect(typeof contract.annotations.destructiveHint).toBe("boolean");
expect(contract.examples).toHaveLength(1);
for (const example of contract.examples) {
expect(example.title.length).toBeGreaterThan(10);
expect(contract.inputSchema.safeParse(example.input).success).toBe(
true,
);
}
}
});
it("keeps exactly seven additive session contracts", () => {
it("keeps exactly eighteen additive session contracts", () => {
expect(
SESSION_TOOL_CONTRACTS.map(({ name, kind }) => ({ name, kind })),
).toEqual([
@@ -47,7 +61,40 @@ describe("tool contract surface", () => {
{ name: "import_evidence_bundle", kind: "session" },
{ name: "capture_process_scenario", kind: "session" },
{ name: "compare_process_captures", kind: "session" },
{ name: "compare_artifacts", kind: "session" },
{ name: "compare_functions", kind: "session" },
{ name: "compare_bundles", kind: "session" },
{ name: "find_changed_behavior", kind: "session" },
{ name: "build_call_path", kind: "session" },
{ name: "correlate_static_and_runtime", kind: "session" },
{ name: "verify_reconstruction", kind: "session" },
{ name: "list_unknowns", kind: "session" },
{ name: "record_unknown", kind: "session" },
{ name: "update_unknown", kind: "session" },
{ name: "verify_unknown_resolution", kind: "session" },
]);
expect(
SESSION_TOOL_CONTRACTS.find(
({ name }) => name === "capture_process_scenario",
)?.annotations.openWorldHint,
).toBe(true);
});
it("advertises evidence filesystem effects conservatively", () => {
const exported = SESSION_TOOL_CONTRACTS.find(
({ name }) => name === "export_evidence_bundle",
);
const imported = SESSION_TOOL_CONTRACTS.find(
({ name }) => name === "import_evidence_bundle",
);
expect(exported?.annotations).toMatchObject({
readOnlyHint: false,
destructiveHint: true,
});
expect(imported?.annotations).toMatchObject({
readOnlyHint: false,
destructiveHint: false,
});
});
it("publishes a dedicated output schema and agent guidance for every tool", () => {
+1 -1
View File
@@ -1,7 +1,7 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
import { ok } from "../src/domain/result.js";
import { observed as ok } from "./fixtures/analysisExecution.js";
import { createServer } from "../src/server/createServer.js";
const analysis = {
+13 -7
View File
@@ -4,7 +4,7 @@ import { afterEach, describe, expect, it } from "vitest";
import type { AnalysisOperationPort } from "../src/application/AnalysisProvider.js";
import { ENHANCED_TOOL_CONTRACTS } from "../src/contracts/toolContracts.js";
import { ok } from "../src/domain/result.js";
import { observed as ok } from "./fixtures/analysisExecution.js";
import { jsonValueSchema, type JsonValue } from "../src/domain/jsonValue.js";
import { createServer } from "../src/server/createServer.js";
@@ -164,9 +164,9 @@ const jsonResult = (result: CallToolResult): JsonValue => {
typeof structured.data === "object" &&
structured.data !== null &&
!Array.isArray(structured.data) &&
"result" in structured.data
"normalized_result" in structured.data
) {
return structured.data.result ?? null;
return structured.data.normalized_result ?? null;
}
const text = result.content.find((item) => item.type === "text");
if (text?.type !== "text")
@@ -181,7 +181,7 @@ describe("enhanced MCP tools", () => {
it("lists the complete 33 plus 10 surface", async () => {
const client = await connect();
const listed = await client.listTools();
expect(listed.tools).toHaveLength(43);
expect(listed.tools).toHaveLength(50);
expect(
listed.tools
.map(({ name }) => name)
@@ -495,7 +495,7 @@ describe("enhanced MCP tools", () => {
expect(result.isError).toBe(true);
const text = result.content.find((item) => item.type === "text");
expect(text?.type === "text" ? text.text : "").toContain(
"AnalysisProtocolError",
"AnalysisOutputError",
);
});
@@ -505,7 +505,13 @@ describe("enhanced MCP tools", () => {
execute: async (name, arguments_, options) => {
const result = await malformedPort.execute(name, arguments_, options);
if (!result.ok || name !== "analyze_function") return result;
const dossier = result.value as Record<string, JsonValue>;
const dossier = result.value.result;
if (
typeof dossier !== "object" ||
dossier === null ||
Array.isArray(dossier)
)
return result;
return ok({
...dossier,
comments: {
@@ -525,7 +531,7 @@ describe("enhanced MCP tools", () => {
expect(result.isError).toBe(true);
const text = result.content.find((item) => item.type === "text");
expect(text?.type === "text" ? text.text : "").toContain(
"AnalysisProtocolError",
"AnalysisOutputError",
);
});
});
+77
View File
@@ -0,0 +1,77 @@
import { describe, expect, it } from "vitest";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
AnalysisInputError,
AnalysisOutputError,
AnalysisProtocolError,
BinaryTargetError,
ConfigurationError,
EvidenceFileError,
EvidenceIntegrityError,
EvidenceLimitError,
HopperCancelledError,
HopperProcessError,
HopperProtocolError,
HopperRemoteError,
HopperStartError,
HopperTimeoutError,
NoBinaryOpenError,
ProviderAdapterError,
ProviderSelectionError,
projectAnalysisError,
type AnalysisError,
} from "../src/domain/errors.js";
import { ProcessCaptureError } from "../src/application/ProcessHarness.js";
describe("analysis error projection", () => {
it("uses the correct provider-neutral protocol tag", () => {
expect(new AnalysisProtocolError("invalid")._tag).toBe(
"AnalysisProtocolError",
);
});
it("exhaustively projects stable tags without causes or local paths", () => {
const secretCause = new Error("secret-token");
const errors: readonly AnalysisError[] = [
new AnalysisProtocolError("protocol"),
new AnalysisInputError("overview", { cause: secretCause }),
new AnalysisOutputError("overview", "invalid shape", {
cause: secretCause,
}),
new AnalysisCapabilityUnavailableError("fixture", "overview", "absent"),
new AnalysisCancelledError("overview"),
new ProviderSelectionError("overview"),
new ProviderAdapterError("fixture", "overview", { cause: secretCause }),
new ProcessCaptureError("capture refused", { cause: secretCause }),
new EvidenceIntegrityError("integrity", { cause: secretCause }),
new EvidenceLimitError("records", 10),
new EvidenceFileError("read", "outside-root", { cause: secretCause }),
new HopperTimeoutError(100),
new HopperCancelledError(),
new HopperProtocolError("wire", { cause: secretCause }),
new HopperRemoteError(7, "safe"),
new HopperProcessError(1),
new HopperStartError({ cause: secretCause }),
new ConfigurationError("configuration", { cause: secretCause }),
new NoBinaryOpenError(),
new BinaryTargetError("/secret/local/path", "invalid", {
cause: secretCause,
}),
];
const projected = errors.map(projectAnalysisError);
expect(new Set(projected.map(({ tag }) => tag)).size).toBe(errors.length);
expect(projected).toHaveLength(20);
expect(JSON.stringify(projected)).not.toContain("secret-token");
expect(JSON.stringify(projected)).not.toContain("/secret/local/path");
expect(
projected.find(({ tag }) => tag === "HopperTimeoutError"),
).toMatchObject({ details: { timeoutMs: 100 } });
expect(
projected.find(({ tag }) => tag === "ProviderAdapterError"),
).toMatchObject({
details: { providerId: "fixture", operation: "overview" },
});
});
});
+189 -20
View File
@@ -1,4 +1,5 @@
import { describe, expect, it } from "vitest";
import { fc, it } from "@fast-check/vitest";
import { describe, expect } from "vitest";
import { EvidenceLedger } from "../src/application/EvidenceLedger.js";
import type { BinaryTarget } from "../src/domain/binaryTarget.js";
@@ -7,6 +8,8 @@ import {
evidenceSchema,
parseEvidence,
} from "../src/domain/evidence.js";
import { createEvidenceBundle } from "../src/domain/evidenceBundle.js";
import { recordUnknownInputSchema } from "../src/domain/residualUnknown.js";
const TARGET: BinaryTarget = {
path: "/tmp/fixture",
@@ -20,12 +23,55 @@ const TARGET: BinaryTarget = {
const PROVIDER = { id: "fixture", name: "Fixture provider", version: "1" };
describe("analysis evidence", () => {
it.prop([
fc.dictionary(
fc.string({ minLength: 1, maxLength: 12 }),
fc.oneof(fc.string(), fc.integer(), fc.boolean(), fc.constant(null)),
),
])("canonicalizes parameter key order", (parameters) => {
const reversed = Object.fromEntries(Object.entries(parameters).reverse());
const first = createEvidence(TARGET, PROVIDER, {
operation: "health",
parameters,
result: true,
});
const second = createEvidence(TARGET, PROVIDER, {
operation: "health",
parameters: reversed,
result: true,
});
expect(second.evidence_id).toBe(first.evidence_id);
});
it.prop([fc.string({ minLength: 1 }), fc.string({ minLength: 1 })])(
"keeps identity path-independent and provider-sensitive",
(firstPath, secondPath) => {
const first = createEvidence(
{ ...TARGET, path: `/first/${firstPath}/artifact` },
PROVIDER,
{ operation: "health", parameters: {}, result: true },
);
const moved = createEvidence(
{ ...TARGET, path: `/second/${secondPath}/artifact` },
PROVIDER,
{ operation: "health", parameters: {}, result: true },
);
const changedProvider = createEvidence(
{ ...TARGET, path: `/second/${secondPath}/artifact` },
{ ...PROVIDER, id: `${PROVIDER.id}-other` },
{ operation: "health", parameters: {}, result: true },
);
expect(moved.evidence_id).toBe(first.evidence_id);
expect(changedProvider.evidence_id).not.toBe(first.evidence_id);
},
);
it("creates provider-neutral, deterministic Evidence v2", () => {
const observation = {
operation: "procedure_info",
parameters: { document: null, procedure: "0x1000" },
result: { name: "main" },
redactedRawPayload: { token: "<redacted:token>" },
rawResult: { token: "<redacted:token>" },
} as const;
const evidence = createEvidence(TARGET, PROVIDER, observation);
expect(evidenceSchema.parse(evidence)).toEqual(evidence);
@@ -36,27 +82,32 @@ describe("analysis evidence", () => {
subject: { digest: { sha256: "a".repeat(64) } },
confidence: "observed",
authority: "shipped-artifact",
raw_result: { token: "<redacted:token>" },
normalized_result: { name: "main" },
});
expect(evidence.evidence_id).toMatch(/^ev_[a-f0-9]{64}$/u);
expect(evidence.raw_payload_sha256).toMatch(/^[a-f0-9]{64}$/u);
expect(createEvidence(TARGET, PROVIDER, observation)).toEqual(evidence);
});
it("excludes local paths and redacted raw payloads from semantic identity", () => {
it("excludes local paths but includes redacted raw results in identity", () => {
const observation = {
operation: "health",
parameters: {},
result: true,
redactedRawPayload: { pid: 100 },
rawResult: { pid: 100 },
} as const;
const first = createEvidence(TARGET, PROVIDER, observation);
const moved = createEvidence(
{ ...TARGET, path: "/other/renamed-fixture" },
PROVIDER,
{ ...observation, redactedRawPayload: { pid: 200 } },
observation,
);
expect(moved.evidence_id).toBe(first.evidence_id);
expect(moved.raw_payload_sha256).not.toBe(first.raw_payload_sha256);
const changedRaw = createEvidence(TARGET, PROVIDER, {
...observation,
rawResult: { pid: 200 },
});
expect(changedRaw.evidence_id).not.toBe(first.evidence_id);
});
it("rejects semantic tampering", () => {
@@ -65,8 +116,14 @@ describe("analysis evidence", () => {
parameters: {},
result: true,
});
expect(() => parseEvidence({ ...evidence, result: false })).toThrow(
"semantic identifier",
expect(() =>
parseEvidence({ ...evidence, normalized_result: false }),
).toThrow("semantic identifier");
});
it("rejects Evidence v1 with actionable upgrade guidance", () => {
expect(() => parseEvidence({ schema_version: 1 })).toThrow(
"Evidence v1 is not accepted. Produce Evidence v2.",
);
});
@@ -76,37 +133,149 @@ describe("analysis evidence", () => {
parameters: {},
result: true,
});
const ledger = new EvidenceLedger({ maxRecords: 1 });
expect(ledger.record(evidence)).toBe("added");
expect(ledger.record(evidence)).toBe("duplicate");
const ledger = new EvidenceLedger({ maxRecords: 1, maxBytes: 1_000_000 });
expect(ledger.record(evidence)).toEqual({ ok: true, value: "added" });
expect(ledger.record(evidence)).toEqual({ ok: true, value: "duplicate" });
const relocated = createEvidence(
{ ...TARGET, path: "/relocated/different-name" },
PROVIDER,
{ operation: "health", parameters: {}, result: true },
);
expect(relocated.evidence_id).toBe(evidence.evidence_id);
expect(ledger.record(relocated)).toBe("duplicate");
expect(ledger.import({ bundle_version: 1, records: [evidence] })).toBe(0);
expect(ledger.record(relocated)).toEqual({
ok: true,
value: "duplicate",
});
expect(ledger.import(createEvidenceBundle([evidence]))).toEqual({
ok: true,
value: 0,
});
expect(ledger.export().records).toEqual([evidence]);
ledger.clear();
expect(ledger.export().records).toEqual([]);
});
it("rejects duplicate semantic IDs with conflicting raw payload hashes", () => {
const ledger = new EvidenceLedger({ maxRecords: 2 });
it("returns typed record and byte limit failures without eviction", () => {
const first = createEvidence(TARGET, PROVIDER, {
operation: "health",
parameters: {},
result: true,
redactedRawPayload: { pid: 1 },
});
const second = createEvidence(TARGET, PROVIDER, {
operation: "health",
parameters: { changed: true },
result: true,
});
const recordBound = new EvidenceLedger({
maxRecords: 1,
maxBytes: 1_000_000,
});
expect(recordBound.record(first).ok).toBe(true);
expect(recordBound.record(second)).toMatchObject({
ok: false,
error: { _tag: "EvidenceLimitError", limit: "records", maximum: 1 },
});
expect(recordBound.export().records).toEqual([first]);
const byteBound = new EvidenceLedger({ maxRecords: 10, maxBytes: 1 });
expect(byteBound.record(first)).toMatchObject({
ok: false,
error: { _tag: "EvidenceLimitError", limit: "bytes", maximum: 1 },
});
expect(byteBound.export().records).toEqual([]);
});
it("derives byte-stable manifests independent of record insertion order", () => {
const artifactEvidence = createEvidence(TARGET, PROVIDER, {
operation: "health",
parameters: {},
result: true,
redactedRawPayload: { pid: 2 },
});
ledger.record(first);
expect(() => ledger.record(second)).toThrow("Conflicting evidence");
const captureEvidence = createEvidence(
undefined,
{
id: "process",
name: "Process capture",
version: "1",
},
{
predicateType: "rea.process-capture/v1",
operation: "capture_process_scenario",
parameters: {},
result: { exit: 0 },
authority: "controlled-replay",
environment: {
id: "linux-x64",
platform: "linux",
architecture: "x64",
isolation: "process",
},
},
);
const forward = createEvidenceBundle([artifactEvidence, captureEvidence]);
const reverse = createEvidenceBundle([captureEvidence, artifactEvidence]);
expect(JSON.stringify(reverse)).toBe(JSON.stringify(forward));
expect(forward).toMatchObject({
artifacts: [{ digest: { sha256: TARGET.sha256 }, format: "mach-o" }],
providers: [{ id: "fixture" }, { id: "process" }],
environments: [{ id: "linux-x64" }],
scenarios: [{ evidence_id: captureEvidence.evidence_id }],
captures: [{ evidence_id: captureEvidence.evidence_id }],
});
});
it("rejects conflicting duplicate IDs without mutating the ledger", () => {
const ledger = new EvidenceLedger({ maxRecords: 2, maxBytes: 1_000_000 });
const first = createEvidence(TARGET, PROVIDER, {
operation: "health",
parameters: {},
result: true,
rawResult: { pid: 1 },
});
expect(ledger.record(first).ok).toBe(true);
const bundle = createEvidenceBundle([first]);
expect(
ledger.import({
...bundle,
records: [{ ...first, normalized_result: false }],
}),
).toMatchObject({
ok: false,
error: { _tag: "EvidenceIntegrityError" },
});
expect(ledger.export().records).toEqual([first]);
});
it("atomically rejects Evidence plus unknown when the batch exceeds limits", () => {
const ledger = new EvidenceLedger({ maxRecords: 2, maxBytes: 1_000_000 });
const output = createEvidence(undefined, PROVIDER, {
operation: "derived",
parameters: {},
result: { status: "unknown" },
});
const mutation = createEvidence(undefined, PROVIDER, {
predicateType: "rea.residual-unknown-mutation/v1",
operation: "record_unknown",
parameters: {},
result: { action: "record" },
});
const unknown = recordUnknownInputSchema.parse({
approved: true,
question: "What remains unresolved?",
severity: "high",
domain: "atomic-test",
supporting_evidence_ids: [],
contradicting_evidence_ids: [],
required_authority: "shipped-artifact",
required_confidence: "observed",
required_environment: null,
recommended_probes: [],
relationships: [],
});
expect(ledger.recordWithUnknown(output, unknown, mutation)).toMatchObject({
ok: false,
error: { _tag: "EvidenceLimitError" },
});
expect(ledger.export()).toMatchObject({ records: [], unknowns: [] });
});
});
+153
View File
@@ -0,0 +1,153 @@
import {
mkdtemp,
mkdir,
readFile,
rm,
symlink,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
readEvidenceBundle,
writeEvidenceBundle,
} from "../src/application/EvidenceBundleFiles.js";
import { createEvidence } from "../src/domain/evidence.js";
import {
createEvidenceBundle,
serializeEvidenceBundle,
type EvidenceFilePolicy,
} from "../src/domain/evidenceBundle.js";
let directory: string | undefined;
afterEach(async () => {
if (directory !== undefined)
await rm(directory, { recursive: true, force: true });
directory = undefined;
});
const bundle = () =>
createEvidenceBundle([
createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
{ operation: "health", parameters: {}, result: true },
),
]);
const policy = (root: string): EvidenceFilePolicy => ({
roots: [root],
maxBytes: 1024 * 1024,
maxDepth: 64,
maxStringLength: 1024,
maxNodes: 10_000,
});
describe("evidence bundle filesystem adapter", () => {
it("round trips canonical bytes and requires explicit overwrite", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-evidence-"));
const path = join(directory, "bundle.json");
const evidenceBundle = bundle();
const first = await writeEvidenceBundle(
evidenceBundle,
path,
false,
policy(directory),
);
expect(first).toMatchObject({ ok: true, value: { path } });
expect(await readFile(path, "utf8")).toBe(
serializeEvidenceBundle(evidenceBundle),
);
expect(await readEvidenceBundle(path, policy(directory))).toEqual({
ok: true,
value: evidenceBundle,
});
expect(
await writeEvidenceBundle(evidenceBundle, path, false, policy(directory)),
).toMatchObject({
ok: false,
error: { _tag: "EvidenceFileError", reason: "exists" },
});
expect(
await writeEvidenceBundle(evidenceBundle, path, true, policy(directory)),
).toMatchObject({ ok: true });
});
it("rejects traversal and symlink escape from approved roots", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-evidence-"));
const root = join(directory, "approved");
const outside = join(directory, "outside");
await mkdir(root);
await mkdir(outside);
const outsidePath = join(outside, "bundle.json");
await writeFile(outsidePath, serializeEvidenceBundle(bundle()));
const link = join(root, "escaped.json");
await symlink(outsidePath, link);
expect(await readEvidenceBundle(link, policy(root))).toMatchObject({
ok: false,
error: { _tag: "EvidenceFileError", reason: "outside-root" },
});
expect(
await writeEvidenceBundle(bundle(), outsidePath, true, policy(root)),
).toMatchObject({
ok: false,
error: { _tag: "EvidenceFileError", reason: "outside-root" },
});
});
it("rejects malformed, tampered, oversized, and deeply nested input", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-evidence-"));
const malformed = join(directory, "malformed.json");
await writeFile(malformed, "{");
expect(
await readEvidenceBundle(malformed, policy(directory)),
).toMatchObject({
ok: false,
error: { _tag: "EvidenceFileError", reason: "invalid-json" },
});
const tampered = bundle();
const tamperedPath = join(directory, "tampered.json");
await writeFile(
tamperedPath,
JSON.stringify({
...tampered,
records: [{ ...tampered.records[0], normalized_result: "changed" }],
}),
);
expect(
await readEvidenceBundle(tamperedPath, policy(directory)),
).toMatchObject({
ok: false,
error: { _tag: "EvidenceIntegrityError" },
});
const oversized = join(directory, "oversized.json");
await writeFile(oversized, "x".repeat(100));
expect(
await readEvidenceBundle(oversized, {
...policy(directory),
maxBytes: 10,
}),
).toMatchObject({
ok: false,
error: { _tag: "EvidenceFileError", reason: "too-large" },
});
const deep = join(directory, "deep.json");
await writeFile(deep, JSON.stringify({ one: { two: { three: null } } }));
expect(
await readEvidenceBundle(deep, {
...policy(directory),
maxDepth: 1,
}),
).toMatchObject({
ok: false,
error: { _tag: "EvidenceFileError", reason: "too-large" },
});
});
});
+12
View File
@@ -0,0 +1,12 @@
import { createAnalysisExecution } from "../../src/application/AnalysisProvider.js";
import { ok } from "../../src/domain/result.js";
const FIXTURE_PROVIDER = {
id: "fixture",
name: "Fixture analysis provider",
version: "1",
} as const;
/** Wrap fixture output in the same atomic provider envelope as production. */
export const observed = (value: unknown) =>
ok(createAnalysisExecution(value, FIXTURE_PROVIDER));
+6 -2
View File
@@ -1,6 +1,6 @@
import { createServer } from "node:net";
const [socketPath, token] = process.argv.slice(2);
const [socketPath, token, runId] = process.argv.slice(2);
const server = createServer((socket) => {
socket.on("error", () => undefined);
socket.setEncoding("utf8");
@@ -24,7 +24,11 @@ const server = createServer((socket) => {
send(
{
id: request.id,
result: { name: "REA Hopper bridge", version: "1.0.0" },
result: {
name: "REA Hopper bridge",
version: "1.0.0",
run_id: runId,
},
},
true,
);
+3 -2
View File
@@ -16,11 +16,12 @@ if (
process.exit(2);
}
const source = readFileSync(process.argv[bootstrapIndex], "utf8");
const [socketLine, tokenLine] = source.split("\n");
const [socketLine, tokenLine, runIdLine] = source.split("\n");
const socketPath = JSON.parse(socketLine.slice(socketLine.indexOf("=") + 1));
const token = JSON.parse(tokenLine.slice(tokenLine.indexOf("=") + 1));
const runId = JSON.parse(runIdLine.slice(runIdLine.indexOf("=") + 1));
const bridge = fileURLToPath(new URL("./fakeHopper.mjs", import.meta.url));
const child = spawn(process.execPath, [bridge, socketPath, token], {
const child = spawn(process.execPath, [bridge, socketPath, token, runId], {
stdio: "ignore",
});
child.on("exit", (code) => process.exit(code ?? 0));
+10
View File
@@ -0,0 +1,10 @@
Executable=/Applications/Fixture.app/Contents/MacOS/Fixture
Identifier=com.example.fixture
Format=app bundle with Mach-O thin (arm64)
CodeDirectory v=20500 size=500 flags=0x10000(runtime) hashes=10+7 location=embedded
Hash choices=sha256
CDHash=abcdef0123456789
Signature size=9000
Authority=Developer ID Application: Example
TeamIdentifier=TEAM12345
Timestamp=Jul 12, 2026 at 12:00:00
+2
View File
@@ -0,0 +1,2 @@
Test.foo() -> ()
plain_symbol
+3
View File
@@ -0,0 +1,3 @@
exports:
0x100001000 _main
0x100001080 _$s4Test3fooyyF
+3
View File
@@ -0,0 +1,3 @@
imports:
0x100001100 libSystem.B.dylib _malloc
0x100001108 libobjc.A.dylib _objc_msgSend weak
+3
View File
@@ -0,0 +1,3 @@
<?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>com.apple.security.app-sandbox</key><true/></dict></plist>
+15
View File
@@ -0,0 +1,15 @@
Fat header in: fixture
fat_magic 0xcafebabe
nfat_arch 2
architecture x86_64
cputype 16777223
cpusubtype 3
offset 16384
size 4096
align 2^14 (16384)
architecture arm64
cputype 16777228
cpusubtype 0
offset 32768
size 8192
align 2^14 (16384)
+1
View File
@@ -0,0 +1 @@
Non-fat file: fixture is architecture: arm64
+49
View File
@@ -0,0 +1,49 @@
fixture:
Mach header
magic cputype cpusubtype caps filetype ncmds sizeofcmds flags
0xfeedfacf 16777228 0 0x00 EXECUTE 4 512 NOUNDEFS DYLDLINK
Load command 0
cmd LC_SEGMENT_64
cmdsize 152
segname __TEXT
vmaddr 0x100000000
vmsize 0x2000
fileoff 0
filesize 8192
maxprot 0x5
initprot 0x5
nsects 1
flags 0x0
Section
sectname __text
segname __TEXT
addr 0x100001000
size 0x100
offset 4096
align 4
flags 0x80000400
Load command 1
cmd LC_UUID
cmdsize 24
uuid 01234567-89AB-CDEF-0123-456789ABCDEF
Load command 2
cmd LC_MAIN
cmdsize 24
entryoff 4096
stacksize 0
Load command 3
cmd LC_BUILD_VERSION
cmdsize 32
platform MACOS
minos 13.0
sdk 14.2
ntools 1
tool LD
version 1000.0
Load command 4
cmd LC_LOAD_DYLIB
cmdsize 64
name /usr/lib/libSystem.B.dylib (offset 24)
time stamp 2 Thu Jan 1 00:00:02 1970
current version 1319.0.0
compatibility version 1.0.0
+7
View File
@@ -0,0 +1,7 @@
{
"CFBundleIdentifier": "com.example.fixture",
"CFBundleExecutable": "Fixture",
"CFBundleName": "Fixture",
"CFBundleVersion": "42",
"CFBundleShortVersionString": "1.2.3"
}
+46
View File
@@ -0,0 +1,46 @@
import { spawn } from "node:child_process";
const mode = process.argv[2];
if (mode === "interactive") {
process.stdin.setRawMode?.(true);
process.stdin.resume();
process.stdout.write("prompt> ");
process.on("SIGWINCH", () => {
process.stdout.write(
`resize:${String(process.stdout.columns)}x${String(process.stdout.rows)}\n`,
);
});
process.on("SIGINT", () => {
process.stdout.write("signal:SIGINT\n");
process.exit(0);
});
process.stdin.on("data", (value) => {
process.stdout.write(`input:${value.toString()} unicode:雪\n`);
});
} else if (mode === "partial") {
process.stdout.write("partial-");
setTimeout(() => {
process.stdout.write("frame\n");
process.exit(0);
}, 25);
} else if (mode === "tree-child") {
spawn(process.execPath, [process.argv[1], "tree-grandchild"], {
stdio: "ignore",
});
setInterval(() => undefined, 1_000);
} else if (mode === "tree-grandchild") {
setInterval(() => undefined, 1_000);
} else if (mode === "tree") {
spawn(process.execPath, [process.argv[1], "tree-child"], { stdio: "ignore" });
process.stdout.write("tree-ready\n");
setInterval(() => undefined, 1_000);
} else if (mode === "crash") {
process.stderr.write("intentional-crash\n");
process.exit(23);
} else if (mode === "hang") {
setInterval(() => undefined, 1_000);
} else {
process.stderr.write("unknown fixture mode\n");
process.exit(2);
}
+205
View File
@@ -0,0 +1,205 @@
import { describe, expect, it } from "vitest";
import { FUNCTION_COMPARISON_EXAMPLE } from "../src/contracts/functionComparisonExample.js";
import { enhancedInputSchemas } from "../src/contracts/enhancedInputs.js";
import {
compareFunctions,
functionComparisonResultSchema,
} from "../src/domain/functionComparison.js";
import { createEvidence, type Evidence } from "../src/domain/evidence.js";
import { functionDossierSchema } from "../src/domain/hopperValues.js";
import { jsonValueSchema } from "../src/domain/jsonValue.js";
const bounded = <Item>(items: readonly Item[]) => ({
items,
total: items.length,
returned: items.length,
truncated: false,
next_offset: null,
});
const dossier = (
text: string,
base: "0x1000" | "0x2000",
successors: readonly string[] = [],
) =>
functionDossierSchema.parse({
procedure: {
address: base,
name: "main",
signature: "int main(void)",
locals: [],
},
pseudocode: {
text,
total_chars: [...text].length,
returned_chars: [...text].length,
truncated: false,
next_offset: null,
},
assembly: bounded(["ret"]),
comments: bounded([]),
callers: bounded([]),
callees: bounded([]),
incoming_references: bounded([]),
outgoing_references: bounded([]),
referenced_strings: bounded([]),
referenced_names: bounded([]),
basic_blocks: bounded([
{
start: base,
end: base === "0x1000" ? "0x1001" : "0x2001",
successors,
},
]),
instruction_scan: { scanned: 1, truncated: false },
});
const observe = (
digit: string,
value: ReturnType<typeof dossier>,
providerId = "rea-workflow",
): Evidence =>
createEvidence(
{
path: `/tmp/function-${digit}`,
sha256: digit.repeat(64),
format: "mach-o",
},
{ id: providerId, name: providerId, version: "1" },
{
operation: "analyze_function",
parameters: enhancedInputSchemas.analyze_function.parse({
procedure: "main",
include_assembly: true,
}),
result: jsonValueSchema.parse(value),
confidence: "derived",
authority: "shipped-artifact",
},
);
describe("function comparison", () => {
it("preserves observed text changes while unavailable facets stay unknown", () => {
const result = compareFunctions(
FUNCTION_COMPARISON_EXAMPLE.left,
FUNCTION_COMPARISON_EXAMPLE.right,
0,
100,
);
expect(functionComparisonResultSchema.parse(result)).toMatchObject({
status: "unknown",
function_match: { status: "matched", method: "symbol" },
});
expect(result.dimensions).toEqual(
expect.arrayContaining([
expect.objectContaining({ dimension: "pseudocode", status: "changed" }),
expect.objectContaining({ dimension: "assembly", status: "unknown" }),
expect.objectContaining({
dimension: "references",
status: "unchanged",
}),
]),
);
for (const dimension of result.dimensions)
expect(dimension.evidence_links).toEqual([
FUNCTION_COMPARISON_EXAMPLE.left.evidence_id,
FUNCTION_COMPARISON_EXAMPLE.right.evidence_id,
]);
});
it("normalizes CFG relocation but preserves changed edges and constants", () => {
const left = observe("2", dossier("return 0x10;", "0x1000"));
const relocated = observe("3", dossier("return 0x10;", "0x2000"));
const same = compareFunctions(left, relocated, 0, 100);
expect(
same.dimensions.find(({ dimension }) => dimension === "cfg"),
).toMatchObject({
status: "unchanged",
});
expect(
same.dimensions.find(({ dimension }) => dimension === "pseudocode"),
).toMatchObject({ status: "unchanged" });
const changed = observe("4", dossier("return 0x20;", "0x2000", ["0x2000"]));
const comparison = compareFunctions(left, changed, 0, 100);
expect(
comparison.dimensions.find(({ dimension }) => dimension === "cfg"),
).toMatchObject({ status: "changed" });
expect(
comparison.dimensions.find(({ dimension }) => dimension === "pseudocode"),
).toMatchObject({ status: "changed" });
});
it("treats provider-specific text as unknown and validates Evidence", () => {
const left = observe("5", dossier("return 0;", "0x1000"), "provider-a");
const right = observe("6", dossier("return 1;", "0x2000"), "provider-b");
const comparison = compareFunctions(left, right, 0, 1);
expect(
comparison.dimensions.find(({ dimension }) => dimension === "pseudocode"),
).toMatchObject({ status: "unknown" });
expect(comparison.changes).toMatchObject({ limit: 1, next_offset: 1 });
expect(() =>
compareFunctions({ ...left, operation: "binary_overview" }, right, 0, 10),
).toThrow(/identifier/u);
});
it("reports fully observed identical dossiers as unchanged", () => {
const left = observe("7", dossier("return 0;\n", "0x1000"));
const right = observe("8", dossier("return 0;\n", "0x2000"));
const comparison = compareFunctions(left, right, 0, 100);
expect(comparison.status).toBe("unchanged");
expect(
comparison.dimensions.every(({ status }) => status === "unchanged"),
).toBe(true);
});
it("does not promote address-derived names through equal signatures", () => {
const autoDossier = (base: "0x1000" | "0x2000") =>
functionDossierSchema.parse({
...dossier("return 0;", base),
procedure: {
address: base,
name: "sub_1000",
signature: "int helper(void)",
locals: [],
},
});
const comparison = compareFunctions(
observe("9", autoDossier("0x1000")),
observe("a", autoDossier("0x2000")),
0,
100,
);
expect(comparison.function_match.status).toBe("ambiguous");
expect(
comparison.dimensions.find(({ dimension }) => dimension === "identity"),
).toMatchObject({ status: "unknown" });
expect(comparison.status).toBe("unknown");
});
it("rejects invalid CFG normalization and preserves newline differences", () => {
const leftDossier = dossier("line\r\n", "0x1000");
const invalidCfg = functionDossierSchema.parse({
...dossier("line\n", "0x2000"),
basic_blocks: bounded([
{ start: "0x2000", end: "0x2001", successors: [] },
{ start: "0x2000", end: "0x2002", successors: [] },
]),
});
const comparison = compareFunctions(
observe("b", leftDossier),
observe("c", invalidCfg),
0,
100,
);
expect(
comparison.dimensions.find(({ dimension }) => dimension === "cfg"),
).toMatchObject({ status: "unknown" });
const pseudocode = comparison.dimensions.find(
({ dimension }) => dimension === "pseudocode",
);
expect(pseudocode).toMatchObject({ status: "changed" });
expect(pseudocode?.left_digest).not.toBe(pseudocode?.right_digest);
});
});
+100
View File
@@ -0,0 +1,100 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { BinarySession } from "../src/application/BinarySession.js";
import { FUNCTION_COMPARISON_EXAMPLE } from "../src/contracts/functionComparisonExample.js";
import { parseEvidence } from "../src/domain/evidence.js";
import { createServer } from "../src/server/createServer.js";
import { observed } from "./fixtures/analysisExecution.js";
describe("function comparison MCP integration", () => {
it("records linked comparison Evidence and an approved residual unknown", async () => {
const session = new BinarySession(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
expect(session.recordEvidence(FUNCTION_COMPARISON_EXAMPLE.left).ok).toBe(
true,
);
expect(session.recordEvidence(FUNCTION_COMPARISON_EXAMPLE.right).ok).toBe(
true,
);
const server = createServer(session, session);
const client = new Client({
name: "function-comparison-test",
version: "1",
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const result = await client.callTool({
name: "compare_functions",
arguments: {
left: FUNCTION_COMPARISON_EXAMPLE.left,
right: FUNCTION_COMPARISON_EXAMPLE.right,
unknown_registry_approved: true,
},
});
expect(result.isError).not.toBe(true);
const evidence = parseEvidence(
z.object({ result: z.unknown() }).parse(result.structuredContent)
.result,
);
expect(evidence).toMatchObject({
provider: { id: "rea-function-comparison" },
evidence_links: [
FUNCTION_COMPARISON_EXAMPLE.left.evidence_id,
FUNCTION_COMPARISON_EXAMPLE.right.evidence_id,
],
});
const unknowns = await client.callTool({
name: "list_unknowns",
arguments: { domain: "function-comparison" },
});
expect(unknowns.structuredContent).toMatchObject({
result: [expect.objectContaining({ domain: "function-comparison" })],
});
} finally {
await Promise.allSettled([
client.close(),
server.close(),
session.close(),
]);
}
});
it("rejects dangling Evidence links before recording output", async () => {
const session = new BinarySession(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const server = createServer(session, session);
const client = new Client({ name: "function-link-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const result = await client.callTool({
name: "compare_functions",
arguments: {
left: FUNCTION_COMPARISON_EXAMPLE.left,
right: FUNCTION_COMPARISON_EXAMPLE.right,
},
});
expect(result.isError).toBe(true);
expect(session.exportEvidenceBundle().records).toEqual([]);
} finally {
await Promise.allSettled([
client.close(),
server.close(),
session.close(),
]);
}
});
});
+1
View File
@@ -30,6 +30,7 @@ class FixtureLauncher implements BridgeLauncher {
fixturePath,
session.socketPath,
this.tokenOverride ?? session.token,
session.runId,
],
{
stdio: ["ignore", "ignore", "pipe"],
+23 -2
View File
@@ -33,8 +33,29 @@ describe("Hopper boundary values", () => {
value: ["0x3"],
});
expect(
parseSegments([{ name: "__TEXT", start: "0x1", end: "0x2" }]).ok,
).toBe(true);
parseSegments([
{
name: "__TEXT",
start: "0x1",
end: "0x2",
readable: true,
writable: false,
executable: null,
},
]),
).toEqual({
ok: true,
value: [
{
name: "__TEXT",
start: "0x1",
end: "0x2",
readable: true,
writable: false,
executable: null,
},
],
});
expect(parseDocuments(["fixture"])).toEqual({
ok: true,
value: ["fixture"],
@@ -20,6 +20,7 @@ describe("configuration parsing integration", () => {
HOPPER_TARGET_PATH: "/usr/bin/true",
HOPPER_TARGET_KIND: "executable",
HOPPER_LOADER_ARGS_JSON: '["-l","Mach-O","--aarch64"]',
REA_EVIDENCE_ROOTS_JSON: '["/tmp/evidence"]',
});
expect(result.ok).toBe(true);
if (!result.ok) throw new Error("unreachable");
@@ -30,6 +31,7 @@ describe("configuration parsing integration", () => {
"Mach-O",
"--aarch64",
]);
expect(result.value.evidenceFilePolicy.roots).toEqual(["/tmp/evidence"]);
});
it("rejects target kind values outside the enum", () => {
+202 -10
View File
@@ -7,9 +7,18 @@ import type {
AnalysisClient,
AnalysisOperationPort,
} from "../../src/application/AnalysisProvider.js";
import { HopperRemoteError } from "../../src/domain/errors.js";
import { err, ok } from "../../src/domain/result.js";
import {
AnalysisCapabilityUnavailableError,
HopperRemoteError,
} from "../../src/domain/errors.js";
import { err } from "../../src/domain/result.js";
import { observed as ok } from "../fixtures/analysisExecution.js";
import { createServer } from "../../src/server/createServer.js";
import { createEvidence } from "../../src/domain/evidence.js";
import { processCaptureSchema } from "../../src/domain/processCapture.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../src/contracts/processCaptureExample.js";
import { jsonValueSchema } from "../../src/domain/jsonValue.js";
import { PROCESS_PROVIDER } from "../../src/server/sessionToolPolicies.js";
const resources: Array<{ close(): Promise<void> }> = [];
@@ -87,8 +96,8 @@ describe("full MCP integration with multi-tool sequences", () => {
expect(structured(listResult)).toMatchObject({
subject: null,
operation: "list_procedures",
provider: { id: "unidentified", version: null },
result: {
provider: { id: "fixture", version: "1" },
normalized_result: {
items: [
{ address: "0x1000", value: "main" },
{ address: "0x2000", value: "helper" },
@@ -105,7 +114,7 @@ describe("full MCP integration with multi-tool sequences", () => {
expect(structured(decompileResult)).toMatchObject({
operation: "procedure_pseudo_code",
parameters: { document: null, procedure: "0x1000" },
result: "pseudo for 0x1000",
normalized_result: "pseudo for 0x1000",
});
const xrefResult = await client.callTool({
@@ -114,11 +123,11 @@ describe("full MCP integration with multi-tool sequences", () => {
});
expect(structured(xrefResult)).toMatchObject({
operation: "xrefs",
result: ["0x1000"],
normalized_result: ["0x1000"],
});
});
it("preserves the complete 50-tool inventory with a session", async () => {
it("preserves the complete 68-tool inventory with a session", async () => {
const session = new BinarySession(
(_path) =>
({
@@ -141,7 +150,7 @@ describe("full MCP integration with multi-tool sequences", () => {
await client.connect(clientTransport);
const listed = await client.listTools();
expect(listed.tools).toHaveLength(50);
expect(listed.tools).toHaveLength(68);
const names = listed.tools.map((t) => t.name);
expect(names).toContain("open_binary");
expect(names).toContain("close_binary");
@@ -150,12 +159,195 @@ describe("full MCP integration with multi-tool sequences", () => {
expect(names).toContain("batch_decompile");
});
it("preserves the 43-tool inventory without a session", async () => {
it("records approved trace truncation as a deduplicated residual unknown", async () => {
const analysis: AnalysisOperationPort = {
execute: () =>
Promise.resolve(
ok({
items: [],
offset: 0,
limit: 500,
total: 0,
next_offset: null,
has_more: false,
}),
),
};
const session = new BinarySession(
() =>
({
execute: () => Promise.resolve(ok(null)),
close: () => Promise.resolve(),
}) satisfies AnalysisClient,
);
const server = createServer(analysis, session);
const client = new Client({ name: "unknown-workflow", version: "1.0.0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server);
await server.connect(serverTransport);
await client.connect(clientTransport);
for (let attempt = 0; attempt < 2; attempt += 1) {
const traced = await client.callTool({
name: "trace_feature",
arguments: {
query: "license",
max_operations: 1,
unknown_registry_approved: true,
},
});
expect(traced.isError).not.toBe(true);
}
const listed = structured(
await client.callTool({ name: "list_unknowns", arguments: {} }),
);
expect(listed).toMatchObject({
result: [
{
status: "open",
domain: "control-flow",
question: "Investigation reached the operation budget.",
},
],
});
});
it("records approved typed capability unavailability without forwarding the flag", async () => {
const received: Array<Readonly<Record<string, unknown>>> = [];
const analysis: AnalysisOperationPort = {
execute: (name, arguments_) => {
received.push(arguments_);
return Promise.resolve(
err(
new AnalysisCapabilityUnavailableError(
"partial",
name,
"Decompiler is not installed.",
),
),
);
},
};
const session = new BinarySession(
() =>
({
execute: () => Promise.resolve(ok(null)),
close: () => Promise.resolve(),
}) satisfies AnalysisClient,
);
const server = createServer(analysis, session);
const client = new Client({ name: "unavailable-unknown", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server);
await server.connect(serverTransport);
await client.connect(clientTransport);
const unavailable = await client.callTool({
name: "procedure_pseudo_code",
arguments: {
procedure: "main",
unknown_registry_approved: true,
},
});
expect(unavailable.isError).toBe(true);
expect(received[0]).not.toHaveProperty("unknown_registry_approved");
expect(
structured(
await client.callTool({ name: "list_unknowns", arguments: {} }),
),
).toMatchObject({
result: [
{
domain: "provider-capability",
question:
"procedure_pseudo_code is unavailable: Decompiler is not installed.",
},
],
});
});
it("records approved capture disagreement as a contradicted unknown", async () => {
const session = new BinarySession(
() =>
({
execute: () => Promise.resolve(ok(null)),
close: () => Promise.resolve(),
}) satisfies AnalysisClient,
);
const left = processCaptureSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE);
const right = processCaptureSchema.parse({
...EMPTY_PROCESS_CAPTURE_EXAMPLE,
exit: { code: 1, signal: null, reason: "exited" },
});
const captureEvidence = (capture: typeof left) =>
createEvidence(undefined, PROCESS_PROVIDER, {
predicateType: "rea.process-capture/v2",
operation: "capture_process_scenario",
parameters: {},
result: jsonValueSchema.parse(capture),
confidence: "observed",
authority: "controlled-replay",
});
const leftEvidence = captureEvidence(left);
const rightEvidence = captureEvidence(right);
expect(session.recordEvidence(leftEvidence).ok).toBe(true);
expect(session.recordEvidence(rightEvidence).ok).toBe(true);
const server = createServer(
{ execute: () => Promise.resolve(ok(null)) },
session,
);
const client = new Client({ name: "comparison-unknown", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server);
await server.connect(serverTransport);
await client.connect(clientTransport);
const mismatched = await client.callTool({
name: "compare_process_captures",
arguments: {
left_evidence_id: leftEvidence.evidence_id,
left: right,
right_evidence_id: rightEvidence.evidence_id,
right,
},
});
expect(mismatched.isError).toBe(true);
const compared = await client.callTool({
name: "compare_process_captures",
arguments: {
left_evidence_id: leftEvidence.evidence_id,
left,
right_evidence_id: rightEvidence.evidence_id,
right,
unknown_registry_approved: true,
},
});
expect(compared.isError).not.toBe(true);
expect(
structured(
await client.callTool({ name: "list_unknowns", arguments: {} }),
),
).toMatchObject({
result: [
{
status: "contradicted",
domain: "process-comparison",
contradicting_evidence_ids: [rightEvidence.evidence_id],
},
],
});
});
it("preserves the 50-tool inventory without a session", async () => {
const client = await connect({
execute: () => Promise.resolve(ok(null)),
});
const listed = await client.listTools();
expect(listed.tools).toHaveLength(43);
expect(listed.tools).toHaveLength(50);
const names = listed.tools.map((t) => t.name);
expect(names).toContain("binary_overview");
expect(names).toContain("batch_decompile");
+217
View File
@@ -0,0 +1,217 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { BinarySession } from "../src/application/BinarySession.js";
import { FUNCTION_COMPARISON_EXAMPLE } from "../src/contracts/functionComparisonExample.js";
import { INVESTIGATION_EXAMPLES } from "../src/contracts/investigationExamples.js";
import {
FUNCTION_COMPARISON_EVIDENCE,
PROCESS_CAPTURE_RECONSTRUCTION,
PROCESS_CAPTURE_REFERENCE,
PROCESS_COMPARISON_EVIDENCE,
} from "../src/contracts/investigationExamples.js";
import { parseEvidence } from "../src/domain/evidence.js";
import { createServer } from "../src/server/createServer.js";
import { observed } from "./fixtures/analysisExecution.js";
describe("investigation MCP workflows", () => {
it("aggregates comparison Evidence and records an approved runtime gap", async () => {
const { session, server, client } = await connected();
const comparison =
INVESTIGATION_EXAMPLES.find_changed_behavior.comparisons[0];
if (comparison === undefined) throw new Error("missing comparison fixture");
for (const evidence of [
FUNCTION_COMPARISON_EXAMPLE.left,
FUNCTION_COMPARISON_EXAMPLE.right,
comparison,
])
expect(session.recordEvidence(evidence).ok).toBe(true);
try {
const response = await client.callTool({
name: "find_changed_behavior",
arguments: {
comparisons: [comparison],
unknown_registry_approved: true,
},
});
expect(response.isError).not.toBe(true);
const evidence = parseEvidence(
z.object({ result: z.unknown() }).parse(response.structuredContent)
.result,
);
expect(evidence).toMatchObject({
provider: { id: "rea-changed-behavior" },
normalized_result: { behavior_status: "unknown" },
});
expect(session.listUnknowns({ domain: "changed-behavior" })).toHaveLength(
1,
);
} finally {
await close(session, server, client);
}
});
it("builds a zero-hop exact-address path with dossier citations", async () => {
const { session, server, client } = await connected();
expect(session.recordEvidence(FUNCTION_COMPARISON_EXAMPLE.left).ok).toBe(
true,
);
try {
const response = await client.callTool({
name: "build_call_path",
arguments: INVESTIGATION_EXAMPLES.build_call_path,
});
expect(response.isError).not.toBe(true);
const evidence = parseEvidence(
z.object({ result: z.unknown() }).parse(response.structuredContent)
.result,
);
expect(evidence).toMatchObject({
provider: { id: "rea-call-path" },
normalized_result: {
status: "found",
shortest_hops: 0,
paths: { total: 1 },
},
evidence_links: [FUNCTION_COMPARISON_EXAMPLE.left.evidence_id],
});
} finally {
await close(session, server, client);
}
});
it("records an explicit non-causal static/runtime hypothesis", async () => {
const { session, server, client } = await connected();
for (const evidence of [
FUNCTION_COMPARISON_EXAMPLE.left,
FUNCTION_COMPARISON_EXAMPLE.right,
FUNCTION_COMPARISON_EVIDENCE,
PROCESS_CAPTURE_REFERENCE,
PROCESS_CAPTURE_RECONSTRUCTION,
PROCESS_COMPARISON_EVIDENCE,
])
expect(session.recordEvidence(evidence).ok).toBe(true);
try {
const response = await client.callTool({
name: "correlate_static_and_runtime",
arguments: INVESTIGATION_EXAMPLES.correlate_static_and_runtime,
});
expect(response.isError).not.toBe(true);
const evidence = parseEvidence(
z.object({ result: z.unknown() }).parse(response.structuredContent)
.result,
);
expect(evidence).toMatchObject({
provider: { id: "rea-static-runtime-correlation" },
confidence: "inferred",
normalized_result: {
status: "correlated",
summary: { hypotheses: 1 },
},
});
} finally {
await close(session, server, client);
}
});
it("passes only the finite declared reconstruction specification", async () => {
const { session, server, client } = await connected();
for (const evidence of [
PROCESS_CAPTURE_REFERENCE,
PROCESS_CAPTURE_RECONSTRUCTION,
PROCESS_COMPARISON_EVIDENCE,
])
expect(session.recordEvidence(evidence).ok).toBe(true);
try {
const response = await client.callTool({
name: "verify_reconstruction",
arguments: INVESTIGATION_EXAMPLES.verify_reconstruction,
});
expect(response.isError).not.toBe(true);
const evidence = parseEvidence(
z.object({ result: z.unknown() }).parse(response.structuredContent)
.result,
);
expect(evidence).toMatchObject({
provider: { id: "rea-reconstruction-verifier" },
normalized_result: { status: "pass", summary: { passed: 1 } },
});
expect(evidence.limitations).toContain(
"Pass means every declared claim passed; it does not establish global implementation equivalence.",
);
} finally {
await close(session, server, client);
}
});
it("cannot omit a session-owned active unknown from reconstruction input", async () => {
const { session, server, client } = await connected();
for (const evidence of [
PROCESS_CAPTURE_REFERENCE,
PROCESS_CAPTURE_RECONSTRUCTION,
PROCESS_COMPARISON_EVIDENCE,
])
expect(session.recordEvidence(evidence).ok).toBe(true);
expect(
session.recordUnknown({
approved: true,
question: "Was terminal equivalence reproduced independently?",
severity: "high",
domain: "reconstruction-verification",
supporting_evidence_ids: [PROCESS_COMPARISON_EVIDENCE.evidence_id],
contradicting_evidence_ids: [],
required_authority: "controlled-replay",
required_confidence: "observed",
required_environment: null,
recommended_probes: [
{
operation: "capture_process_scenario",
rationale: "Repeat both sides under one controlled environment.",
},
],
relationships: [],
}).ok,
).toBe(true);
try {
const response = await client.callTool({
name: "verify_reconstruction",
arguments: INVESTIGATION_EXAMPLES.verify_reconstruction,
});
expect(response.isError).not.toBe(true);
const evidence = parseEvidence(
z.object({ result: z.unknown() }).parse(response.structuredContent)
.result,
);
expect(evidence.normalized_result).toMatchObject({
status: "unknown",
summary: { unknown: 1 },
});
} finally {
await close(session, server, client);
}
});
});
const connected = async () => {
const session = new BinarySession(() => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
close: () => Promise.resolve(),
}));
const server = createServer(session, session);
const client = new Client({ name: "investigation-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
return { session, server, client };
};
const close = async (
session: BinarySession,
server: Awaited<ReturnType<typeof createServer>>,
client: Client,
) => {
await Promise.allSettled([client.close(), server.close(), session.close()]);
};
+235
View File
@@ -0,0 +1,235 @@
import { mkdtemp, mkdir, rm, writeFile, readFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { NativeMacOSProvider } from "../src/native/NativeMacOSProvider.js";
import {
NativeCommandFailure,
type NativeCommandCapture,
type NativeCommandRunner,
} from "../src/native/CommandRunner.js";
import type { BinaryTarget } from "../src/domain/binaryTarget.js";
import { err, ok } from "../src/domain/result.js";
import { parseLipoArchitectures } from "../src/native/parsers/lipo.js";
let directory: string | undefined;
afterEach(async () => {
if (directory !== undefined)
await rm(directory, { recursive: true, force: true });
directory = undefined;
});
describe("native macOS provider", () => {
it("normalizes comprehensive Mach-O inspection with exact bounded provenance", async () => {
const runner = new FixtureRunner();
const client = new NativeMacOSProvider(runner, "darwin").createClient(
machoTarget("/private/fixture"),
);
const execution = await client.execute("inspect_macho", {});
expect(execution.ok).toBe(true);
if (!execution.ok) return;
expect(execution.value.provider.id).toBe("native-macos");
expect(execution.value.result).toMatchObject({
format: "mach-o",
word_size: 64,
uuid: "01234567-89AB-CDEF-0123-456789ABCDEF",
architectures: { total: 2, exhaustive: true },
dependencies: {
items: [{ path: "/usr/lib/libSystem.B.dylib", kind: "LC_LOAD_DYLIB" }],
},
segments: {
items: [
{
name: "__TEXT",
initial_permissions: { read: true, write: false, execute: true },
sections: { items: [{ segment: "__TEXT", name: "__text" }] },
},
],
},
imports: { exhaustive: false },
exports: { exhaustive: false },
});
expect(JSON.stringify(execution.value.result)).not.toContain(
"/private/fixture",
);
expect(execution.value.locations).toContainEqual({
kind: "file-offset-range",
start: 16384,
end: 20480,
});
});
it("supports architectures, signatures, plists, and ordered demangling", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-native-"));
const app = join(directory, "Fixture.app");
const executable = join(app, "Contents/MacOS/Fixture");
await mkdir(join(app, "Contents/MacOS"), { recursive: true });
await writeFile(executable, "fixture");
await writeFile(join(app, "Contents/Info.plist"), "fixture");
const client = new NativeMacOSProvider(
new FixtureRunner(),
"darwin",
).createClient(machoTarget(executable, app));
const architectures = await client.execute("list_architectures", {});
expect(architectures.ok && architectures.value.result).toMatchObject({
architectures: { total: 2 },
});
const signature = await client.execute("inspect_signature", {});
expect(signature.ok && signature.value.result).toMatchObject({
signed: true,
identifier: "com.example.fixture",
hardened_runtime: true,
entitlements: { "com.apple.security.app-sandbox": true },
});
const plist = await client.execute("inspect_plist", {
relative_path: "Contents/Info.plist",
});
expect(plist.ok && plist.value.result).toMatchObject({
bundle: { identifier: "com.example.fixture", version: "42" },
source_path: "Contents/Info.plist",
});
const demangled = await client.execute("demangle_swift", {
symbols: ["$s4Test3fooyyF", "plain_symbol"],
});
expect(demangled.ok && demangled.value.result).toMatchObject({
symbols: [
{ input: "$s4Test3fooyyF", status: "demangled" },
{ input: "plain_symbol", status: "unchanged" },
],
});
});
it("classifies unavailable, malformed, timeout, and cancellation", async () => {
const unavailable = new NativeMacOSProvider(
new FailingRunner("unavailable"),
"darwin",
).createClient(machoTarget("/fixture"));
const unavailableResult = await unavailable.execute(
"list_architectures",
{},
);
expect(!unavailableResult.ok && unavailableResult.error._tag).toBe(
"AnalysisCapabilityUnavailableError",
);
const malformed = new NativeMacOSProvider(
new FixtureRunner({ lipo: "malformed" }),
"darwin",
).createClient(machoTarget("/fixture"));
const malformedResult = await malformed.execute("list_architectures", {});
expect(!malformedResult.ok && malformedResult.error._tag).toBe(
"AnalysisOutputError",
);
for (const [reason, tag] of [
["timeout", "AnalysisTimeoutError"],
["cancelled", "AnalysisCancelledError"],
] as const) {
const client = new NativeMacOSProvider(
new FailingRunner(reason),
"darwin",
).createClient(machoTarget("/fixture"));
const result = await client.execute("list_architectures", {});
expect(!result.ok && result.error._tag).toBe(tag);
}
});
it("parses thin and universal lipo fixtures", async () => {
expect(
parseLipoArchitectures(await fixture("lipo-thin.txt")),
).toMatchObject([{ name: "arm64" }]);
expect(parseLipoArchitectures(await fixture("lipo-fat.txt"))).toMatchObject(
[
{ name: "x86_64", file_offset: 16384, size: 4096 },
{ name: "arm64", file_offset: 32768, size: 8192 },
],
);
});
});
class FixtureRunner implements NativeCommandRunner {
constructor(
private readonly overrides: Readonly<Record<string, string>> = {},
) {}
async run(tool: string, arguments_: readonly string[]) {
const output = this.overrides[tool] ?? (await outputFor(tool, arguments_));
return ok(capture(tool, arguments_, output));
}
}
class FailingRunner implements NativeCommandRunner {
constructor(private readonly reason: NativeCommandFailure["reason"]) {}
run(tool: string) {
return Promise.resolve(err(new NativeCommandFailure(tool, this.reason)));
}
}
const outputFor = async (
tool: string,
arguments_: readonly string[],
): Promise<string> => {
if (tool === "lipo") return fixture("lipo-fat.txt");
if (tool === "otool") return fixture("otool-load.txt");
if (tool === "nm") return "_main\n_$s4Test3fooyyF\n";
if (tool === "dyld_info")
return fixture(
arguments_[0] === "-imports" ? "dyld-imports.txt" : "dyld-exports.txt",
);
if (tool === "dwarfdump")
return "UUID: 01234567-89AB-CDEF-0123-456789ABCDEF (arm64) fixture\n";
if (tool === "file")
return arguments_.at(-1)?.endsWith(".plist") === true
? "XML 1.0 document text\n"
: "Mach-O 64-bit executable arm64, little-endian\n";
if (tool === "vtool") return "Load command 3 LC_BUILD_VERSION\n";
if (tool === "swift-demangle") return fixture("demangle.txt");
if (tool === "plutil") return fixture("plist.json");
if (tool === "codesign") {
if (arguments_.includes("--entitlements"))
return fixture("entitlements.xml");
if (arguments_.includes("-r-"))
return "designated => identifier com.example.fixture\n";
return fixture("codesign.txt");
}
throw new Error(`Unexpected fixture tool ${tool}`);
};
const capture = (
tool: string,
arguments_: readonly string[],
output: string,
): NativeCommandCapture => ({
tool,
executable: `/usr/bin/${tool}`,
executableSha256: "a".repeat(64),
toolVersion: null,
versionReason: "fixture",
arguments: [...arguments_],
stdout: tool === "codesign" ? "" : output,
stderr: tool === "codesign" ? output : "",
stdoutBytes: Buffer.byteLength(tool === "codesign" ? "" : output),
stderrBytes: Buffer.byteLength(tool === "codesign" ? output : ""),
stdoutTruncated: false,
stderrTruncated: false,
exitCode: 0,
signal: null,
});
const machoTarget = (path: string, sourcePath?: string): BinaryTarget => ({
path,
...(sourcePath === undefined ? {} : { sourcePath }),
sha256: "0".repeat(64),
kind: "executable",
format: "mach-o",
architecture: "arm64",
availableArchitectures: ["x86_64", "arm64"],
loaderArgs: [],
});
const fixture = (name: string): Promise<string> =>
readFile(new URL(`./fixtures/native-macos/${name}`, import.meta.url), "utf8");
+7 -3
View File
@@ -4,7 +4,8 @@ import { afterEach, describe, expect, it } from "vitest";
import type { AnalysisOperationPort } from "../src/application/AnalysisProvider.js";
import { OFFICIAL_TOOL_CONTRACTS } from "../src/contracts/toolContracts.js";
import { HopperRemoteError } from "../src/domain/errors.js";
import { err, ok } from "../src/domain/result.js";
import { err } from "../src/domain/result.js";
import { observed as ok } from "./fixtures/analysisExecution.js";
import type { JsonValue } from "../src/domain/jsonValue.js";
import { createServer } from "../src/server/createServer.js";
@@ -98,7 +99,7 @@ const outputFor = (name: string): JsonValue => {
)
return true;
if (name === "set_addresses_names") return { "0x1000": true };
if (["search_procedures", "search_strings"].includes(name)) return {};
if (["search_procedures", "search_strings"].includes(name)) return page;
if (name === "procedure_info")
return {
name: "main",
@@ -137,7 +138,7 @@ describe("official Hopper proxy tools", () => {
execute: () => Promise.resolve(ok(null)),
});
const listed = await client.listTools();
const officialNames = new Set(
const officialNames = new Set<string>(
OFFICIAL_TOOL_CONTRACTS.map(({ name }) => name),
);
expect(
@@ -178,7 +179,10 @@ describe("official Hopper proxy tools", () => {
invocations.find(({ name }) => name === "search_procedures")?.arguments_,
).toEqual({
pattern: "main",
mode: "literal",
case_sensitive: false,
offset: 0,
limit: 100,
document: null,
});
});
+425 -3
View File
@@ -1,8 +1,11 @@
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { describe, expect, it } from "vitest";
import WebSocket from "ws";
import { fileURLToPath } from "node:url";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { startLoopbackReplay } from "../src/application/LoopbackReplay.js";
import {
captureProcessScenario,
@@ -16,6 +19,11 @@ import {
type ProcessExecutionPolicy,
} from "../src/domain/processCapture.js";
const processFixture = fileURLToPath(
new URL("./fixtures/processFidelity.mjs", import.meta.url),
);
const execFileAsync = promisify(execFile);
describe("process capture domain", () => {
const base = {
approved: true as const,
@@ -34,6 +42,33 @@ describe("process capture domain", () => {
],
}),
).toThrow(/ordered/);
expect(() =>
parseProcessScenario({
...base,
environment: { HOME: "/unsafe" },
}),
).toThrow(/reserved/);
expect(() =>
parseProcessScenario({
...base,
events: [{ type: "input", at_ms: 31_000, data: "late" }],
}),
).toThrow(/after the scenario timeout/);
});
it("requires explicit operator approval for host network access", () => {
expect(
authorizeProcessScenario(parseProcessScenario(base), {
enabled: true,
executableRoots: ["/bin"],
workingRoots: ["/tmp"],
allowedEnvironment: [],
allowExternalNetwork: false,
}),
).toEqual({
allowed: false,
reason: "host network access is not approved by operator policy",
});
});
it("refuses paths and environment outside operator policy", () => {
@@ -47,6 +82,7 @@ describe("process capture domain", () => {
executableRoots: ["/bin"],
workingRoots: ["/tmp"],
allowedEnvironment: [],
allowExternalNetwork: true,
}),
).toEqual({
allowed: false,
@@ -56,18 +92,142 @@ describe("process capture domain", () => {
it("never considers truncated captures equivalent", () => {
const capture = {
schema_version: 1 as const,
schema_version: 2 as const,
normalization: {
paths: true,
pids: true,
ports: true,
time_bucket_ms: 10,
patterns: [],
},
frames: [],
exit: { code: 0, signal: null },
exit: { code: 0, signal: null, reason: "exited" as const },
process_samples: [],
protocol_events: [],
files_before: [],
files_after: [],
filesystem_effects: [],
truncated: true,
limitations: [],
residual_unknowns: [],
cleanup: {
owned_process_group: "verified" as const,
temporary_root: "removed" as const,
},
};
expect(compareProcessCaptures(capture, capture).status).toBe("truncated");
});
it("classifies missing observations as unknown and one-sided evidence as added", () => {
const base = {
schema_version: 2 as const,
normalization: {
paths: true,
pids: true,
ports: true,
time_bucket_ms: 10,
patterns: [],
},
frames: [],
exit: { code: 0, signal: null, reason: "exited" as const },
process_samples: [],
protocol_events: [],
files_before: [],
files_after: [],
filesystem_effects: [],
truncated: false,
limitations: [],
residual_unknowns: [],
cleanup: {
owned_process_group: "verified" as const,
temporary_root: "removed" as const,
},
};
const added = compareProcessCaptures(base, {
...base,
frames: [{ sequence: 0, at_ms: 0, data: "new" }],
});
expect(added.terminal).toBe("added");
expect(added.status).toBe("changed");
const unknown = compareProcessCaptures(
{ ...base, residual_unknowns: [{ scope: "process", reason: "sampled" }] },
base,
);
expect(unknown.process).toBe("unknown");
expect(unknown.status).toBe("unknown");
});
it("keeps filesystem evidence unknown when stable snapshots match", () => {
const capture = {
schema_version: 2 as const,
normalization: {
paths: true,
pids: true,
ports: true,
time_bucket_ms: 10,
patterns: [],
},
frames: [],
exit: { code: 0, signal: null, reason: "exited" as const },
process_samples: [],
protocol_events: [],
files_before: [],
files_after: [],
filesystem_effects: [],
truncated: false,
limitations: [],
residual_unknowns: [
{ scope: "filesystem" as const, reason: "watcher unavailable" },
],
cleanup: {
owned_process_group: "verified" as const,
temporary_root: "removed" as const,
},
};
const comparison = compareProcessCaptures(capture, capture);
expect(comparison.filesystem).toBe("unknown");
expect(comparison.status).toBe("unknown");
});
it("detects changes in normalized process sample metadata", () => {
const capture = {
schema_version: 2 as const,
normalization: {
paths: true,
pids: true,
ports: true,
time_bucket_ms: 10,
patterns: [],
},
frames: [],
exit: { code: 0, signal: null, reason: "exited" as const },
process_samples: [
{ at_ms: 10, pid: 1, parent_pid: 0, command: "worker" },
],
protocol_events: [],
files_before: [],
files_after: [],
filesystem_effects: [],
truncated: false,
limitations: [],
residual_unknowns: [],
cleanup: {
owned_process_group: "verified" as const,
temporary_root: "removed" as const,
},
};
const changed = {
...capture,
process_samples: [
{ at_ms: 20, pid: 1, parent_pid: 2, command: "worker" },
],
};
const comparison = compareProcessCaptures(capture, changed);
expect(comparison.process).toBe("changed");
expect(comparison.status).toBe("changed");
});
});
describe("process capture adapter", () => {
@@ -105,6 +265,102 @@ describe("process capture adapter", () => {
}
});
it("matches bounded HTTP scripts without persisting request secrets", async () => {
const scenario = parseProcessScenario({
approved: true,
executable: "/bin/sh",
working_directory: "/tmp",
replay: {
http: [
{
method: "POST",
path: "/callback",
request_headers: { authorization: "Bearer fixture-secret" },
request_body: "credential-body",
status: 302,
response_headers: { location: "/done" },
body: "redirecting",
max_calls: 1,
},
{
method: "GET",
path: "/disconnect",
status: 200,
body: "",
disconnect: true,
},
],
},
});
const replay = await startLoopbackReplay(scenario);
try {
const request = () =>
fetch(`${replay.httpUrl}/callback`, {
method: "POST",
headers: { authorization: "Bearer fixture-secret" },
body: "credential-body",
redirect: "manual",
});
const matched = await request();
expect(matched.status).toBe(302);
expect(matched.headers.get("location")).toBe("/done");
expect((await request()).status).toBe(409);
expect((await fetch(`${replay.httpUrl}/missing`)).status).toBe(404);
await expect(fetch(`${replay.httpUrl}/disconnect`)).rejects.toThrow();
expect(replay.events.map(({ outcome }) => outcome)).toEqual(
expect.arrayContaining([
"matched",
"script_exhausted",
"unmatched",
"disconnected",
]),
);
expect(JSON.stringify(replay.events)).not.toContain("fixture-secret");
expect(JSON.stringify(replay.events)).not.toContain("credential-body");
} finally {
await replay.close();
}
});
it("consumes ordered WebSocket reconnect scripts and reports exhaustion", async () => {
const scenario = parseProcessScenario({
approved: true,
executable: "/bin/sh",
working_directory: "/tmp",
replay: {
websocket_connections: [
{
messages: [{ data: "first", delay_ms: 1 }],
disconnect_after: true,
},
{
messages: [{ data: "second" }],
disconnect_after: true,
},
],
},
});
const replay = await startLoopbackReplay(scenario);
const receive = () =>
new Promise<string>((resolveMessage, rejectMessage) => {
const socket = new WebSocket(replay.websocketUrl);
socket.once("message", (value) => resolveMessage(value.toString()));
socket.once("error", rejectMessage);
});
try {
await expect(receive()).resolves.toBe("first");
await expect(receive()).resolves.toBe("second");
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("script_exhausted");
} 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");
@@ -127,6 +383,7 @@ describe("process capture adapter", () => {
executableRoots: [dirname(process.execPath)],
workingRoots: [root],
allowedEnvironment: ["SECRET"],
allowExternalNetwork: true,
};
const scenario = parseProcessScenario({
approved: true,
@@ -160,6 +417,12 @@ describe("process capture adapter", () => {
file.path.endsWith("result.txt"),
),
).toBe(true);
expect(
capture.value.filesystem_effects.some(
(effect) =>
effect.path.endsWith(":result.txt") && effect.status === "created",
),
).toBe(true);
expect(
capture.value.protocol_events.some(
(event) => event.protocol === "http" && event.path === "/probe",
@@ -167,6 +430,44 @@ describe("process capture adapter", () => {
).toBe(true);
expect(JSON.stringify(capture.value)).not.toContain("do-not-record");
expect(await readFile(join(root, "result.txt"), "utf8")).toBe("created");
expect(JSON.stringify(capture.value.files_after)).not.toContain(root);
} finally {
await rm(root, { recursive: true, force: true });
}
});
it("does not follow or disclose symlink targets outside declared roots", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-symlink-test-"));
await symlink("/etc/passwd", join(root, "escape"));
try {
const capability = await probeProcessCaptureCapability();
if (!capability.available) return;
const result = await captureProcessScenario(
parseProcessScenario({
approved: true,
executable: "/bin/true",
working_directory: root,
filesystem_roots: [root],
}),
{
enabled: true,
executableRoots: ["/bin"],
workingRoots: [root],
allowedEnvironment: [],
allowExternalNetwork: true,
},
);
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
const escaped = result.value.files_after.find((file) =>
file.path.endsWith(":escape"),
);
expect(escaped?.symlink_target).toBe("<outside-declared-root>");
expect(result.value.truncated).toBe(true);
expect(JSON.stringify(result.value.files_after)).not.toContain(root);
expect(JSON.stringify(result.value.files_after)).not.toContain(
"/etc/passwd",
);
} finally {
await rm(root, { recursive: true, force: true });
}
@@ -183,9 +484,130 @@ describe("process capture adapter", () => {
executableRoots: [],
workingRoots: [],
allowedEnvironment: [],
allowExternalNetwork: true,
});
expect(result.ok).toBe(false);
if (result.ok) throw new Error("expected policy refusal");
expect(result.error).toBeInstanceOf(ProcessCaptureError);
});
it("distinguishes timeout from cancellation and cleans both runs", async () => {
const capability = await probeProcessCaptureCapability();
if (!capability.available) return;
const policy: ProcessExecutionPolicy = {
enabled: true,
executableRoots: ["/bin"],
workingRoots: ["/tmp"],
allowedEnvironment: [],
allowExternalNetwork: true,
};
const timedOut = await captureProcessScenario(
parseProcessScenario({
approved: true,
executable: "/bin/sh",
arguments: ["-c", "sleep 5"],
working_directory: "/tmp",
timeout_ms: 50,
idle_timeout_ms: 5_000,
}),
policy,
);
expect(timedOut.ok).toBe(true);
if (!timedOut.ok) throw timedOut.error;
expect(timedOut.value.exit.reason).toBe("timeout");
expect(timedOut.value.cleanup).toEqual({
owned_process_group: "verified",
temporary_root: "removed",
});
const controller = new AbortController();
setTimeout(() => controller.abort(), 50);
const cancelled = await captureProcessScenario(
parseProcessScenario({
approved: true,
executable: "/bin/sh",
arguments: ["-c", "sleep 5"],
working_directory: "/tmp",
timeout_ms: 5_000,
idle_timeout_ms: 5_000,
}),
policy,
controller.signal,
);
expect(cancelled.ok).toBe(false);
if (cancelled.ok) throw new Error("expected cancellation");
expect(cancelled.error.message).toContain("cancelled");
});
it("captures source-owned interactive, resize, Unicode, and signal behavior", async () => {
const capability = await probeProcessCaptureCapability();
if (!capability.available) return;
const result = await captureProcessScenario(
parseProcessScenario({
approved: true,
executable: process.execPath,
arguments: [processFixture, "interactive"],
working_directory: dirname(processFixture),
events: [
{ type: "input", at_ms: 100, data: "answer" },
{ type: "resize", at_ms: 300, columns: 100, rows: 40 },
{ type: "signal", at_ms: 700, signal: "SIGINT" },
],
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;
const output = result.value.frames.map(({ data }) => data).join("");
expect(output).toContain("prompt>");
expect(output).toContain("input:answer unicode:雪");
expect(output).toContain("resize:100x40");
expect(output).toContain("signal:SIGINT");
expect(result.value.exit.code).toBe(0);
});
it("samples and cleans a source-owned child and grandchild process tree", async () => {
const capability = await probeProcessCaptureCapability();
if (!capability.available) return;
const result = await captureProcessScenario(
parseProcessScenario({
approved: true,
executable: process.execPath,
arguments: [processFixture, "tree"],
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;
const commands = result.value.process_samples.map(({ command }) => command);
expect(commands.some((command) => command.includes("tree-child"))).toBe(
true,
);
expect(
commands.some((command) => command.includes("tree-grandchild")),
).toBe(true);
expect(JSON.stringify(result.value.process_samples)).not.toContain(
dirname(processFixture),
);
const { stdout } = await execFileAsync("ps", ["-axo", "command="]);
expect(stdout).not.toContain(`${processFixture} tree-child`);
expect(stdout).not.toContain(`${processFixture} tree-grandchild`);
});
});
+70
View File
@@ -0,0 +1,70 @@
import { describe, expect, it, vi } from "vitest";
import {
cleanupOwnedProcessGroup,
type ProcessOwnershipHost,
} from "../src/application/ProcessOwnership.js";
const ownership = {
runId: "run-token",
leaderPid: 100,
processGroupId: 100,
};
const host = (
environments: Readonly<Record<number, Readonly<Record<string, string>>>>,
): {
readonly adapter: ProcessOwnershipHost;
readonly signalGroup: ReturnType<typeof vi.fn>;
} => {
const signalGroup = vi.fn();
return {
adapter: {
listMembers: () =>
Promise.resolve(
Object.keys(environments).map((pid) => ({
pid: Number(pid),
parentPid: Number(pid) === 100 ? 1 : 100,
processGroupId: 100,
command: "fixture",
})),
),
environment: (pid) => Promise.resolve(environments[pid] ?? {}),
signalGroup,
},
signalGroup,
};
};
describe("owned process-group cleanup", () => {
it("signals only a group whose every member carries the run token", async () => {
const { adapter, signalGroup } = host({
100: { REA_PROCESS_RUN_ID: "run-token" },
101: { REA_PROCESS_RUN_ID: "run-token" },
});
expect(await cleanupOwnedProcessGroup(ownership, adapter)).toEqual({
cleaned: true,
signaled: true,
});
expect(signalGroup).toHaveBeenCalledWith(100, "SIGKILL");
});
it("fails closed for stale metadata or an unrelated concurrent process", async () => {
const { adapter, signalGroup } = host({
100: { REA_PROCESS_RUN_ID: "run-token" },
101: { REA_PROCESS_RUN_ID: "different-run" },
});
expect(await cleanupOwnedProcessGroup(ownership, adapter)).toEqual({
cleaned: false,
reason: "process group contains an unowned or PID-reused process",
});
expect(signalGroup).not.toHaveBeenCalled();
});
it("is idempotent when the owned group has already exited", async () => {
const { adapter } = host({});
expect(await cleanupOwnedProcessGroup(ownership, adapter)).toEqual({
cleaned: true,
signaled: false,
});
});
});
+38
View File
@@ -4,6 +4,10 @@ import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import { parseConfig } from "../src/config.js";
import { HopperProvider } from "../src/hopper/HopperProvider.js";
import { silentLogger } from "../src/logger.js";
const sourceRoot = new URL("../src/", import.meta.url);
describe("provider-neutral architecture", () => {
@@ -23,6 +27,40 @@ describe("provider-neutral architecture", () => {
}
expect(violations).toEqual([]);
});
it("publishes deterministic immutable Hopper capability descriptors", () => {
const config = parseConfig({});
expect(config.ok).toBe(true);
if (!config.ok) return;
const provider = new HopperProvider(config.value, silentLogger);
const capabilities = provider.capabilities();
expect(capabilities).toHaveLength(34);
expect(new Set(capabilities.map(({ operation }) => operation)).size).toBe(
capabilities.length,
);
expect(Object.isFrozen(capabilities)).toBe(true);
for (const descriptor of capabilities) {
expect(descriptor.provider).toEqual(provider.identity());
expect(descriptor).toMatchObject({
inputContractVersion: 1,
outputContractVersion: 1,
available: true,
reason: null,
});
expect(Object.isFrozen(descriptor)).toBe(true);
expect(Object.isFrozen(descriptor.effects)).toBe(true);
expect(Object.isFrozen(descriptor.limits)).toBe(true);
expect(Object.isFrozen(descriptor.limitations)).toBe(true);
}
expect(
capabilities.find(({ operation }) => operation === "list_procedures"),
).toMatchObject({ pagination: "offset" });
expect(
capabilities.find(({ operation }) => operation === "set_comment"),
).toMatchObject({
effects: { mutatesArtifact: true, mayWriteFilesystem: true },
});
});
});
const typescriptFiles = async (
+19 -4
View File
@@ -2,6 +2,14 @@ import { readFile } from "node:fs/promises";
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
import {
ENHANCED_TOOL_CONTRACTS,
OFFICIAL_TOOL_CONTRACTS,
SESSION_TOOL_CONTRACTS,
TOOL_CONTRACTS,
} from "../src/contracts/toolContracts.js";
import { NATIVE_TOOL_CONTRACTS } from "../src/contracts/nativeToolContracts.js";
import { ARTIFACT_TOOL_CONTRACTS } from "../src/contracts/artifactToolContracts.js";
const readmes = [
"README.md",
@@ -22,10 +30,17 @@ describe("localized README product facts", () => {
expect(content).toContain('"args": ["-y", "rea-agents", "mcp"]');
expect(content).toContain("Node.js 24");
expect(content).toContain("macOS 12");
expect(content).toMatch(/\b50\b/u);
expect(content).toMatch(/\b33\b/u);
expect(content).toMatch(/\b10\b/u);
expect(content).toMatch(/\b3\b/u);
expect(content).toContain(`MCP_tools-${String(TOOL_CONTRACTS.length)}`);
for (const count of [
OFFICIAL_TOOL_CONTRACTS.length,
ENHANCED_TOOL_CONTRACTS.length,
NATIVE_TOOL_CONTRACTS.length,
ARTIFACT_TOOL_CONTRACTS.length,
SESSION_TOOL_CONTRACTS.length,
])
expect(content).toMatch(
new RegExp(`\\|\\s*${String(count)}\\s*\\|`, "u"),
);
},
);
});
+109
View File
@@ -0,0 +1,109 @@
import { describe, expect, it } from "vitest";
import {
firstProcedureAddress,
requireAddressArray,
requireFunctionDossier,
requirePseudocode,
} from "../src/application/RealHopperAssertions.js";
describe("real Hopper semantic assertions", () => {
it("extracts only a real procedure address from a structured page", () => {
expect(
firstProcedureAddress({
items: [{ address: "0x1000", name: "main" }],
offset: 0,
limit: 100,
total: 1,
next_offset: null,
has_more: false,
}),
).toBe("0x1000");
expect(() =>
firstProcedureAddress({ items: { address: "0x1000" } }),
).toThrow();
expect(() =>
firstProcedureAddress({ items: [{ address: "items" }] }),
).toThrow();
});
it("rejects empty and embedded per-item decompilation failures", () => {
expect(requirePseudocode("return 0;", "batch_decompile")).toBe("return 0;");
for (const invalid of ["", " ", "No output", "Error: invalid address"])
expect(() => requirePseudocode(invalid, "batch_decompile")).toThrow();
});
it("requires address-shaped relationship evidence", () => {
expect(requireAddressArray(["0x1000"], "xrefs")).toEqual(["0x1000"]);
expect(() => requireAddressArray(["main"], "xrefs")).toThrow();
});
it("rejects success-shaped dossiers without truthful semantic content", () => {
const dossier = validDossier();
expect(requireFunctionDossier(dossier, "0x1000")).toEqual(dossier);
expect(() =>
requireFunctionDossier(
{
...dossier,
pseudocode: {
text: "Error: failed",
returned_chars: 13,
total_chars: 13,
},
},
"0x1000",
),
).toThrow(/embedded failure/u);
expect(() =>
requireFunctionDossier(
{ ...dossier, instruction_scan: { scanned: 0, truncated: false } },
"0x1000",
),
).toThrow(/instruction scan/u);
});
it("counts Unicode code points and accepts terminal scan truncation", () => {
const dossier = validDossier();
const scanLimited = {
...dossier,
pseudocode: { text: "😀", returned_chars: 1, total_chars: 1 },
comments: {
items: [],
total: null,
returned: 0,
truncated: true,
next_offset: null,
},
instruction_scan: { scanned: 1, truncated: true },
};
expect(requireFunctionDossier(scanLimited, "0x1000")).toEqual(scanLimited);
});
});
const validDossier = () => {
const collection = {
items: [],
total: 0,
returned: 0,
truncated: false,
next_offset: null,
};
return {
procedure: { address: "0x1000", name: "main" },
pseudocode: { text: "return 0;", returned_chars: 9, total_chars: 9 },
comments: collection,
callers: collection,
callees: collection,
incoming_references: collection,
outgoing_references: collection,
referenced_strings: collection,
referenced_names: collection,
basic_blocks: {
...collection,
items: [{ successors: [] }],
total: 1,
returned: 1,
},
instruction_scan: { scanned: 1, truncated: false },
};
};
+330
View File
@@ -0,0 +1,330 @@
import { describe, expect, it } from "vitest";
import { createEvidence, type Evidence } from "../src/domain/evidence.js";
import { createEvidenceBundle } from "../src/domain/evidenceBundle.js";
import {
reconstructionVerificationResultSchema,
verifyReconstruction,
} from "../src/domain/reconstructionVerification.js";
import type { JsonValue } from "../src/domain/jsonValue.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../src/contracts/processCaptureExample.js";
import { ARTIFACT_COMPARISON_EXAMPLE } from "../src/contracts/artifactComparisonExample.js";
import { createResidualUnknown } from "../src/domain/residualUnknown.js";
const environment = {
id: "fixture-linux",
platform: "linux",
architecture: "x86_64",
isolation: "container" as const,
};
const source = (
digit: string,
authority: "controlled-replay" | "shipped-artifact",
confidence: "observed" | "derived" = "observed",
): Evidence =>
createEvidence(
{
path: `/tmp/source-${digit}`,
sha256: digit.repeat(64),
format: "file",
},
{ id: "fixture", name: "Fixture", version: "1" },
{
predicateType:
authority === "controlled-replay"
? "rea.process-capture/v2"
: "rea.analysis/v2",
operation:
authority === "controlled-replay"
? "capture_process_scenario"
: "inventory_artifact",
parameters: {},
result:
authority === "controlled-replay"
? EMPTY_PROCESS_CAPTURE_EXAMPLE
: { digit },
confidence,
authority,
environment: authority === "controlled-replay" ? environment : null,
},
);
const processResult = (
terminal: "unchanged" | "changed" | "unknown" = "unchanged",
): JsonValue => ({
status: terminal === "changed" ? "changed" : terminal,
terminal,
exit: "unchanged",
filesystem: "unchanged",
protocol: "unchanged",
process: "unchanged",
limitations: [],
});
const processComparison = (
left: Evidence,
right: Evidence,
result: JsonValue,
extraLinks: readonly string[] = [],
): Evidence =>
createEvidence(
undefined,
{
id: "rea-process",
name: "REA deterministic process harness",
version: "1",
},
{
predicateType: "rea.process-comparison/v1",
operation: "compare_process_captures",
parameters: {
left_evidence_id: left.evidence_id,
right_evidence_id: right.evidence_id,
},
result,
confidence: "derived",
authority: "analyst-inference",
evidenceLinks: [left.evidence_id, right.evidence_id, ...extraLinks],
},
);
const behavioralSpec = (comparison: Evidence) => ({
schema_version: 1 as const,
name: "CLI compatibility",
claims: [
{
kind: "behavioral" as const,
claim_id: "terminal-output",
title: "Terminal output remains equal",
comparison_evidence_id: comparison.evidence_id,
dimension: "terminal" as const,
},
],
});
const artifactResult = (partial = false): JsonValue => ({
status: "unchanged",
left_manifest_id: `agm_${"3".repeat(64)}`,
right_manifest_id: `agm_${"4".repeat(64)}`,
summary: { unchanged: 1, added: 0, removed: 0, changed: 0, unknown: 0 },
changes: {
items: [],
offset: 0,
limit: 100,
total: partial ? 1 : 0,
next_offset: partial ? 1 : null,
},
limitations: [],
});
const artifactComparison = (
left: Evidence,
right: Evidence,
partial = false,
): Evidence =>
createEvidence(
undefined,
{
id: "rea-artifact-comparison",
name: "REA artifact comparison",
version: "1",
},
{
predicateType: "rea.artifact-comparison/v1",
operation: "compare_artifacts",
parameters: {
left_evidence_ids: [left.evidence_id],
right_evidence_ids: [right.evidence_id],
},
result: artifactResult(partial),
confidence: "derived",
authority: "analyst-inference",
evidenceLinks: [left.evidence_id, right.evidence_id],
},
);
describe("reconstruction verification", () => {
it("passes a complete authoritative claim with two-sided citations", () => {
const left = source("1", "controlled-replay");
const right = source("2", "controlled-replay");
const comparison = processComparison(left, right, processResult());
const result = verifyReconstruction(
behavioralSpec(comparison),
createEvidenceBundle([comparison, right, left]),
0,
100,
);
expect(reconstructionVerificationResultSchema.parse(result)).toMatchObject({
status: "pass",
summary: { total: 1, passed: 1, failed: 0, unknown: 0 },
claims: { total: 1, next_offset: null },
});
expect(result.claims.items[0]?.evidence_links).toEqual(
expect.arrayContaining([
comparison.evidence_id,
left.evidence_id,
right.evidence_id,
]),
);
});
it("fails an authoritative observed disagreement", () => {
const left = source("1", "controlled-replay");
const right = source("2", "controlled-replay");
const comparison = processComparison(left, right, processResult("changed"));
const result = verifyReconstruction(
behavioralSpec(comparison),
createEvidenceBundle([left, right, comparison]),
0,
100,
);
expect(result).toMatchObject({
status: "fail",
summary: { failed: 1 },
claims: { items: [{ status: "fail", observed_status: "changed" }] },
});
});
it("keeps insufficient authority and partial structural evidence unknown", () => {
const weakLeft = source("1", "controlled-replay", "derived");
const replayRight = source("2", "controlled-replay");
const runtime = processComparison(weakLeft, replayRight, processResult());
expect(
verifyReconstruction(
behavioralSpec(runtime),
createEvidenceBundle([weakLeft, replayRight, runtime]),
0,
100,
).status,
).toBe("unknown");
const left = ARTIFACT_COMPARISON_EXAMPLE.left;
const right = ARTIFACT_COMPARISON_EXAMPLE.right;
const comparison = artifactComparison(left, right, true);
const result = verifyReconstruction(
{
schema_version: 1,
name: "Artifact structure",
claims: [
{
kind: "structural-artifact",
claim_id: "artifact-graph",
title: "Artifact graph remains equal",
comparison_evidence_id: comparison.evidence_id,
dimension: "overall",
},
],
},
createEvidenceBundle([left, comparison, right]),
0,
100,
);
expect(result.status).toBe("unknown");
expect(result.recommended_probes[0]?.operation).toBe("inventory_artifact");
});
it("rejects dangling or extra comparison closure", () => {
const left = source("1", "controlled-replay");
const right = source("2", "controlled-replay");
const extra = source("3", "controlled-replay");
const comparison = processComparison(left, right, processResult(), [
extra.evidence_id,
]);
expect(() =>
verifyReconstruction(
behavioralSpec(comparison),
createEvidenceBundle([left, right, extra, comparison]),
0,
100,
),
).toThrow(/closure disagrees/u);
});
it("pages claims deterministically and gives specification a stable digest", () => {
const left = source("1", "controlled-replay");
const right = source("2", "controlled-replay");
const comparison = processComparison(left, right, processResult());
const claims = [
{
kind: "behavioral" as const,
claim_id: "z-exit",
title: "Exit remains equal",
comparison_evidence_id: comparison.evidence_id,
dimension: "exit" as const,
},
behavioralSpec(comparison).claims[0],
];
const bundle = createEvidenceBundle([right, comparison, left]);
const first = verifyReconstruction(
{ schema_version: 1, name: "Compatibility", claims },
bundle,
0,
1,
);
const repeated = verifyReconstruction(
{
name: "Compatibility",
claims: [...claims].reverse(),
schema_version: 1,
},
bundle,
0,
1,
);
expect(first).toEqual(repeated);
expect(first.claims.items[0]?.claim_id).toBe("terminal-output");
expect(first.claims.next_offset).toBe(1);
});
it("keeps all active unknowns gating while bounding their projection", () => {
const left = source("1", "controlled-replay");
const right = source("2", "controlled-replay");
const comparison = processComparison(left, right, processResult());
const mutations = Array.from({ length: 101 }, (_, index) =>
createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
{
predicateType: "rea.residual-unknown-mutation/v1",
operation: "record_unknown",
parameters: { index },
result: { action: "record" },
confidence: "derived",
authority: "analyst-inference",
evidenceLinks: [comparison.evidence_id],
},
),
);
const unknowns = mutations.map((mutation, index) =>
createResidualUnknown(
{
approved: true,
question: `Unresolved replay ${index}`,
severity: "high",
domain: "reconstruction-verification",
supporting_evidence_ids: [comparison.evidence_id],
contradicting_evidence_ids: [],
required_authority: "controlled-replay",
required_confidence: "observed",
required_environment: null,
recommended_probes: [],
relationships: [],
},
mutation.evidence_id,
null,
),
);
const result = verifyReconstruction(
behavioralSpec(comparison),
createEvidenceBundle([left, right, comparison, ...mutations], unknowns),
0,
100,
);
expect(result.status).toBe("unknown");
expect(result.claims.items[0]?.unknown_ids).toHaveLength(100);
expect(result.claims.items[0]?.limitations).toContain(
"1 additional active residual unknowns affect this claim but are omitted by the 100-item display limit.",
);
});
});
+261
View File
@@ -0,0 +1,261 @@
import { describe, expect, it } from "vitest";
import {
computeHistoricalSourceGraphSha256,
createHistoricalSourceGraph,
createHistoricalSourceManifest,
historicalSourceGraphSchema,
parseHistoricalSourceGraph,
parseHistoricalSourceManifest,
type HistoricalSourceGraphInput,
} from "../src/domain/referenceSourceGraph.js";
const HASH_A = "a".repeat(64);
const HASH_B = "b".repeat(64);
type Entry = HistoricalSourceGraphInput["entries"][number];
type DirectoryEntry = Extract<Entry, { kind: "directory" }>;
type FileEntry = Extract<Entry, { kind: "file" }>;
type SymlinkEntry = Extract<Entry, { kind: "symlink" }>;
const directoryEntry = (
treeState: DirectoryEntry["tree_state"] = "enumerated",
): DirectoryEntry => ({
path: "src",
kind: "directory",
classifications: ["source"],
tree_state: treeState,
limitations: [],
});
const fileEntry = (overrides: Partial<FileEntry> = {}): FileEntry => ({
path: "src/main.ts",
kind: "file",
sha256: HASH_B,
size: 20,
language: "TypeScript",
classifications: ["source"],
content_state: "hashed",
limitations: [],
...overrides,
});
const symlinkEntry = (overrides: Partial<SymlinkEntry> = {}): SymlinkEntry => ({
path: "src/package.json",
kind: "symlink",
target: "main.ts",
target_state: "internal",
classifications: ["manifest"],
limitations: [],
...overrides,
});
const graphInput = (): HistoricalSourceGraphInput => ({
schema: "HistoricalSourceGraph/v1",
authority: "historical-reference",
root_alias: "$REFERENCE_ROOT",
inventory_state: "complete",
entries: [directoryEntry(), fileEntry(), symlinkEntry()],
relationships: [
{
from_path: "src/main.ts",
to: "node:fs",
kind: "imports",
resolution: "external",
parse_state: "parsed",
},
{
from_path: "src/main.ts",
to: "src",
kind: "references",
resolution: "internal",
parse_state: "parsed",
},
],
parse_failures: [],
exclusions: [],
languages: ["TypeScript"],
manifests: [],
vcs: { kind: "git", head: HASH_A, dirty: false },
provenance: { importer: "rea", importer_version: "1", caller: "test" },
limitations: [],
});
describe("historical source graph", () => {
it("builds and verifies internal root and manifest commitments", () => {
const graph = createHistoricalSourceGraph(graphInput());
const first = createHistoricalSourceManifest(graph);
const second = createHistoricalSourceManifest(structuredClone(graph));
expect(first).toEqual(second);
expect(parseHistoricalSourceGraph(graph)).toEqual(graph);
expect(parseHistoricalSourceManifest(first)).toEqual(first);
expect(first.graph_sha256).toBe(computeHistoricalSourceGraphSha256(graph));
});
it("rejects stale roots and commits file, directory, and symlink semantics", () => {
const original = createHistoricalSourceGraph(graphInput());
expect(() =>
parseHistoricalSourceGraph({ ...original, root_sha256: HASH_A }),
).toThrow(/root commitment/u);
for (const mutate of [
(input: HistoricalSourceGraphInput) => {
input.entries[0] = directoryEntry("partial");
input.inventory_state = "partial";
},
(input: HistoricalSourceGraphInput) => {
input.entries[1] = fileEntry({ sha256: "c".repeat(64) });
},
(input: HistoricalSourceGraphInput) => {
input.entries[2] = symlinkEntry({
target: "other.json",
target_state: "missing",
});
input.inventory_state = "partial";
},
(input: HistoricalSourceGraphInput) => {
input.exclusions = [
{ path: "private.env", reason: "configured-secret" },
];
input.inventory_state = "partial";
},
]) {
const changed = graphInput();
mutate(changed);
expect(createHistoricalSourceGraph(changed).root_sha256).not.toBe(
original.root_sha256,
);
}
});
it("derives language and manifest indexes and enforces code-point order", () => {
const input = graphInput();
input.entries[1] = fileEntry({ classifications: ["source", "test"] });
expect(() =>
createHistoricalSourceGraph({ ...input, languages: [] }),
).toThrow(/derived/u);
expect(() =>
createHistoricalSourceGraph({ ...input, manifests: ["src/main.ts"] }),
).toThrow(/derived/u);
expect(() =>
createHistoricalSourceGraph({
...input,
entries: input.entries.toReversed(),
}),
).toThrow(/Unicode code point/u);
expect(() =>
createHistoricalSourceGraph({
...input,
entries: input.entries.map((entry) =>
entry.path === "src/main.ts"
? { ...entry, classifications: ["test", "source"] }
: entry,
),
}),
).toThrow(/Unicode code point/u);
});
it("preserves partial observations but rejects every partial complete graph", () => {
const partial = graphInput();
partial.inventory_state = "partial";
partial.entries[1] = fileEntry({
sha256: null,
size: null,
content_state: "unreadable",
limitations: ["Permission denied"],
});
partial.parse_failures = [
{ path: "src/main.ts", parser: "typescript", reason: "Malformed input" },
];
expect(createHistoricalSourceGraph(partial).inventory_state).toBe(
"partial",
);
for (const change of [
{ entries: partial.entries },
{ parse_failures: partial.parse_failures },
{
exclusions: [{ path: "secret", reason: "configured-secret" as const }],
},
{ limitations: ["Incomplete"] },
{
relationships: [
{
...graphInput().relationships[0]!,
parse_state: "partial" as const,
},
],
},
])
expect(() =>
createHistoricalSourceGraph({ ...graphInput(), ...change }),
).toThrow(/Complete inventory/u);
});
it("rejects strict unknown fields, invalid VCS, dangling internal edges, and false manifests", () => {
expect(() =>
createHistoricalSourceGraph({ ...graphInput(), surprise: true }),
).toThrow();
expect(() =>
createHistoricalSourceGraph({
...graphInput(),
vcs: { kind: "git", head: "main", dirty: false },
}),
).toThrow();
expect(() =>
createHistoricalSourceGraph({
...graphInput(),
relationships: [
{ ...graphInput().relationships[1]!, to: "missing.ts" },
],
}),
).toThrow(/normalized and inventoried/u);
expect(() =>
createHistoricalSourceGraph({
...graphInput(),
inventory_state: "partial",
entries: graphInput().entries.map((entry) =>
entry.kind === "symlink"
? { ...entry, target: "/etc/passwd", target_state: "external" }
: entry,
),
}),
).toThrow();
expect(() =>
createHistoricalSourceGraph({
...graphInput(),
inventory_state: "partial",
entries: graphInput().entries.map((entry) =>
entry.kind === "symlink"
? {
...entry,
target: "<outside-root>",
target_state: "external",
}
: entry,
),
}),
).not.toThrow();
expect(() =>
createHistoricalSourceGraph({
...graphInput(),
relationships: [
{ ...graphInput().relationships[1]!, to: "../escape.ts" },
],
}),
).toThrow(/normalized and inventoried/u);
expect(() =>
historicalSourceGraphSchema.parse({
...createHistoricalSourceGraph(graphInput()),
extra: true,
}),
).toThrow();
const manifest = createHistoricalSourceManifest(
createHistoricalSourceGraph(graphInput()),
);
expect(() =>
parseHistoricalSourceManifest({ ...manifest, entry_count: 999 }),
).toThrow(/identifier does not match/u);
});
});
+126
View File
@@ -0,0 +1,126 @@
import fs from "node:fs";
import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { add, commit, init } from "isomorphic-git";
import { describe, expect, it } from "vitest";
import { importReferenceSource } from "../src/application/ReferenceSourceImport.js";
import { createHistoricalSourceManifest } from "../src/domain/referenceSourceGraph.js";
const limits = {
maxBytes: 1024 * 1024,
maxEntries: 1_000,
maxDepth: 16,
maxPathBytes: 4_096,
};
const fixture = async (parent: string, name: string): Promise<string> => {
const root = join(parent, name);
await mkdir(join(root, "src"), { recursive: true });
await Promise.all([
writeFile(join(root, "src", "main.ts"), 'import "./dep";\n'),
writeFile(join(root, "src", "dep.ts"), "export const value = 1;\n"),
writeFile(join(root, "src", "broken.ts"), "const = ;\n"),
writeFile(join(root, ".env"), "SECRET_SENTINEL=do-not-record\n"),
writeFile(join(root, "package.json"), '{"name":"fixture"}\n'),
]);
return root;
};
const importTree = (root: string, approvedRoot: string, signal?: AbortSignal) =>
importReferenceSource({
root,
caller: "reference-import-test",
policy: {
roots: [approvedRoot],
secretPatterns: [".env", ".env.*"],
...limits,
},
limits,
...(signal === undefined ? {} : { signal }),
});
describe("reference source import", () => {
it("is relocation-stable, resolves imports, and excludes secrets before capture", async () => {
const parent = await mkdtemp(join(tmpdir(), "rea-reference-import-"));
try {
const leftRoot = await fixture(parent, "left");
const rightRoot = await fixture(parent, "right");
const [left, right] = await Promise.all([
importTree(leftRoot, parent),
importTree(rightRoot, parent),
]);
expect(left.ok).toBe(true);
expect(right.ok).toBe(true);
if (!left.ok || !right.ok) throw new Error("expected imports to pass");
expect(createHistoricalSourceManifest(left.value)).toEqual(
createHistoricalSourceManifest(right.value),
);
expect(left.value.relationships).toContainEqual(
expect.objectContaining({
from_path: "src/main.ts",
to: "src/dep.ts",
resolution: "internal",
}),
);
expect(left.value.parse_failures).toHaveLength(1);
expect(left.value.exclusions).toContainEqual({
path: ".env",
reason: "configured-secret",
});
expect(JSON.stringify(left.value)).not.toContain("SECRET_SENTINEL");
expect(JSON.stringify(left.value)).not.toContain(leftRoot);
} finally {
await rm(parent, { recursive: true, force: true });
}
});
it("fails closed outside policy and honors cancellation", async () => {
const parent = await mkdtemp(join(tmpdir(), "rea-reference-policy-"));
const outside = await mkdtemp(join(tmpdir(), "rea-reference-outside-"));
try {
const root = await fixture(outside, "tree");
const denied = await importTree(root, parent);
expect(denied).toMatchObject({
ok: false,
error: { code: "policy" },
});
const controller = new AbortController();
controller.abort();
const cancelled = await importTree(root, outside, controller.signal);
expect(cancelled).toMatchObject({
ok: false,
error: { code: "cancelled" },
});
} finally {
await Promise.all([
rm(parent, { recursive: true, force: true }),
rm(outside, { recursive: true, force: true }),
]);
}
});
it("records bounded local Git state without invoking Git", async () => {
const parent = await mkdtemp(join(tmpdir(), "rea-reference-git-"));
try {
const root = await fixture(parent, "repo");
await init({ fs, dir: root, defaultBranch: "main" });
for (const filepath of ["package.json", "src/main.ts", "src/dep.ts"])
await add({ fs, dir: root, filepath });
const oid = await commit({
fs,
dir: root,
author: { name: "REA Test", email: "rea@example.invalid" },
message: "fixture",
});
const result = await importTree(root, parent);
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
expect(result.value.vcs).toEqual({ kind: "git", head: oid, dirty: true });
} finally {
await rm(parent, { recursive: true, force: true });
}
});
});
+224
View File
@@ -0,0 +1,224 @@
import { mkdtemp, mkdir, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { readReferenceSource } from "../src/reference/ReferenceSourceReader.js";
const limits = {
maxBytes: 1_024,
maxEntries: 10,
maxDepth: 4,
maxPathBytes: 100,
} as const;
describe("readReferenceSource", () => {
it("returns explicit entries in canonical code-point path order", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-reference-"));
await mkdir(join(root, "nested"));
await writeFile(join(root, "z.js"), "z");
await writeFile(join(root, "a.js"), "a");
await writeFile(join(root, "nested", "b.js"), "b");
await writeFile(join(root, "\u{e000}"), "p");
await writeFile(join(root, "\u{10000}"), "a");
const result = await readReferenceSource(root, limits);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.entries.map(({ path }) => path)).toEqual([
"a.js",
"nested",
"nested/b.js",
"z.js",
"",
"𐀀",
]);
expect(result.value.bytesRead).toBe(5);
expect(result.value.truncated).toBe(false);
expect(
result.value.entries.map((entry) =>
entry.status === "read" && entry.kind === "file"
? Buffer.from(entry.bytes).toString()
: entry.status === "read"
? entry.kind
: entry.code,
),
).toEqual(["a", "directory", "b", "z", "p", "a"]);
expect(result.value.limitations).toHaveLength(1);
});
it("sanitizes internal, external, and missing symlink targets", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-reference-"));
const outside = await mkdtemp(join(tmpdir(), "rea-outside-"));
await writeFile(join(outside, "secret"), "secret");
await writeFile(join(root, "local"), "local");
await symlink("local", join(root, "internal"));
await symlink(join(outside, "secret"), join(root, "external"));
await symlink("absent", join(root, "missing"));
const result = await readReferenceSource(root, limits);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.entries).toEqual([
{
status: "read",
kind: "symlink",
path: "external",
target: "<outside-root>",
targetState: "external",
},
{
status: "read",
kind: "symlink",
path: "internal",
target: "local",
targetState: "internal",
},
{
status: "read",
kind: "file",
path: "local",
bytes: expect.any(Uint8Array),
size: 5,
},
{
status: "read",
kind: "symlink",
path: "missing",
target: "absent",
targetState: "missing",
},
]);
expect(result.value.bytesRead).toBe(5);
expect(JSON.stringify(result.value.entries)).not.toContain(outside);
});
it("makes byte, file, depth, and path limits explicit per entry", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-reference-"));
await writeFile(join(root, "a"), "too large");
await writeFile(join(root, "b"), "b");
await mkdir(join(root, "deep"));
await writeFile(join(root, "deep", "c"), "c");
const result = await readReferenceSource(root, {
maxBytes: 1,
maxEntries: 1,
maxDepth: 1,
maxPathBytes: 4,
});
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.truncated).toBe(true);
expect(result.value.entries).toEqual([
expect.objectContaining({
path: "a",
kind: "file",
status: "failed",
code: "limit",
size: 9,
}),
]);
expect(result.value.limitations).toContain(
"Traversal stopped because the entry limit was reached.",
);
expect(result.value.entries).not.toContainEqual(
expect.objectContaining({ path: "<tree>" }),
);
});
it("applies maxEntries as a global limit across every entry kind", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-reference-"));
await writeFile(join(root, "a"), "a");
await writeFile(join(root, "b"), "b");
await writeFile(join(root, "c"), "c");
const result = await readReferenceSource(root, {
...limits,
maxEntries: 1,
});
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.entries.map(({ path }) => path)).toEqual(["a"]);
expect(result.value.bytesRead).toBe(1);
expect(result.value.truncated).toBe(true);
});
it("applies exclusions to normalized paths before reading entries", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-reference-"));
await mkdir(join(root, "ignored"));
await writeFile(join(root, "ignored", "secret"), "secret");
await writeFile(join(root, "kept"), "kept");
const checked: string[] = [];
const result = await readReferenceSource(root, limits, {
shouldExclude: (path) => {
checked.push(path);
return path === "ignored";
},
});
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(checked).toEqual(["ignored", "kept"]);
expect(result.value.entries.map(({ path }) => path)).toEqual(["kept"]);
});
it("sanitizes exclusion callback failures", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-reference-"));
await writeFile(join(root, "file"), "value");
const result = await readReferenceSource(root, limits, {
shouldExclude: () => {
throw new Error("private callback detail");
},
});
expect(result).toEqual({
ok: false,
error: {
tag: "reference-source-reader",
code: "io",
message: "Reference source exclusion check failed",
},
});
});
it("sanitizes filesystem errors", async () => {
const missing = join(tmpdir(), "rea-secret-root-that-does-not-exist");
const result = await readReferenceSource(missing, limits);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error.message).toBe(
"Reference source root could not be resolved",
);
expect(result.error.message).not.toContain(missing);
});
it("returns typed failures for cancellation and invalid roots", async () => {
const controller = new AbortController();
controller.abort();
const cancelled = await readReferenceSource("/unused", limits, {
signal: controller.signal,
});
expect(cancelled).toEqual({
ok: false,
error: {
tag: "reference-source-reader",
code: "cancelled",
message: "Reference source traversal cancelled",
},
});
const invalid = await readReferenceSource(
"/path/that/does/not/exist",
limits,
);
expect(invalid.ok).toBe(false);
if (invalid.ok) return;
expect(invalid.error.code).toBe("invalid-root");
});
});
+286
View File
@@ -0,0 +1,286 @@
import { describe, expect, it } from "vitest";
import { EvidenceLedger } from "../src/application/EvidenceLedger.js";
import { createEvidence } from "../src/domain/evidence.js";
import {
createEvidenceBundle,
parseEvidenceBundle,
serializeEvidenceBundle,
} from "../src/domain/evidenceBundle.js";
import {
createResidualUnknown,
recordUnknownInputSchema,
updateUnknownInputSchema,
type RecordUnknownInput,
type ResidualUnknown,
} from "../src/domain/residualUnknown.js";
const provider = { id: "fixture", name: "Fixture", version: "1" };
const ledger = (): EvidenceLedger =>
new EvidenceLedger({ maxRecords: 1_000, maxBytes: 4 * 1024 * 1024 });
const evidence = (
label: string,
confidence: "observed" | "derived" | "inferred" = "derived",
) =>
createEvidence(undefined, provider, {
operation: label,
parameters: {},
result: { label },
confidence,
authority:
confidence === "observed" ? "controlled-replay" : "analyst-inference",
environment:
confidence === "observed"
? {
id: "fixture-linux",
platform: "linux",
architecture: "x86_64",
isolation: "process",
}
: null,
});
const input = (
question: string,
overrides: Partial<RecordUnknownInput> = {},
): RecordUnknownInput =>
recordUnknownInputSchema.parse({
approved: true,
question,
severity: "high",
domain: "protocol",
required_authority: "controlled-replay",
required_confidence: "observed",
required_environment: null,
recommended_probes: [],
relationships: [],
...overrides,
});
const mutation = (label: string) => evidence(`mutation-${label}`);
const update = (
unknown: ResidualUnknown,
overrides: Readonly<Record<string, unknown>> = {},
) =>
updateUnknownInputSchema.parse({
approved: true,
unknown_id: unknown.unknown_id,
expected_revision: unknown.revision,
status: "investigating",
severity: unknown.severity,
supporting_evidence_ids: unknown.supporting_evidence_ids,
contradicting_evidence_ids: unknown.contradicting_evidence_ids,
required_authority: unknown.required_authority,
required_confidence: unknown.required_confidence,
required_environment: unknown.required_environment,
recommended_probes: unknown.recommended_probes,
relationships: unknown.relationships,
resolution: null,
...overrides,
});
describe("residual unknown registry", () => {
it("requires approval, derives stable IDs, filters heads, and rejects duplicate creation", () => {
expect(() =>
recordUnknownInputSchema.parse({
...input("Is branch live?"),
approved: false,
}),
).toThrow();
const store = ledger();
const first = store.recordUnknown(
input(" Is branch live? "),
mutation("one"),
);
expect(first.ok).toBe(true);
if (!first.ok) return;
expect(first.value.unknown_id).toMatch(/^unk_[a-f0-9]{64}$/u);
expect(first.value.revision).toBe(1);
expect(store.listUnknowns({ severity: "high" })).toHaveLength(1);
expect(store.listUnknowns({ status: "resolved" })).toEqual([]);
const duplicate = store.recordUnknown(
input("Is branch live?"),
mutation("two"),
);
expect(duplicate.ok).toBe(false);
if (!duplicate.ok)
expect(duplicate.error._tag).toBe("UnknownRegistryError");
const mutationId = `ev_${"a".repeat(64)}`;
const normalized = createResidualUnknown(
input("A scoped question"),
mutationId,
"0".repeat(64),
);
expect(
createResidualUnknown(
input("A scoped question"),
mutationId,
"0".repeat(64),
).unknown_id,
).toBe(normalized.unknown_id);
expect(
createResidualUnknown(
input("A scoped question"),
mutationId,
"1".repeat(64),
).unknown_id,
).not.toBe(normalized.unknown_id);
});
it("uses immutable CAS revisions and rejects a stale concurrent writer atomically", () => {
const store = ledger();
const created = store.recordUnknown(
input("Which codec wins?"),
mutation("create"),
);
if (!created.ok) throw created.error;
const command = update(created.value);
const winner = store.updateUnknown(command, mutation("winner"));
expect(winner.ok).toBe(true);
const loser = store.updateUnknown(command, mutation("loser"));
expect(loser.ok).toBe(false);
if (!loser.ok) expect(loser.error.message).toContain("revision-conflict");
expect(store.export().unknowns.map(({ revision }) => revision)).toEqual([
1, 2,
]);
});
it("rejects inference for observed resolution, then accepts matching live evidence", () => {
const store = ledger();
const inferred = evidence("inference", "inferred");
expect(store.record(inferred).ok).toBe(true);
const created = store.recordUnknown(
input("Does replay confirm response?", {
supporting_evidence_ids: [inferred.evidence_id],
required_environment: {
id: "fixture-linux",
platform: "linux",
architecture: "x86_64",
isolation: "process",
},
}),
mutation("create-resolution"),
);
if (!created.ok) throw created.error;
const invalid = store.updateUnknown(
update(created.value, {
status: "resolved",
resolution: {
disposition: "verified",
rationale: "Inference alone is insufficient.",
evidence_ids: [inferred.evidence_id],
},
}),
mutation("invalid-resolution"),
);
expect(invalid.ok).toBe(false);
expect(store.listUnknowns()[0]?.revision).toBe(1);
const observed = evidence("replay", "observed");
expect(store.record(observed).ok).toBe(true);
const valid = store.updateUnknown(
update(created.value, {
status: "resolved",
supporting_evidence_ids: [inferred.evidence_id, observed.evidence_id],
resolution: {
disposition: "verified",
rationale: "Controlled replay directly observed response.",
evidence_ids: [observed.evidence_id],
},
}),
mutation("valid-resolution"),
);
expect(valid.ok).toBe(true);
if (valid.ok)
expect(store.verifyUnknownResolution(valid.value.unknown_id)).toEqual({
ok: true,
value: { valid: true, truthVerified: true, unknown: valid.value },
});
});
it("rejects broken references, dependency cycles, deletion, and tampering", () => {
const store = ledger();
const first = store.recordUnknown(input("First?"), mutation("first"));
if (!first.ok) throw first.error;
const second = store.recordUnknown(
input("Second?", {
relationships: [
{ type: "depends-on", unknown_id: first.value.unknown_id },
],
}),
mutation("second"),
);
if (!second.ok) throw second.error;
const cycle = store.updateUnknown(
update(first.value, {
relationships: [
{ type: "depends-on", unknown_id: second.value.unknown_id },
],
}),
mutation("cycle"),
);
expect(cycle.ok).toBe(false);
const bundle = store.export();
expect(parseEvidenceBundle(bundle)).toEqual(bundle);
expect(serializeEvidenceBundle(bundle)).toBe(
serializeEvidenceBundle(
createEvidenceBundle(
[...bundle.records].reverse(),
[...bundle.unknowns].reverse(),
),
),
);
expect(() =>
parseEvidenceBundle({ ...bundle, records: bundle.records.slice(1) }),
).toThrow(/missing evidence/u);
expect(() =>
parseEvidenceBundle({
...bundle,
unknowns: bundle.unknowns.map((unknown, index) =>
index === 0 ? { ...unknown, question: "tampered" } : unknown,
),
}),
).toThrow();
});
it("merges independent histories commutatively and rejects divergent heads atomically", () => {
const left = ledger();
const right = ledger();
expect(left.recordUnknown(input("Left?"), mutation("left")).ok).toBe(true);
expect(right.recordUnknown(input("Right?"), mutation("right")).ok).toBe(
true,
);
const leftThenRight = ledger();
const rightThenLeft = ledger();
expect(leftThenRight.import(left.export()).ok).toBe(true);
expect(leftThenRight.import(right.export()).ok).toBe(true);
expect(rightThenLeft.import(right.export()).ok).toBe(true);
expect(rightThenLeft.import(left.export()).ok).toBe(true);
expect(serializeEvidenceBundle(leftThenRight.export())).toBe(
serializeEvidenceBundle(rightThenLeft.export()),
);
const base = ledger();
const created = base.recordUnknown(input("Divergent?"), mutation("base"));
if (!created.ok) throw created.error;
const branch = ledger();
expect(branch.import(base.export()).ok).toBe(true);
expect(
base.updateUnknown(update(created.value), mutation("branch-left")).ok,
).toBe(true);
expect(
branch.updateUnknown(
update(created.value, { severity: "critical" }),
mutation("branch-right"),
).ok,
).toBe(true);
const before = serializeEvidenceBundle(base.export());
expect(base.import(branch.export()).ok).toBe(false);
expect(serializeEvidenceBundle(base.export())).toBe(before);
const bounded = new EvidenceLedger({ maxRecords: 1, maxBytes: 1_000_000 });
expect(
bounded.recordUnknown(input("Too many?"), mutation("bounded")).ok,
).toBe(false);
expect(bounded.export()).toMatchObject({ records: [], unknowns: [] });
});
});
+4 -4
View File
@@ -10,7 +10,7 @@ const fixturePath = fileURLToPath(
);
describe("production stdio runtime", () => {
it("starts the built entrypoint, lists 50 tools, calls one, and shuts down", async () => {
it("starts the built entrypoint, lists 68 tools, calls one, and shuts down", async () => {
const transport = new StdioClientTransport({
command: process.execPath,
args: [mainPath],
@@ -32,7 +32,7 @@ describe("production stdio runtime", () => {
try {
await client.connect(transport);
const tools = await client.listTools();
expect(tools.tools).toHaveLength(50);
expect(tools.tools).toHaveLength(68);
const result = await client.callTool({
name: "current_document",
arguments: {},
@@ -58,7 +58,7 @@ describe("production stdio runtime", () => {
);
expect(stderr).not.toContain("HOPPER_LOADER_ARGS_JSON");
expect(stderr).not.toContain(fixturePath);
});
}, 20_000);
it("honors the configured kind for an initial database target", async () => {
const transport = new StdioClientTransport({
@@ -78,7 +78,7 @@ describe("production stdio runtime", () => {
try {
await client.connect(transport);
expect((await client.listTools()).tools).toHaveLength(50);
expect((await client.listTools()).tools).toHaveLength(68);
} finally {
await client.close();
await transport.close();
+39
View File
@@ -0,0 +1,39 @@
import { access, mkdtemp, readdir } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { Readable } from "node:stream";
import { describe, expect, it } from "vitest";
import { SafeOutputTree } from "../src/artifacts/SafeOutputTree.js";
const LIMITS = {
maxEntries: 10,
maxTotalBytes: 1_024,
maxEntryBytes: 512,
maxCompressionRatio: 10,
maxDepth: 8,
maxPathBytes: 256,
} as const;
describe("safe artifact output transaction", () => {
it("removes only its owned tree after digest failure and proves absence", async () => {
const parent = await mkdtemp(join(tmpdir(), "rea-safe-output-"));
const output = join(parent, "published");
const transaction = await SafeOutputTree.create(output, LIMITS);
await expect(
transaction.write(
"nested/file.txt",
Readable.from(Buffer.from("unexpected")),
"0".repeat(64),
),
).rejects.toThrow(/disagrees/u);
expect(await transaction.rollback()).toMatchObject({
attempted: true,
verified: true,
residualPaths: [],
});
await expect(access(output)).rejects.toThrow();
expect(await readdir(parent)).toEqual([]);
});
});
+136 -4
View File
@@ -8,9 +8,10 @@ import { z } from "zod";
import { BinarySession } from "../src/application/BinarySession.js";
import type { AnalysisClient } from "../src/application/AnalysisProvider.js";
import { ok } from "../src/domain/result.js";
import { observed as ok } from "./fixtures/analysisExecution.js";
import { createServer } from "../src/server/createServer.js";
import { evidenceBundleSchema } from "../src/domain/evidenceBundle.js";
import { silentLogger } from "../src/logger.js";
const resources: Array<{ close(): Promise<unknown> }> = [];
let directory: string | undefined;
@@ -30,7 +31,16 @@ describe("target-free MCP lifecycle", () => {
await writeFile(second, "two");
const closed: string[] = [];
const session = new BinarySession((target) => client(target.path, closed));
const server = createServer(session, session);
const server = createServer(session, session, {
logger: silentLogger,
evidenceFilePolicy: {
roots: [directory],
maxBytes: 1024 * 1024,
maxDepth: 68,
maxStringLength: 1024,
maxNodes: 10_000,
},
});
const mcp = new Client({ name: "session-test", version: "1.0.0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
@@ -44,7 +54,7 @@ describe("target-free MCP lifecycle", () => {
});
expect(before.isError).toBe(true);
expect(text(before)).toContain("NoBinaryOpenError");
expect((await mcp.listTools()).tools).toHaveLength(50);
expect((await mcp.listTools()).tools).toHaveLength(68);
const deniedCapture = await mcp.callTool({
name: "capture_process_scenario",
arguments: {
@@ -68,14 +78,89 @@ describe("target-free MCP lifecycle", () => {
});
const bundle = evidenceBundleSchema.parse(structured(exported).result);
expect(bundle.records).toHaveLength(1);
const evidencePath = join(directory, "evidence.json");
expect(
structured(
await mcp.callTool({
name: "export_evidence_bundle",
arguments: { path: evidencePath },
}),
).result,
).toMatchObject({ path: evidencePath, records: 1 });
expect(
structured(
await mcp.callTool({
name: "import_evidence_bundle",
arguments: { bundle },
arguments: { path: evidencePath },
}),
).result,
).toEqual({ imported: 0, total: 1 });
const recordedUnknown = z
.object({
result: z.object({
unknown_id: z.string(),
revision: z.number(),
}),
})
.parse(
structured(
await mcp.callTool({
name: "record_unknown",
arguments: {
approved: true,
question: "Does the alternate branch execute?",
severity: "medium",
domain: "control-flow",
required_authority: "controlled-replay",
required_confidence: "observed",
required_environment: null,
recommended_probes: [],
relationships: [],
},
}),
),
).result;
expect(recordedUnknown.revision).toBe(1);
expect(
z
.object({ result: z.array(z.unknown()) })
.parse(
structured(
await mcp.callTool({ name: "list_unknowns", arguments: {} }),
),
).result,
).toHaveLength(1);
const resolved = await mcp.callTool({
name: "update_unknown",
arguments: {
approved: true,
unknown_id: recordedUnknown.unknown_id,
expected_revision: 1,
status: "resolved",
severity: "medium",
supporting_evidence_ids: [],
contradicting_evidence_ids: [],
required_authority: "controlled-replay",
required_confidence: "observed",
required_environment: null,
recommended_probes: [],
relationships: [],
resolution: {
disposition: "out-of-scope",
rationale: "Operator explicitly excluded this branch from scope.",
evidence_ids: [],
},
},
});
expect(resolved.isError).not.toBe(true);
expect(
structured(
await mcp.callTool({
name: "verify_unknown_resolution",
arguments: { unknown_id: recordedUnknown.unknown_id },
}),
).result,
).toMatchObject({ valid: true, truthVerified: false });
await mcp.callTool({ name: "open_binary", arguments: { path: second } });
expect(closed.some((path) => path.endsWith("first.hop"))).toBe(true);
expect(
@@ -85,6 +170,53 @@ describe("target-free MCP lifecycle", () => {
expect(
text(await mcp.callTool({ name: "binary_session", arguments: {} })),
).toContain('"open": false');
}, 20_000);
it("records approved process residuals in the unknown registry", async () => {
const session = new BinarySession(() => client("fixture", []));
const server = createServer(session, session, {
logger: silentLogger,
processPolicy: {
enabled: true,
executableRoots: ["/usr/bin"],
workingRoots: ["/tmp"],
allowedEnvironment: [],
allowExternalNetwork: true,
},
});
const mcp = new Client({ name: "process-unknown", version: "1.0.0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(mcp, server);
await server.connect(serverTransport);
await mcp.connect(clientTransport);
const captured = await mcp.callTool({
name: "capture_process_scenario",
arguments: {
approved: true,
unknown_registry_approved: true,
executable: "/usr/bin/printf",
arguments: ["abcdef"],
working_directory: "/tmp",
limits: { output_bytes: 1 },
},
});
expect(captured.isError).not.toBe(true);
const listed = z
.object({
result: z.array(z.object({ question: z.string(), domain: z.string() })),
})
.parse(
structured(
await mcp.callTool({ name: "list_unknowns", arguments: {} }),
),
).result;
expect(listed).toContainEqual({
question:
"network: External network isolation is not enforced by this adapter.",
domain: "process-network",
});
});
});
+37
View File
@@ -0,0 +1,37 @@
import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { installCanonicalSkill } from "../src/application/Setup.js";
import { TOOL_CONTRACTS } from "../src/contracts/toolContracts.js";
const roots: string[] = [];
afterEach(async () => {
await Promise.all(
roots.splice(0).map((root) => rm(root, { recursive: true })),
);
});
describe("canonical skill transaction", () => {
it("backs up and upgrades a stale managed skill without touching siblings", async () => {
const home = await mkdtemp(join(tmpdir(), "rea-skill-test-"));
roots.push(home);
const destination = join(home, ".agents/skills/rea-analysis/SKILL.md");
const sibling = join(home, ".agents/skills/unrelated/SKILL.md");
await mkdir(dirname(destination), { recursive: true });
await mkdir(dirname(sibling), { recursive: true });
await writeFile(destination, "stale managed skill\n");
await writeFile(sibling, "unrelated skill\n");
expect(await installCanonicalSkill(home)).toBe("installed");
expect(await readFile(`${destination}.rea.backup`, "utf8")).toBe(
"stale managed skill\n",
);
expect(await readFile(destination, "utf8")).toContain('version: "10"');
expect(await readFile(destination, "utf8")).toContain(
`tool_count: ${String(TOOL_CONTRACTS.length)}`,
);
expect(await readFile(sibling, "utf8")).toBe("unrelated skill\n");
expect(await installCanonicalSkill(home)).toBe("unchanged");
});
});
+244
View File
@@ -0,0 +1,244 @@
import { describe, expect, it } from "vitest";
import { INVESTIGATION_EXAMPLES } from "../src/contracts/investigationExamples.js";
import { createEvidence, type Evidence } from "../src/domain/evidence.js";
import type { JsonValue } from "../src/domain/jsonValue.js";
import {
correlateStaticAndRuntime,
staticRuntimeCorrelationResultSchema,
} from "../src/domain/staticRuntimeCorrelation.js";
const staticComparison =
INVESTIGATION_EXAMPLES.find_changed_behavior.comparisons[0];
if (staticComparison === undefined)
throw new Error("Missing static comparison fixture");
const capture = (digit: string): Evidence =>
createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
{
predicateType: "rea.process-capture/v2",
operation: "capture_process_scenario",
parameters: {},
result: { digit },
authority: "controlled-replay",
environment: {
id: `fixture-${digit}`,
platform: "test",
architecture: "test",
isolation: "process",
},
},
);
const leftCapture = capture("1");
const rightCapture = capture("2");
const processComparison = (
terminal: "unchanged" | "changed" | "unknown" | "truncated",
): Evidence => {
const result = {
status: terminal,
terminal,
exit: terminal === "truncated" ? "truncated" : "unchanged",
filesystem: terminal === "truncated" ? "truncated" : "unchanged",
protocol: terminal === "truncated" ? "truncated" : "unchanged",
process: terminal === "truncated" ? "truncated" : "unchanged",
limitations: terminal === "unknown" ? ["Terminal unavailable."] : [],
} satisfies JsonValue;
return createEvidence(
undefined,
{
id: "rea-process",
name: "REA deterministic process harness",
version: "1",
},
{
predicateType: "rea.process-comparison/v1",
operation: "compare_process_captures",
parameters: {
left_evidence_id: leftCapture.evidence_id,
right_evidence_id: rightCapture.evidence_id,
},
result,
confidence: "derived",
authority: "analyst-inference",
evidenceLinks: [leftCapture.evidence_id, rightCapture.evidence_id],
},
);
};
const mapping = (
runtime: Evidence,
expected: "cochanged" | "static_only" | "runtime_only" | "both_unchanged",
dimension: "terminal" | "exit" = "terminal",
) => ({
static_comparisons: [staticComparison],
runtime_comparisons: [runtime],
mappings: [
{
static: {
comparison_evidence_id: staticComparison.evidence_id,
selector: {
kind: "function" as const,
dimension: "pseudocode" as const,
},
},
runtime: {
comparison_evidence_id: runtime.evidence_id,
dimension,
},
side_alignment: "left_to_left" as const,
hypothesis: {
statement: "The static edit is associated with terminal behavior.",
expected_pattern: expected,
},
},
],
});
describe("static/runtime correlation", () => {
it("keeps consistent cochange as a hypothesis with complete citations", () => {
const runtime = processComparison("changed");
const result = correlateStaticAndRuntime(mapping(runtime, "cochanged"));
expect(staticRuntimeCorrelationResultSchema.parse(result)).toMatchObject({
status: "correlated",
summary: { hypotheses: 1, contradictions: 0, unresolved: 0 },
correlations: {
total: 1,
items: [
{
observed_pattern: "cochanged",
classification: "hypothesis",
side_alignment: "left_to_left",
},
],
},
});
expect(result.correlations.items[0]?.evidence_links).toEqual(
expect.arrayContaining([
staticComparison.evidence_id,
runtime.evidence_id,
leftCapture.evidence_id,
rightCapture.evidence_id,
]),
);
expect(result.limitations.join(" ")).toMatch(
/does not establish causality/u,
);
});
it("classifies an explicit expectation mismatch as contradiction", () => {
const result = correlateStaticAndRuntime(
mapping(processComparison("unchanged"), "cochanged"),
);
expect(result).toMatchObject({
status: "contradicted",
summary: { hypotheses: 0, contradictions: 1, unresolved: 0 },
correlations: {
items: [
{ observed_pattern: "static_only", classification: "contradiction" },
],
},
});
});
it("lets unknown and truncation dominate rather than imply equivalence", () => {
const unknown = correlateStaticAndRuntime(
mapping(processComparison("unknown"), "cochanged"),
);
const truncated = correlateStaticAndRuntime(
mapping(processComparison("truncated"), "cochanged"),
);
expect(unknown).toMatchObject({
status: "unknown",
correlations: { items: [{ classification: "unresolved_branch" }] },
});
expect(truncated).toMatchObject({
status: "truncated",
correlations: { items: [{ observed_pattern: "truncated" }] },
});
});
it("is order-stable, paginated, and rejects duplicates and absent selectors", () => {
const runtime = processComparison("changed");
const base = mapping(runtime, "cochanged");
const second = {
...base.mappings[0],
runtime: { ...base.mappings[0]!.runtime, dimension: "exit" as const },
hypothesis: {
statement: "The edit is associated with exit behavior.",
expected_pattern: "static_only" as const,
},
};
const forward = correlateStaticAndRuntime({
...base,
mappings: [base.mappings[0], second],
offset: 0,
limit: 1,
});
const reversed = correlateStaticAndRuntime({
...base,
mappings: [second, base.mappings[0]],
offset: 0,
limit: 1,
});
expect(reversed).toEqual(forward);
expect(forward.correlations).toMatchObject({ total: 2, next_offset: 1 });
expect(() =>
correlateStaticAndRuntime({
...base,
mappings: [base.mappings[0], base.mappings[0]],
}),
).toThrow(/duplicate mappings/u);
expect(() =>
correlateStaticAndRuntime({
...base,
mappings: [
{
...base.mappings[0],
static: {
...base.mappings[0]!.static,
selector: { kind: "function", dimension: "assembly" },
},
},
],
}),
).not.toThrow();
expect(() =>
correlateStaticAndRuntime({
...base,
mappings: [
{
...base.mappings[0],
static: {
comparison_evidence_id: runtime.evidence_id,
selector: { kind: "function", dimension: "pseudocode" },
},
},
],
}),
).toThrow(/absent static comparison/u);
});
it("rejects comparison citations that disagree with source parameters", () => {
const runtime = processComparison("changed");
const forged = createEvidence(undefined, runtime.provider, {
predicateType: runtime.predicate_type,
operation: runtime.operation,
parameters: {
left_evidence_id: leftCapture.evidence_id,
right_evidence_id: staticComparison.evidence_id,
},
result: runtime.normalized_result,
confidence: runtime.confidence,
authority: runtime.authority,
evidenceLinks: runtime.evidence_links,
});
const input = mapping(forged, "cochanged");
expect(() => correlateStaticAndRuntime(input)).toThrow(
/closure disagrees with its source parameters/u,
);
});
});
+18 -3
View File
@@ -6,11 +6,15 @@ import {
SESSION_TOOL_CONTRACTS,
TOOL_CONTRACTS,
} from "../src/contracts/toolContracts.js";
import { ARTIFACT_TOOL_CONTRACTS } from "../src/contracts/artifactToolContracts.js";
import { NATIVE_TOOL_CONTRACTS } from "../src/contracts/nativeToolContracts.js";
describe("tool contract inventory", () => {
it("publishes 43 analysis contracts and seven session tools", () => {
it("publishes 50 analysis contracts and eighteen session tools", () => {
expect(OFFICIAL_TOOL_CONTRACTS).toHaveLength(33);
expect(ENHANCED_TOOL_CONTRACTS).toHaveLength(10);
expect(NATIVE_TOOL_CONTRACTS).toHaveLength(5);
expect(ARTIFACT_TOOL_CONTRACTS).toHaveLength(2);
expect(SESSION_TOOL_CONTRACTS.map(({ name }) => name)).toEqual([
"open_binary",
"close_binary",
@@ -19,9 +23,20 @@ describe("tool contract inventory", () => {
"import_evidence_bundle",
"capture_process_scenario",
"compare_process_captures",
"compare_artifacts",
"compare_functions",
"compare_bundles",
"find_changed_behavior",
"build_call_path",
"correlate_static_and_runtime",
"verify_reconstruction",
"list_unknowns",
"record_unknown",
"update_unknown",
"verify_unknown_resolution",
]);
expect(TOOL_CONTRACTS).toHaveLength(50);
expect(new Set(TOOL_CONTRACTS.map(({ name }) => name)).size).toBe(50);
expect(TOOL_CONTRACTS).toHaveLength(68);
expect(new Set(TOOL_CONTRACTS.map(({ name }) => name)).size).toBe(68);
});
it("retains documented enhanced-tool limits at the input boundary", () => {
+35
View File
@@ -0,0 +1,35 @@
import { describe, expect, it } from "vitest";
import { z } from "zod";
import type { ToolContract } from "../src/contracts/toolContracts.js";
import { ok } from "../src/domain/result.js";
import { toCallToolResult } from "../src/server/toolResult.js";
const contract: ToolContract = {
name: "provider_neutral_fixture",
description: "Fixture contract for provider-neutral output validation.",
kind: "enhanced",
inputSchema: z.object({}),
outputSchema: z.object({ value: z.string() }),
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
},
examples: [{ title: "Example fixture request", input: {} }],
};
describe("tool result projection", () => {
it("classifies output contract failures without naming a provider", () => {
expect(toCallToolResult(ok({ value: 42 }), contract)).toEqual({
content: [
{
type: "text",
text: "AnalysisOutputError: Analysis output does not match the tool contract",
},
],
isError: true,
});
});
});