fix: resolve triaged correctness issues

This commit is contained in:
N0zoM1z0
2026-07-14 14:39:02 +08:00
parent 998697155d
commit e8ed3073ac
47 changed files with 992 additions and 197 deletions
+44
View File
@@ -8,6 +8,7 @@ import {
readAnalysisSnapshot,
writeAnalysisSnapshot,
} from "../src/application/AnalysisSnapshotFiles.js";
import { AnalysisSnapshotCache } from "../src/application/AnalysisSnapshotCache.js";
import {
createAnalysisSnapshotEntry,
parseAnalysisSnapshot,
@@ -27,6 +28,49 @@ afterEach(async () => {
});
describe("analysis snapshots", () => {
it("returns detached cache entries and evidence bundles", () => {
const cache = new AnalysisSnapshotCache();
const target = {
path: "/tmp/app",
sha256: "a".repeat(64),
kind: "executable",
format: "mach-o",
architecture: "arm64",
loaderArgs: [],
} as const;
const provider = { id: "fixture", name: "Fixture", version: "1" };
cache.record(
target,
"address_name",
{ address: "0x1000", document: "fixture" },
createAnalysisExecution("main", provider),
);
const exported = cache.export(target, createEvidenceBundle([]));
expect(exported.ok).toBe(true);
if (!exported.ok) return;
const entry = exported.value.entries[0];
if (entry !== undefined) {
Reflect.set(entry.execution, "provider", {
id: "forged",
name: "Forged",
version: "9",
});
(entry.execution.limitations as string[]).push("forged");
}
expect(
cache.lookup(
target,
"address_name",
{ address: "0x1000", document: "fixture" },
provider,
),
).toMatchObject({
provider,
limitations: [expect.stringContaining("local REA analysis snapshot")],
});
});
it("finds exact CLI evidence for provider-free replay", () => {
const target = {
path: "/tmp/app",
+4
View File
@@ -382,6 +382,10 @@ describe("artifact graph provider", () => {
expect(reader.provenance()).toEqual([
expect.objectContaining({ tool: "lipo", effects: ["read"] }),
]);
const provenance = reader.provenance();
if (provenance[0] !== undefined)
Reflect.set(provenance[0], "tool", "forged");
expect(reader.provenance()[0]?.tool).toBe("lipo");
});
});
+31
View File
@@ -14,6 +14,8 @@ import {
ProviderAdapterError,
} from "../src/domain/errors.js";
import { err } from "../src/domain/result.js";
import { createEvidenceBundle } from "../src/domain/evidenceBundle.js";
import { createInvestigationWorkspace } from "../src/domain/investigationWorkspace.js";
import { observed as ok } from "./fixtures/analysisExecution.js";
let directory: string | undefined;
@@ -24,6 +26,35 @@ afterEach(async () => {
});
describe("binary session", () => {
it("returns detached provider, target, and workspace metadata", async () => {
const [first] = await targets();
const session = new BinarySession(cacheProvider([]));
expect((await session.open(first)).ok).toBe(true);
const identity = session.providerIdentity();
Reflect.set(identity, "id", "forged");
expect(session.providerIdentity().id).toBe("fixture");
const active = session.activeTarget();
expect(active).toBeDefined();
if (active !== undefined) Reflect.set(active, "path", "/tmp/forged");
expect(session.activeTarget()?.path).toBe(first);
const workspace = createInvestigationWorkspace(
"Detached workspace",
createEvidenceBundle([]),
[],
);
expect(session.retainInvestigationWorkspace(workspace)).toBe("added");
const direct = session.investigationWorkspace(workspace.workspace_id, 1);
if (direct !== undefined) Reflect.set(direct, "revision", 999);
const listed = session.investigationWorkspaces()[0];
if (listed !== undefined) Reflect.set(listed, "workspace_id", "forged");
expect(
session.investigationWorkspace(workspace.workspace_id, 1),
).toMatchObject({ revision: 1, workspace_id: workspace.workspace_id });
await session.close();
});
it("runs through a non-Hopper analysis provider", async () => {
const [first] = await targets();
const operations: string[] = [];
+29 -2
View File
@@ -53,17 +53,19 @@ const processResult = (
overrides: Partial<{
status: "unchanged" | "changed" | "unknown" | "truncated";
terminal: "unchanged" | "changed" | "unknown" | "truncated";
interaction: "unchanged" | "changed" | "unknown" | "truncated";
exit: "unchanged" | "changed" | "unknown" | "truncated";
shim: "unchanged" | "changed" | "unknown" | "truncated";
}> = {},
): JsonValue => ({
status: overrides.status ?? "unchanged",
terminal: overrides.terminal ?? "unchanged",
interaction: "unchanged",
interaction: overrides.interaction ?? "unchanged",
exit: overrides.exit ?? "unchanged",
filesystem: "unchanged",
protocol: "unchanged",
process: "unchanged",
shim: "unchanged",
shim: overrides.shim ?? "unchanged",
first_divergence:
overrides.status === "changed"
? {
@@ -121,6 +123,31 @@ const artifactResult = (
});
describe("changed behavior", () => {
it("reports interaction and shim-only process changes", () => {
const evidence = comparison(
"compare_process_captures",
processResult({
status: "changed",
interaction: "changed",
shim: "changed",
}),
);
expect(findChangedBehavior([evidence], 0, 100)).toMatchObject({
behavior_status: "observed_changed",
summary: { observed_changes: 2 },
findings: {
items: expect.arrayContaining([
expect.objectContaining({
dimension: "interaction",
scope: "runtime",
}),
expect.objectContaining({ dimension: "shim", scope: "protocol" }),
]),
},
});
});
it("classifies runtime changes as observed and cites both observations", () => {
const evidence = comparison(
"compare_process_captures",
+18
View File
@@ -69,4 +69,22 @@ describe("derived MCP operation boundary", () => {
expect(notifications.map(({ params }) => params?.progress)).toEqual([0, 2]);
expect(notifications.every(({ params }) => params?.total === 2)).toBe(true);
});
it("projects synchronous computation failures into a typed result", async () => {
const result = await runDerivedOperation(
context(new AbortController()),
"compare_artifacts",
() => {
throw new TypeError("malformed comparison evidence");
},
);
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisInputError",
operation: "compare_artifacts",
},
});
});
});
+1 -2
View File
@@ -215,8 +215,7 @@ describe("enhanced MCP tools", () => {
);
}
expect(results[0]).toMatchObject({ count: 1 });
// Legacy behavior treats any `_OBJC_` label, including protocol labels, as a class.
expect(results[1]).toMatchObject({ count: 2 });
expect(results[1]).toMatchObject({ count: 1 });
expect(results[2]).toMatchObject({ count: 1 });
expect(results[3]).toEqual({
items: [
+22 -1
View File
@@ -290,7 +290,27 @@ describe("full MCP integration with multi-tool sequences", () => {
const left = processCaptureSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE);
const right = processCaptureSchema.parse({
...EMPTY_PROCESS_CAPTURE_EXAMPLE,
exit: { code: 1, signal: null, reason: "exited" },
interaction_events: [
{
sequence: 0,
scheduled_at_ms: 0,
dispatched_at_ms: 0,
type: "input",
data: "fixture",
outcome: "dispatched",
},
],
shim_events: [
{
sequence: 0,
at_ms: 0,
command: "fixture",
route_index: null,
arguments: [],
working_directory: "/tmp",
outcome: "unmatched",
},
],
});
const captureEvidence = (capture: typeof left) =>
createEvidence(undefined, PROCESS_PROVIDER, {
@@ -347,6 +367,7 @@ describe("full MCP integration with multi-tool sequences", () => {
{
status: "contradicted",
domain: "process-comparison",
question: "Process captures disagree across: interaction, shim",
contradicting_evidence_ids: [rightEvidence.evidence_id],
},
],
+4
View File
@@ -41,6 +41,10 @@ describe("native DMG artifact reader", () => {
const entries = [];
for await (const entry of reader.entries()) entries.push(entry.path);
expect(entries).toContain("image.dmg/Fixture/hello.txt");
const provenance = reader.provenance();
if (provenance[0] !== undefined)
Reflect.set(provenance[0], "tool", "forged");
expect(reader.provenance()[0]?.tool).toBe("hdiutil");
await reader.close();
expect(calls).toContainEqual(["verify", "/tmp/image.dmg"]);
expect(calls).toContainEqual(["detach", "/dev/disk-fixture"]);
+19
View File
@@ -7,6 +7,7 @@ import { afterEach, describe, expect, it } from "vitest";
import { NativeMacOSProvider } from "../src/native/NativeMacOSProvider.js";
import {
NativeCommandFailure,
XcrunCommandRunner,
type NativeCommandCapture,
type NativeCommandRunner,
} from "../src/native/CommandRunner.js";
@@ -22,6 +23,24 @@ afterEach(async () => {
});
describe("native macOS provider", () => {
it("retries a failed native tool resolution and caches only success", async () => {
let resolutions = 0;
const runner = new XcrunCommandRunner((tool) => {
resolutions += 1;
return Promise.resolve(
resolutions === 1
? err(new NativeCommandFailure(tool, "unavailable"))
: ok({ path: "/bin/true", sha256: "a".repeat(64) }),
);
});
const options = { timeoutMs: 1_000, maxOutputBytes: 1_024 };
expect((await runner.run("file", [], options)).ok).toBe(false);
expect((await runner.run("file", [], options)).ok).toBe(true);
expect((await runner.run("file", [], options)).ok).toBe(true);
expect(resolutions).toBe(2);
});
it("normalizes comprehensive Mach-O inspection with exact bounded provenance", async () => {
const runner = new FixtureRunner();
const client = new NativeMacOSProvider(runner, "darwin").createClient(
+134
View File
@@ -13,6 +13,14 @@ import {
ProcessCaptureError,
} from "../src/application/ProcessHarness.js";
import { snapshotRoots } from "../src/application/FilesystemSnapshot.js";
import {
prepareProcessCapture,
type ProcessPreparationHost,
} from "../src/application/ProcessCaptureLifecycle.js";
import { ProcessCheckpoints } from "../src/application/ProcessCheckpoints.js";
import { normalizeProcessSamples } from "../src/application/ProcessNormalization.js";
import { readLinuxChildren } from "../src/application/ProcessSampling.js";
import { TerminalRenderer } from "../src/application/TerminalRenderer.js";
import {
authorizeProcessScenario,
compareProcessCaptures,
@@ -106,6 +114,132 @@ describe("process capture domain", () => {
working_directory: "/tmp",
};
it("returns detached terminal and filesystem checkpoint observations", async () => {
const renderer = new TerminalRenderer({
columns: 40,
rows: 12,
scrollback: 100,
maxFrames: 10,
maxBytes: 10_000,
normalize: (value) => value,
});
renderer.write("A", 0);
const frames = await renderer.frames();
if (frames[0] !== undefined) Reflect.set(frames[0], "cursor_x", 999);
expect((await renderer.frames())[0]?.cursor_x).not.toBe(999);
await renderer.dispose();
const scenario = parseProcessScenario(base);
const checkpoints = new ProcessCheckpoints(
scenario,
Date.now(),
{ files: [], truncated: false },
undefined,
);
const first = await checkpoints.finish({ files: [], truncated: false });
if (first[0] !== undefined) Reflect.set(first[0], "name", "tampered");
const second = await checkpoints.finish({ files: [], truncated: false });
expect(second[0]?.name).toBe("before");
await checkpoints.dispose();
});
it("cleans the temporary root when capture home creation fails", async () => {
const cleaned: string[] = [];
const host: ProcessPreparationHost = {
createTemporaryRoot: () => Promise.resolve("/tmp/rea-process-fixture"),
createHome: () => Promise.reject(new Error("mkdir failed")),
cleanup: (path) => {
cleaned.push(path);
return Promise.resolve();
},
};
await expect(
prepareProcessCapture(
parseProcessScenario(base),
{
enabled: true,
executableRoots: ["/bin"],
workingRoots: ["/tmp"],
allowedEnvironment: [],
allowExternalNetwork: true,
},
undefined,
host,
),
).rejects.toThrow("mkdir failed");
expect(cleaned).toEqual(["/tmp/rea-process-fixture"]);
});
it("normalizes every sampled process identifier in command text", () => {
const samples = normalizeProcessSamples(
[
{
at_ms: 0,
pid: 101,
parent_pid: 0,
process_group_id: 101,
session_id: 101,
command: "root 101",
},
{
at_ms: 10,
pid: 202,
parent_pid: 101,
process_group_id: 101,
session_id: 101,
command: "child 202 peer=101 unrelated 1202",
},
],
parseProcessScenario(base),
101,
);
expect(samples[1]?.command).toBe("child <pid> peer=<pid> unrelated 1202");
});
it("collects and deduplicates children from every Linux thread", async () => {
const signal = new AbortController().signal;
expect(
await readLinuxChildren(100, signal, {
taskIds: () => Promise.resolve([100, 101, 102]),
children: (_pid, taskId) =>
Promise.resolve(
taskId === 100 ? "201 202" : taskId === 101 ? "202 203" : "",
),
}),
).toEqual([201, 202, 203]);
});
it("keeps interaction and shim residual uncertainty in separate scopes", () => {
const baseCapture = emptyCapture();
const interaction = parseProcessCapture({
...baseCapture,
residual_unknowns: [
{ scope: "interaction", reason: "Interaction capture was partial." },
],
});
const shim = parseProcessCapture({
...baseCapture,
residual_unknowns: [
{ scope: "shim", reason: "Shim capture was partial." },
],
});
expect(compareProcessCaptures(interaction, baseCapture)).toMatchObject({
status: "unknown",
terminal: "unchanged",
interaction: "unknown",
shim: "unchanged",
});
expect(compareProcessCaptures(shim, baseCapture)).toMatchObject({
status: "unknown",
terminal: "unchanged",
interaction: "unchanged",
shim: "unknown",
});
});
it("cancels filesystem snapshots before traversing declared roots", async () => {
const controller = new AbortController();
controller.abort();
+13
View File
@@ -175,4 +175,17 @@ describe("process CLI errors", () => {
"Capture evidence is not from the current process-capture workflow. Create new capture evidence, then try again.",
});
});
it("classifies malformed capture evidence as invalid input", async () => {
const root = await fixture();
const malformed = join(root, "malformed-evidence.json");
await writeFile(malformed, "{}");
expect(await compareProcessEvidenceFiles(malformed, malformed)).toEqual({
error: "Process command failed",
category: "invalid_input",
message:
"Capture evidence is malformed. Create new capture evidence, then try again.",
});
});
});
+7
View File
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from "vitest";
import {
cleanupOwnedProcessGroup,
parseProcessEnvironment,
type ProcessOwnershipHost,
} from "../src/application/ProcessOwnership.js";
@@ -36,6 +37,12 @@ const host = (
};
describe("owned process-group cleanup", () => {
it("drops nameless Linux environment entries", () => {
expect(
parseProcessEnvironment("=ignored\0REA_PROCESS_RUN_ID=owned\0EMPTY=\0"),
).toEqual({ REA_PROCESS_RUN_ID: "owned", EMPTY: "" });
});
it("signals only a group whose every member carries the run token", async () => {
const { adapter, signalGroup } = host({
100: { REA_PROCESS_RUN_ID: "run-token" },
+40
View File
@@ -6,6 +6,7 @@ import { describe, expect, it } from "vitest";
import {
readProjectPermissionStore,
revokeProjectPermissionGrant,
writeProjectPermissionStore,
} from "../src/application/ProjectPermissionStore.js";
@@ -60,4 +61,43 @@ describe("project permission store", () => {
error: { reason: "invalid" },
});
});
it("serializes concurrent grant revocations without losing an update", async () => {
const project = await mkdtemp(join(tmpdir(), "rea-policy-revoke-"));
const path = join(project, ".rea", "permissions.json");
const grant = (grantId: string) => ({
grant_id: grantId,
capability: "evidence_read" as const,
roots: [project],
executables: [],
environment_names: [],
network: "none" as const,
mount: false,
lifetime: "project" as const,
operation_identity: null,
expires_at: null,
});
expect(
(
await writeProjectPermissionStore(path, project, [
grant("grant-one"),
grant("grant-two"),
])
).ok,
).toBe(true);
const revoked = await Promise.all([
revokeProjectPermissionGrant(path, project, "grant-one"),
revokeProjectPermissionGrant(path, project, "grant-two"),
]);
expect(revoked).toEqual([
{ ok: true, value: true },
{ ok: true, value: true },
]);
expect(await readProjectPermissionStore(path, project)).toMatchObject({
ok: true,
value: { grants: [] },
});
});
});
+56
View File
@@ -161,6 +161,62 @@ const artifactComparison = (
);
describe("reconstruction verification", () => {
it("accepts interaction and shim behavioral claim dimensions", () => {
const left = source("1", "controlled-replay");
const right = source("2", "controlled-replay");
const result = {
status: "changed",
terminal: "unchanged",
interaction: "changed",
exit: "unchanged",
filesystem: "unchanged",
protocol: "unchanged",
process: "unchanged",
shim: "unchanged",
first_divergence: {
status: "found",
dimension: "interaction",
index: 0,
left_at_ms: 0,
right_at_ms: 0,
left: "left",
right: "right",
},
limitations: [],
} satisfies JsonValue;
const comparison = processComparison(left, right, result);
expect(
verifyReconstruction(
{
schema_version: 1,
name: "Interaction reconstruction",
claims: [
{
kind: "behavioral",
claim_id: "interaction",
title: "Interaction remains equivalent",
comparison_evidence_id: comparison.evidence_id,
dimension: "interaction",
},
{
kind: "behavioral",
claim_id: "shim",
title: "Shim remains equivalent",
comparison_evidence_id: comparison.evidence_id,
dimension: "shim",
},
],
},
createEvidenceBundle([comparison, right, left]),
0,
100,
),
).toMatchObject({
summary: { total: 2, passed: 1, failed: 1, unknown: 0 },
});
});
it("passes a complete authoritative claim with two-sided citations", () => {
const left = source("1", "controlled-replay");
const right = source("2", "controlled-replay");
+32
View File
@@ -78,6 +78,38 @@ const update = (
});
describe("residual unknown registry", () => {
it("returns detached unknowns and evidence bundles from every read surface", () => {
const store = ledger();
expect(store.record(evidence("detached-record")).ok).toBe(true);
const created = store.recordUnknown(
input("Does detached state remain intact?"),
mutation("detached-unknown"),
);
expect(created.ok).toBe(true);
if (!created.ok) return;
Reflect.set(created.value, "status", "resolved");
const listed = store.listUnknowns();
expect(listed[0]?.status).toBe("open");
if (listed[0] !== undefined) Reflect.set(listed[0], "status", "resolved");
const verified = store.verifyUnknownResolution(created.value.unknown_id);
expect(verified).toMatchObject({ ok: true, value: { valid: false } });
if (verified.ok) Reflect.set(verified.value.unknown, "status", "resolved");
const exported = store.export();
const exportedRecord = exported.records.find(
({ operation }) => operation === "detached-record",
);
if (exportedRecord !== undefined)
Reflect.set(exportedRecord, "operation", "forged");
expect(store.export().records.map(({ operation }) => operation)).toContain(
"detached-record",
);
expect(
store.verifyUnknownResolution(created.value.unknown_id),
).toMatchObject({ ok: true, value: { valid: false } });
});
it("requires approval, derives stable IDs, filters heads, and rejects duplicate creation", () => {
expect(() =>
recordUnknownInputSchema.parse({
+10
View File
@@ -56,4 +56,14 @@ describe("safe artifact output tree", () => {
"visible before seal",
);
});
it("returns detached cleanup reports", async () => {
const parent = await mkdtemp(join(tmpdir(), "rea-safe-output-"));
const tree = await SafeOutputTree.create(join(parent, "published"), LIMITS);
const cleanup = await tree.rollback();
(cleanup.residualPaths as string[]).push("/forged/path");
expect(tree.cleanup.residualPaths).toEqual([]);
expect((await tree.rollback()).residualPaths).toEqual([]);
});
});
+38 -1
View File
@@ -12,7 +12,11 @@ import type { AnalysisClient } from "../src/application/AnalysisProvider.js";
import { probeProcessCaptureCapability } from "../src/application/ProcessHarness.js";
import { observed as ok } from "./fixtures/analysisExecution.js";
import { createServer } from "../src/server/createServer.js";
import { evidenceBundleSchema } from "../src/domain/evidenceBundle.js";
import {
createEvidenceBundle,
evidenceBundleSchema,
} from "../src/domain/evidenceBundle.js";
import { createEvidence } from "../src/domain/evidence.js";
import { silentLogger } from "../src/logger.js";
const resources: Array<{ close(): Promise<unknown> }> = [];
@@ -54,6 +58,10 @@ describe("target-free MCP lifecycle", () => {
},
});
const mcp = new Client({ name: "session-test", version: "1.0.0" });
let resourceListChanges = 0;
mcp.setNotificationHandler("notifications/resources/list_changed", () => {
resourceListChanges += 1;
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(mcp, server);
@@ -116,6 +124,31 @@ describe("target-free MCP lifecycle", () => {
}),
).result,
).toEqual({ imported: 0, total: 1 });
const externalEvidencePath = join(directory, "external-evidence.json");
await writeFile(
externalEvidencePath,
JSON.stringify(
createEvidenceBundle([
createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
{ operation: "external_observation", parameters: {}, result: true },
),
]),
),
);
let changesBeforeMutation = resourceListChanges;
expect(
structured(
await mcp.callTool({
name: "import_evidence_bundle",
arguments: { path: externalEvidencePath },
}),
).result,
).toEqual({ imported: 1, total: 2 });
await new Promise<void>((resolve) => setImmediate(resolve));
expect(resourceListChanges).toBe(changesBeforeMutation + 1);
changesBeforeMutation = resourceListChanges;
const recordedUnknown = z
.object({
result: z.object({
@@ -142,6 +175,8 @@ describe("target-free MCP lifecycle", () => {
),
).result;
expect(recordedUnknown.revision).toBe(1);
await new Promise<void>((resolve) => setImmediate(resolve));
expect(resourceListChanges).toBe(changesBeforeMutation + 1);
expect(
z
.object({ result: z.array(z.unknown()) })
@@ -174,6 +209,8 @@ describe("target-free MCP lifecycle", () => {
},
});
expect(resolved.isError).not.toBe(true);
await new Promise<void>((resolve) => setImmediate(resolve));
expect(resourceListChanges).toBe(changesBeforeMutation + 2);
expect(
structured(
await mcp.callTool({
+11 -1
View File
@@ -88,7 +88,7 @@ const processComparison = (
const mapping = (
runtime: Evidence,
expected: "cochanged" | "static_only" | "runtime_only" | "both_unchanged",
dimension: "terminal" | "exit" = "terminal",
dimension: "terminal" | "interaction" | "exit" | "shim" = "terminal",
) => ({
static_comparisons: [staticComparison],
runtime_comparisons: [runtime],
@@ -115,6 +115,16 @@ const mapping = (
});
describe("static/runtime correlation", () => {
it("accepts interaction and shim runtime dimensions", () => {
const runtime = processComparison("unchanged");
expect(
correlateStaticAndRuntime(mapping(runtime, "static_only", "interaction")),
).toMatchObject({ status: "correlated" });
expect(
correlateStaticAndRuntime(mapping(runtime, "static_only", "shim")),
).toMatchObject({ status: "correlated" });
});
it("keeps consistent cochange as a hypothesis with complete citations", () => {
const runtime = processComparison("changed");
const result = correlateStaticAndRuntime(mapping(runtime, "cochanged"));
+18
View File
@@ -39,6 +39,24 @@ describe("symbol analysis", () => {
expect(discoverObjcProtocols(names)).toMatchObject({ count: 1 });
});
it("excludes Objective-C ivars, metaclasses, properties, and protocols from classes", () => {
const result = discoverObjcClasses(
[
{ address: "0x1", name: "_OBJC_IVAR_$_Fixture.value" },
{ address: "0x2", name: "_OBJC_METACLASS_$_Fixture" },
{ address: "0x3", name: "_OBJC_PROP_$_Fixture.value" },
{ address: "0x4", name: "_OBJC_PROTOCOL_$_FixtureProtocol" },
{ address: "0x5", name: "_OBJC_CLASS_$_Fixture" },
],
"",
);
expect(result).toMatchObject({
count: 1,
classes: [{ address: "0x5", name: "_OBJC_CLASS_$_Fixture" }],
});
});
it("categorizes every Swift mangling family and deduplicates names", () => {
const result = categorizeSwiftTypes([
{ address: "1", name: "_TtCClass" },