diff --git a/src/cli/analysisSelector.ts b/src/cli/analysisSelector.ts index b0908fe33f..10debee869 100644 --- a/src/cli/analysisSelector.ts +++ b/src/cli/analysisSelector.ts @@ -1,5 +1,6 @@ import { nativeAddressInputSchema } from "../domain/native/nativeAddress.js"; import { AnalysisInputError } from "../domain/analysisErrorCore.js"; +import { err, ok, type Result } from "../domain/result.js"; /** Each separately emitted args/options schema must expose the selector choice. */ export const requiredSelectorGuidance = (alternatives: string): string => @@ -17,14 +18,28 @@ export const equalSelectorGuidance = export const dataTypeSelectorGuidance = "Supply exactly one of --type or --address."; -/** Preserve a CLI selector supplied positionally or through its named option. */ -export const resolveCliAnalysisSelector = ( +/** + * How two spellings of one selector agree: `text` only when identical, + * `native` also when both are the same native address. + */ +export type CliSelectorKind = "text" | "native"; + +/** + * Select the value of a selector the caller may give positionally or + * through its named option, preserving the named spelling. Equal values + * agree; different values, or neither when `required`, are refused. + */ +export const selectCliAnalysisSelector = ( positional: string | undefined, named: string | undefined, - option: string, - operation: string, - kind: "text" | "native" = "text", -): string => { + selector: { + readonly option: string; + readonly operation: string; + readonly kind: CliSelectorKind; + readonly required: boolean; + }, +): Result => { + const { option, operation, kind, required } = selector; const equivalent = (): boolean => { if (positional === named) return true; if (kind !== "native") return false; @@ -33,22 +48,44 @@ export const resolveCliAnalysisSelector = ( return left.success && right.success && left.data === right.data; }; if (positional !== undefined && named !== undefined && !equivalent()) - throw new AnalysisInputError(operation, undefined, [ - { - path: [option], - reason: "invalid_value", - message: `The positional selector and --${option} select different objects; supply one selector.`, - }, - ]); + return err( + new AnalysisInputError(operation, undefined, [ + { + path: [option], + reason: "invalid_value", + message: `The positional selector and --${option} select different objects; supply one selector.`, + }, + ]), + ); const selected = named ?? positional; - if (selected === undefined) - throw new AnalysisInputError(operation, undefined, [ - { - path: [option], - reason: "missing_argument", - message: `Supply a positional selector or --${option}=. Use the named option for values beginning with a dash.`, - expected: "string", - }, - ]); - return selected; + if (selected === undefined && required) + return err( + new AnalysisInputError(operation, undefined, [ + { + path: [option], + reason: "missing_argument", + message: `Supply a positional selector or --${option}=. Use the named option for values beginning with a dash.`, + expected: "string", + }, + ]), + ); + return ok(selected); +}; + +/** Preserve a CLI selector supplied positionally or through its named option. */ +export const resolveCliAnalysisSelector = ( + positional: string | undefined, + named: string | undefined, + option: string, + operation: string, + kind: CliSelectorKind = "text", +): string => { + const selected = selectCliAnalysisSelector(positional, named, { + option, + operation, + kind, + required: true, + }); + if (!selected.ok) throw selected.error; + return selected.value!; }; diff --git a/src/cli/contractCliDescription.ts b/src/cli/contractCliDescription.ts index 5687346d38..080b64e6e8 100644 --- a/src/cli/contractCliDescription.ts +++ b/src/cli/contractCliDescription.ts @@ -16,6 +16,10 @@ import { getEvidenceInputContract } from "../domain/evidenceInputContract.js"; import { cliJsonCallerPathSchema } from "../cliJsonInput.js"; import { safeParseJson } from "../domain/safeJson.js"; import { cliDecimalShape } from "./options.js"; +import { + selectCliAnalysisSelector, + type CliSelectorKind, +} from "./analysisSelector.js"; /** * Framework-neutral CLI description of a tool contract. This module owns @@ -71,6 +75,14 @@ export interface CliContractProjection< readonly description: string; /** Fields taken as positional arguments, in argv order. */ readonly positionals?: readonly Field[]; + /** + * Positional selectors the caller may instead give with a named option, + * for values that begin with a dash. The positional becomes optional and + * neither spelling may be empty; equal values agree and different ones are + * refused before the target is opened, as is neither when the field is + * required. + */ + readonly selectorOptions?: { readonly [Key in Field]?: CliSelectorOption }; /** * Absolute-path fields, or lists of them, the caller may spell relative to * the working directory. The CLI admits each nonempty, NUL-free, @@ -183,6 +195,12 @@ export interface CliTargetOpening { export interface CliOpeningFieldProjection extends CliFieldProjection { /** The values this command admits: a subset of the field's enum. */ readonly values?: readonly [string, ...string[]]; + /** + * A local path the caller may spell relative to the working directory. + * It is admitted resolved and passed on as the caller spelled it, like the + * target itself. + */ + readonly callerPath?: true; } /** An option that supplies one field of the opening contract. */ @@ -191,6 +209,8 @@ export interface ContractCliOpeningOption { readonly key: string; readonly description: string | undefined; readonly schema: z.ZodType; + /** Passed on as the caller spelled it once its resolved form is admitted. */ + readonly callerPath: boolean; } /** The described session target of a contract command. */ @@ -248,6 +268,35 @@ export interface CliEvidenceDeliveryChoice { readonly view?: AnalysisViewRequest; } +/** The named option of a positional selector. */ +export interface CliSelectorOption { + /** The option key; its flag is the kebab-case spelling. */ + readonly name: string; + readonly description: string; + /** How the two spellings agree; `text` by default. */ + readonly kind?: CliSelectorKind; + /** + * The command needs a selector although the contract admits omission, + * such as a one-shot command that has no current position to fall back on. + */ + readonly required?: true; +} + +/** The described named option of a positional selector. */ +export interface ContractCliSelectorOption { + readonly key: string; + /** + * The key of the option's parsed value, beside the positional's own + * value, which may share the option's key. + */ + readonly valueKey: string; + readonly description: string; + readonly schema: z.ZodType; + readonly kind: CliSelectorKind; + /** Neither spelling may be omitted. */ + readonly required: boolean; +} + /** One positional argument or option of a contract command. */ export interface ContractCliParameter { /** The contract input field this parameter supplies. */ @@ -288,6 +337,8 @@ export interface ContractCliParameter { readonly nullFlag: string | undefined; /** The member of the object field this option supplies, if flattened. */ readonly member: string | undefined; + /** The named option of a positional selector, if any. */ + readonly selectorOption: ContractCliSelectorOption | undefined; } /** The contract input and delivery one invocation selected. */ @@ -454,11 +505,19 @@ const assertArgvField = ( schema: z.ZodType, ) => { const current = core(schema); + // A union of text forms, such as `auto` or a provider ID, is one token. + const text = (member: z.ZodType): boolean => + member instanceof z.ZodString || + member instanceof z.ZodEnum || + (member instanceof z.ZodLiteral && + [...member.values].every((value) => typeof value === "string")); const scalar = current instanceof z.ZodString || current instanceof z.ZodNumber || current instanceof z.ZodBoolean || - current instanceof z.ZodEnum; + current instanceof z.ZodEnum || + (current instanceof z.ZodUnion && + (current.options as readonly z.ZodType[]).every(text)); const element = current instanceof z.ZodArray ? core(current.element as z.ZodType) : null; if ( @@ -786,7 +845,11 @@ const describeSessionTarget = ( if (!admitsOmission(declared)) throw new Error(`${opener}.${field} is required`); let schema: z.ZodType; - if (projected.values === undefined) { + if (projected.callerPath === true) { + if (!(core(declared) instanceof z.ZodString)) + throw new Error(`${opener}.${field} is not a path`); + schema = localPathStringSchema.optional(); + } else if (projected.values === undefined) { assertArgvField(opener, field, declared); schema = cliDecimalShape({ field: argvOptional(declared) }).field; } else { @@ -802,6 +865,7 @@ const describeSessionTarget = ( key: projected.name ?? camelCase(field), description, schema, + callerPath: projected.callerPath === true, }; }); const keyOf = new Map(options.map(({ field, key }) => [field, key])); @@ -818,8 +882,18 @@ const describeSessionTarget = ( ); // The target itself was admitted as the positional. if (Object.keys(selected).length === 0) return ok({}); + const callerPaths: ReadonlySet = new Set( + options.flatMap(({ field, callerPath }) => (callerPath ? [field] : [])), + ); const candidate = { - ...selected, + ...Object.fromEntries( + Object.entries(selected).map(([field, value]) => [ + field, + callerPaths.has(field) + ? absoluteCallerPath(value as string) + : value, + ]), + ), [SESSION_TARGET_KEY]: absoluteCallerPath( values[SESSION_TARGET_KEY] as string, ), @@ -843,7 +917,10 @@ const describeSessionTarget = ( const data = admitted.data as Readonly>; return ok( Object.fromEntries( - Object.keys(selected).map((field) => [field, data[field]]), + Object.keys(selected).map((field) => [ + field, + callerPaths.has(field) ? selected[field] : data[field], + ]), ), ); }, @@ -1085,6 +1162,12 @@ export const describeContractCommand = < if (viewDelivery !== undefined && !admitsOmission(shape.view ?? z.never())) throw new Error(`${contract.name} has no optional input field view`); const positionals: readonly string[] = projection.positionals ?? []; + const selectorOptions: Readonly< + Record + > = projection.selectorOptions ?? {}; + for (const field of Object.keys(selectorOptions)) + if (!positionals.includes(field)) + throw new Error(`${contract.name}.${field} is not a positional selector`); const callerPaths: ReadonlySet = new Set( projection.callerPaths ?? [], ); @@ -1168,6 +1251,25 @@ export const describeContractCommand = < schema = schema.describe(projected.description); const description = schema.description; const value = core(declared); + const selector = selectorOptions[field]; + let selectorOption: ContractCliSelectorOption | undefined; + if (selector !== undefined) { + if (!(value instanceof z.ZodString)) + throw new Error(`${contract.name}.${field} is not a text selector`); + // Either spelling may supply the selector. A selector names one + // object, so an empty one is refused even where the contract's text + // admits it. + schema = value.min(1).optional(); + if (description !== undefined) schema = schema.describe(description); + selectorOption = { + key: selector.name, + valueKey: `--${selector.name}`, + description: selector.description, + schema: schema.describe(selector.description), + kind: selector.kind ?? "text", + required: selector.required === true || !admitsOmission(declared), + }; + } return { field, key, @@ -1185,6 +1287,7 @@ export const describeContractCommand = < runtimeJson, nullFlag, member: undefined, + selectorOption, }; }; const flattened: Readonly< @@ -1226,6 +1329,7 @@ export const describeContractCommand = < runtimeJson: undefined, nullFlag: undefined, member, + selectorOption: undefined, }; }); }; @@ -1269,14 +1373,29 @@ export const describeContractCommand = < sessionTarget === undefined ? [] : [sessionTarget.key, ...sessionTarget.options.map(({ key }) => key)]; + const selectorKeys = parameters.flatMap(({ selectorOption }) => + selectorOption === undefined ? [] : [selectorOption.key], + ); + // A selector option may share its positional's key: argv keeps them apart. const keys = new Set([ ...sessionTargetKeys, ...parameters.map(({ key }) => key), ...cliOnlyOptions.map(({ key }) => key), ]); + const optionKeys = new Set([ + ...sessionTargetKeys, + ...parameters.flatMap(({ key, positional }) => (positional ? [] : [key])), + ...cliOnlyOptions.map(({ key }) => key), + ...selectorKeys, + ]); if ( keys.size !== - sessionTargetKeys.length + parameters.length + cliOnlyOptions.length + sessionTargetKeys.length + parameters.length + cliOnlyOptions.length || + optionKeys.size !== + sessionTargetKeys.length + + parameters.filter(({ positional }) => !positional).length + + cliOnlyOptions.length + + selectorKeys.length ) throw new Error(`${contract.name} projects two fields to one CLI key`); const cliOptionDependencies = Object.fromEntries( @@ -1299,8 +1418,19 @@ export const describeContractCommand = < values: Readonly>, ): Record => { const input: Record = {}; - for (const { field, key, callerPath, delivery, member } of parameters) { - const value = values[key]; + for (const { + field, + key, + callerPath, + delivery, + member, + selectorOption, + } of parameters) { + // The named spelling is preserved when both agree. + const value = + (selectorOption === undefined + ? undefined + : values[selectorOption.valueKey]) ?? values[key]; if (value === undefined || delivery || member !== undefined) continue; input[field] = !callerPath ? value @@ -1424,14 +1554,29 @@ export const describeContractCommand = < ), }, evidenceDelivery, - admit: (values) => - admitInvocation( + admit: (values) => { + for (const { key, selectorOption } of parameters) { + if (selectorOption === undefined) continue; + const selected = selectCliAnalysisSelector( + values[key] as string | undefined, + values[selectorOption.valueKey] as string | undefined, + { + option: selectorOption.key, + operation: contract.name, + kind: selectorOption.kind, + required: selectorOption.required, + }, + ); + if (!selected.ok) return selected; + } + return admitInvocation( contract, { evidenceDelivery, viewDelivery, parameters, shape }, values, toContractInput, rename, - ), + ); + }, }; }; diff --git a/src/cli/contractCommand.ts b/src/cli/contractCommand.ts index f3bc1dd932..b8288bad52 100644 --- a/src/cli/contractCommand.ts +++ b/src/cli/contractCommand.ts @@ -3,6 +3,8 @@ import type { Logger } from "pino"; import { logCliCommand } from "../cliLogging.js"; import type { AnalysisError } from "../domain/analysisErrorBase.js"; +import { AnalysisOutputError } from "../domain/analysisErrorCore.js"; +import type { AnalysisProviderSelector } from "../domain/providerSelection.js"; import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js"; import type { DirectAnalysis } from "../composition/directAnalysis.js"; @@ -186,6 +188,84 @@ type SessionTargetOperation = Parameters< DirectAnalysis["runProviderAnalysis"] >[1]; +/** Operations `runDirectAnalysis` runs on a target it opens. */ +type DirectAnalysisOperation = Parameters< + DirectAnalysis["runDirectAnalysis"] +>[1]; + +/** + * The one-shot open the caller selected with `open_binary` fields: its + * target interpretation, provider and analysis snapshot. + */ +const directAnalysisOpening = ({ + provider_id: providerId, + snapshot_path: snapshotPath, + ...selection +}: Readonly>) => ({ + ...openBinaryTargetSelection(selection), + ...(providerId === undefined + ? {} + : { providerId: providerId as AnalysisProviderSelector }), + ...(snapshotPath === undefined + ? {} + : { snapshotPath: snapshotPath as string }), +}); + +/** + * Open the session target for one operation with the `open_binary` fields + * the caller selected, run it, and release the provider. A projection with + * `evidenceDelivery` delivers complete Evidence or a summary beside its + * bundle. `requireSourceEvidence` refuses a bundle whose composed result did + * not return the source Evidence it cites. + */ +export const runDirectOnTarget = + ( + runDirectAnalysis: DirectAnalysis["runDirectAnalysis"], + logger: Logger, + options: { readonly requireSourceEvidence?: true } = {}, + ) => + async (input: object, context: ContractCommandContext) => { + const { sessionTarget, operation, signal, delivery, opening } = context; + if (sessionTarget === undefined) + throw new Error(`${operation} declares no session target`); + const evidenceOutput = delivery?.evidenceOutput; + const result = await runDirectAnalysis( + sessionTarget, + operation as DirectAnalysisOperation, + // Argv values are decoded text, and absent options are left out. + input as Readonly>, + { + logger, + signal, + ...directAnalysisOpening(opening), + ...(evidenceOutput === undefined + ? {} + : { includeEvidenceSources: true }), + }, + ); + if (delivery === undefined) + return projectCliAnalysisResult(result, context.inputBinding); + if ( + options.requireSourceEvidence === true && + result.ok && + evidenceOutput !== undefined && + result.sourceEvidence === undefined + ) + return projectAnalysisError( + new AnalysisOutputError( + operation, + "The CLI session did not return its source Evidence.", + ).retainPartialObservation(result.value), + ); + return publishCliAnalysisEvidence(result, { + providerId: "auto", + operation, + signal, + detail: delivery.detail, + evidenceOutput, + }); + }; + /** * Run an analysis that selects no target path through a closeable service * and finish its cleanup. @@ -265,6 +345,11 @@ const incurOptions = (description: ContractCliDescription): z.ZodType => { ...description.cliOnlyOptions.map( ({ key, schema }) => [key, schema] as const, ), + ...description.parameters.flatMap(({ selectorOption }) => + selectorOption === undefined + ? [] + : [[selectorOption.key, selectorOption.schema] as const], + ), ]), ); const constrained = @@ -330,7 +415,13 @@ export const registerContractCommand = < readonly args?: Readonly>; readonly options: Readonly>; }) => { - const values = { ...options, ...args }; + const values: Record = { ...options, ...args }; + // A selector's positional and named option may share one key. + for (const { key, selectorOption } of description.parameters) + if (selectorOption !== undefined) { + values[key] = args?.[key]; + values[selectorOption.valueKey] = options[selectorOption.key]; + } return withCommandCancellation((signal) => logCliCommand(logger, description.command, async () => { const admitted = description.admit(values); diff --git a/src/cli/coreBinaryCommands.ts b/src/cli/coreBinaryCommands.ts index 9594d68c1a..22e003b8ef 100644 --- a/src/cli/coreBinaryCommands.ts +++ b/src/cli/coreBinaryCommands.ts @@ -1,3 +1,4 @@ +import { contractNamed } from "./contractCliDescription.js"; import { projectCliAnalysisResult } from "./projectCliAnalysisResult.js"; import { z } from "incur"; import { realpath, stat } from "node:fs/promises"; @@ -16,6 +17,7 @@ import type { Logger } from "pino"; import { directAnalysisOptionsFromCli, nativeOpenOptionFields, + nativeTarget, snapshotSelectionOption, } from "./options.js"; import type { CliInstance } from "./types.js"; @@ -24,19 +26,21 @@ import { runCliJavaScriptApplicationAnalysis, } from "./javascriptApplicationAnalysis.js"; import { withCommandCancellation } from "./commandCancellation.js"; -import { - analysisEvidenceDeliveryOptions, - cliEvidenceDeliveryInputError, - publishCliAnalysisEvidence, -} from "./analysisEvidenceDelivery.js"; -import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import { javascriptApplicationOptions } from "../cliObservationOptions.js"; import { AnalysisInputError } from "../domain/analysisErrorCore.js"; import { localPathStringSchema } from "../domain/localPath.js"; import type { ExecutableFormatHint } from "../domain/dosCom.js"; import { absoluteCallerPath } from "../filesystem/callerPath.js"; import { registerDecompileDirectoryCommand } from "./decompileDirectoryCommand.js"; -import { decompileAnalysisSelection } from "../contracts/officialToolContracts.js"; +import { + decompileAnalysisSelection, + OFFICIAL_TOOL_CONTRACTS, +} from "../contracts/officialToolContracts.js"; +import { ENHANCED_TOOL_CONTRACTS } from "../contracts/enhancedToolContracts.js"; +import { + registerContractCommand, + runDirectOnTarget, +} from "./contractCommand.js"; const decompileSelectorGuidance = `${addressOrProcedureGuidance} Alternatively, use --file-offset alone.`; const namedAddressGuidance = requiredSelectorGuidance( @@ -59,11 +63,139 @@ export const registerCoreBinaryCommands = ( registerOverviewCommands(cli, logger, runDirectAnalysis, environment); registerDecompileCommand(cli, logger, runDirectAnalysis); registerDecompileDirectoryCommand(cli, logger, runDirectAnalysis); - registerFunctionCommand(cli, logger, runDirectAnalysis); - registerInstructionsCommand(cli, logger, runDirectAnalysis); registerSearchCommand(cli, logger, runDirectAnalysis); - registerXrefsCommand(cli, logger, runDirectAnalysis); - registerTraceCommand(cli, logger, runDirectAnalysis); + registerContractBinaryCommands( + cli, + logger, + runDirectOnTarget(runDirectAnalysis, logger), + ); +}; + +/** The CLI has no Hopper document selection; it opens one target per call. */ +const noDocument = { + document: + "The CLI opens one target per invocation and selects no Hopper document", +} as const; + +const program = nativeTarget("App or program path", true); + +/** The positional procedure, or `--procedure` for a leading dash. */ +const procedureSelector = { + positionals: ["procedure"], + selectorOptions: { + procedure: { + name: "procedure", + description: `Procedure name or address; use --procedure= for leading dashes. ${addressOrProcedureGuidance}`, + kind: "native", + }, + }, + fields: { + procedure: { + name: "address", + description: `Procedure name or address. ${addressOrProcedureGuidance}`, + }, + }, +} as const; + +/** Register the core binary commands derived from their contracts. */ +const registerContractBinaryCommands = ( + cli: CliInstance, + logger: Logger, + run: ReturnType, +): void => { + registerContractCommand( + cli, + logger, + contractNamed(ENHANCED_TOOL_CONTRACTS, "binary_overview"), + { + command: CLI_COMMANDS.inspect, + description: "Inspect an app overview with evidence", + sessionTarget: nativeTarget( + "App, program, or analysis database path", + true, + ), + }, + run, + ); + registerContractCommand( + cli, + logger, + contractNamed(OFFICIAL_TOOL_CONTRACTS, "xrefs"), + { + command: CLI_COMMANDS.xrefs, + description: `List bounded, untyped references to an analyzed address. For typed incoming references, use inspect-native-instruction at the target address where supported. ${namedAddressGuidance} ${equalSelectorGuidance}`, + sessionTarget: program, + positionals: ["address"], + selectorOptions: { + address: { + name: "address", + description: `Address or symbol name; use --address= for leading dashes. ${namedAddressGuidance}`, + kind: "native", + required: true, + }, + }, + omit: noDocument, + fields: { + address: { + description: `Address or symbol name. ${namedAddressGuidance}`, + }, + }, + }, + run, + ); + registerContractCommand( + cli, + logger, + contractNamed(ENHANCED_TOOL_CONTRACTS, "trace_feature"), + { + command: CLI_COMMANDS.trace, + description: `Trace a literal feature through analyzed references. ${querySelectorGuidance} ${equalSelectorGuidance}`, + sessionTarget: program, + positionals: ["query"], + selectorOptions: { + query: { + name: "query", + description: `Complete literal feature query; use --query= for leading dashes. ${querySelectorGuidance}`, + }, + }, + evidenceDelivery: true, + fields: { + query: { + description: `Literal feature query. ${querySelectorGuidance}`, + }, + case_sensitive: { + description: "Match the query with exact letter case", + }, + }, + }, + run, + ); + registerContractCommand( + cli, + logger, + contractNamed(ENHANCED_TOOL_CONTRACTS, "analyze_function"), + { + command: CLI_COMMANDS.function, + description: `Analyze one complete function with evidence. ${addressOrProcedureGuidance} ${equalSelectorGuidance}`, + sessionTarget: program, + ...procedureSelector, + evidenceDelivery: true, + }, + run, + ); + registerContractCommand( + cli, + logger, + contractNamed(OFFICIAL_TOOL_CONTRACTS, "read_function_instructions"), + { + command: CLI_COMMANDS.instructions, + description: `Read every raw instruction without decompiling. ${addressOrProcedureGuidance} ${equalSelectorGuidance}`, + sessionTarget: program, + ...procedureSelector, + omit: noDocument, + }, + run, + ); }; const registerOverviewCommands = ( @@ -172,24 +304,6 @@ const registerOverviewCommands = ( }); }, }); - cli.command(CLI_COMMANDS.inspect, { - description: "Inspect an app overview with evidence", - args: z.object({ - path: localPathStringSchema.describe( - "App, program, or analysis database path", - ), - }), - options: overviewOptions, - run: ({ args, options }) => - logCliCommand(logger, "inspect", () => - runDirectAnalysis( - args.path, - "binary_overview", - {}, - directAnalysisOptionsFromCli(logger, options), - ).then(projectCliAnalysisResult), - ), - }); }; const registerDecompileCommand = ( @@ -290,229 +404,6 @@ const isJavaScriptApplicationPath = async (path: string): Promise => { } }; -const registerXrefsCommand = ( - cli: CliInstance, - logger: Logger, - runDirectAnalysis: DirectAnalysis["runDirectAnalysis"], -): void => { - cli.command(CLI_COMMANDS.xrefs, { - description: `List bounded, untyped references to an analyzed address. For typed incoming references, use inspect-native-instruction at the target address where supported. ${namedAddressGuidance} ${equalSelectorGuidance}`, - args: z.object({ - path: localPathStringSchema.describe("App or program path"), - address: z - .string() - .min(1) - .optional() - .describe(`Address or symbol name. ${namedAddressGuidance}`), - }), - options: z.object({ - address: z - .string() - .min(1) - .optional() - .describe( - `Address or symbol name; use --address= for leading dashes. ${namedAddressGuidance}`, - ), - snapshot: snapshotSelectionOption, - ...nativeOpenOptionFields, - }), - run: ({ args, options }) => - logCliCommand(logger, "xrefs", () => - runDirectAnalysis( - args.path, - "xrefs", - { - address: resolveCliAnalysisSelector( - args.address, - options.address, - "address", - "xrefs", - "native", - ), - }, - directAnalysisOptionsFromCli(logger, options), - ).then(projectCliAnalysisResult), - ), - }); -}; - -const registerTraceCommand = ( - cli: CliInstance, - logger: Logger, - runDirectAnalysis: DirectAnalysis["runDirectAnalysis"], -): void => { - cli.command(CLI_COMMANDS.trace, { - description: `Trace a literal feature through analyzed references. ${querySelectorGuidance} ${equalSelectorGuidance}`, - args: z.object({ - path: localPathStringSchema.describe("App or program path"), - query: z - .string() - .min(1) - .optional() - .describe(`Literal feature query. ${querySelectorGuidance}`), - }), - options: z.object({ - query: z - .string() - .min(1) - .optional() - .describe( - `Complete literal feature query; use --query= for leading dashes. ${querySelectorGuidance}`, - ), - caseSensitive: z - .boolean() - .default(false) - .describe("Match the query with exact letter case"), - snapshot: snapshotSelectionOption, - ...analysisEvidenceDeliveryOptions, - ...nativeOpenOptionFields, - }), - run: ({ args, options }) => - withCommandCancellation((signal) => - logCliCommand(logger, "trace", async () => { - const delivery = { - providerId: "auto", - operation: "trace_feature", - signal, - detail: options.detail, - evidenceOutput: options.evidence_output, - }; - const inputError = cliEvidenceDeliveryInputError(delivery); - if (inputError !== undefined) return projectAnalysisError(inputError); - const complete = await runDirectAnalysis( - args.path, - "trace_feature", - { - query: resolveCliAnalysisSelector( - args.query, - options.query, - "query", - "trace_feature", - ), - case_sensitive: options.caseSensitive, - }, - { - ...directAnalysisOptionsFromCli(logger, options), - signal, - includeEvidenceSources: options.evidence_output !== undefined, - }, - ); - return publishCliAnalysisEvidence(complete, delivery); - }), - ), - }); -}; - -const registerFunctionCommand = ( - cli: CliInstance, - logger: Logger, - runDirectAnalysis: DirectAnalysis["runDirectAnalysis"], -): void => { - cli.command(CLI_COMMANDS.function, { - description: `Analyze one complete function with evidence. ${addressOrProcedureGuidance} ${equalSelectorGuidance}`, - args: z.object({ - path: localPathStringSchema.describe("App or program path"), - address: z - .string() - .min(1) - .optional() - .describe(`Procedure name or address. ${addressOrProcedureGuidance}`), - }), - options: z.object({ - procedure: z - .string() - .min(1) - .optional() - .describe( - `Procedure name or address; use --procedure= for leading dashes. ${addressOrProcedureGuidance}`, - ), - snapshot: snapshotSelectionOption, - ...analysisEvidenceDeliveryOptions, - ...nativeOpenOptionFields, - }), - run: ({ args, options }) => - withCommandCancellation((signal) => - logCliCommand(logger, "function", async () => { - const delivery = { - providerId: "auto", - operation: "analyze_function", - signal, - detail: options.detail, - evidenceOutput: options.evidence_output, - }; - // Fail before analysis when summary delivery lacks its Evidence bundle sink. - const inputError = cliEvidenceDeliveryInputError(delivery); - if (inputError !== undefined) return projectAnalysisError(inputError); - const complete = await runDirectAnalysis( - args.path, - "analyze_function", - { - procedure: resolveCliAnalysisSelector( - args.address, - options.procedure, - "procedure", - "analyze_function", - "native", - ), - }, - { - ...directAnalysisOptionsFromCli(logger, options), - signal, - includeEvidenceSources: options.evidence_output !== undefined, - }, - ); - return publishCliAnalysisEvidence(complete, delivery); - }), - ), - }); -}; - -const registerInstructionsCommand = ( - cli: CliInstance, - logger: Logger, - runDirectAnalysis: DirectAnalysis["runDirectAnalysis"], -): void => { - cli.command(CLI_COMMANDS.instructions, { - description: `Read every raw instruction without decompiling. ${addressOrProcedureGuidance} ${equalSelectorGuidance}`, - args: z.object({ - path: localPathStringSchema.describe("App or program path"), - address: z - .string() - .min(1) - .optional() - .describe(`Procedure name or address. ${addressOrProcedureGuidance}`), - }), - options: z.object({ - procedure: z - .string() - .min(1) - .optional() - .describe( - `Procedure name or address; use --procedure= for leading dashes. ${addressOrProcedureGuidance}`, - ), - snapshot: snapshotSelectionOption, - ...nativeOpenOptionFields, - }), - run: ({ args, options }) => - logCliCommand(logger, CLI_COMMANDS.instructions, () => - runDirectAnalysis( - args.path, - "read_function_instructions", - { - procedure: resolveCliAnalysisSelector( - args.address, - options.procedure, - "procedure", - "read_function_instructions", - "native", - ), - }, - directAnalysisOptionsFromCli(logger, options), - ).then(projectCliAnalysisResult), - ), - }); -}; - const registerSearchCommand = ( cli: CliInstance, logger: Logger, diff --git a/src/cli/coreNativeCommands.ts b/src/cli/coreNativeCommands.ts index d4990a76c3..1e677e319e 100644 --- a/src/cli/coreNativeCommands.ts +++ b/src/cli/coreNativeCommands.ts @@ -1,49 +1,29 @@ -import { nativeInstructionInputSchema } from "../domain/native/nativeInstruction.js"; -import { nativeFunctionAnnotationsInputSchema } from "../domain/native/nativeFunctionAnnotations.js"; -import { projectCliAnalysisResult } from "./projectCliAnalysisResult.js"; -import { nativeDispatchMetadataInputSchema } from "../domain/native/objcSwiftMetadata.js"; -import { nativeInvestigationTraceLimitsSchema } from "../domain/native/nativeInvestigationGraph.js"; -import { nativeValueTraceInputSchema } from "../domain/native/nativeValueTrace.js"; -import { nativeDataTypeInputSchema } from "../domain/native/nativeDataType.js"; -import { z } from "incur"; -import { - bytePatternFields, - validateBytePattern, - MAX_BYTE_SEARCH_MATCHES, -} from "../domain/native/bytePattern.js"; -import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js"; -import { localPathStringSchema } from "../domain/localPath.js"; - import { addressOrProcedureGuidance, dataTypeSelectorGuidance, equalSelectorGuidance, - resolveCliAnalysisSelector, } from "./analysisSelector.js"; - import type { DirectAnalysis } from "../composition/directAnalysis.js"; import { CLI_COMMANDS } from "../cliCommandNames.js"; -import { logCliCommand } from "../cliLogging.js"; import type { Logger } from "pino"; -import { - cliDecimalField, - directAnalysisOptionsFromCli, - nativeOpenOptionFields, - snapshotSelectionOption, -} from "./options.js"; +import { nativeTarget } from "./options.js"; import type { CliInstance } from "./types.js"; -import { withCommandCancellation } from "./commandCancellation.js"; +import { contractNamed } from "./contractCliDescription.js"; +import { ENHANCED_TOOL_CONTRACTS } from "../contracts/enhancedToolContracts.js"; +import { OFFICIAL_TOOL_CONTRACTS } from "../contracts/officialToolContracts.js"; import { - analysisEvidenceDeliveryOptions, - cliEvidenceDeliveryInputError, - publishCliAnalysisEvidence, -} from "./analysisEvidenceDelivery.js"; -import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; -import { AnalysisOutputError } from "../domain/analysisErrorCore.js"; + registerContractCommand, + runDirectOnTarget, +} from "./contractCommand.js"; -const bytePatternInputSchema = z - .object(bytePatternFields) - .superRefine(validateBytePattern); +const executable = nativeTarget("Local executable path"); +const nativeApplication = nativeTarget("Local native executable or app path"); + +/** The CLI has no Hopper document selection; it opens one target per call. */ +const noDocument = { + document: + "The CLI opens one target per invocation and selects no Hopper document", +} as const; /** Register native load-image, memory, and annotation CLI commands. */ export const registerCoreNativeCommands = ( @@ -51,551 +31,291 @@ export const registerCoreNativeCommands = ( logger: Logger, runDirectAnalysis: DirectAnalysis["runDirectAnalysis"], ): void => { - registerAnnotationCommand(cli, logger, runDirectAnalysis); - cli.command(CLI_COMMANDS.searchBytes, { - description: - "Find masked bytes; unbounded searches skip unloaded blocks and overlays", - args: z.object({ - path: localPathStringSchema.describe("Local executable path"), - pattern: bytePatternFields.pattern, - }), - options: z.object({ - mask: bytePatternFields.mask, - start: z - .string() - .optional() - .describe( - "Inclusive start address; use an overlay address space to search it", - ), - end: z - .string() - .optional() - .describe( - "Inclusive end address; use an overlay address space to search it", - ), - cursor: z - .string() - .optional() - .describe("Continuation from the same query's next_cursor"), - limit: cliDecimalField( - z - .number() - .int() - .min(1) - .max(MAX_BYTE_SEARCH_MATCHES) - .default(100) - .describe("Maximum matches on this page"), - ), - ...nativeOpenOptionFields, - }), - run: ({ args, options }) => - logCliCommand(logger, CLI_COMMANDS.searchBytes, async () => { - const selection = { - pattern: args.pattern, - ...(options.mask === undefined ? {} : { mask: options.mask }), - }; - const parsed = bytePatternInputSchema.safeParse(selection); - if (!parsed.success) - return projectAnalysisError( - analysisInputErrorFromIssues( - "search_bytes", - parsed.error.issues, - selection, - { cause: parsed.error }, - ), - ); - return runDirectAnalysis( - args.path, - "search_bytes", - { - pattern: parsed.data.pattern, - ...(parsed.data.mask === undefined - ? {} - : { mask: parsed.data.mask }), - limit: options.limit, - ...(options.start === undefined ? {} : { start: options.start }), - ...(options.end === undefined ? {} : { end: options.end }), - ...(options.cursor === undefined ? {} : { cursor: options.cursor }), - }, - directAnalysisOptionsFromCli(logger, options), - ).then(projectCliAnalysisResult); - }), - }); - cli.command(CLI_COMMANDS.inspectNativeLoadImage, { - description: - "Inspect native load observations and supported snapshot verification", - args: z.object({ - path: localPathStringSchema.describe("Local executable path"), - }), - options: z.object({ - ...analysisEvidenceDeliveryOptions, - ...nativeOpenOptionFields, - }), - run: ({ args, options }) => - withCommandCancellation((signal) => - logCliCommand(logger, CLI_COMMANDS.inspectNativeLoadImage, async () => { - const delivery = { - providerId: "auto", - operation: "inspect_native_load_image", - signal, - detail: options.detail, - evidenceOutput: options.evidence_output, - }; - const invalid = cliEvidenceDeliveryInputError(delivery); - if (invalid !== undefined) return projectAnalysisError(invalid); - const complete = await runDirectAnalysis( - args.path, - "inspect_native_load_image", - {}, - { ...directAnalysisOptionsFromCli(logger, options), signal }, - ); - return publishCliAnalysisEvidence(complete, delivery); - }), - ), - }); - cli.command(CLI_COMMANDS.procedureReferences, { - description: `Inspect incoming or outgoing references for one native procedure. ${addressOrProcedureGuidance} ${equalSelectorGuidance}`, - args: z.object({ - path: localPathStringSchema.describe("Local executable path"), - procedure: z - .string() - .min(1) - .optional() - .describe( - `Procedure name or provider address. ${addressOrProcedureGuidance}`, - ), - }), - options: z.object({ - procedure: z - .string() - .min(1) - .optional() - .describe( - `Procedure name or provider address; use --procedure= for leading dashes. ${addressOrProcedureGuidance}`, - ), - direction: z - .enum(["incoming", "outgoing"]) - .default("outgoing") - .describe("Reference direction. Defaults to outgoing."), - snapshot: snapshotSelectionOption, - ...analysisEvidenceDeliveryOptions, - ...nativeOpenOptionFields, - }), - run: ({ args, options }) => - withCommandCancellation((signal) => - logCliCommand(logger, CLI_COMMANDS.procedureReferences, async () => { - const delivery = { - providerId: "auto", - operation: "procedure_references", - signal, - detail: options.detail, - evidenceOutput: options.evidence_output, - }; - const invalid = cliEvidenceDeliveryInputError(delivery); - if (invalid !== undefined) return projectAnalysisError(invalid); - const result = await runDirectAnalysis( - args.path, - "procedure_references", - { - procedure: resolveCliAnalysisSelector( - args.procedure, - options.procedure, - "procedure", - "procedure_references", - "native", - ), - direction: options.direction, - }, - { - ...directAnalysisOptionsFromCli(logger, options), - signal, - includeEvidenceSources: options.evidence_output !== undefined, - }, - ); - return publishCliAnalysisEvidence(result, delivery); - }), - ), - }); - cli.command(CLI_COMMANDS.readBytes, { - description: - "Read provider memory bytes; Ghidra memory may include loader fixups and differ from file bytes", - args: z.object({ - path: localPathStringSchema.describe("Local executable path"), - address: z.string().describe("Exact provider memory address"), - }), - options: z.object({ - length: cliDecimalField( - z.number().int().min(1).default(256).describe("Requested byte count"), - ), - ...nativeOpenOptionFields, - }), - run: ({ args, options }) => - logCliCommand(logger, CLI_COMMANDS.readBytes, () => - runDirectAnalysis( - args.path, - "read_bytes", - { address: args.address, length: options.length }, - directAnalysisOptionsFromCli(logger, options), - ).then(projectCliAnalysisResult), - ), - }); - cli.command(CLI_COMMANDS.addressToFileOffset, { - description: - "Map one analysis address to a file offset; memory bytes may differ and ranges may not be contiguous", - args: z.object({ - path: localPathStringSchema.describe("Local executable path"), - address: z.string().describe("Exact provider memory address"), - }), - options: z.object({ - ...nativeOpenOptionFields, - }), - run: ({ args, options }) => - logCliCommand(logger, CLI_COMMANDS.addressToFileOffset, () => - runDirectAnalysis( - args.path, - "address_to_file_offset", - { address: args.address }, - directAnalysisOptionsFromCli(logger, options), - ).then(projectCliAnalysisResult), - ), - }); - cli.command(CLI_COMMANDS.traceNativeValues, { - description: "Trace bounded native def-use and call dependencies", - args: z.object({ - path: localPathStringSchema.describe( - "Local native executable or app path", - ), - procedure: nativeValueTraceInputSchema.shape.procedure.describe( - "Explicit native procedure symbol or address", - ), - }), - options: z.object({ - maxDepth: cliDecimalField( - nativeValueTraceInputSchema.shape.max_depth, - ).describe("Maximum call traversal depth"), - maxFunctions: cliDecimalField( - nativeValueTraceInputSchema.shape.max_functions, - ).describe("Maximum function decompilations"), - maxCallSites: cliDecimalField( - nativeValueTraceInputSchema.shape.max_call_sites, - ).describe("Maximum static call-site resolutions"), - maxNodes: cliDecimalField( - nativeValueTraceInputSchema.shape.max_nodes, - ).describe("Maximum retained graph nodes"), - maxEdges: cliDecimalField( - nativeValueTraceInputSchema.shape.max_edges, - ).describe("Maximum retained graph edges"), - offset: cliDecimalField( - nativeValueTraceInputSchema.shape.offset, - ).describe("First graph node index"), - limit: cliDecimalField(nativeValueTraceInputSchema.shape.limit).describe( - "Maximum nodes on this page", - ), - ...analysisEvidenceDeliveryOptions, - ...nativeOpenOptionFields, - }), - run: ({ args, options }) => - withCommandCancellation((signal) => - logCliCommand(logger, CLI_COMMANDS.traceNativeValues, async () => { - const delivery = { - providerId: "auto", - operation: "trace_native_values", - signal, - detail: options.detail, - evidenceOutput: options.evidence_output, - }; - const invalid = cliEvidenceDeliveryInputError(delivery); - if (invalid !== undefined) return projectAnalysisError(invalid); - const complete = await runDirectAnalysis( - args.path, - "trace_native_values", - { - procedure: args.procedure, - max_depth: options.maxDepth, - max_functions: options.maxFunctions, - max_call_sites: options.maxCallSites, - max_nodes: options.maxNodes, - max_edges: options.maxEdges, - offset: options.offset, - limit: options.limit, - }, - { - ...directAnalysisOptionsFromCli(logger, options), - signal, - includeEvidenceSources: options.evidence_output !== undefined, - }, - ); - if (!complete.ok || options.evidence_output === undefined) - return publishCliAnalysisEvidence(complete, delivery); - if (complete.sourceEvidence === undefined) - return projectAnalysisError( - new AnalysisOutputError( - "trace_native_values", - "The CLI session did not return its source Evidence.", - ).retainPartialObservation(complete.value), - ); - return publishCliAnalysisEvidence(complete, delivery); - }), - ), - }); - cli.command(CLI_COMMANDS.inspectNativeDataType, { - description: `Inspect one recovered database type or typed data object. ${dataTypeSelectorGuidance}`, - args: z.object({ - path: localPathStringSchema.describe( - "Local native executable or app path", - ), - }), - options: z.object({ - type: z - .string() - .optional() - .describe( - `Exact database type category path. ${dataTypeSelectorGuidance}`, - ), - address: z - .string() - .optional() - .describe(`Exact native address. ${dataTypeSelectorGuidance}`), - ...nativeOpenOptionFields, - }), - run: ({ args, options }) => - logCliCommand(logger, CLI_COMMANDS.inspectNativeDataType, async () => { - const input = { - ...(options.type === undefined ? {} : { type: options.type }), - ...(options.address === undefined - ? {} - : { address: options.address }), - }; - // Admit the canonical selector choice before opening the target. - const selected = nativeDataTypeInputSchema.safeParse(input); - if (!selected.success) - return projectAnalysisError( - analysisInputErrorFromIssues( - "inspect_native_data_type", - selected.error.issues, - input, - { cause: selected.error }, - ), - ); - return runDirectAnalysis( - args.path, - "inspect_native_data_type", - input, - directAnalysisOptionsFromCli(logger, options), - ).then(projectCliAnalysisResult); - }), - }); - for (const [command, operation] of [ - [CLI_COMMANDS.inspectNativeInstruction, "inspect_native_instruction"], - [CLI_COMMANDS.resolveNativeCallTargets, "resolve_native_call_targets"], - ] as const) { - cli.command(command, { + const run = runDirectOnTarget(runDirectAnalysis, logger); + registerContractCommand( + cli, + logger, + contractNamed(OFFICIAL_TOOL_CONTRACTS, "annotate_native_function"), + { + command: CLI_COMMANDS.annotateNativeFunction, + description: "Edit function annotations and return refreshed analysis", + sessionTarget: executable, + positionals: ["procedure"], + fields: { + procedure: { + description: + "Function name or address; Ghidra resolves interior addresses to the containing function and edits its entry", + }, + name: { description: "Analyst function name" }, + comment: { description: "Regular entry comment; empty text clears it" }, + inline_comment: { + name: "inline-comment", + description: "Inline entry comment; empty text clears it", + }, + }, + }, + run, + ); + registerContractCommand( + cli, + logger, + contractNamed(OFFICIAL_TOOL_CONTRACTS, "search_bytes"), + { + command: CLI_COMMANDS.searchBytes, description: - operation === "inspect_native_instruction" - ? "Inspect a code or data address, its containing Ghidra listing object, and typed incoming references where supported" - : "Resolve one static native call site", - args: z.object({ - path: localPathStringSchema.describe( - "Local native executable or app path", - ), - address: nativeInstructionInputSchema.shape.address.describe( - "Exact native address", - ), - }), - options: z.object({ - ...nativeOpenOptionFields, - }), - run: ({ args, options }) => - logCliCommand(logger, command, () => - runDirectAnalysis( - args.path, - operation, - { address: args.address }, - directAnalysisOptionsFromCli(logger, options), - ).then(projectCliAnalysisResult), - ), - }); - } - registerNativeApiCommand(cli, logger, runDirectAnalysis); - registerNativeUiActionCommand(cli, logger, runDirectAnalysis); - registerNativeDispatchMetadataCommand(cli, logger, runDirectAnalysis); -}; - -const registerNativeDispatchMetadataCommand = ( - cli: CliInstance, - logger: Logger, - runDirectAnalysis: DirectAnalysis["runDirectAnalysis"], -): void => { - cli.command(CLI_COMMANDS.inspectNativeDispatchMetadata, { - description: "Inspect typed Objective-C and Swift dispatch metadata", - args: z.object({ - path: localPathStringSchema.describe( - "Target path used to bind the result evidence", - ), + "Find masked bytes; unbounded searches skip unloaded blocks and overlays", + sessionTarget: executable, + positionals: ["pattern"], + omit: noDocument, + fields: { + start: { + description: + "Inclusive start address; use an overlay address space to search it", + }, + end: { + description: + "Inclusive end address; use an overlay address space to search it", + }, + cursor: { + description: "Continuation from the same query's next_cursor", + }, + limit: { description: "Maximum matches on this page" }, + }, + }, + run, + ); + registerContractCommand( + cli, + logger, + contractNamed(OFFICIAL_TOOL_CONTRACTS, "inspect_native_load_image"), + { + command: CLI_COMMANDS.inspectNativeLoadImage, + description: + "Inspect native load observations and supported snapshot verification", + sessionTarget: executable, + evidenceDelivery: true, + }, + run, + ); + registerProcedureSelectorCommands(cli, logger, run); + registerContractCommand( + cli, + logger, + contractNamed(OFFICIAL_TOOL_CONTRACTS, "read_bytes"), + { + command: CLI_COMMANDS.readBytes, + description: + "Read provider memory bytes; Ghidra memory may include loader fixups and differ from file bytes", + sessionTarget: executable, + positionals: ["address"], + omit: noDocument, + fields: { + address: { description: "Exact provider memory address" }, + length: { description: "Requested byte count" }, + }, + }, + run, + ); + registerContractCommand( + cli, + logger, + contractNamed(OFFICIAL_TOOL_CONTRACTS, "address_to_file_offset"), + { + command: CLI_COMMANDS.addressToFileOffset, + description: + "Map one analysis address to a file offset; memory bytes may differ and ranges may not be contiguous", + sessionTarget: executable, + positionals: ["address"], + omit: noDocument, + fields: { address: { description: "Exact provider memory address" } }, + }, + run, + ); + registerContractCommand( + cli, + logger, + contractNamed(ENHANCED_TOOL_CONTRACTS, "trace_native_values"), + { + command: CLI_COMMANDS.traceNativeValues, + description: "Trace bounded native def-use and call dependencies", + sessionTarget: nativeApplication, + positionals: ["procedure"], + evidenceDelivery: true, + fields: { + procedure: { + description: "Explicit native procedure symbol or address", + }, + max_depth: { description: "Maximum call traversal depth" }, + max_functions: { description: "Maximum function decompilations" }, + max_call_sites: { description: "Maximum static call-site resolutions" }, + max_nodes: { description: "Maximum retained graph nodes" }, + max_edges: { description: "Maximum retained graph edges" }, + offset: { description: "First graph node index" }, + limit: { description: "Maximum nodes on this page" }, + }, + }, + runDirectOnTarget(runDirectAnalysis, logger, { + requireSourceEvidence: true, }), - options: z.object({ - maxRecords: cliDecimalField( - nativeDispatchMetadataInputSchema.shape.max_records, - ).describe("Maximum symbol records to inspect"), - maxInputBytes: cliDecimalField( - nativeDispatchMetadataInputSchema.shape.max_input_bytes, - ), - snapshot: snapshotSelectionOption.describe( + ); + registerContractCommand( + cli, + logger, + contractNamed(OFFICIAL_TOOL_CONTRACTS, "inspect_native_data_type"), + { + command: CLI_COMMANDS.inspectNativeDataType, + description: `Inspect one recovered database type or typed data object. ${dataTypeSelectorGuidance}`, + sessionTarget: nativeApplication, + omit: noDocument, + fields: { + type: { + description: `Exact database type category path. ${dataTypeSelectorGuidance}`, + }, + address: { + description: `Exact native address. ${dataTypeSelectorGuidance}`, + }, + }, + }, + run, + ); + for (const [command, operation, description] of [ + [ + CLI_COMMANDS.inspectNativeInstruction, + "inspect_native_instruction", + "Inspect a code or data address, its containing Ghidra listing object, and typed incoming references where supported", + ], + [ + CLI_COMMANDS.resolveNativeCallTargets, + "resolve_native_call_targets", + "Resolve one static native call site", + ], + ] as const) + registerContractCommand( + cli, + logger, + contractNamed(OFFICIAL_TOOL_CONTRACTS, operation), + { + command, + description, + sessionTarget: nativeApplication, + positionals: ["address"], + omit: noDocument, + fields: { address: { description: "Exact native address" } }, + }, + run, + ); + const evidenceTarget = "Target path used to bind the result evidence"; + registerContractCommand( + cli, + logger, + contractNamed(ENHANCED_TOOL_CONTRACTS, "trace_native_ui_action"), + { + command: CLI_COMMANDS.traceNativeUiAction, + description: + "Trace a compiled UI action selector to its native handler and direct callees", + sessionTarget: nativeTarget(evidenceTarget), + positionals: ["action"], + fields: { + action: { + description: + "A unique compiled UI action selector or interface object ID", + }, + max_depth: { description: "Maximum relationship depth" }, + max_nodes: { description: "Maximum returned graph nodes" }, + max_edges: { description: "Maximum returned graph edges" }, + }, + }, + run, + ); + registerContractCommand( + cli, + logger, + contractNamed(ENHANCED_TOOL_CONTRACTS, "inspect_native_dispatch_metadata"), + { + command: CLI_COMMANDS.inspectNativeDispatchMetadata, + description: "Inspect typed Objective-C and Swift dispatch metadata", + sessionTarget: nativeTarget( + evidenceTarget, "Load or update the local analysis snapshot", ), - ...nativeOpenOptionFields, - }), - run: async ({ args, options }) => - logCliCommand(logger, "inspect-native-dispatch-metadata", () => - runDirectAnalysis( - args.path, - "inspect_native_dispatch_metadata", - { - max_records: options.maxRecords, - ...(options.maxInputBytes === undefined - ? {} - : { max_input_bytes: options.maxInputBytes }), - }, - directAnalysisOptionsFromCli(logger, options), - ).then(projectCliAnalysisResult), - ), - }); + fields: { + max_records: { description: "Maximum symbol records to inspect" }, + objc_class_import_addresses: { + name: "objcClassImportAddress", + description: + "Exact pointer-slot address from the selected name inventory, used to report decoded Objective-C class import bindings (repeatable)", + }, + objc_class_import_addresses_complete: { + description: + "The addresses include every selected class-label row; otherwise binding coverage stays partial when the record budget truncates the scan", + }, + }, + }, + run, + ); }; -const registerNativeUiActionCommand = ( +/** + * Register the native commands whose procedure is given positionally or, + * for symbols beginning with a dash, as `--procedure`. + */ +const registerProcedureSelectorCommands = ( cli: CliInstance, logger: Logger, - runDirectAnalysis: DirectAnalysis["runDirectAnalysis"], + run: ReturnType, ): void => { - cli.command(CLI_COMMANDS.traceNativeUiAction, { - description: - "Trace a compiled UI action selector to its native handler and direct callees", - args: z.object({ - path: localPathStringSchema.describe( - "Target path used to bind the result evidence", - ), - action: z - .string() - .min(1) - .describe( - "A unique compiled UI action selector or interface object ID", - ), - }), - options: z.object({ - maxDepth: cliDecimalField( - nativeInvestigationTraceLimitsSchema.shape.max_depth, - ).describe("Maximum relationship depth"), - maxNodes: cliDecimalField( - nativeInvestigationTraceLimitsSchema.shape.max_nodes, - ).describe("Maximum returned graph nodes"), - maxEdges: cliDecimalField( - nativeInvestigationTraceLimitsSchema.shape.max_edges, - ).describe("Maximum returned graph edges"), - ...nativeOpenOptionFields, - }), - run: async ({ args, options }) => - logCliCommand(logger, "trace-native-ui-action", () => - runDirectAnalysis( - args.path, - "trace_native_ui_action", - { - action: args.action, - max_depth: options.maxDepth, - max_nodes: options.maxNodes, - max_edges: options.maxEdges, - }, - directAnalysisOptionsFromCli(logger, options), - ).then(projectCliAnalysisResult), - ), - }); -}; - -const registerNativeApiCommand = ( - cli: CliInstance, - logger: Logger, - runDirectAnalysis: DirectAnalysis["runDirectAnalysis"], -): void => { - cli.command(CLI_COMMANDS.inspectNativeApi, { - description: `Reconstruct one native function API boundary with evidence. ${addressOrProcedureGuidance} ${equalSelectorGuidance}`, - args: z.object({ - path: localPathStringSchema.describe("App or program path"), - address: z - .string() - .optional() - .describe(`Procedure name or address. ${addressOrProcedureGuidance}`), - }), - options: z.object({ - procedure: z - .string() - .optional() - .describe( - `Procedure selector; use this option for symbols beginning with a dash. ${addressOrProcedureGuidance}`, - ), - snapshot: snapshotSelectionOption, - ...nativeOpenOptionFields, - }), - run: ({ args, options }) => - logCliCommand(logger, "inspect-native-api", () => - runDirectAnalysis( - args.path, - "inspect_native_api", - { - procedure: resolveCliAnalysisSelector( - args.address, - options.procedure, - "procedure", - "inspect_native_api", - "native", - ), - }, - directAnalysisOptionsFromCli(logger, options), - ).then(projectCliAnalysisResult), - ), - }); -}; - -const registerAnnotationCommand = ( - cli: CliInstance, - logger: Logger, - runDirectAnalysis: DirectAnalysis["runDirectAnalysis"], -): void => { - cli.command(CLI_COMMANDS.annotateNativeFunction, { - description: "Edit function annotations and return refreshed analysis", - args: z.object({ - path: localPathStringSchema.describe("Local executable path"), - procedure: nativeFunctionAnnotationsInputSchema.shape.procedure.describe( - "Function name or address; Ghidra resolves interior addresses to the containing function and edits its entry", - ), - }), - options: z.object({ - name: z.string().min(1).optional().describe("Analyst function name"), - comment: z - .string() - .optional() - .describe("Regular entry comment; empty text clears it"), - "inline-comment": z - .string() - .optional() - .describe("Inline entry comment; empty text clears it"), - ...nativeOpenOptionFields, - }), - run: ({ args, options }) => - logCliCommand(logger, CLI_COMMANDS.annotateNativeFunction, () => - runDirectAnalysis( - args.path, - "annotate_native_function", - { - procedure: args.procedure, - ...(options.name === undefined ? {} : { name: options.name }), - ...(options.comment === undefined - ? {} - : { comment: options.comment }), - ...(options["inline-comment"] === undefined - ? {} - : { inline_comment: options["inline-comment"] }), - }, - directAnalysisOptionsFromCli(logger, options), - ).then(projectCliAnalysisResult), - ), - }); + registerContractCommand( + cli, + logger, + contractNamed(OFFICIAL_TOOL_CONTRACTS, "procedure_references"), + { + command: CLI_COMMANDS.procedureReferences, + description: `Inspect incoming or outgoing references for one native procedure. ${addressOrProcedureGuidance} ${equalSelectorGuidance}`, + sessionTarget: nativeTarget("Local executable path", true), + positionals: ["procedure"], + selectorOptions: { + procedure: { + name: "procedure", + description: `Procedure name or provider address; use --procedure= for leading dashes. ${addressOrProcedureGuidance}`, + kind: "native", + }, + }, + evidenceDelivery: true, + omit: noDocument, + fields: { + procedure: { + description: `Procedure name or provider address. ${addressOrProcedureGuidance}`, + }, + direction: { + description: "Reference direction. Defaults to outgoing.", + }, + }, + }, + run, + ); + registerContractCommand( + cli, + logger, + contractNamed(ENHANCED_TOOL_CONTRACTS, "inspect_native_api"), + { + command: CLI_COMMANDS.inspectNativeApi, + description: `Reconstruct one native function API boundary with evidence. ${addressOrProcedureGuidance} ${equalSelectorGuidance}`, + sessionTarget: nativeTarget("App or program path", true), + positionals: ["procedure"], + selectorOptions: { + procedure: { + name: "procedure", + description: `Procedure selector; use this option for symbols beginning with a dash. ${addressOrProcedureGuidance}`, + kind: "native", + }, + }, + fields: { + procedure: { + name: "address", + description: `Procedure name or address. ${addressOrProcedureGuidance}`, + }, + }, + }, + run, + ); }; diff --git a/src/cli/options.ts b/src/cli/options.ts index 2f5645cae9..7a6b7526df 100644 --- a/src/cli/options.ts +++ b/src/cli/options.ts @@ -13,6 +13,8 @@ import { import { analysisProviderSelectorSchema } from "../domain/providerSelection.js"; import type { AnalysisProviderSelector } from "../domain/providerSelection.js"; import type { Logger } from "pino"; +import { OPEN_BINARY_TOOL_CONTRACT } from "../contracts/sessionToolContracts.js"; +import type { CliSessionTarget } from "./contractCliDescription.js"; /** Decimal integer argv text. Leading zeros stay decimal; `0x` and exponent spellings do not. */ const DECIMAL_INTEGER_TOKEN = /^[0-9]+$/u; @@ -158,16 +160,27 @@ export const cliDecimalShape = >( ]), ) as Shape; +/** Help of the flags that bind a native target interpretation. */ +const NATIVE_OPEN_HELP = { + format: + "Explicit interpretation: dos-com or raw-binary (headerless), or gamecube-dol (GameCube/Wii DOL, never auto-detected); omission preserves header-based detection", + architecture: + "Caller-supplied CPU family; required with --target-format raw-binary, must be omitted with gamecube-dol", + entryPoint: + "Caller-supplied load and entry address (0xhex); required with --target-format raw-binary, optional with gamecube-dol (must equal the DOL header entry)", + provider: + "Bind deep analysis to a provider ID or use deterministic auto selection", + snapshot: "Load and update a local analysis snapshot", +} as const; + export const providerSelectionOption = analysisProviderSelectorSchema .optional() - .describe( - "Bind deep analysis to a provider ID or use deterministic auto selection", - ); + .describe(NATIVE_OPEN_HELP.provider); /** Optional path to the local analysis snapshot loaded or updated by a command. */ export const snapshotSelectionOption = localPathStringSchema .optional() - .describe("Load and update a local analysis snapshot"); + .describe(NATIVE_OPEN_HELP.snapshot); /** * Explicit interpretation for headerless native executable formats. Flash @@ -176,21 +189,15 @@ export const snapshotSelectionOption = localPathStringSchema const formatSelectionOption = executableFormatHintSchema .exclude(["esp-flash-image"]) .optional() - .describe( - "Explicit interpretation: dos-com or raw-binary (headerless), or gamecube-dol (GameCube/Wii DOL, never auto-detected); omission preserves header-based detection", - ); + .describe(NATIVE_OPEN_HELP.format); export const architectureSelectionOption = binaryArchitectureSchema .optional() - .describe( - "Caller-supplied CPU family; required with --target-format raw-binary, must be omitted with gamecube-dol", - ); + .describe(NATIVE_OPEN_HELP.architecture); export const entryPointSelectionOption = rawBinaryEntryPointSchema .optional() - .describe( - "Caller-supplied load and entry address (0xhex); required with --target-format raw-binary, optional with gamecube-dol (must equal the DOL header entry)", - ); + .describe(NATIVE_OPEN_HELP.entryPoint); /** Shared CLI flags that bind a native target interpretation. */ export const nativeOpenOptionFields = { @@ -200,6 +207,45 @@ export const nativeOpenOptionFields = { provider: providerSelectionOption, }; +/** + * A native executable opened as an MCP client opens it, with `open_binary`'s + * format, architecture, entry point and provider fields. An operation that + * loads and updates an analysis snapshot also takes `snapshot_path`, with + * `snapshot` as its help when it differs from the shared one. + */ +export const nativeTarget = ( + description: string, + snapshot?: true | string, +): CliSessionTarget => ({ + description, + open: { + contract: OPEN_BINARY_TOOL_CONTRACT, + fields: { + ...(snapshot === undefined + ? {} + : { + snapshot_path: { + name: "snapshot", + callerPath: true, + description: + snapshot === true ? NATIVE_OPEN_HELP.snapshot : snapshot, + }, + }), + format: { + name: "target-format", + values: ["dos-com", "raw-binary", "gamecube-dol"], + description: NATIVE_OPEN_HELP.format, + }, + architecture: { description: NATIVE_OPEN_HELP.architecture }, + entry_point: { + name: "entry-point", + description: NATIVE_OPEN_HELP.entryPoint, + }, + provider_id: { name: "provider", description: NATIVE_OPEN_HELP.provider }, + }, + }, +}); + /** Native CLI flags consumed when opening a target for one-shot analysis. */ export interface NativeOpenCliFlags { readonly snapshot?: string | undefined; diff --git a/tests/acceptance/searchBytesAdmissionCli.test.ts b/tests/acceptance/searchBytesAdmissionCli.test.ts index cd2dbecb37..42d035b2ff 100644 --- a/tests/acceptance/searchBytesAdmissionCli.test.ts +++ b/tests/acceptance/searchBytesAdmissionCli.test.ts @@ -9,6 +9,7 @@ cliTest.for([ { pattern: "ZZ", mask: undefined, field: "pattern" }, { pattern: "", mask: undefined, field: "pattern" }, { pattern: "AB", mask: "FFFF", field: "mask" }, + { pattern: "AB", mask: "00", field: "pattern" }, ])( "reports query correction before target refusal ($pattern/$mask)", async ({ pattern, mask, field }, { cli }) => { diff --git a/tests/boundary/cli/analysisSelectorCli.test.ts b/tests/boundary/cli/analysisSelectorCli.test.ts index e9d919c123..9e7400e283 100644 --- a/tests/boundary/cli/analysisSelectorCli.test.ts +++ b/tests/boundary/cli/analysisSelectorCli.test.ts @@ -6,6 +6,7 @@ import { cliTest } from "../../support/cli/cliFixture.js"; const selectors = [ ["function", "procedure", "analyze_function"], ["inspect-native-api", "procedure", "inspect_native_api"], + ["procedure-references", "procedure", "procedure_references"], ["instructions", "procedure", "read_function_instructions"], ["decompile", "procedure", "procedure_pseudo_code"], ["xrefs", "address", "xrefs"], @@ -72,6 +73,28 @@ describe("CLI analysis selector boundaries", () => { } }, ); + cliTest( + `rejects empty ${command} selectors in either spelling before opening a target`, + async ({ cli }) => { + for (const selection of [[""], [`--${option}=`]]) { + const label = `${command} ${JSON.stringify(selection)}`; + const result = await cli.run({ + arguments: [ + command, + "does-not-exist", + ...selection, + "--format", + "json", + ], + environment: { REA_LOG_LEVEL: "silent" }, + }); + expect(result.exitCode, label).not.toBe(0); + expect(result.json, label).toMatchObject({ + code: "VALIDATION_ERROR", + }); + } + }, + ); cliTest( `keeps named ${command} dash values out of global-option parsing`, async ({ cli }) => { @@ -162,14 +185,9 @@ cliTest( for (const [selection, expected] of [ [[], choice], [["--type", "/MyStruct", "--address", "0x1000"], choice], - [ - ["--type", ""], - invalid({ path: ["type"], reason: "out_of_range", minimum: 1 }), - ], - [ - ["--address", ""], - invalid({ path: ["address"], reason: "out_of_range", minimum: 1 }), - ], + // Each selector's own constraint is an argv constraint. + [["--type", ""], { code: "VALIDATION_ERROR" }], + [["--address", ""], { code: "VALIDATION_ERROR" }], [["--type", "/MyStruct"], { code: "target_unavailable" }], [["--address", "0x1000"], { code: "target_unavailable" }], ] as const) { @@ -227,6 +245,7 @@ for (const [command, option] of [ ["instructions", "procedure"], ["decompile", "procedure"], ["inspect-native-api", "procedure"], + ["procedure-references", "procedure"], ] as const) { cliTest( `admits equivalent native coordinates through ${command}`, diff --git a/tests/boundary/cli/cliContractCommandParity.test.ts b/tests/boundary/cli/cliContractCommandParity.test.ts index 087399c36e..fb5c14c9fc 100644 --- a/tests/boundary/cli/cliContractCommandParity.test.ts +++ b/tests/boundary/cli/cliContractCommandParity.test.ts @@ -108,6 +108,12 @@ const expectedAdmission = ( contractField: z.ZodType, value: unknown, ): boolean => { + // The named option may supply a selector in place of the positional, and + // a selector names one object, so it is never empty. + if (parameter.selectorOption !== undefined) { + if (value === undefined) return true; + if (value === "") return false; + } if (parameter.jsonText) { // JSON text is decoded once, then the contract field admits the value. if (typeof value !== "string") @@ -188,10 +194,18 @@ const argvValues = ( description: ContractCliDescription, options: Readonly>, ): Record => { + const positional: ReadonlySet = new Set( + description.parameters + .filter((parameter) => parameter.positional) + .map(({ key }) => key), + ); + // A required selector is supplied positionally. const required = description.parameters.filter( (parameter) => - !admits(registeredField(description, parameter), undefined) && - (parameter.positional || !Object.hasOwn(options, parameter.key)), + (parameter.selectorOption === undefined + ? !admits(registeredField(description, parameter), undefined) + : parameter.selectorOption.required) && + !Object.hasOwn(options, parameter.key), ); const filled = Object.fromEntries( required.map((parameter) => [ @@ -200,8 +214,13 @@ const argvValues = ( ]), ); return { + ...Object.fromEntries( + Object.entries(options).filter(([key]) => positional.has(key)), + ), ...(registered.get(description.command)!.options as z.ZodObject).parse({ - ...options, + ...Object.fromEntries( + Object.entries(options).filter(([key]) => !positional.has(key)), + ), ...Object.fromEntries( required .filter(({ positional }) => !positional) @@ -216,42 +235,75 @@ const argvValues = ( }; }; +/** + * Argv for commands whose contract rules need more than one value per + * required field: a selector choice, a pattern grammar or a change to make. + */ +const ARGV_SATISFYING_RULES: Readonly< + Record>> +> = { + "annotate-native-function": { name: "renamed" }, + "search-bytes": { pattern: "41 ??" }, + "inspect-native-data-type": { type: "/struct" }, +}; + const each = descriptions.map( (description) => [description.command, description] as const, ); +/** Commands whose CLI projection is derived from a tool contract. */ +const MIGRATED_COMMANDS = [ + "inspect-sqlite-database", + "inspect-elf-notes", + "inspect-pe-resources", + "inspect-devicetree", + "inspect-go-binary", + "inspect-v8-code-cache", + "inspect-rust-binary", + "inspect-python-pyc", + "inspect-erlang-beam", + "inspect-model-artifact", + "inspect-apk-signature", + "inspect-desktop-application", + "inspect-evm-interface", + "audit-release-exposure", + "inspect-il2cpp-metadata", + "inspect-gpu-code-objects", + "inspect-signal-decoders", + "decode-signal-recording", + "inspect-packet-fields", + "inspect-packet-capture", + "inspect-wasm-artifact", + "inspect-firmware-regions", + "extract-firmware", + "inspect-keyed-archive", + "trace-dylib-resolution", + "inspect-asset-catalog", + "decode-interface-builder", + "annotate-native-function", + "search-bytes", + "inspect-native-load-image", + "read-bytes", + "address-to-file-offset", + "trace-native-values", + "inspect-native-data-type", + "inspect-native-instruction", + "resolve-native-call-targets", + "trace-native-ui-action", + "inspect-native-dispatch-metadata", + "procedure-references", + "inspect-native-api", + "inspect", + "xrefs", + "trace", + "function", + "instructions", +]; + describe("CLI commands projected from tool contracts", () => { it("registers the migrated commands", () => { expect(descriptions.map(({ command }) => command)).toEqual( - expect.arrayContaining([ - "inspect-sqlite-database", - "inspect-elf-notes", - "inspect-pe-resources", - "inspect-devicetree", - "inspect-go-binary", - "inspect-v8-code-cache", - "inspect-rust-binary", - "inspect-python-pyc", - "inspect-erlang-beam", - "inspect-model-artifact", - "inspect-apk-signature", - "inspect-desktop-application", - "inspect-evm-interface", - "audit-release-exposure", - "inspect-il2cpp-metadata", - "inspect-gpu-code-objects", - "inspect-signal-decoders", - "decode-signal-recording", - "inspect-packet-fields", - "inspect-packet-capture", - "inspect-wasm-artifact", - "inspect-firmware-regions", - "extract-firmware", - "inspect-keyed-archive", - "trace-dylib-resolution", - "inspect-asset-catalog", - "decode-interface-builder", - ]), + expect.arrayContaining(MIGRATED_COMMANDS), ); }); @@ -288,6 +340,9 @@ describe("CLI commands projected from tool contracts", () => { .map(({ key }) => key), ...(description.sessionTarget?.options ?? []).map(({ key }) => key), ...description.cliOnlyOptions.map(({ key }) => key), + ...description.parameters.flatMap(({ selectorOption }) => + selectorOption === undefined ? [] : [selectorOption.key], + ), ].toSorted(), ); }, @@ -349,8 +404,11 @@ describe("CLI commands projected from tool contracts", () => { it.each(each)( "%s maps parsed argv to an admitted contract input", - (_command, description) => { - const values = argvValues(description, {}); + (command, description) => { + const values = argvValues( + description, + ARGV_SATISFYING_RULES[command] ?? {}, + ); const input = description.toContractInput(values); expect(description.contract.inputSchema.safeParse(input).error).toBe( undefined, @@ -653,12 +711,100 @@ describe("Session targets of contract commands", () => { }, ); + it("refuses a session target beside a contract field keyed path", () => { + expect(() => + describeContractCommand( + { name: "probe", inputSchema: z.object({ path: z.string() }) }, + { + command: "probe", + description: "Probe", + sessionTarget: { description: "Target" }, + }, + ), + ).toThrow("probe projects two fields to one CLI key"); + }); +}); + +const openingKeys = (description: ContractCliDescription) => + description.sessionTarget!.options.map(({ key }) => key); + +describe("Opening options of session-targeted contract commands", () => { it.each( sessionTargeted.filter( ([, description]) => description.sessionTarget!.options.length > 0, ), )( - "%s admits opening options with the opening contract and keeps them out of the contract input", + "%s keeps opening options out of the contract input", + (_command, description) => { + for (const key of openingKeys(description)) + expect(Object.keys(description.fields), key).not.toContain(key); + expect( + description.sessionTarget!.admitOpening(description.contract.name, {}), + ).toEqual({ ok: true, value: {} }); + }, + ); + + it.each( + sessionTargeted.filter(([, description]) => + openingKeys(description).includes("entry-point"), + ), + )( + "%s admits a native target interpretation with open_binary", + (_command, description) => { + const target = description.sessionTarget!; + const snapshot = openingKeys(description).includes("snapshot"); + const values = { + ...argvValues( + description, + ARGV_SATISFYING_RULES[description.command] ?? {}, + ), + [target.key]: "rel/app", + "target-format": "raw-binary", + architecture: "x86", + "entry-point": "0x100", + provider: "ghidra", + ...(snapshot ? { snapshot: "rel/snapshot.json" } : {}), + }; + expect(Object.values(description.toContractInput(values))).not.toContain( + "0x100", + ); + // The snapshot is admitted resolved and passed on as typed. + expect(target.admitOpening(description.contract.name, values)).toEqual({ + ok: true, + value: { + format: "raw-binary", + architecture: "x86", + entry_point: "0x100", + provider_id: "ghidra", + ...(snapshot ? { snapshot_path: "rel/snapshot.json" } : {}), + }, + }); + // The pairing rule refuses before the target opens and names CLI keys. + const unpaired = target.admitOpening(description.contract.name, { + [target.key]: "rel/app", + "target-format": "raw-binary", + architecture: "x86", + }); + expect(unpaired.ok).toBe(false); + if (!unpaired.ok) + expect(unpaired.error.issues).toEqual([ + expect.objectContaining({ + path: ["entry-point"], + message: expect.stringMatching(/requires architecture/u), + }), + ]); + const format = target.options.find(({ key }) => key === "target-format")!; + expect(admits(format.schema, "raw-binary")).toBe(true); + expect(admits(format.schema, "esp-flash-image")).toBe(false); + }, + ); + + it.each( + sessionTargeted.filter(([, description]) => + openingKeys(description).includes("flashOffset"), + ), + )( + "%s admits ESP flash options with the opening contract and keeps them out of the contract input", (_command, description) => { const target = description.sessionTarget!; const values = { @@ -699,7 +845,9 @@ describe("Session targets of contract commands", () => { expect(admits(format.schema, "raw-binary")).toBe(false); }, ); +}); +describe("Opening fields a session target projects", () => { it("refuses opening fields the opening contract cannot supply", () => { const opening = { name: "open", @@ -709,7 +857,9 @@ describe("Session targets of contract commands", () => { required: z.string(), }), }; - const describeOpening = (fields: Record) => + const describeOpening = ( + fields: Record, + ) => describeContractCommand( { name: "probe", inputSchema: z.object({}) }, { @@ -733,19 +883,9 @@ describe("Session targets of contract commands", () => { expect(() => describeOpening({ mode: { values: ["c"] } })).toThrow( "open.mode does not admit c", ); - }); - - it("refuses a session target beside a contract field keyed path", () => { - expect(() => - describeContractCommand( - { name: "probe", inputSchema: z.object({ path: z.string() }) }, - { - command: "probe", - description: "Probe", - sessionTarget: { description: "Target" }, - }, - ), - ).toThrow("probe projects two fields to one CLI key"); + expect(() => describeOpening({ mode: { callerPath: true } })).toThrow( + "open.mode is not a path", + ); }); }); @@ -1061,3 +1201,91 @@ describe("JSON-document delivery options", () => { ); }); }); + +const selecting = each.flatMap(([command, description]) => + description.parameters.flatMap((parameter) => + parameter.selectorOption === undefined + ? [] + : [[command, description, parameter, parameter.selectorOption] as const], + ), +); + +describe("Positional selectors with a named option", () => { + it.each(selecting)( + "%s takes its selector positionally or by its named option", + (_command, description, parameter, option) => { + const command = registered.get(description.command)!; + const named = (command.options as z.ZodObject).shape[option.key]; + expect(admits(named as z.ZodType, undefined)).toBe(true); + expect(admits(named as z.ZodType, "-dash")).toBe(true); + // A required selector is refused when neither spelling is given, + // including where only the CLI requires it. + expect(option.required).toBe( + option.required || + !admits(description.fields[parameter.field]!, undefined), + ); + const { required } = option; + const admit = (values: Record) => + description.admit({ + [description.sessionTarget?.key ?? "path"]: "rel/app", + ...values, + }); + const selected = (values: Record) => { + const result = admit(values); + return result.ok ? result.value.input[parameter.field] : result.error; + }; + expect(selected({ [parameter.key]: "main" })).toBe("main"); + expect(selected({ [option.valueKey]: "-main" })).toBe("-main"); + expect(selected({ [parameter.key]: "m", [option.valueKey]: "m" })).toBe( + "m", + ); + const issues = (values: Record) => { + const result = admit(values); + return result.ok ? [] : result.error.issues; + }; + expect(issues({ [parameter.key]: "a", [option.valueKey]: "b" })).toEqual([ + expect.objectContaining({ + path: [option.key], + reason: "invalid_value", + }), + ]); + if (required) + expect(issues({})).toEqual([ + expect.objectContaining({ + path: [option.key], + reason: "missing_argument", + }), + ]); + if (option.kind === "native") + // The named spelling is kept when both name one native address. + expect( + selected({ [parameter.key]: "0x1a", [option.valueKey]: "0x1A" }), + ).toBe("0x1A"); + }, + ); + + it("refuses a selector option on a field that is not a positional text selector", () => { + const describeSelector = ( + positionals: readonly ("text" | "count")[], + field: "text" | "count", + ) => + describeContractCommand( + { + name: "probe", + inputSchema: z.object({ text: z.string(), count: z.number() }), + }, + { + command: "probe", + description: "Probe", + positionals, + selectorOptions: { [field]: { name: "named", description: "Named" } }, + }, + ); + expect(() => describeSelector([], "text")).toThrow( + "probe.text is not a positional selector", + ); + expect(() => describeSelector(["count"], "count")).toThrow( + "probe.count is not a text selector", + ); + }); +}); diff --git a/tests/boundary/cli/rawBinaryCli.test.ts b/tests/boundary/cli/rawBinaryCli.test.ts index b9d520a928..7988ac195c 100644 --- a/tests/boundary/cli/rawBinaryCli.test.ts +++ b/tests/boundary/cli/rawBinaryCli.test.ts @@ -26,12 +26,19 @@ cliTest( environment: { HOME: root, XDG_CONFIG_HOME: root, XDG_CACHE_HOME: root }, }); expect(result.exitCode).toBe(1); + // open_binary's pairing rule refuses before the target is opened. expect(result.json).toMatchObject({ code: "invalid_request", details: { - reason: expect.stringMatching( - /gamecube-dol.*architecture.*DOL header/iu, - ), + operation: "binary_overview", + issues: [ + expect.objectContaining({ + path: ["architecture"], + message: expect.stringMatching( + /gamecube-dol.*architecture.*DOL header/iu, + ), + }), + ], }, }); const invalid = await cli.run({ @@ -78,7 +85,14 @@ cliTest( expect(missing.exitCode).toBe(1); expect(missing.json).toMatchObject({ code: "invalid_request", - details: { reason: expect.stringContaining("architecture") }, + details: { + issues: [ + expect.objectContaining({ + path: ["architecture"], + message: expect.stringContaining("architecture"), + }), + ], + }, }); }, ); diff --git a/tests/boundary/cli/searchBytesAdmission.test.ts b/tests/boundary/cli/searchBytesAdmission.test.ts index 97ad8fc1ab..98a2eff205 100644 --- a/tests/boundary/cli/searchBytesAdmission.test.ts +++ b/tests/boundary/cli/searchBytesAdmission.test.ts @@ -13,46 +13,6 @@ const registry = () => { return { cli, run }; }; -it.each([ - { pattern: "??", mask: undefined, field: "pattern" }, - { pattern: "ZZ", mask: undefined, field: "pattern" }, - { pattern: "", mask: undefined, field: "pattern" }, - { pattern: "AB", mask: "FFFF", field: "mask" }, - { pattern: "AB", mask: "00", field: "pattern" }, -])( - "rejects $pattern/$mask before any target access", - async ({ pattern, mask, field }) => { - const { cli, run } = registry(); - let stdout = ""; - await cli.serve( - [ - "search-bytes", - "/missing-target", - pattern, - ...(mask === undefined ? [] : ["--mask", mask]), - "--json", - ], - { - stdout: (text) => { - stdout += text; - }, - exit: () => undefined, - }, - ); - expect(run).not.toHaveBeenCalled(); - expect(JSON.parse(stdout)).toMatchObject({ - code: "invalid_request", - category: "invalid_input", - details: { - operation: "search_bytes", - issues: [ - expect.objectContaining({ path: [field], reason: "invalid_value" }), - ], - }, - }); - }, -); - it("forwards admitted original strings and caller-selected search/provider controls", async () => { const { cli, run } = registry(); await cli.serve(