diff --git a/docs/native-function-matching.md b/docs/native-function-matching.md index a6b97b38c29..e75f7415216 100644 --- a/docs/native-function-matching.md +++ b/docs/native-function-matching.md @@ -122,14 +122,27 @@ the same analysis-profile identity. Empty leaf-function buckets are excluded. dossier link preserves the full supporting facts. Group membership does not assert that every member pair is a candidate or equivalent. -CLI uses the same service and JSON input: +CLI uses the same service and JSON input. `rea list-procedures` produces each +`list_procedures` inventory. `search --kind procedures` returns a pattern-filtered +`search_procedures` result, which matching refuses as an inventory. ```bash +rea list-procedures left.exe --provider ghidra \ + --detail summary --evidence_output left-bundle.json --json +rea list-procedures right.exe --provider ghidra \ + --detail summary --evidence_output right-bundle.json --json +# request.json: {"left": {"kind": "retained-evidence", "evidence_id": ""}, +# "right": {"kind": "retained-evidence", "evidence_id": ""}} rea match-native-functions request.json \ --source_bundle left-bundle.json --source_bundle right-bundle.json \ --evidence_output matching-bundle.json --json ``` +Each summary's `normalized_result.parent_evidence_id` names the complete +inventory in its bundle. Without `--detail summary`, `list-procedures --json` +prints the complete Evidence, which the request can carry inline as `left` or +`right`. + `source_bundle` resolves exact references from authenticated local bundles. Default summary requires `evidence_output`, retaining full matching Evidence and its selected source closure, including transitive Evidence links across supplied diff --git a/src/application/native/NativeMatchingSources.ts b/src/application/native/NativeMatchingSources.ts index f227050cf66..a628d0994a9 100644 --- a/src/application/native/NativeMatchingSources.ts +++ b/src/application/native/NativeMatchingSources.ts @@ -17,13 +17,30 @@ import type { NativeMatchingAdmission } from "./NativeMatchingAdmission.js"; import { nativeMatchingInputError } from "./NativeMatchingInputError.js"; -const INVENTORY_OPERATIONS = ["list_procedures"] as const; -const OBSERVATION_OPERATIONS = [ - "list_names", - "procedure_info", - "read_bytes", - "analyze_function", -] as const; +/** The operations one selected role admits, and how to produce them. */ +interface MatchingSourceRole { + readonly operations: readonly string[]; + /** Matching borrows the record when it never copies the result. */ + readonly borrowable: boolean; + readonly remediationAction?: string; +} + +/** A filtered search cannot replace the inventory, so its refusal names the producers. */ +const INVENTORY_ROLE: MatchingSourceRole = { + operations: ["list_procedures"], + borrowable: true, + remediationAction: + "Select complete list_procedures Evidence: MCP list_procedures, or CLI rea list-procedures --json (or --detail summary --evidence_output with --source_bundle). search_procedures results are filtered by their pattern and are not inventories.", +}; +const OBSERVATION_ROLE: MatchingSourceRole = { + operations: [ + "list_names", + "procedure_info", + "read_bytes", + "analyze_function", + ], + borrowable: false, +}; /** Authenticate selected roles and their closure without interpreting dependencies as observations. */ export const resolveNativeMatchingSources = async ( @@ -82,8 +99,7 @@ export const resolveNativeMatchingSources = async ( const select = async ( raw: unknown, path: readonly (string | number)[], - operations: readonly string[], - borrowable = false, + { operations, borrowable, remediationAction }: MatchingSourceRole, ): Promise => { const evidence = await resolve(raw, path, borrowable); if ( @@ -94,20 +110,18 @@ export const resolveNativeMatchingSources = async ( const message = `Expected artifact-bound rea.analysis ${operations.join(" or ")} Evidence, received ${evidence.predicate_type} ${evidence.operation}`; throw new AnalysisInputError( admission.operation, - { userMessage: message }, + { + userMessage: message, + ...(remediationAction === undefined ? {} : { remediationAction }), + }, [{ path, reason: "invalid_value", message }], ); } return evidence; }; // readFunctionInventory charges each inventory row before parsing it. - const left = await select(input.left, ["left"], INVENTORY_OPERATIONS, true); - const right = await select( - input.right, - ["right"], - INVENTORY_OPERATIONS, - true, - ); + const left = await select(input.left, ["left"], INVENTORY_ROLE); + const right = await select(input.right, ["right"], INVENTORY_ROLE); const observations = async ( inputs: readonly unknown[], field: "left_observations" | "right_observations", @@ -116,11 +130,7 @@ export const resolveNativeMatchingSources = async ( const result: Evidence[] = []; const seen = new Set(); for (const [index, input] of inputs.entries()) { - const record = await select( - input, - [field, index], - OBSERVATION_OPERATIONS, - ); + const record = await select(input, [field, index], OBSERVATION_ROLE); if ( digestCanonicalValue(record.subject) !== digestCanonicalValue(inventory.subject) || diff --git a/src/cli/coreBinaryCommands.ts b/src/cli/coreBinaryCommands.ts index 18c23bf383c..138f54dcc72 100644 --- a/src/cli/coreBinaryCommands.ts +++ b/src/cli/coreBinaryCommands.ts @@ -51,6 +51,7 @@ export const registerCoreBinaryCommands = ( registerDecompileCommand(cli, logger, run); registerDecompileDirectoryCommand(cli, logger, run); registerSearchCommand(cli, logger, run); + registerProcedureInventoryCommand(cli, logger, run); registerContractBinaryCommands(cli, logger, run); }; @@ -274,6 +275,27 @@ const isJavaScriptApplicationPath = async (path: string): Promise => { } }; +/** The complete procedure inventory, which function matching consumes. */ +const registerProcedureInventoryCommand = ( + cli: CliInstance, + logger: Logger, + run: ReturnType, +): void => { + registerContractCommand( + cli, + logger, + contractNamed(OFFICIAL_TOOL_CONTRACTS, "list_procedures"), + { + description: + "List every analyzed procedure as list_procedures Evidence, the inventory match-native-functions accepts. search --kind procedures returns a filtered search_procedures result instead.", + sessionTarget: program, + evidenceDelivery: true, + omit: noDocument, + }, + run, + ); +}; + const registerSearchCommand = ( cli: CliInstance, logger: Logger, diff --git a/src/contracts/officialToolContracts.ts b/src/contracts/officialToolContracts.ts index ba0270ed456..00423636a4b 100644 --- a/src/contracts/officialToolContracts.ts +++ b/src/contracts/officialToolContracts.ts @@ -41,6 +41,7 @@ const OFFICIAL_CLI_CONTRACTS: ReadonlySet = new Set([ "inspect_native_data_type", "inspect_native_instruction", "resolve_native_call_targets", + "list_procedures", "procedure_references", "xrefs", "search_bytes", diff --git a/tests/boundary/cli/listProceduresMatchingCli.test.ts b/tests/boundary/cli/listProceduresMatchingCli.test.ts new file mode 100644 index 00000000000..ac76837a62a --- /dev/null +++ b/tests/boundary/cli/listProceduresMatchingCli.test.ts @@ -0,0 +1,216 @@ +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { describe, expect } from "vitest"; + +import { elf } from "../../../src/domain/binaryTarget.fixture.js"; +import { parseEvidence } from "../../../src/domain/evidence.js"; +import { parseEvidenceBundle } from "../../../src/domain/evidenceBundle.js"; +import { nativeFunctionMatchingSchema } from "../../../src/domain/native/functionMatching.js"; +import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js"; +import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { cliTest } from "../../support/cli/cliFixture.js"; +import { writeFakeKuna } from "../providers/kuna/fakeKuna.js"; + +/** Two fake-Kuna targets whose inventories share `main` and differ otherwise. */ +const createSides = async () => { + const root = await createTestTempDirectory("rea-list-procedures-cli-"); + const side = async ( + name: string, + functions: { name: string; addr: string }[], + ) => { + const directory = join(root, name); + await mkdir(directory); + const kuna = await writeFakeKuna(directory, { functions }); + const target = join(directory, "target.elf"); + // Distinct bytes give the two sides distinct target identities. + await writeFile(target, Buffer.concat([elf(2, 1, 62), Buffer.from(name)])); + return { directory, kuna, target }; + }; + return { + root, + left: await side("left", [ + { name: "main", addr: "0x1000" }, + { name: "old_name", addr: "0x1100" }, + ]), + right: await side("right", [ + { name: "main", addr: "0x2000" }, + { name: "new_name", addr: "0x2100" }, + ]), + }; +}; + +const kunaEnvironment = (side: { directory: string; kuna: string }) => ({ + REA_LOG_LEVEL: "silent", + REA_KUNA_COMMAND: side.kuna, + REA_KUNA_CACHE_DIR: join(side.directory, "cache"), +}); + +describe("list-procedures feeds match-native-functions", () => { + cliTest( + "produces the inventory the matcher accepts, inline and through a bundle", + async ({ cli }) => { + const { root, left, right } = await createSides(); + const list = async ( + side: typeof left, + ...extra: string[] + ): Promise => { + const result = await cli.run({ + arguments: [ + "list-procedures", + side.target, + "--provider", + "kuna", + "--json", + ...extra, + ], + cwd: root, + environment: kunaEnvironment(side), + }); + expect(result.exitCode, result.stderr).toBe(0); + return result.json; + }; + + // Complete delivery: stdout is the list_procedures Evidence itself. + const leftEvidence = parseEvidence(await list(left)); + expect(leftEvidence).toMatchObject({ + operation: "list_procedures", + normalized_result: expect.arrayContaining([ + expect.objectContaining({ address: "0x1000", value: "main" }), + expect.objectContaining({ address: "0x1100", value: "old_name" }), + ]), + }); + + // Summary delivery retains the complete inventory in a bundle. + const bundlePath = join(root, "right-bundle.json"); + const delivered = (await list( + right, + "--detail", + "summary", + "--evidence_output", + bundlePath, + )) as { summary: unknown }; + const summary = parseEvidence(delivered.summary); + const parentId = ( + summary.normalized_result as { parent_evidence_id: string } + ).parent_evidence_id; + const bundle = parseEvidenceBundle( + JSON.parse(await readFile(bundlePath, "utf8")), + ); + expect( + bundle.records.find((record) => record.evidence_id === parentId), + ).toMatchObject({ operation: "list_procedures" }); + + const request = join(root, "request.json"); + await writeFile( + request, + JSON.stringify({ + left: leftEvidence, + right: { kind: "retained-evidence", evidence_id: parentId }, + detail: "complete", + }), + ); + const matched = await cli.run({ + arguments: [ + "match-native-functions", + request, + "--source_bundle", + bundlePath, + "--evidence_output", + join(root, "matching.json"), + "--json", + ], + cwd: root, + environment: { REA_LOG_LEVEL: "silent" }, + }); + expect(matched.exitCode, matched.stderr).toBe(0); + const report = nativeFunctionMatchingSchema.parse( + parseEvidence(matched.json).normalized_result, + ); + // Every row of both selected inventories is accounted for. + const rows = (evidence: { normalized_result: unknown }) => + (evidence.normalized_result as unknown[]).length; + const rightComplete = parseEvidence( + bundle.records.find((record) => record.evidence_id === parentId), + ); + // Independently of matching: the bundled inventory kept the fixture rows. + expect(rightComplete.normalized_result).toEqual( + expect.arrayContaining([ + expect.objectContaining({ address: "0x2000", value: "main" }), + expect.objectContaining({ address: "0x2100", value: "new_name" }), + ]), + ); + const { + matched: pairs, + only_left, + only_right, + unresolved, + } = report.summary; + expect(unresolved).toBe(0); + expect(pairs + only_left).toBe(rows(leftEvidence)); + expect(pairs + only_right).toBe(rows(rightComplete)); + }, + ); +}); + +describe("match-native-functions inventory refusal", () => { + cliTest( + "names the inventory producer when a search result is selected", + async ({ cli }) => { + const { root, left } = await createSides(); + const search = await cli.run({ + arguments: [ + "search", + left.target, + "--pattern=.", + "--mode", + "regex", + "--kind", + "procedures", + "--provider", + "kuna", + "--json", + ], + cwd: root, + environment: kunaEnvironment(left), + }); + expect(search.exitCode, search.stderr).toBe(0); + const searched = parseEvidence(search.json); + expect(searched.operation).toBe("search_procedures"); + + const request = join(root, "request.json"); + await writeFile( + request, + JSON.stringify({ left: searched, right: searched, detail: "complete" }), + ); + const refused = await cli.run({ + arguments: ["match-native-functions", request, "--json"], + cwd: root, + environment: { REA_LOG_LEVEL: "silent" }, + }); + expect(refused.exitCode).not.toBe(0); + expect(refused.json).toMatchObject({ + code: "invalid_request", + details: { issues: [{ path: ["left"], reason: "invalid_value" }] }, + remediation: { + action: expect.stringContaining("rea list-procedures"), + }, + }); + + const { call } = await connectLocalToolsMcp(); + const mcp = await call("match_native_functions", { + left: searched, + right: searched, + }); + expect(mcp.isError).toBe(true); + expect(parseMcpToolError(mcp)).toMatchObject({ + error: { + code: "invalid_request", + remediation: { + action: expect.stringContaining("MCP list_procedures"), + }, + }, + }); + }, + ); +});