refactor!: enforce canonical evidence and provider boundaries

Deliver complete Evidence directly through MCP with required nullable analysis profiles and immutable per-server delivery settings. Bind selected environments at construction and require typed cleanup outcomes with retained retry ownership.

Remove test-only routing, duplicate session and snapshot metadata, producer-field repairs, and ambiguous provider arguments. Separate artifact byte identity from occurrence classification and retain typed source-map and partial native facts across CLI, MCP, and verifier consumers.

BREAKING CHANGE: obsolete Evidence envelopes, session aliases, incomplete snapshots, and missing normalized producer facts are no longer accepted.
This commit is contained in:
morluto
2026-10-09 20:18:52 +08:00
parent 2a7746998d
commit 63bf91405c
514 changed files with 9296 additions and 5825 deletions
+50
View File
@@ -2,10 +2,13 @@ import { describe, expect, it } from "vitest";
import {
CPU,
LC,
dylibCommand,
fatImage,
machoImage,
} from "../artifacts/apple/MachoImage.fixture.js";
import { parseMachoLayout } from "./AppleMachoSelection.js";
import { decodeAppleDispatchMetadata } from "./AppleDispatchMetadata.js";
describe("native Mach-O slice selection", () => {
it("accepts a FAT slice whose table identity and embedded header agree", () => {
@@ -28,3 +31,50 @@ describe("native Mach-O slice selection", () => {
);
});
});
describe("native Mach-O fixup load command boundaries", () => {
const decode = (command: Uint8Array) =>
decodeAppleDispatchMetadata(
Buffer.from(machoImage({ commands: [command] })),
100,
{ path: "/fixture/malformed.macho", sha256: "a".repeat(64) },
);
it.each<[string, number, number]>([
["chained-fixups", 0x80000034, 16],
["dyld-info", 0x22, 48],
["dyld-info-only", 0x80000022, 48],
["dylib", LC.LOAD_DYLIB, 24],
])(
"rejects truncated %s commands instead of reporting absent, complete fixups",
(_name, kind, minimumSize) => {
const command = Buffer.alloc(minimumSize - 8);
command.writeUInt32LE(kind, 0);
command.writeUInt32LE(command.length, 4);
expect(() => decode(command)).toThrow(/Truncated/u);
},
);
it("preserves valid library identity and rejects install names outside the command", () => {
const original = dylibCommand(LC.LOAD_DYLIB, "/usr/lib/libobjc.A.dylib");
const layout = parseMachoLayout(
Buffer.from(machoImage({ commands: [original] })),
"arm64",
);
expect(layout.fixups.dylibs).toEqual(["/usr/lib/libobjc.A.dylib"]);
for (const offset of [8, original.length]) {
const command = Buffer.from(original);
command.writeUInt32LE(offset, 8);
expect(() => decode(command)).toThrow(/outside its load command/u);
}
});
it("does not consume the following command's NUL as a dylib name terminator", () => {
const unterminated = Buffer.alloc(32, 0x41);
unterminated.writeUInt32LE(LC.LOAD_DYLIB, 0);
unterminated.writeUInt32LE(unterminated.length, 4);
unterminated.writeUInt32LE(24, 8);
// machoImage includes zero padding after sizeofcmds; it is outside this command.
expect(() => decode(unterminated)).toThrow(/Unterminated dylib/u);
});
});
+11 -8
View File
@@ -268,9 +268,11 @@ const collectFixupCommand = (
throw new RangeError("Fixup data exceeds the Mach-O slice");
return { offset, size: length };
};
if (kind === LC_DYLD_CHAINED_FIXUPS && size >= 16)
if (kind === LC_DYLD_CHAINED_FIXUPS) {
if (size < 16) throw new RangeError("Truncated chained-fixups command");
state.chained = range(cursor + 8);
else if ((kind === LC_DYLD_INFO || kind === LC_DYLD_INFO_ONLY) && size >= 48)
} else if (kind === LC_DYLD_INFO || kind === LC_DYLD_INFO_ONLY) {
if (size < 48) throw new RangeError("Truncated dyld-info command");
for (const [at, stream] of [
[cursor + 16, "bind"],
[cursor + 24, "weak"],
@@ -279,13 +281,14 @@ const collectFixupCommand = (
const bound = range(at);
if (bound.size > 0) state.binds.push({ ...bound, stream });
}
else if (DYLIB_COMMANDS.includes(kind) && size >= 24) {
} else if (DYLIB_COMMANDS.includes(kind)) {
if (size < 24) throw new RangeError("Truncated dylib command");
const nameOffset = bytes.readUInt32LE(cursor + 8);
if (nameOffset < 24 || nameOffset >= size)
throw new RangeError("Dylib install name is outside its load command");
const end = bytes.indexOf(0, cursor + nameOffset);
state.dylibs.push(
nameOffset >= size || end < 0 || end > cursor + size
? ""
: bytes.toString("utf8", cursor + nameOffset, end),
);
if (end < 0 || end >= cursor + size)
throw new RangeError("Unterminated dylib install name");
state.dylibs.push(bytes.toString("utf8", cursor + nameOffset, end));
}
};
+12 -4
View File
@@ -1,3 +1,4 @@
import { snapshotEnvironment } from "../process/snapshotEnvironment.js";
import { createHash, randomUUID } from "node:crypto";
import { createReadStream } from "node:fs";
import { realpath } from "node:fs/promises";
@@ -83,10 +84,14 @@ export type NativeToolResolver = (
/** Run allowlisted Xcode tools directly without a shell. */
export class XcrunCommandRunner implements NativeCommandRunner {
private readonly environment: NodeJS.ProcessEnv;
constructor(
environment: Readonly<NodeJS.ProcessEnv>,
private readonly resolveTool: NativeToolResolver = (tool, signal) =>
resolveXcrunTool(tool, signal),
) {}
resolveXcrunTool(tool, this.environment, signal),
) {
this.environment = snapshotEnvironment(environment);
}
run(
tool: string,
@@ -104,6 +109,7 @@ export class XcrunCommandRunner implements NativeCommandRunner {
arguments_,
tool,
options,
this.environment,
);
return captured.ok
? ok({
@@ -144,6 +150,7 @@ const ALLOWED_TOOLS = new Set([
/** Locate an Xcode tool through `xcrun --find` and sample its executable digest. */
export const resolveXcrunTool = async (
tool: string,
environment: Readonly<NodeJS.ProcessEnv>,
signal?: AbortSignal,
): Promise<Result<ResolvedTool, NativeCommandFailure>> => {
const found = await captureProcess(
@@ -151,6 +158,7 @@ export const resolveXcrunTool = async (
["--find", tool],
"xcrun",
signal === undefined ? {} : { signal },
environment,
);
if (!found.ok) {
return err(
@@ -247,6 +255,7 @@ const captureProcess = async (
readonly signal?: AbortSignal;
readonly acceptNonZero?: boolean;
},
environment: Readonly<NodeJS.ProcessEnv>,
): Promise<Result<ProcessCapture, NativeCommandFailure>> => {
const runId = `rea-native-command-${randomUUID()}`;
try {
@@ -256,11 +265,10 @@ const captureProcess = async (
arguments: [...arguments_],
runId,
env: {
PATH: "/usr/bin:/bin:/usr/sbin:/sbin",
LC_ALL: "C",
LANG: "C",
},
hostEnvironment: {},
hostEnvironment: environment,
...(options.signal === undefined ? {} : { signal: options.signal }),
},
{
+14 -2
View File
@@ -1,3 +1,4 @@
import { snapshotEnvironment } from "../process/snapshotEnvironment.js";
import { randomUUID } from "node:crypto";
import { open, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -165,10 +166,18 @@ const ATTACH_REMEDIATION =
/** Production tracer: `lldb --batch` running the REA LLDB bridge. */
export class LldbCallTracer implements NativeCallTracer {
private readonly environment: NodeJS.ProcessEnv;
constructor(
environment: Readonly<NodeJS.ProcessEnv>,
private readonly launch: typeof runLldb = runLldb,
private readonly resolveTool: typeof resolveXcrunTool = resolveXcrunTool,
) {}
private readonly resolveTool: (
tool: string,
signal?: AbortSignal,
) => ReturnType<typeof resolveXcrunTool> = (tool, signal) =>
resolveXcrunTool(tool, this.environment, signal),
) {
this.environment = snapshotEnvironment(environment);
}
async trace(
request: Parameters<NativeCallTracer["trace"]>[0],
@@ -258,6 +267,7 @@ export class LldbCallTracer implements NativeCallTracer {
deadlineMs: input.duration_ms + DEADLINE_GRACE_MS,
pidPath: paths.pid,
identityAckPath: paths.identityAck,
environment: this.environment,
...(signal === undefined ? {} : { signal }),
},
);
@@ -606,6 +616,7 @@ const runLldb = async (
readonly deadlineMs: number;
readonly pidPath: string;
readonly identityAckPath: string;
readonly environment: Readonly<NodeJS.ProcessEnv>;
},
): Promise<LldbExit> => {
if (options.signal?.aborted === true)
@@ -627,6 +638,7 @@ const runLldb = async (
runId: randomUUID(),
expectedCommand: executable,
signal: deadline.signal,
hostEnvironment: options.environment,
});
supervisor = new ProviderProcessSupervisor(
{
+33 -13
View File
@@ -1,8 +1,8 @@
import { snapshotEnvironment } from "../process/snapshotEnvironment.js";
import {
NATIVE_MACOS_PROVIDER_IDENTITY as IDENTITY,
nativeMacOSCapabilities,
} from "./NativeMacOSProviderMetadata.js";
export { NATIVE_MACOS_PROVIDER_IDENTITY } from "./NativeMacOSProviderMetadata.js";
import { inspectAppleDispatchMetadata } from "./AppleDispatchMetadata.js";
import { observeNativeUi } from "./NativeUiObservation.js";
import { LldbCallTracer, type NativeCallTracer } from "./LldbCallTracer.js";
@@ -25,6 +25,8 @@ import {
type NativeToolName,
} from "../contracts/native/nativeToolContracts.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import { toolContract } from "../contracts/toolContracts.js";
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
import type { EvidenceLocation } from "../domain/evidence.js";
import {
AnalysisCancelledError,
@@ -79,12 +81,17 @@ import {
/** Read-only semantic provider composed from Xcode command-line utilities. */
export class NativeMacOSProvider implements AnalysisProvider {
readonly #capabilities: readonly CapabilityDescriptor[];
readonly #environment: NodeJS.ProcessEnv;
constructor(
private readonly runner: NativeCommandRunner = new XcrunCommandRunner(),
environment: Readonly<NodeJS.ProcessEnv>,
private readonly runner: NativeCommandRunner = new XcrunCommandRunner(
environment,
),
platform: NodeJS.Platform = process.platform,
private readonly tracer: NativeCallTracer = new LldbCallTracer(),
private readonly tracer: NativeCallTracer = new LldbCallTracer(environment),
) {
this.#environment = snapshotEnvironment(environment, platform);
this.#capabilities = nativeMacOSCapabilities(platform);
}
@@ -97,7 +104,12 @@ export class NativeMacOSProvider implements AnalysisProvider {
}
createClient(target: BinaryTarget): AnalysisClient {
return new NativeMacOSClient(target, this.runner, this.tracer);
return new NativeMacOSClient(
target,
this.runner,
this.tracer,
this.#environment,
);
}
}
@@ -106,6 +118,7 @@ class NativeMacOSClient implements AnalysisClient {
private readonly target: BinaryTarget,
private readonly runner: NativeCommandRunner,
private readonly tracer: NativeCallTracer,
private readonly environment: Readonly<NodeJS.ProcessEnv>,
) {}
async execute(
@@ -118,6 +131,18 @@ class NativeMacOSClient implements AnalysisClient {
if (operation === "health")
return ok(createAnalysisExecution(null, IDENTITY));
if (operation === "inspect_native_dispatch_metadata") {
const input = toolContract(operation).inputSchema.safeParse(parameters);
if (!input.success)
return err(
analysisInputErrorFromIssues(
operation,
input.error.issues,
parameters,
{
cause: input.error,
},
),
);
if (this.target.kind !== "executable" || this.target.format !== "mach-o")
return err(
new AnalysisCapabilityUnavailableError(
@@ -127,15 +152,9 @@ class NativeMacOSClient implements AnalysisClient {
),
);
try {
const maxRecords = z
.number()
.int()
.min(1)
.max(20000)
.parse(parameters.max_records ?? 5000);
const result = await inspectAppleDispatchMetadata(
this.target,
maxRecords,
input.data.max_records,
options?.signal,
);
return ok(
@@ -191,6 +210,7 @@ class NativeMacOSClient implements AnalysisClient {
operation === "capture_native_ui_scenario"
) {
const result = await observeNativeUi(this.target, operation, parameters, {
environment: this.environment,
signal: options?.signal,
});
return result.ok
@@ -225,8 +245,8 @@ class NativeMacOSClient implements AnalysisClient {
}
}
close(): Promise<void> {
return Promise.resolve();
close(): Promise<Result<null, AnalysisError>> {
return Promise.resolve(ok(null));
}
#dispatch(
@@ -0,0 +1,60 @@
import { describe, expect, it } from "vitest";
import { NativeMacOSProvider } from "./NativeMacOSProvider.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import {
NativeFixtureRunner,
nativeMachoTarget,
} from "../../tests/fixtures/nativeCommands.js";
describe("native dispatch metadata input boundary", () => {
it("retains canonical argument failures before attempting target inspection", async () => {
const client = new NativeMacOSProvider(
{},
new NativeFixtureRunner(),
"darwin",
).createClient(nativeMachoTarget("/does-not-exist"));
const cases: ReadonlyArray<{
parameters: Readonly<Record<string, JsonValue>>;
path: string;
reason: string;
}> = [
{
parameters: { max_records: null },
path: "max_records",
reason: "invalid_type",
},
{
parameters: { max_records: "5" },
path: "max_records",
reason: "invalid_type",
},
{
parameters: { max_records: 0 },
path: "max_records",
reason: "out_of_range",
},
{
parameters: { max_record: 5 },
path: "max_record",
reason: "unknown_argument",
},
];
for (const { parameters, path, reason } of cases) {
const result = await client.execute(
"inspect_native_dispatch_metadata",
parameters,
);
if (result.ok)
throw new Error("Expected invalid dispatch metadata input");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "invalid_request",
details: {
operation: "inspect_native_dispatch_metadata",
issues: [{ path: [path], reason }],
},
});
}
});
});
+7 -2
View File
@@ -1,3 +1,4 @@
import { snapshotEnvironment } from "../process/snapshotEnvironment.js";
import { mkdir, mkdtemp, rm, symlink } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -9,7 +10,10 @@ import type { NativeUiHelper } from "./NativeUiObservation.js";
import { NATIVE_UI_HELPER_MAX_BUFFER } from "./NativeUiOutputBudget.js";
/** Lazily compile one owned helper per observation/scenario and remove its compiler cache. */
export const createNativeUiHelperRuntime = () => {
export const createNativeUiHelperRuntime = (
environment: Readonly<NodeJS.ProcessEnv>,
) => {
const selectedEnvironment = snapshotEnvironment(environment);
let root: string | undefined;
let executable: string | undefined;
const invoke: NativeUiHelper = async (parameters, signal) => {
@@ -46,7 +50,7 @@ export const createNativeUiHelperRuntime = () => {
timeout: 60_000,
maxBuffer: 1024 * 1024,
stopSignal: SWIFTC_INTERRUPT,
env: { ...process.env, TMPDIR: compilerTemporary },
env: { ...selectedEnvironment, TMPDIR: compilerTemporary },
...(signal === undefined ? {} : { signal }),
},
);
@@ -58,6 +62,7 @@ export const createNativeUiHelperRuntime = () => {
{
timeout: 30_000,
maxBuffer: NATIVE_UI_HELPER_MAX_BUFFER,
env: selectedEnvironment,
...(signal === undefined ? {} : { signal }),
},
);
+17 -4
View File
@@ -49,6 +49,7 @@ describe("native UI screenshot validation", () => {
"observe_native_ui",
{ ...scope, screenshot: true },
{
environment: {},
invoke: async () => ({
ok: true,
result: { ...snapshot, screenshot },
@@ -78,6 +79,7 @@ describe("native UI screenshot validation", () => {
"observe_native_ui",
{ ...scope, screenshot: true },
{
environment: {},
invoke: async () => ({
ok: true,
result: { ...snapshot, screenshot },
@@ -102,6 +104,7 @@ describe("native UI screenshot validation", () => {
"observe_native_ui",
{ ...scope, screenshot: true },
{
environment: {},
invoke: async () => ({
ok: true,
result: { ...snapshot, screenshot },
@@ -131,7 +134,7 @@ describe("native UI screenshot validation", () => {
target,
"observe_native_ui",
{ ...scope, accessibility: true },
{ invoke: async () => ({ ok: true, result: partial }) },
{ environment: {}, invoke: async () => ({ ok: true, result: partial }) },
);
expect(result.ok).toBe(true);
if (result.ok)
@@ -154,7 +157,7 @@ describe("native UI capture selection and budgets", () => {
target,
"observe_native_ui",
{ pid: 123, window_id: 456, screenshot: false, accessibility: true },
{ invoke },
{ environment: {}, invoke },
);
expect(observed.ok).toBe(true);
const captured = await observeNativeUi(
@@ -167,7 +170,7 @@ describe("native UI capture selection and budgets", () => {
accessibility: true,
steps: [{ kind: "click", path: [] }],
},
{ invoke },
{ environment: {}, invoke },
);
expect(captured.ok).toBe(true);
expect(calls).toBe(3);
@@ -190,6 +193,7 @@ describe("native UI capture selection and budgets", () => {
steps,
},
{
environment: {},
invoke: async (parameters) => {
nodeLimits.push(parameters.max_nodes);
return { ok: true, result: snapshot };
@@ -221,6 +225,7 @@ describe("native UI capture selection and budgets", () => {
})),
},
{
environment: {},
signal: controller.signal,
invoke: async () => {
controller.abort();
@@ -247,7 +252,10 @@ describe("native UI capture selection and budgets", () => {
...scope,
steps: [{ kind: "wait", milliseconds: 0 }],
},
{ invoke: async () => ({ ok: true, result: largeSnapshot }) },
{
environment: {},
invoke: async () => ({ ok: true, result: largeSnapshot }),
},
);
expect(result.ok).toBe(true);
if (result.ok)
@@ -265,6 +273,7 @@ describe("native UI target and cancellation failures", () => {
"ambiguous-window",
])("preserves actionable %s without fallback", async (code) => {
const result = await observeNativeUi(target, "observe_native_ui", scope, {
environment: {},
invoke: async () => ({
ok: false,
code,
@@ -276,6 +285,7 @@ describe("native UI target and cancellation failures", () => {
});
it("preserves the underlying helper failure reason in diagnostics", async () => {
const result = await observeNativeUi(target, "observe_native_ui", scope, {
environment: {},
invoke: async () => {
throw new Error(
"Native helper returned invalid JSON: Unexpected token",
@@ -305,6 +315,7 @@ describe("native UI target and cancellation failures", () => {
],
},
{
environment: {},
invoke: async (parameters) => {
calls.push(parameters);
return calls.length === 1
@@ -342,6 +353,7 @@ describe("native UI target and cancellation failures", () => {
],
},
{
environment: {},
signal: controller.signal,
invoke: async () => {
calls++;
@@ -354,6 +366,7 @@ describe("native UI target and cancellation failures", () => {
expect(result.ok).toBe(true);
if (result.ok) expect(result.value.steps[0]?.outcome).toBe("cancelled");
const replaced = await observeNativeUi(target, "observe_native_ui", scope, {
environment: {},
invoke: async () => ({
ok: true,
result: { ...snapshot, window: { ...snapshot.window, pid: 999 } },
+6 -2
View File
@@ -43,9 +43,13 @@ export const observeNativeUi = async (
target: BinaryTarget,
operation: "observe_native_ui" | "capture_native_ui_scenario",
parameters: unknown,
options: { signal?: AbortSignal | undefined; invoke?: NativeUiHelper } = {},
options: {
environment: Readonly<NodeJS.ProcessEnv>;
signal?: AbortSignal | undefined;
invoke?: NativeUiHelper;
},
): Promise<Result<z.infer<typeof nativeUiResultSchema>, AnalysisError>> => {
const runtime = createNativeUiHelperRuntime();
const runtime = createNativeUiHelperRuntime(options.environment);
try {
return await observeWithHelper(target, operation, parameters, {
...options,