Reverse engineer anything with agents, from app behavior down to native binaries.
TypeScript agent-skillsai-agentsbinary-analysisclaude-codeclicodexcordisdecompilerdeveloper-toolsdshdsh-pluginghidrahopperllmmcpmodel-context-protocolreareverse-engineeringstatic-analysistouhou
Merge origin/main into feat/native-call-observation
Kaoru082290b25f2e306d
diff --cc src/cli/nativeCallCommands.tsindex 0b134484b,000000000..8a796a2dfmode 100644,000000..100644--- a/src/cli/nativeCallCommands.ts+++ b/src/cli/nativeCallCommands.ts@@@ -1,57 -1,0 +1,57 @@@+import { z } from "incur";++import { runProviderAnalysis } from "../composition/directAnalysis.js";+import { CLI_COMMANDS } from "../cliCommandNames.js";+import { parseCliJsonInput } from "../cliJsonInput.js";+import { logCliCommand } from "../cliLogging.js";+import { AnalysisInputError } from "../domain/analysisErrorCore.js";+import { projectAnalysisError } from "../domain/analysisErrorProjection.js";+import { projectInputIssues } from "../domain/inputIssueProjection.js";+import { jsonValueSchema } from "../domain/jsonValue.js";- import { nativeCallObservationInputSchema } from "../domain/nativeCallObservation.js";++import { nativeCallObservationInputSchema } from "../domain/native/nativeCallObservation.js";+import type { Logger } from "../logger.js";+import type { CliInstance } from "./types.js";++const OPERATION = "observe_native_calls";++/** `observe-native-calls <path> <input-json>`: the MCP input object as JSON. */+export const registerNativeCallCommands = (+ cli: CliInstance,+ logger: Logger,+): void => {+ cli.command(CLI_COMMANDS.observeNativeCalls, {+ description:+ "Launch a Mach-O under LLDB and record entries into selected functions or Objective-C methods",+ args: z.object({+ path: z.string().describe("Mach-O or app path"),+ inputJson: z+ .string()+ .describe(+ "Inline JSON or a JSON file path: breakpoints, arguments, environment, duration_ms, max_events, argument_registers, backtrace_frames",+ ),+ }),+ run: ({ args }) =>+ logCliCommand(logger, CLI_COMMANDS.observeNativeCalls, async () => {+ const input = await parseCliJsonInput(args.inputJson, OPERATION);+ if (!input.ok) return input.error;+ const parsed = nativeCallObservationInputSchema.safeParse(input.value);+ if (!parsed.success)+ return {+ error: "Analysis failed",+ ...projectAnalysisError(+ new AnalysisInputError(+ OPERATION,+ undefined,+ projectInputIssues(parsed.error.issues, input.value),+ ),+ ),+ };+ return runProviderAnalysis(+ args.path,+ OPERATION,+ z.record(z.string(), jsonValueSchema).parse(parsed.data),+ logger,+ );+ }),+ });+};diff --cc src/contracts/native/nativeToolContracts.tsindex 52f20bfde,1e3785d4c..1a783043f--- a/src/contracts/native/nativeToolContracts.ts+++ b/src/contracts/native/nativeToolContracts.ts@@@ -1,5 -1,4 +1,5 @@@import { z } from "zod";- import { nativeCallObservationInputSchema } from "../domain/nativeCallObservation.js";++import { nativeCallObservationInputSchema } from "../../domain/native/nativeCallObservation.js";import {nativeUiObservationInputSchema,nativeUiScenarioInputSchema,diff --cc src/contracts/toolOutputSchemaGroups.tsindex 242960961,d939ff237..164fbc37e--- a/src/contracts/toolOutputSchemaGroups.ts+++ b/src/contracts/toolOutputSchemaGroups.ts@@@ -1,10 -1,9 +1,10 @@@import { z } from "zod";- import { nativeFunctionAnnotationsSchema } from "../domain/nativeFunctionAnnotations.js";- import { nativeLoadImageSchema } from "../domain/nativeLoadImage.js";- import { nativeUiResultSchema } from "../domain/nativeUiObservation.js";- import { nativeCallObservationResultSchema } from "../domain/nativeCallObservation.js";- import { nativeValueTraceSchema } from "../domain/nativeValueTrace.js";- import { nativeDataTypeSchema } from "../domain/nativeDataType.js";+ import { nativeFunctionAnnotationsSchema } from "../domain/native/nativeFunctionAnnotations.js";+ import { nativeLoadImageSchema } from "../domain/native/nativeLoadImage.js";+ import { nativeUiResultSchema } from "../domain/native/nativeUiObservation.js";+ import { nativeValueTraceSchema } from "../domain/native/nativeValueTrace.js";+ import { nativeDataTypeSchema } from "../domain/native/nativeDataType.js";++import { nativeCallObservationResultSchema } from "../domain/native/nativeCallObservation.js";import {nativeInstructionSchema,nativeCallTargetsSchema,diff --cc src/domain/native/nativeCallObservation.tsindex ecea77d77,000000000..ecea77d77mode 100644,000000..100644--- a/src/domain/native/nativeCallObservation.ts+++ b/src/domain/native/nativeCallObservation.tsdiff --cc src/native/LldbCallTracer.tsindex c57df4301,000000000..31b14731emode 100644,000000..100644--- a/src/native/LldbCallTracer.ts+++ b/src/native/LldbCallTracer.ts@@@ -1,400 -1,0 +1,400 @@@+import { spawn } from "node:child_process";+import { open, readFile, writeFile } from "node:fs/promises";+import { join } from "node:path";+import { fileURLToPath } from "node:url";++import { z } from "zod";++import {+ AnalysisCancelledError,+ AnalysisCapabilityUnavailableError,+ AnalysisTimeoutError,+} from "../domain/analysisErrorCore.js";+import type { AnalysisError } from "../domain/analysisErrorBase.js";+import {+ nativeCallEventSchema,+ nativeCodeLocationSchema,+ type NativeCallObservationInput,- } from "../domain/nativeCallObservation.js";++} from "../domain/native/nativeCallObservation.js";+import { ProviderAdapterError } from "../domain/providerAdapterError.js";+import { err, ok, type Result } from "../domain/result.js";+import { safeParseJson } from "../domain/safeJson.js";+import { execFileOutput } from "../process/ExecFileOutput.js";+import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";+import { resolveXcrunTool, type ResolvedTool } from "./CommandRunner.js";++const OPERATION = "observe_native_calls";+const PROVIDER = "native-macos";+/** Captured target output kept per stream; the rest is counted, not stored. */+const MAX_OUTPUT_BYTES = 1024 * 1024;+/** LLDB startup, symbol loading and teardown beyond the observation window. */+const DEADLINE_GRACE_MS = 60_000;+const DIAGNOSTIC_BYTES = 16 * 1024;++const BRIDGE = fileURLToPath(+ new URL("../../bridge/native/rea_lldb_tracer.py", import.meta.url),+);++/** JSON the LLDB bridge writes after a completed run. */+const tracedSchema = z.strictObject({+ status: z.literal("traced"),+ version: z.string(),+ pid: z.number().int().positive(),+ outcome: z.enum(["exited", "duration-elapsed", "event-limit", "stop-limit"]),+ exit_status: z.number().int().nullable(),+ exit_description: z.string().nullable(),+ killed: z.boolean(),+ terminated: z.boolean(),+ elapsed_ms: z.number().nonnegative(),+ breakpoints: z.array(+ z.strictObject({+ index: z.number().int().nonnegative(),+ location_count: z.number().int().nonnegative(),+ locations: z.array(nativeCodeLocationSchema),+ }),+ ),+ events: z.array(nativeCallEventSchema),+ other_stops: z.array(z.string()),+});++const tracerOutputSchema = z.discriminatedUnion("status", [+ tracedSchema,+ z.strictObject({+ status: z.enum(["target-error", "launch-error", "tracer-error"]),+ error: z.string().nullable(),+ }),+]);++/** Bounded text of one target output stream. */+export interface CapturedOutput {+ readonly text: string;+ readonly bytes: number;+ readonly truncated: boolean;+}++/** One completed LLDB observation, before projection into the result contract. */+export interface NativeCallTrace {+ readonly debugger: ResolvedTool & { readonly version: string | null };+ readonly run: z.infer<typeof tracedSchema>;+ readonly stdout: CapturedOutput;+ readonly stderr: CapturedOutput;+ /** REA confirmed the traced process no longer exists. */+ readonly terminated: boolean;+}++/** Launch one owned process under a debugger and record calls. */+export interface NativeCallTracer {+ trace(+ request: {+ readonly executable: string;+ readonly architecture: string;+ readonly input: NativeCallObservationInput;+ },+ signal?: AbortSignal,+ ): Promise<Result<NativeCallTrace, AnalysisError>>;+}++/** Remediation for a target LLDB may not debug. */+const ATTACH_REMEDIATION =+ "Allow debugging for this user (Developer Tools access: `DevToolsSecurity -enable`, or membership in the _developer group). A hardened-runtime target is debuggable only with the com.apple.security.get-task-allow entitlement; see inspect_signature's debugger-attach facet.";++/** Production tracer: `lldb --batch` running the REA LLDB bridge. */+export class LldbCallTracer implements NativeCallTracer {+ async trace(+ request: Parameters<NativeCallTracer["trace"]>[0],+ signal?: AbortSignal,+ ): Promise<Result<NativeCallTrace, AnalysisError>> {+ const lldb = await resolveXcrunTool("lldb", signal);+ if (!lldb.ok)+ return err(+ lldb.error.reason === "cancelled"+ ? new AnalysisCancelledError(OPERATION)+ : new AnalysisCapabilityUnavailableError(+ PROVIDER,+ OPERATION,+ "LLDB from Xcode or the Command Line Tools is not available",+ ),+ );+ const root = await PrivateRuntimeRoot.create({ prefix: "rea-lldb-" });+ try {+ return await this.#run(lldb.value, root.path, request, signal);+ } finally {+ await root.close();+ }+ }++ async #run(+ lldb: ResolvedTool,+ directory: string,+ request: Parameters<NativeCallTracer["trace"]>[0],+ signal?: AbortSignal,+ ): Promise<Result<NativeCallTrace, AnalysisError>> {+ const paths = {+ config: join(directory, "config.json"),+ result: join(directory, "result.json"),+ pid: join(directory, "pid"),+ stdout: join(directory, "stdout"),+ stderr: join(directory, "stderr"),+ };+ const { input } = request;+ await writeFile(+ paths.config,+ JSON.stringify({+ executable: request.executable,+ architecture: request.architecture,+ arguments: input.arguments,+ environment: input.environment,+ working_directory: input.working_directory ?? null,+ breakpoints: input.breakpoints.map((breakpoint) =>+ breakpoint.kind === "function"+ ? { ...breakpoint, module: breakpoint.module ?? null }+ : { ...breakpoint, class_name: breakpoint.class_name ?? null },+ ),+ duration_ms: input.duration_ms,+ max_events: input.max_events,+ argument_registers: input.argument_registers,+ backtrace_frames: input.backtrace_frames,+ stdout_path: paths.stdout,+ stderr_path: paths.stderr,+ result_path: paths.result,+ pid_path: paths.pid,+ }),+ { mode: 0o600 },+ );+ const exited = await runLldb(+ lldb.path,+ [+ "--batch",+ "--no-lldbinit",+ "--no-use-colors",+ "-o",+ `command script import ${quote(BRIDGE)}`,+ "-o",+ `rea_trace ${paths.config}`,+ ],+ {+ deadlineMs: input.duration_ms + DEADLINE_GRACE_MS,+ ...(signal === undefined ? {} : { signal }),+ },+ );+ const terminated = await ensureTerminated(paths.pid, request.executable);+ if (exited.kind === "cancelled")+ return err(new AnalysisCancelledError(OPERATION));+ if (exited.kind === "timeout")+ return err(+ new AnalysisTimeoutError(+ OPERATION,+ input.duration_ms + DEADLINE_GRACE_MS,+ ),+ );+ const output = await readTracerOutput(paths.result);+ if (output === undefined)+ return err(+ new ProviderAdapterError(PROVIDER, OPERATION, {+ diagnostics: {+ reason: "LLDB exited without a tracer result",+ exit_code: exited.exitCode,+ lldb_output: exited.output,+ },+ }),+ );+ if (output.status !== "traced") return err(tracerFailure(output));+ return ok({+ debugger: { ...lldb, version: output.version },+ run: output,+ stdout: await capturedOutput(paths.stdout),+ stderr: await capturedOutput(paths.stderr),+ terminated,+ });+ }+}++/** LLDB command arguments are quoted; the bridge path is REA's own install path. */+const quote = (value: string): string =>+ `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;++const tracerFailure = (output: {+ readonly status: "target-error" | "launch-error" | "tracer-error";+ readonly error: string | null;+}): AnalysisError => {+ const message = output.error ?? "no LLDB error text";+ if (output.status === "tracer-error")+ return new ProviderAdapterError(PROVIDER, OPERATION, {+ diagnostics: { reason: `LLDB bridge failed: ${message}` },+ });+ if (output.status === "target-error")+ return new AnalysisCapabilityUnavailableError(+ PROVIDER,+ OPERATION,+ `lldb-target-unloadable: ${message}`,+ );+ // debugserver reports denied task access as an attach failure.+ return /attach|not allowed|permission|denied|debugserver/iu.test(message)+ ? new AnalysisCapabilityUnavailableError(+ PROVIDER,+ OPERATION,+ `debugger-attach-denied: ${message}`,+ { userMessage: ATTACH_REMEDIATION },+ )+ : new AnalysisCapabilityUnavailableError(+ PROVIDER,+ OPERATION,+ `launch-failed: ${message}`,+ );+};++const readTracerOutput = async (+ path: string,+): Promise<z.infer<typeof tracerOutputSchema> | undefined> => {+ let text: string;+ try {+ text = await readFile(path, "utf8");+ } catch {+ return undefined;+ }+ const parsed = safeParseJson(text);+ if (!parsed.ok) return undefined;+ const output = tracerOutputSchema.safeParse(parsed.value);+ return output.success ? output.data : undefined;+};++const capturedOutput = async (path: string): Promise<CapturedOutput> => {+ let handle;+ try {+ handle = await open(path, "r");+ } catch {+ return { text: "", bytes: 0, truncated: false };+ }+ try {+ const { size } = await handle.stat();+ const buffer = Buffer.alloc(Math.min(size, MAX_OUTPUT_BYTES));+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);+ return {+ text: buffer.subarray(0, bytesRead).toString("utf8"),+ bytes: size,+ truncated: size > MAX_OUTPUT_BYTES,+ };+ } finally {+ await handle.close();+ }+};++type LldbExit =+ | {+ readonly kind: "exited";+ readonly exitCode: number | null;+ readonly output: string;+ }+ | { readonly kind: "cancelled" }+ | { readonly kind: "timeout" };++/** Run LLDB in its own process group so cancellation can stop it and debugserver. */+const runLldb = (+ executable: string,+ arguments_: readonly string[],+ options: { readonly signal?: AbortSignal; readonly deadlineMs: number },+): Promise<LldbExit> =>+ new Promise((resolve) => {+ if (options.signal?.aborted === true) {+ resolve({ kind: "cancelled" });+ return;+ }+ const child = spawn(executable, [...arguments_], {+ shell: false,+ detached: true,+ stdio: ["ignore", "pipe", "pipe"],+ });+ let output = "";+ let stopped: "cancelled" | "timeout" | undefined;+ const keep = (chunk: Buffer): void => {+ output = (output + chunk.toString("utf8")).slice(-DIAGNOSTIC_BYTES);+ };+ child.stdout.on("data", keep);+ child.stderr.on("data", keep);+ const kill = (reason: "cancelled" | "timeout"): void => {+ stopped ??= reason;+ if (child.pid !== undefined)+ try {+ process.kill(-child.pid, "SIGKILL");+ } catch {+ // The group already exited.+ }+ };+ const timer = setTimeout(() => {+ kill("timeout");+ }, options.deadlineMs);+ const onAbort = (): void => {+ kill("cancelled");+ };+ options.signal?.addEventListener("abort", onAbort, { once: true });+ const finish = (exitCode: number | null): void => {+ clearTimeout(timer);+ options.signal?.removeEventListener("abort", onAbort);+ resolve(+ stopped === undefined+ ? { kind: "exited", exitCode, output }+ : { kind: stopped },+ );+ };+ child.on("error", () => {+ finish(null);+ });+ child.on("close", (code) => {+ finish(code);+ });+ });++/**+ * debugserver kills the traced process when LLDB exits. Confirm it, and kill a+ * survivor only when its executable is still the traced one.+ */+const ensureTerminated = async (+ pidPath: string,+ executable: string,+): Promise<boolean> => {+ let pid: number;+ try {+ pid = Number.parseInt(await readFile(pidPath, "utf8"), 10);+ } catch {+ // LLDB never launched the target.+ return true;+ }+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;+ for (let attempt = 0; attempt < 20; attempt++) {+ if (!alive(pid)) return true;+ if (attempt === 10 && (await commandOf(pid)) === executable)+ try {+ process.kill(pid, "SIGKILL");+ } catch {+ // It exited between the checks.+ }+ await new Promise((resolve) => setTimeout(resolve, 100));+ }+ return !alive(pid);+};++const alive = (pid: number): boolean => {+ try {+ process.kill(pid, 0);+ return true;+ } catch (cause: unknown) {+ return !(+ cause instanceof Error &&+ "code" in cause &&+ cause.code === "ESRCH"+ );+ }+};++const commandOf = async (pid: number): Promise<string | undefined> => {+ try {+ const { stdout } = await execFileOutput(+ "/bin/ps",+ ["-o", "comm=", "-p", String(pid)],+ { timeout: 5_000 },+ );+ return stdout.trim();+ } catch {+ return undefined;+ }+};diff --cc src/native/NativeCallObservation.tsindex 9fabda350,000000000..747ee58a6mode 100644,000000..100644--- a/src/native/NativeCallObservation.ts+++ b/src/native/NativeCallObservation.ts@@@ -1,182 -1,0 +1,182 @@@+import { createHash } from "node:crypto";+import { open } from "node:fs/promises";++import {+ AnalysisCancelledError,+ AnalysisCapabilityUnavailableError,+ AnalysisInputError,+} from "../domain/analysisErrorCore.js";+import type { AnalysisError } from "../domain/analysisErrorBase.js";+import type { BinaryTarget } from "../domain/binaryTarget.js";+import { EvidenceIntegrityError } from "../domain/evidenceErrors.js";+import type { JsonValue } from "../domain/jsonValue.js";+import {+ nativeCallObservationInputSchema,+ nativeCallObservationResultSchema,+ type NativeCallObservationInput,+ type NativeCallObservationResult,- } from "../domain/nativeCallObservation.js";++} from "../domain/native/nativeCallObservation.js";+import { err, ok, type Result } from "../domain/result.js";+import type { NativeCallTrace, NativeCallTracer } from "./LldbCallTracer.js";++const OPERATION = "observe_native_calls";++/** What every call observation leaves unobserved or approximated. */+export const NATIVE_CALL_OBSERVATION_LIMITATIONS = [+ "Only entries are observed; return values, floating-point and stack-passed arguments are not captured.",+ "Registers are the raw integer argument registers at entry. For Objective-C methods the first two hold the receiver and the selector.",+ "Receiver classes come from LLDB's Objective-C runtime reader without running target code; they are null for class methods and for receivers LLDB cannot classify.",+ "Calls that never reach a symbol's entry, such as inlined code or objc_direct methods called directly, are not observed.",+ "The target is launched directly under LLDB, not through LaunchServices; LLDB disables ASLR for it, so load addresses can equal file addresses.",+ "The observation window is checked about once a second, and recording pauses the process at every entry, which slows it.",+] as const;++/** Launch the active Mach-O under LLDB, record requested call entries, then stop it. */+export const observeNativeCalls = async (+ target: BinaryTarget,+ parameters: Readonly<Record<string, JsonValue>>,+ tracer: NativeCallTracer,+ signal?: AbortSignal,+): Promise<Result<NativeCallObservationResult, AnalysisError>> => {+ if (target.kind !== "executable" || target.format !== "mach-o")+ return err(+ new AnalysisCapabilityUnavailableError(+ "native-macos",+ OPERATION,+ "Native call observation launches a Mach-O executable; the active target is not one",+ ),+ );+ const parsed = nativeCallObservationInputSchema.safeParse(parameters);+ if (!parsed.success)+ return err(new AnalysisInputError(OPERATION, { cause: parsed.error }));+ // Observe the bytes the session's other Evidence describes.+ if ((await fileSha256(target.path, signal)) !== target.sha256)+ return err(+ new EvidenceIntegrityError(+ "Native call observation target digest changed after session binding",+ ),+ );+ if (signal?.aborted === true)+ return err(new AnalysisCancelledError(OPERATION));+ const traced = await tracer.trace(+ {+ executable: target.path,+ architecture: target.architecture,+ input: parsed.data,+ },+ signal,+ );+ if (!traced.ok) return traced;+ return ok(projectNativeCalls(target, parsed.data, traced.value));+};++/** Join the request, the tracer's run and REA's own checks into the result contract. */+export const projectNativeCalls = (+ target: Pick<BinaryTarget, "path" | "sha256"> & {+ readonly architecture: string;+ },+ input: NativeCallObservationInput,+ trace: NativeCallTrace,+): NativeCallObservationResult => {+ const { run } = trace;+ const unresolved = run.breakpoints+ .filter(({ location_count: count }) => count === 0)+ .map(({ index }) => index);+ const eventLimit = run.outcome === "event-limit";+ const partial =+ eventLimit || run.outcome === "stop-limit" || unresolved.length > 0;+ return nativeCallObservationResultSchema.parse({+ target: {+ path: target.path,+ sha256: target.sha256,+ architecture: target.architecture,+ arguments: input.arguments,+ working_directory: input.working_directory ?? null,+ },+ debugger: trace.debugger,+ process: {+ pid: run.pid,+ outcome: run.outcome,+ exit_status: run.exit_status,+ exit_description: run.exit_description,+ terminated: run.terminated && trace.terminated,+ elapsed_ms: run.elapsed_ms,+ stdout: trace.stdout,+ stderr: trace.stderr,+ other_stops: run.other_stops,+ },+ breakpoints: input.breakpoints.map((request, index) => ({+ index,+ request:+ request.kind === "function"+ ? { ...request, module: request.module ?? null }+ : { ...request, class_name: request.class_name ?? null },+ location_count: run.breakpoints[index]?.location_count ?? 0,+ locations: run.breakpoints[index]?.locations ?? [],+ })),+ events: run.events,+ coverage: {+ status: partial ? "partial" : "complete",+ event_limit_reached: eventLimit,+ unresolved_breakpoints: unresolved,+ },+ limitations: [+ ...NATIVE_CALL_OBSERVATION_LIMITATIONS,+ ...(eventLimit+ ? [+ `Observation stopped at max_events (${input.max_events}); later calls were not recorded and the process was killed.`,+ ]+ : []),+ ...(run.outcome === "duration-elapsed"+ ? [+ `The process was still running after duration_ms (${input.duration_ms}) and was killed.`,+ ]+ : []),+ ...(run.outcome === "stop-limit"+ ? [+ "Observation stopped after repeated signal or exception stops; the process was killed.",+ ]+ : []),+ ...(unresolved.length === 0+ ? []+ : [+ `Breakpoints ${unresolved.join(", ")} matched no code in any image loaded while observing; their calls could not be observed.`,+ ]),+ ...(run.breakpoints.some(+ ({ location_count: count, locations }) => locations.length < count,+ )+ ? [+ "Breakpoints with many matching locations list only the first 64; location_count gives the total.",+ ]+ : []),+ ...(trace.stdout.truncated || trace.stderr.truncated+ ? ["Target output beyond 1 MiB per stream is counted but not kept."]+ : []),+ ...(run.terminated && trace.terminated+ ? []+ : [+ `REA could not confirm that process ${run.pid} exited; check for it before relying on host state.`,+ ]),+ ],+ });+};++const fileSha256 = async (+ path: string,+ signal?: AbortSignal,+): Promise<string> => {+ const handle = await open(path, "r");+ try {+ const hash = createHash("sha256");+ const buffer = new Uint8Array(1024 * 1024);+ for (;;) {+ signal?.throwIfAborted();+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);+ if (bytesRead === 0) break;+ hash.update(buffer.subarray(0, bytesRead));+ }+ return hash.digest("hex");+ } finally {+ await handle.close();+ }+};diff --cc tests/boundary/mcp/nativeCallObservationMcp.test.tsindex 12a3969d4,000000000..ba16770damode 100644,000000..100644--- a/tests/boundary/mcp/nativeCallObservationMcp.test.ts+++ b/tests/boundary/mcp/nativeCallObservationMcp.test.ts@@@ -1,114 -1,0 +1,114 @@@+import { writeFile } from "node:fs/promises";+import { join } from "node:path";++import { Client, InMemoryTransport } from "@modelcontextprotocol/client";+import { expect, it } from "vitest";+import { z } from "zod";+- import { nativeCallObservationResultSchema } from "../../../src/domain/nativeCallObservation.js";++import { nativeCallObservationResultSchema } from "../../../src/domain/native/nativeCallObservation.js";+import { ok } from "../../../src/domain/result.js";+import type { NativeCallTracer } from "../../../src/native/LldbCallTracer.js";+import { NativeMacOSProvider } from "../../../src/native/NativeMacOSProvider.js";+import { createServer } from "../../../src/server/createServer.js";+import { createTestBinarySession } from "../../fixtures/binarySession.js";+import { NativeFixtureRunner } from "../../fixtures/nativeCommands.js";+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";++/** A thin little-endian arm64 MH_EXECUTE header with no load commands. */+const machoHeader = (): Buffer => {+ const header = Buffer.alloc(32);+ header.writeUInt32LE(0xfeedfacf, 0);+ header.writeUInt32LE(0x0100000c, 4);+ header.writeUInt32LE(2, 12);+ return header;+};++const tracer: NativeCallTracer & { calls: number } = {+ calls: 0,+ trace(request) {+ this.calls++;+ return Promise.resolve(+ ok({+ debugger: {+ path: "/usr/bin/lldb",+ sha256: "b".repeat(64),+ version: "lldb-fixture",+ },+ run: {+ status: "traced",+ version: "lldb-fixture",+ pid: 99,+ outcome: "exited",+ exit_status: 0,+ exit_description: null,+ killed: false,+ terminated: true,+ elapsed_ms: 1,+ breakpoints: request.input.breakpoints.map((_, index) => ({+ index,+ location_count: 1,+ locations: [],+ })),+ events: [],+ other_stops: [],+ },+ stdout: { text: "", bytes: 0, truncated: false },+ stderr: { text: "", bytes: 0, truncated: false },+ terminated: true,+ }),+ );+ },+};++it("routes observe_native_calls through MCP with schema-checked input and output", async () => {+ const directory = await createTestTempDirectory("rea-native-calls-mcp-");+ const path = join(directory, "Tool");+ await writeFile(path, machoHeader());+ const session = createTestBinarySession(+ new NativeMacOSProvider(new NativeFixtureRunner(), "darwin", tracer),+ );+ const server = createServer(session, session);+ const client = new Client({ name: "native-calls-mcp-test", version: "1" });+ const [clientTransport, serverTransport] =+ InMemoryTransport.createLinkedPair();+ try {+ await server.connect(serverTransport);+ await client.connect(clientTransport);+ const opened = await client.callTool({+ name: "open_binary",+ arguments: { path },+ });+ expect(opened.isError, JSON.stringify(opened)).not.toBe(true);+ const called = await client.callTool({+ name: "observe_native_calls",+ arguments: {+ breakpoints: [{ kind: "function", name: "open" }],+ duration_ms: 1000,+ },+ });+ expect(called.isError, JSON.stringify(called.structuredContent)).not.toBe(+ true,+ );+ const result = nativeCallObservationResultSchema.parse(+ z.object({ result: z.unknown() }).parse(called.structuredContent).result,+ );+ expect(result.process).toMatchObject({ pid: 99, outcome: "exited" });+ expect(result.breakpoints[0]?.request).toEqual({+ kind: "function",+ name: "open",+ module: null,+ });+ const rejected = await client.callTool({+ name: "observe_native_calls",+ arguments: {+ breakpoints: [{ kind: "function", name: "open" }],+ duration_ms: 1,+ },+ });+ expect(rejected.isError).toBe(true);+ expect(tracer.calls).toBe(1);+ } finally {+ await client.close();+ await server.close();+ }+});diff --cc tests/boundary/providers/native/nativeCallObservation.test.tsindex 45c204f0a,000000000..4192a5276mode 100644,000000..100644--- a/tests/boundary/providers/native/nativeCallObservation.test.ts+++ b/tests/boundary/providers/native/nativeCallObservation.test.ts@@@ -1,293 -1,0 +1,293 @@@+import { createHash } from "node:crypto";+import { writeFile } from "node:fs/promises";+import { join } from "node:path";++import { describe, expect, it } from "vitest";++import {+ AnalysisCapabilityUnavailableError,+ AnalysisCancelledError,+ AnalysisInputError,+} from "../../../../src/domain/analysisErrorCore.js";+import type { AnalysisError } from "../../../../src/domain/analysisErrorBase.js";+import { EvidenceIntegrityError } from "../../../../src/domain/evidenceErrors.js";- import { nativeCallObservationResultSchema } from "../../../../src/domain/nativeCallObservation.js";++import { nativeCallObservationResultSchema } from "../../../../src/domain/native/nativeCallObservation.js";+import { err, ok, type Result } from "../../../../src/domain/result.js";+import type {+ NativeCallTrace,+ NativeCallTracer,+} from "../../../../src/native/LldbCallTracer.js";+import { NativeMacOSProvider } from "../../../../src/native/NativeMacOSProvider.js";+import {+ NativeFixtureRunner,+ nativeMachoTarget,+} from "../../../fixtures/nativeCommands.js";+import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";++const LOCATION = {+ load_address: "0x100000928",+ file_address: "0x100000928",+ module: "Fixture",+ module_path: "/tmp/Fixture",+ symbol: "-[Greeter greet:times:]",+};++const run = (+ overrides: Partial<NativeCallTrace["run"]> = {},+): NativeCallTrace["run"] => ({+ status: "traced",+ version: "lldb-2100.0.17.203",+ pid: 4242,+ outcome: "exited",+ exit_status: 0,+ exit_description: null,+ killed: false,+ terminated: true,+ elapsed_ms: 12.5,+ breakpoints: [+ { index: 0, location_count: 1, locations: [LOCATION] },+ { index: 1, location_count: 1, locations: [LOCATION] },+ ],+ events: [+ {+ sequence: 0,+ elapsed_ms: 3,+ thread_id: 7,+ breakpoint_index: 0,+ ...LOCATION,+ receiver_class: "Greeter",+ selector: "greet:times:",+ registers: [+ { name: "x0", value: "0x6000" },+ { name: "x1", value: "0x7000" },+ ],+ backtrace: [],+ },+ ],+ other_stops: [],+ ...overrides,+});++/** Records the request and returns a canned run or failure. */+class FixtureTracer implements NativeCallTracer {+ readonly requests: Parameters<NativeCallTracer["trace"]>[0][] = [];++ constructor(+ private readonly outcome: Result<NativeCallTrace, AnalysisError> = ok({+ debugger: {+ path: "/usr/bin/lldb",+ sha256: "a".repeat(64),+ version: "lldb-2100.0.17.203",+ },+ run: run(),+ stdout: { text: "hello\n", bytes: 6, truncated: false },+ stderr: { text: "", bytes: 0, truncated: false },+ terminated: true,+ }),+ ) {}++ trace(request: Parameters<NativeCallTracer["trace"]>[0]) {+ this.requests.push(request);+ return Promise.resolve(this.outcome);+ }+}++const BREAKPOINTS = [+ { kind: "objc-method", class_name: "Greeter", selector: "greet:times:" },+ { kind: "function", name: "rea_add" },+];++const fixtureTarget = async () => {+ const directory = await createTestTempDirectory("rea-native-calls-");+ const path = join(directory, "Fixture");+ await writeFile(path, "fixture executable");+ return {+ ...nativeMachoTarget(path),+ sha256: createHash("sha256").update("fixture executable").digest("hex"),+ };+};++const observe = async (+ tracer: NativeCallTracer,+ parameters: Record<string, unknown>,+ target?: Awaited<ReturnType<typeof fixtureTarget>>,+ signal?: AbortSignal,+) =>+ new NativeMacOSProvider(new NativeFixtureRunner(), "darwin", tracer)+ .createClient(target ?? (await fixtureTarget()))+ .execute(+ "observe_native_calls",+ // The provider parses JSON-like parameters itself.+ JSON.parse(JSON.stringify(parameters)),+ signal === undefined ? undefined : { signal },+ );++describe("observe_native_calls projection", () => {+ it("launches the active Mach-O through the tracer and projects its run", async () => {+ const tracer = new FixtureTracer();+ const target = await fixtureTarget();+ const observed = await observe(+ tracer,+ { breakpoints: BREAKPOINTS, arguments: ["--flag"] },+ target,+ );+ if (!observed.ok) throw observed.error;+ expect(tracer.requests[0]).toMatchObject({+ executable: target.path,+ architecture: "arm64",+ input: {+ arguments: ["--flag"],+ duration_ms: 10_000,+ max_events: 1_000,+ argument_registers: 4,+ backtrace_frames: 0,+ },+ });+ const result = nativeCallObservationResultSchema.parse(+ observed.value.result,+ );+ expect(result.breakpoints.map(({ request }) => request)).toEqual([+ {+ kind: "objc-method",+ class_name: "Greeter",+ selector: "greet:times:",+ method_type: "any",+ },+ { kind: "function", name: "rea_add", module: null },+ ]);+ expect(result.process).toMatchObject({+ pid: 4242,+ outcome: "exited",+ exit_status: 0,+ terminated: true,+ stdout: { text: "hello\n" },+ });+ expect(result.events[0]).toMatchObject({+ receiver_class: "Greeter",+ selector: "greet:times:",+ });+ expect(result.coverage).toEqual({+ status: "complete",+ event_limit_reached: false,+ unresolved_breakpoints: [],+ });+ expect(observed.value.locations).toEqual([+ { kind: "artifact-path", path: target.path },+ ]);+ });++ it("marks event limits, unresolved breakpoints and unconfirmed exits", async () => {+ const tracer = new FixtureTracer(+ ok({+ debugger: {+ path: "/usr/bin/lldb",+ sha256: "a".repeat(64),+ version: null,+ },+ run: run({+ outcome: "event-limit",+ exit_status: null,+ killed: true,+ terminated: false,+ breakpoints: [+ { index: 0, location_count: 1, locations: [LOCATION] },+ { index: 1, location_count: 0, locations: [] },+ ],+ }),+ stdout: { text: "", bytes: 0, truncated: false },+ stderr: { text: "x".repeat(16), bytes: 2_000_000, truncated: true },+ terminated: true,+ }),+ );+ const observed = await observe(tracer, {+ breakpoints: BREAKPOINTS,+ max_events: 1,+ });+ if (!observed.ok) throw observed.error;+ const result = nativeCallObservationResultSchema.parse(+ observed.value.result,+ );+ expect(result.coverage).toEqual({+ status: "partial",+ event_limit_reached: true,+ unresolved_breakpoints: [1],+ });+ expect(result.process.terminated).toBe(false);+ expect(result.limitations).toEqual(+ expect.arrayContaining([+ "Observation stopped at max_events (1); later calls were not recorded and the process was killed.",+ "Breakpoints 1 matched no code in any image loaded while observing; their calls could not be observed.",+ "Target output beyond 1 MiB per stream is counted but not kept.",+ "REA could not confirm that process 4242 exited; check for it before relying on host state.",+ ]),+ );+ });+});++describe("observe_native_calls failures", () => {+ it("rejects malformed input before launching anything", async () => {+ for (const parameters of [+ { breakpoints: [] },+ { breakpoints: [{ kind: "objc-method", selector: "-[A b]" }] },+ { breakpoints: BREAKPOINTS, environment: { "A=B": "x" } },+ { breakpoints: BREAKPOINTS, argument_registers: 9 },+ ]) {+ const tracer = new FixtureTracer();+ const observed = await observe(tracer, parameters);+ expect(observed.ok).toBe(false);+ if (!observed.ok)+ expect(observed.error).toBeInstanceOf(AnalysisInputError);+ expect(tracer.requests).toEqual([]);+ }+ });++ it("refuses a changed or non-Mach-O target", async () => {+ const tracer = new FixtureTracer();+ const target = await fixtureTarget();+ const changed = await observe(+ tracer,+ { breakpoints: BREAKPOINTS },+ { ...target, sha256: "f".repeat(64) },+ );+ expect(!changed.ok && changed.error).toBeInstanceOf(EvidenceIntegrityError);+ const database = await new NativeMacOSProvider(+ new NativeFixtureRunner(),+ "darwin",+ tracer,+ )+ .createClient({+ path: target.path,+ sha256: target.sha256,+ kind: "database",+ format: "analysis-database",+ })+ .execute("observe_native_calls", { breakpoints: [] });+ expect(!database.ok && database.error).toBeInstanceOf(+ AnalysisCapabilityUnavailableError,+ );+ expect(tracer.requests).toEqual([]);+ });++ it("keeps the tracer's failure reason and caller cancellation", async () => {+ const denied = new AnalysisCapabilityUnavailableError(+ "native-macos",+ "observe_native_calls",+ "debugger-attach-denied: attach failed",+ );+ const failed = await observe(new FixtureTracer(err(denied)), {+ breakpoints: BREAKPOINTS,+ });+ expect(!failed.ok && failed.error).toBe(denied);+ const controller = new AbortController();+ controller.abort();+ const cancelled = await observe(+ new FixtureTracer(),+ { breakpoints: BREAKPOINTS },+ undefined,+ controller.signal,+ );+ expect(!cancelled.ok && cancelled.error).toBeInstanceOf(+ AnalysisCancelledError,+ );+ });+});