From b1912b18e1723c594a030b16acf01341f083455b Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Mon, 13 Jul 2026 03:15:01 +0000 Subject: [PATCH] feat(cli): align terminal workflows with MCP --- scripts/verify-package.mjs | 103 +++++++- src/application/BinarySession.ts | 11 +- src/application/DirectAnalysis.ts | 37 ++- src/application/EvidenceBundleCommands.ts | 36 ++- src/cli.ts | 287 +++++++++++++++------- src/cliEvidenceCommands.ts | 89 +++++++ src/cliLogging.ts | 32 +++ tests/binarySession.test.ts | 1 + tests/evidenceBundleFiles.test.ts | 16 ++ 9 files changed, 514 insertions(+), 98 deletions(-) create mode 100644 src/cliEvidenceCommands.ts create mode 100644 src/cliLogging.ts diff --git a/scripts/verify-package.mjs b/scripts/verify-package.mjs index a61a2600c..3d2649e71 100644 --- a/scripts/verify-package.mjs +++ b/scripts/verify-package.mjs @@ -122,7 +122,15 @@ try { !help.includes("inventory-artifact") || !help.includes("extract-artifact") || !help.includes("import-reference-source") || + !help.includes("compare") || !llms.includes("decompile") || + !llms.includes("function") || + !llms.includes("search") || + !llms.includes("inspect") || + !llms.includes("xrefs") || + !llms.includes("trace") || + !llms.includes("capabilities") || + !llms.includes("providers") || !llms.includes("inventory-artifact") || doctor.healthy !== expectedDoctorHealth || doctor.checks?.find(({ name }) => name === "hopper")?.ok !== true @@ -157,6 +165,86 @@ try { throw new Error( `packaged Hopper-backed analyze CLI failed: ${JSON.stringify(overview)}`, ); + const inspected = json( + await run( + cli, + [ + "inspect", + process.execPath, + "--detail", + "detailed", + "--limit", + "1", + "--json", + ], + environment, + ), + ); + if ( + inspected.operation !== "binary_overview" || + inspected.normalized_result?.detail !== "detailed" + ) + throw new Error("packaged inspect CLI failed"); + const functionResult = json( + await run( + cli, + ["function", process.execPath, "0x1000", "--json"], + environment, + ), + ); + if ( + functionResult.operation !== "analyze_function" || + functionResult.normalized_result?.procedure?.address !== "0x1000" + ) + throw new Error( + `packaged function CLI failed: ${JSON.stringify(functionResult)}`, + ); + const xrefs = json( + await run( + cli, + ["xrefs", process.execPath, "0x1000", "--json"], + environment, + ), + ); + if ( + xrefs.operation !== "xrefs" || + JSON.stringify(xrefs.normalized_result) !== JSON.stringify(["0x1000"]) + ) + throw new Error(`packaged xrefs CLI failed: ${JSON.stringify(xrefs)}`); + const trace = json( + await run( + cli, + ["trace", process.execPath, "fixture", "--json"], + environment, + ), + ); + if (trace.operation !== "trace_feature") + throw new Error(`packaged trace CLI failed: ${JSON.stringify(trace)}`); + const capabilities = json( + await run(cli, ["capabilities", "--json"], environment), + ); + if (!Array.isArray(capabilities.capabilities)) + throw new Error("packaged capabilities CLI failed"); + const providers = json(await run(cli, ["providers", "--json"], environment)); + if ( + !Array.isArray(providers.providers) || + providers.providers.some(({ id }) => typeof id !== "string") + ) + throw new Error("packaged providers CLI failed"); + const searchResult = json( + await run( + cli, + ["search", process.execPath, "fixture", "--json"], + environment, + ), + ); + if ( + searchResult.operation !== "search_strings" || + searchResult.normalized_result?.items?.length !== 1 + ) + throw new Error( + `packaged search CLI failed: ${JSON.stringify(searchResult)}`, + ); const referenceImport = json( await run( cli, @@ -201,14 +289,25 @@ try { environment, ), ); + const comparedBundle = json( + await run( + cli, + ["compare", sourceBundlePath, canonicalBundlePath, "--json"], + environment, + ), + ); if ( importedBundle.imported !== 1 || importedBundle.total !== 1 || exportedBundle.records !== 1 || (await readFile(canonicalBundlePath, "utf8")) !== - serializeEvidenceBundle(sourceBundle) + serializeEvidenceBundle(sourceBundle) || + comparedBundle.status !== "unchanged" || + comparedBundle.summary?.records_unchanged !== 1 ) - throw new Error("packaged CLI evidence bundle round trip failed"); + throw new Error( + "packaged CLI evidence bundle comparison round trip failed", + ); await run(cli, ["mcp", "add"], environment); const mcpRegistration = await readFile(npxLog, "utf8"); if (!mcpRegistration.includes("add-mcp npx -y rea-agents mcp --name rea")) diff --git a/src/application/BinarySession.ts b/src/application/BinarySession.ts index ebf44969a..ea7fb4a42 100644 --- a/src/application/BinarySession.ts +++ b/src/application/BinarySession.ts @@ -316,6 +316,14 @@ export class BinarySession implements BinarySessionPort { name: this.#providerIdentity.name, version: this.#providerIdentity.version, }; + const providers = new Map(); + if (this.#capabilities === undefined) providers.set(provider.id, provider); + else + for (const descriptor of this.#capabilities.values()) + providers.set(descriptor.provider.id, descriptor.provider); + const providerList = [...providers.values()] + .sort((left, right) => left.id.localeCompare(right.id)) + .map(({ id, name, version }) => ({ id, name, version })); const capabilities = this.#capabilities === undefined ? [] @@ -348,10 +356,11 @@ export class BinarySession implements BinarySessionPort { limitations: [...descriptor.limitations], })); return target === undefined - ? { open: false, provider, capabilities } + ? { open: false, provider, providers: providerList, capabilities } : { open: true, provider, + providers: providerList, capabilities, path: target.path, sha256: target.sha256, diff --git a/src/application/DirectAnalysis.ts b/src/application/DirectAnalysis.ts index 07e299e4d..b7f605f83 100644 --- a/src/application/DirectAnalysis.ts +++ b/src/application/DirectAnalysis.ts @@ -20,7 +20,14 @@ const WORKFLOW_PROVIDER = { */ export const runDirectAnalysis = async ( path: string, - tool: "binary_overview" | "procedure_pseudo_code", + tool: + | "binary_overview" + | "procedure_pseudo_code" + | "analyze_function" + | "search_strings" + | "search_procedures" + | "xrefs" + | "trace_feature", arguments_: Readonly>, logger: Logger = silentLogger, ): Promise => runAnalysis(path, tool, arguments_, logger); @@ -33,13 +40,33 @@ export const runProviderAnalysis = async ( logger: Logger = silentLogger, ): Promise => runAnalysis(path, tool, arguments_, logger); +/** Describe configured providers without opening a target or launching Hopper. */ +export const runSessionStatus = async ( + logger: Logger = silentLogger, +): Promise => { + const config = parseConfig(process.env); + if (!config.ok) + return { error: config.error._tag, message: config.error.message }; + const session = createBinarySession(config.value, logger); + try { + return session.status(); + } finally { + await session.close(); + } +}; + const runAnalysis = async ( path: string, tool: | NativeToolName | ArtifactToolName | "binary_overview" - | "procedure_pseudo_code", + | "procedure_pseudo_code" + | "analyze_function" + | "search_strings" + | "search_procedures" + | "xrefs" + | "trace_feature", arguments_: Readonly>, logger: Logger, ): Promise => { @@ -51,7 +78,11 @@ const runAnalysis = async ( const opened = await session.open(path); if (!opened.ok) return { error: opened.error._tag, message: opened.error.message }; - if (tool === "binary_overview") { + if ( + tool === "binary_overview" || + tool === "analyze_function" || + tool === "trace_feature" + ) { const result = await new EnhancedTools(session).execute(tool, arguments_); return result.ok ? createEvidence(opened.value, WORKFLOW_PROVIDER, { diff --git a/src/application/EvidenceBundleCommands.ts b/src/application/EvidenceBundleCommands.ts index 76860677f..3b1a487b0 100644 --- a/src/application/EvidenceBundleCommands.ts +++ b/src/application/EvidenceBundleCommands.ts @@ -1,10 +1,15 @@ -import type { AnalysisError } from "../domain/errors.js"; +import { + EvidenceIntegrityError, + type AnalysisError, +} from "../domain/errors.js"; import type { EvidenceFilePolicy, EvidenceBundle, } from "../domain/evidenceBundle.js"; import type { JsonValue } from "../domain/jsonValue.js"; +import { jsonValueSchema } from "../domain/jsonValue.js"; import { err, ok, type Result } from "../domain/result.js"; +import { compareBundles } from "../domain/bundleComparison.js"; import { EvidenceLedger } from "./EvidenceLedger.js"; import { readEvidenceBundle, @@ -40,6 +45,35 @@ export const exportEvidenceBundleCommand = async ( ); }; +/** Compare two validated canonical Evidence v2 bundles without session state. */ +export const compareEvidenceBundlesCommand = async (input: { + readonly leftPath: string; + readonly rightPath: string; + readonly offset: number; + readonly limit: number; + readonly policy: EvidenceFilePolicy; +}): Promise> => { + const [left, right] = await Promise.all([ + readEvidenceBundle(input.leftPath, input.policy), + readEvidenceBundle(input.rightPath, input.policy), + ]); + if (!left.ok) return left; + if (!right.ok) return right; + try { + return ok( + jsonValueSchema.parse( + compareBundles(left.value, right.value, [], input.offset, input.limit), + ), + ); + } catch (cause: unknown) { + return err( + new EvidenceIntegrityError("Evidence bundle comparison failed", { + cause, + }), + ); + } +}; + const createLedger = (): EvidenceLedger => new EvidenceLedger({ maxRecords: 10_000, maxBytes: 64 * 1024 * 1024 }); diff --git a/src/cli.ts b/src/cli.ts index 143a6083f..a16b049d7 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -5,17 +5,16 @@ import { runDoctor } from "./application/Doctor.js"; import { runDirectAnalysis, runProviderAnalysis, + runSessionStatus, } from "./application/DirectAnalysis.js"; import { runSetup } from "./application/Setup.js"; import { runUninstall } from "./application/Uninstall.js"; import { PRODUCT_IDENTITY } from "./identity.js"; import { createLogger, parseLogLevel, type Logger } from "./logger.js"; +import { logCliCommand } from "./cliLogging.js"; import { parseConfig } from "./config.js"; -import { - exportEvidenceBundleCommand, - importEvidenceBundleCommand, -} from "./application/EvidenceBundleCommands.js"; import { importReferenceSource } from "./application/ReferenceSourceImport.js"; +import { registerEvidenceCommands } from "./cliEvidenceCommands.js"; /** * Build the one-shot Incur CLI without starting Hopper at import time. @@ -49,6 +48,27 @@ export const createCli = (): ReturnType => { }, }); + registerCoreCommands(cli, logger); + registerFunctionCommand(cli, logger); + registerSearchCommand(cli, logger); + registerXrefsCommand(cli, logger); + registerTraceCommand(cli, logger); + registerCapabilityCommands(cli, logger); + registerNativeCommands(cli, logger); + registerArtifactCommands(cli, logger); + registerEvidenceCommands(cli, logger); + registerReferenceSourceCommand(cli, logger); + return cli; +}; + +const registerCoreCommands = ( + cli: ReturnType, + logger: Logger, +): void => { + const overviewOptions = z.object({ + detail: z.enum(["concise", "detailed"]).default("concise"), + limit: z.number().int().min(1).max(50).default(10), + }); cli.command("setup", { description: "Install requirements and configure coding agents", options: z.object({ @@ -86,9 +106,31 @@ export const createCli = (): ReturnType => { args: z.object({ path: z.string().describe("App, program, or Hopper database path"), }), - run: ({ args }) => + options: overviewOptions, + run: ({ args, options }) => logCliCommand(logger, "analyze", () => - runDirectAnalysis(args.path, "binary_overview", {}, logger), + runDirectAnalysis( + args.path, + "binary_overview", + { detail: options.detail, limit: options.limit }, + logger, + ), + ), + }); + cli.command("inspect", { + description: "Inspect an app overview with evidence", + args: z.object({ + path: z.string().describe("App, program, or Hopper database path"), + }), + options: overviewOptions, + run: ({ args, options }) => + logCliCommand(logger, "inspect", () => + runDirectAnalysis( + args.path, + "binary_overview", + { detail: options.detail, limit: options.limit }, + logger, + ), ), }); cli.command("decompile", { @@ -107,11 +149,154 @@ export const createCli = (): ReturnType => { ), ), }); - registerNativeCommands(cli, logger); - registerArtifactCommands(cli, logger); - registerEvidenceCommands(cli, logger); - registerReferenceSourceCommand(cli, logger); - return cli; +}; + +const registerXrefsCommand = ( + cli: ReturnType, + logger: Logger, +): void => { + cli.command("xrefs", { + description: "List bounded references to an analyzed address", + args: z.object({ + path: z.string().describe("App or program path"), + address: z.string().describe("Hexadecimal address"), + }), + run: ({ args }) => + logCliCommand(logger, "xrefs", () => + runDirectAnalysis( + args.path, + "xrefs", + { address: args.address }, + logger, + ), + ), + }); +}; + +const registerTraceCommand = ( + cli: ReturnType, + logger: Logger, +): void => { + cli.command("trace", { + description: "Trace a bounded literal feature through analyzed references", + args: z.object({ + path: z.string().describe("App or program path"), + query: z.string().min(1).describe("Literal feature query"), + }), + options: z.object({ + caseSensitive: z.boolean().default(false), + limit: z.number().int().min(1).max(100).default(20), + maxOperations: z.number().int().min(1).max(100).default(20), + }), + alias: { + caseSensitive: "case-sensitive", + maxOperations: "max-operations", + }, + run: ({ args, options }) => + logCliCommand(logger, "trace", () => + runDirectAnalysis( + args.path, + "trace_feature", + { + query: args.query, + case_sensitive: options.caseSensitive, + limit: options.limit, + max_operations: options.maxOperations, + }, + logger, + ), + ), + }); +}; + +const registerCapabilityCommands = ( + cli: ReturnType, + logger: Logger, +): void => { + for (const command of ["capabilities", "providers"] as const) { + cli.command(command, { + description: + command === "capabilities" + ? "List provider capabilities and side effects" + : "List configured analysis providers", + run: () => logCliCommand(logger, command, () => runSessionStatus(logger)), + }); + } +}; + +const registerFunctionCommand = ( + cli: ReturnType, + logger: Logger, +): void => { + cli.command("function", { + description: "Analyze one bounded function with evidence", + args: z.object({ + path: z.string().describe("App or program path"), + address: z.string().describe("Procedure name or address"), + }), + options: z.object({ + includeAssembly: z.boolean().default(false), + limit: z.number().int().min(1).max(500).default(100), + maxPseudocodeChars: z.number().int().min(1).max(100_000).default(20_000), + maxInstructions: z.number().int().min(1).max(5_000).default(500), + }), + alias: { + includeAssembly: "include-assembly", + maxPseudocodeChars: "max-pseudocode-chars", + maxInstructions: "max-instructions", + }, + run: ({ args, options }) => + logCliCommand(logger, "function", () => + runDirectAnalysis( + args.path, + "analyze_function", + { + procedure: args.address, + include_assembly: options.includeAssembly, + limit: options.limit, + max_pseudocode_chars: options.maxPseudocodeChars, + max_instructions: options.maxInstructions, + }, + logger, + ), + ), + }); +}; + +const registerSearchCommand = ( + cli: ReturnType, + logger: Logger, +): void => { + cli.command("search", { + description: "Search bounded analyzed strings or procedure names", + args: z.object({ + path: z.string().describe("App or program path"), + pattern: z.string().min(1).describe("Literal text or regex pattern"), + }), + options: z.object({ + kind: z.enum(["strings", "procedures"]).default("strings"), + mode: z.enum(["literal", "regex"]).default("literal"), + caseSensitive: z.boolean().default(false), + offset: z.number().int().min(0).default(0), + limit: z.number().int().min(1).max(100).default(100), + }), + alias: { caseSensitive: "case-sensitive" }, + run: ({ args, options }) => + logCliCommand(logger, "search", () => + runDirectAnalysis( + args.path, + options.kind === "strings" ? "search_strings" : "search_procedures", + { + pattern: args.pattern, + mode: options.mode, + case_sensitive: options.caseSensitive, + offset: options.offset, + limit: options.limit, + }, + logger, + ), + ), + }); }; const registerReferenceSourceCommand = ( @@ -253,83 +438,3 @@ const registerNativeCommands = ( ), }); }; - -const registerEvidenceCommands = ( - cli: ReturnType, - logger: Logger, -): void => { - cli.command("evidence-import", { - description: "Validate and import a bounded local Evidence v2 bundle", - args: z.object({ - path: z.string().describe("Evidence bundle JSON path"), - }), - run: ({ args }) => - logCliCommand(logger, "evidence-import", async () => { - const config = parseConfig(process.env); - if (!config.ok) - return { error: config.error._tag, message: config.error.message }; - const imported = await importEvidenceBundleCommand( - args.path, - config.value.evidenceFilePolicy, - ); - return imported.ok - ? imported.value - : { error: imported.error._tag, message: imported.error.message }; - }), - }); - cli.command("evidence-export", { - description: "Validate and atomically export canonical Evidence v2 JSON", - args: z.object({ - source: z.string().describe("Existing evidence bundle JSON path"), - output: z.string().describe("Canonical output JSON path"), - }), - options: z.object({ - overwrite: z.boolean().default(false).describe("Replace output file"), - }), - run: ({ args, options }) => - logCliCommand(logger, "evidence-export", async () => { - const config = parseConfig(process.env); - if (!config.ok) - return { error: config.error._tag, message: config.error.message }; - const exported = await exportEvidenceBundleCommand( - args.source, - args.output, - options.overwrite, - config.value.evidenceFilePolicy, - ); - return exported.ok - ? exported.value - : { error: exported.error._tag, message: exported.error.message }; - }), - }); -}; - -const logCliCommand = async ( - logger: Logger, - command: string, - execute: () => Promise, -): Promise => { - const startedAt = performance.now(); - try { - const value = await execute(); - logger.info( - { - command, - durationMs: Math.round((performance.now() - startedAt) * 100) / 100, - status: "ok", - }, - "CLI command completed", - ); - return value; - } catch (cause: unknown) { - logger.error( - { - command, - durationMs: Math.round((performance.now() - startedAt) * 100) / 100, - status: "error", - }, - "CLI command failed", - ); - throw cause; - } -}; diff --git a/src/cliEvidenceCommands.ts b/src/cliEvidenceCommands.ts new file mode 100644 index 000000000..82ddca626 --- /dev/null +++ b/src/cliEvidenceCommands.ts @@ -0,0 +1,89 @@ +import { Cli, z } from "incur"; + +import { + compareEvidenceBundlesCommand, + exportEvidenceBundleCommand, + importEvidenceBundleCommand, +} from "./application/EvidenceBundleCommands.js"; +import { parseConfig } from "./config.js"; +import { logCliCommand } from "./cliLogging.js"; +import type { Logger } from "./logger.js"; + +/** Register filesystem-gated Evidence v2 commands shared by package smoke tests. */ +export const registerEvidenceCommands = ( + cli: ReturnType, + logger: Logger, +): void => { + cli.command("evidence-import", { + description: "Validate and import a bounded local Evidence v2 bundle", + args: z.object({ + path: z.string().describe("Evidence bundle JSON path"), + }), + run: ({ args }) => + logCliCommand(logger, "evidence-import", async () => { + const config = parseConfig(process.env); + if (!config.ok) + return { error: config.error._tag, message: config.error.message }; + const imported = await importEvidenceBundleCommand( + args.path, + config.value.evidenceFilePolicy, + ); + return imported.ok + ? imported.value + : { error: imported.error._tag, message: imported.error.message }; + }), + }); + cli.command("evidence-export", { + description: "Validate and atomically export canonical Evidence v2 JSON", + args: z.object({ + source: z.string().describe("Existing evidence bundle JSON path"), + output: z.string().describe("Canonical output JSON path"), + }), + options: z.object({ + overwrite: z.boolean().default(false).describe("Replace output file"), + }), + run: ({ args, options }) => + logCliCommand(logger, "evidence-export", async () => { + const config = parseConfig(process.env); + if (!config.ok) + return { error: config.error._tag, message: config.error.message }; + const exported = await exportEvidenceBundleCommand( + args.source, + args.output, + options.overwrite, + config.value.evidenceFilePolicy, + ); + return exported.ok + ? exported.value + : { error: exported.error._tag, message: exported.error.message }; + }), + }); + cli.command("compare", { + aliases: ["compare-bundles"], + description: "Compare two canonical Evidence v2 bundles", + args: z.object({ + left: z.string().describe("Left Evidence bundle JSON path"), + right: z.string().describe("Right Evidence bundle JSON path"), + }), + options: z.object({ + offset: z.number().int().min(0).default(0), + limit: z.number().int().min(1).max(500).default(100), + }), + run: ({ args, options }) => + logCliCommand(logger, "compare", async () => { + const config = parseConfig(process.env); + if (!config.ok) + return { error: config.error._tag, message: config.error.message }; + const compared = await compareEvidenceBundlesCommand({ + leftPath: args.left, + rightPath: args.right, + offset: options.offset, + limit: options.limit, + policy: config.value.evidenceFilePolicy, + }); + return compared.ok + ? compared.value + : { error: compared.error._tag, message: compared.error.message }; + }), + }); +}; diff --git a/src/cliLogging.ts b/src/cliLogging.ts new file mode 100644 index 000000000..4f960c3d3 --- /dev/null +++ b/src/cliLogging.ts @@ -0,0 +1,32 @@ +import type { Logger } from "./logger.js"; + +/** Log one CLI command with duration and a stable success or failure status. */ +export const logCliCommand = async ( + logger: Logger, + command: string, + execute: () => Promise, +): Promise => { + const startedAt = performance.now(); + try { + const value = await execute(); + logger.info( + { + command, + durationMs: Math.round((performance.now() - startedAt) * 100) / 100, + status: "ok", + }, + "CLI command completed", + ); + return value; + } catch (cause: unknown) { + logger.error( + { + command, + durationMs: Math.round((performance.now() - startedAt) * 100) / 100, + status: "error", + }, + "CLI command failed", + ); + throw cause; + } +}; diff --git a/tests/binarySession.test.ts b/tests/binarySession.test.ts index 7a0b2e214..b5407eae9 100644 --- a/tests/binarySession.test.ts +++ b/tests/binarySession.test.ts @@ -79,6 +79,7 @@ describe("binary session", () => { expect(provider.capabilities()[0]?.operation).toBe("address_name"); expect(session.status()).toMatchObject({ provider: { id: "fixture", name: "Fixture", version: "1" }, + providers: [{ id: "fixture", name: "Fixture", version: "1" }], capabilities: [ { operation: "address_name", diff --git a/tests/evidenceBundleFiles.test.ts b/tests/evidenceBundleFiles.test.ts index 28546ac24..76ff41694 100644 --- a/tests/evidenceBundleFiles.test.ts +++ b/tests/evidenceBundleFiles.test.ts @@ -15,6 +15,7 @@ import { readEvidenceBundle, writeEvidenceBundle, } from "../src/application/EvidenceBundleFiles.js"; +import { compareEvidenceBundlesCommand } from "../src/application/EvidenceBundleCommands.js"; import { createEvidence } from "../src/domain/evidence.js"; import { createEvidenceBundle, @@ -66,6 +67,21 @@ describe("evidence bundle filesystem adapter", () => { ok: true, value: evidenceBundle, }); + expect( + await compareEvidenceBundlesCommand({ + leftPath: path, + rightPath: path, + offset: 0, + limit: 100, + policy: policy(directory), + }), + ).toMatchObject({ + ok: true, + value: { + status: "unchanged", + summary: { records_unchanged: 1 }, + }, + }); expect( await writeEvidenceBundle(evidenceBundle, path, false, policy(directory)), ).toMatchObject({