diff --git a/scripts/verify/architecture-guards.mjs b/scripts/verify/architecture-guards.mjs index e6cf62c5ae..6a1264382e 100644 --- a/scripts/verify/architecture-guards.mjs +++ b/scripts/verify/architecture-guards.mjs @@ -959,6 +959,18 @@ checkCounted( [], ); +// Every CLI command is registered through src/cli/commandRegistry.ts, which +// records it in REA's command table (name, inputs, contract operations and +// their flags) before handing it to the dispatcher (#11654). A direct +// `cli.command(...)` would be dispatched but missing from that table. +checkCounted( + "CLI command registered outside REA's command table (use registerCliCommand)", + "cli-command-outside-registry", + files, + /\bcli\.command\(/gu, + ["src/cli/commandRegistry.ts"], +); + // `find` on a parsed section, program-header or load-command table silently // keeps the first of repeated declarations. Select keyed entries through // src/domain/keyedCollection (`uniqueKeyed`, `allKeyed`, or diff --git a/src/cli/analysisViewCommands.ts b/src/cli/analysisViewCommands.ts index 46ae5d0805..3546d9e5bc 100644 --- a/src/cli/analysisViewCommands.ts +++ b/src/cli/analysisViewCommands.ts @@ -15,6 +15,7 @@ import { logCliCommand } from "../cliLogging.js"; import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js"; import type { Logger } from "pino"; +import { registerCliCommand } from "./commandRegistry.js"; import type { CliInstance } from "./types.js"; import { localPathStringSchema } from "../domain/localPath.js"; import { withCommandCancellation } from "./commandCancellation.js"; @@ -33,7 +34,7 @@ export const registerAnalysisViewCommands = ( cli: CliInstance, logger: Logger, ): void => { - cli.command(CLI_COMMANDS.inspectEvidenceBundle, { + registerCliCommand(cli, CLI_COMMANDS.inspectEvidenceBundle, { description: "Inspect a local Evidence bundle completely, as discovery metadata, as a page of selected complete records, or as direct-link and retained-closure membership.", args: z.object({ diff --git a/src/cli/cliShell.ts b/src/cli/cliShell.ts index f72ff89093..26a5d67cbc 100644 --- a/src/cli/cliShell.ts +++ b/src/cli/cliShell.ts @@ -153,10 +153,7 @@ export const createCliShell = (options: CliShellOptions): CliInstance => { const serveDeclared = excludeDeclaredSensitiveArguments(cli); encodeCliArgumentErrors(cli); const serve = cli.serve.bind(cli); - const complete = createCliCompletions( - cli as unknown as Parameters[0], - environment, - ); + const complete = createCliCompletions(cli, environment); cli.serve = (arguments_ = process.argv.slice(2), serveOptions) => { if (complete(arguments_, serveOptions ?? {})) return Promise.resolve(); const normalized = normalizeCliArguments(arguments_); diff --git a/src/cli/commandRegistry.ts b/src/cli/commandRegistry.ts new file mode 100644 index 0000000000..e42dd15b19 --- /dev/null +++ b/src/cli/commandRegistry.ts @@ -0,0 +1,167 @@ +import type { z } from "zod"; + +import type { + ContractCliDescription, + ContractCliDocumentDescription, +} from "./contractCliDescription.js"; +import type { CliInstance } from "./types.js"; + +/** One contract operation a command can run, with the flag of each field it takes. */ +export interface CliCommandOperation { + /** The contract name, which is the MCP operation. */ + readonly name: string; + /** + * The flag that sets each contract field, or `field.member`, on this + * command, such as `{ entry_point: "--entry-point" }`. Positionals and + * delivery fields have no flag. + */ + readonly flags: Readonly>; +} + +type Inputs = Schema extends z.ZodObject + ? z.output + : Record; + +/** What a command's handler receives. */ +export interface CliCommandRunContext< + Args extends z.ZodObject | undefined, + Options extends z.ZodObject | undefined, +> { + readonly args: Inputs; + readonly options: Inputs; + /** The caller chose an output format (`--format` or `--json`). */ + readonly formatExplicit: boolean; +} + +/** A command as its registrar defines it. */ +export interface CliCommandDefinition< + Args extends z.ZodObject | undefined = undefined, + Options extends z.ZodObject | undefined = undefined, +> { + readonly description?: string | undefined; + /** Positionals, in argv order. */ + readonly args?: Args; + readonly options?: Options; + /** Short alias by option key, such as `{ yes: "y" }`. */ + readonly alias?: Readonly> | undefined; + /** `agent-only` hides the result on a terminal unless a format is chosen. */ + readonly outputPolicy?: "all" | "agent-only" | undefined; + readonly run: (context: CliCommandRunContext) => unknown; +} + +/** How a command was described, for readers that need the full projection. */ +export type CliCommandSource = + | { readonly kind: "contract"; readonly description: ContractCliDescription } + | { + readonly kind: "routed"; + readonly descriptions: readonly ContractCliDescription[]; + } + | { + readonly kind: "document"; + readonly description: ContractCliDocumentDescription; + } + | { readonly kind: "host" }; + +/** One registered command. */ +export interface CliCommandEntry { + readonly name: string; + /** + * The definition the dispatcher runs. Shell owners may still replace its + * inputs and handler in place before serving (omittable defaults, result + * output, argument policy), so readers see what is served. + */ + readonly definition: CliCommandDefinition< + z.ZodObject | undefined, + z.ZodObject | undefined + >; + /** Contract operations the command runs, in the order it chooses them. */ + readonly operations: readonly CliCommandOperation[]; + readonly source: CliCommandSource; +} + +const registries = new WeakMap(); + +/** + * Register one command: record it in REA's command table, in registration + * order, and hand it to the dispatcher. Every command is registered here. + */ +export const registerCliCommand = < + const Args extends z.ZodObject | undefined = undefined, + const Options extends z.ZodObject | undefined = undefined, +>( + cli: CliInstance, + name: string, + definition: CliCommandDefinition, + registration: { + readonly operations?: readonly CliCommandOperation[]; + readonly source?: CliCommandSource; + } = {}, +): void => { + const entries = registries.get(cli) ?? []; + if (entries.some((entry) => entry.name === name)) + throw new Error(`CLI command ${name} is registered twice`); + // The dispatcher keeps this object, so in-place changes reach both. + (cli.command as (name: string, definition: object) => unknown)( + name, + definition, + ); + entries.push({ + name, + definition: definition as CliCommandEntry["definition"], + operations: registration.operations ?? [], + source: registration.source ?? { kind: "host" }, + }); + registries.set(cli, entries); +}; + +/** Commands registered on this CLI, in registration order. */ +export const cliCommands = (cli: CliInstance): readonly CliCommandEntry[] => + registries.get(cli) ?? []; + +const kebabCase = (key: string): string => + key.replaceAll(/[A-Z]/gu, (letter) => `-${letter.toLowerCase()}`); + +/** + * The operations one contract description runs: its own contract, the + * contract that opens its session target, and the source of its Evidence + * targets, each with the flags this command gives its fields. + */ +export const contractDescriptionOperations = ( + description: Pick & { + readonly inputBinding?: ContractCliDescription["inputBinding"]; + readonly contract: { readonly name: string }; + readonly evidenceTargets?: ContractCliDescription["evidenceTargets"]; + }, +): readonly CliCommandOperation[] => { + const { sessionTarget, evidenceTargets } = description; + return [ + { + name: description.contract.name, + flags: description.inputBinding?.flags ?? {}, + }, + ...(sessionTarget?.opening === undefined + ? [] + : [ + { + name: sessionTarget.opening, + flags: Object.fromEntries( + sessionTarget.options.map(({ field, key }) => [ + field, + `--${kebabCase(key)}`, + ]), + ), + }, + ]), + ...(evidenceTargets === undefined + ? [] + : [{ name: evidenceTargets.source, flags: evidenceTargets.sourceFlags }]), + ]; +}; + +/** Merge operation lists, keeping the first entry of each operation. */ +export const distinctOperations = ( + operations: readonly CliCommandOperation[], +): readonly CliCommandOperation[] => { + const seen = new Set(); + return operations.filter(({ name }) => !seen.has(name) && seen.add(name)); +}; diff --git a/src/cli/completions.ts b/src/cli/completions.ts index 837cf2a604..33da47afcf 100644 --- a/src/cli/completions.ts +++ b/src/cli/completions.ts @@ -1,4 +1,3 @@ -import { Cli } from "incur"; import { z } from "zod"; import { @@ -17,11 +16,12 @@ import { formatCompletions, type CompletionCommand, } from "./completionProtocol.js"; +import { cliCommands } from "./commandRegistry.js"; import { MCP_SUBCOMMANDS } from "./mcpBuiltinCommands.js"; +import type { CliInstance } from "./types.js"; import { MCP_DOCTOR_ALIAS, MCP_DOCTOR_OPTIONS } from "../mcpDoctorOptions.js"; -type CompletionCli = Parameters[0]; -type ServeOptions = NonNullable[1]>; +type ServeOptions = NonNullable[1]>; const ROOT_FLAGS = new Set(["--mcp", "--update", "--version"]); /** Supplement Incur's built-in setup instructions without replacing its help. */ @@ -85,12 +85,19 @@ const standardGlobals = (root: boolean): z.ZodObject => ]), ); -/** Pinned Incur builtins are not exported in its registered command map. */ +/** Registered commands in registration order, then the builtin groups. */ const completionCommands = ( - cli: CompletionCli, + cli: CliInstance, ): ReadonlyMap => { const commands = new Map( - Cli.toCommands.get(cli) as ReadonlyMap, + cliCommands(cli).map(({ name, definition }) => [ + name, + { + description: definition.description, + options: definition.options, + alias: definition.alias, + }, + ]), ); commands.set("mcp", { _group: true, @@ -108,7 +115,7 @@ const completionCommands = ( /** One tree owns command scope; completionProtocol owns candidates and shell encoding. */ export const createCliCompletions = ( - cli: CompletionCli, + cli: CliInstance, environment: Readonly, ) => { const script = (shell: (typeof CLI_COMPLETION_SHELLS)[number]) => diff --git a/src/cli/contractCliDescription.ts b/src/cli/contractCliDescription.ts index 9ddc6575e0..d6b2fc2aa2 100644 --- a/src/cli/contractCliDescription.ts +++ b/src/cli/contractCliDescription.ts @@ -382,6 +382,8 @@ export interface ContractCliSessionTarget { /** The positional key, taken before every other positional. */ readonly key: string; readonly schema: z.ZodType; + /** The contract that opens the target, when the command takes its fields. */ + readonly opening: string | undefined; /** Options that supply fields of the opening contract. */ readonly options: readonly ContractCliOpeningOption[]; /** @@ -699,7 +701,9 @@ export interface ContractCliDescription { * Contract fields the CLI spells differently, so input issues reported * after argv parsing can name the CLI key, and the flag of each contract * field (or `field.member`) the command takes as an option, so a failure - * that names a per-call control can name the flag that sets it. + * that names a per-call control can name the flag that sets it. Each field + * of a field group maps to the group's option, and a positional selector + * to its named option. */ readonly inputBinding: { readonly operation: string; @@ -1488,6 +1492,7 @@ const describeSessionTarget = ( return { key: SESSION_TARGET_KEY, schema: localPathStringSchema.describe(target.description), + opening: target.open?.contract.name, options, admitOpening: (operation, values) => admit(operation, values, values[SESSION_TARGET_KEY] as string), @@ -2435,15 +2440,33 @@ export const describeContractCommand = < ].flatMap(({ field, key }) => (key === field ? [] : [[field, key]])), ), flags: Object.fromEntries( - parameters.flatMap(({ field, key, member, positional, delivery }) => - positional || delivery - ? [] - : [ - [ - member === undefined ? field : [field, ...member].join("."), - `--${kebabCase(key)}`, - ], - ], + parameters.flatMap( + ({ + field, + key, + member, + positional, + delivery, + group, + selectorOption, + }) => { + if (delivery) return []; + // A positional selector is also set by its named option. + if (positional) + return selectorOption === undefined + ? [] + : [[field, `--${kebabCase(selectorOption.key)}`] as const]; + const flag = `--${kebabCase(key)}`; + // A field group's option supplies each of its contract fields. + if (group !== undefined) + return group.map((grouped) => [grouped, flag] as const); + return [ + [ + member === undefined ? field : [field, ...member].join("."), + flag, + ] as const, + ]; + }, ), ), }, diff --git a/src/cli/contractCommand.ts b/src/cli/contractCommand.ts index d1e7e01fec..87354286be 100644 --- a/src/cli/contractCommand.ts +++ b/src/cli/contractCommand.ts @@ -58,6 +58,12 @@ import { projectCliAnalysisResult, projectCliInputFields, } from "./projectCliAnalysisResult.js"; +import { + cliCommands, + contractDescriptionOperations, + distinctOperations, + registerCliCommand, +} from "./commandRegistry.js"; import type { CliInstance } from "./types.js"; import { isRecord } from "../kernel/isRecord.js"; @@ -549,12 +555,13 @@ const commandPositionals = ( ...description.cliPositionals, ]; -const descriptions = new WeakMap(); - /** Commands registered on this CLI through `registerContractCommand`. */ export const contractCommandDescriptions = ( cli: CliInstance, -): readonly ContractCliDescription[] => descriptions.get(cli) ?? []; +): readonly ContractCliDescription[] => + cliCommands(cli).flatMap(({ source }) => + source.kind === "contract" ? [source.description] : [], + ); const incurOptions = (description: ContractCliDescription): z.ZodType => { const object = z.object( @@ -624,118 +631,128 @@ export const registerContractCommand = < short === undefined || positional ? [] : [[key, short]], ), ); - cli.command(description.command, { - description: description.description, - ...(positionals.length === 0 - ? {} - : { - args: z.object( - Object.fromEntries( - positionals.map(({ key, schema }) => [key, schema]), + registerCliCommand( + cli, + description.command, + { + description: description.description, + ...(positionals.length === 0 + ? {} + : { + args: z.object( + Object.fromEntries( + positionals.map(({ key, schema }) => [key, schema]), + ), ), - ), - }), - options: incurOptions(description), - ...(Object.keys(alias).length === 0 ? {} : { alias }), - run: ({ - args, - options, - }: { - readonly args?: Readonly>; - readonly options: Readonly>; - }) => { - 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]; - for (const option of [selectorOption, selectorOption.alternative]) - if (option !== undefined) - values[option.valueKey] = options[option.key]; - } - const selected = - projection.operationBy === undefined - ? description - : (chosen.get(values[projection.operationBy.option]) ?? description); - return withCommandCancellation((signal) => - logCliCommand(logger, description.command, async () => { - const options = selected.admitDeliveryOptions(values); - if (!options.ok) return projectAnalysisError(options.error); - const read = await readJsonInputs(selected, values, signal); - if (!read.ok) return read.error; - const admitted = selected.admit(read.value); - // Admission and handler issues alike name renamed fields by CLI key. - if (!admitted.ok) - return projectCliInputFields( - projectAnalysisError(admitted.error), - selected.inputBinding, + }), + options: incurOptions(description), + ...(Object.keys(alias).length === 0 ? {} : { alias }), + run: ({ + args, + options, + }: { + readonly args?: Readonly>; + readonly options: Readonly>; + }) => { + 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]; + for (const option of [selectorOption, selectorOption.alternative]) + if (option !== undefined) + values[option.valueKey] = options[option.key]; + } + const selected = + projection.operationBy === undefined + ? description + : (chosen.get(values[projection.operationBy.option]) ?? + description); + return withCommandCancellation((signal) => + logCliCommand(logger, description.command, async () => { + const options = selected.admitDeliveryOptions(values); + if (!options.ok) return projectAnalysisError(options.error); + const read = await readJsonInputs(selected, values, signal); + if (!read.ok) return read.error; + const admitted = selected.admit(read.value); + // Admission and handler issues alike name renamed fields by CLI key. + if (!admitted.ok) + return projectCliInputFields( + projectAnalysisError(admitted.error), + selected.inputBinding, + ); + const opening = admitOpening(selected, values); + if (!opening.ok) return projectAnalysisError(opening.error); + // A composed command also takes its sources' options; a control + // its result records from a source is set by that option. + const resultBinding = + description.evidenceTargets === undefined + ? selected.inputBinding + : { + ...selected.inputBinding, + flags: { + ...description.evidenceTargets.sourceFlags, + ...selected.inputBinding.flags, + }, + }; + return projectCliResult( + await run( + admitted.value.input as z.input, + { + signal, + operation: selected.contract.name, + callerInputs: selected.callerInputs(values), + sessionTarget: + description.sessionTarget === undefined + ? undefined + : (values[description.sessionTarget.key] as string), + evidenceTargets: + description.evidenceTargets === undefined + ? undefined + : { + source: description.evidenceTargets.source, + sourceFlags: description.evidenceTargets.sourceFlags, + targets: description.evidenceTargets.targets.map( + ({ field, key }) => ({ + field, + key, + target: values[key] as string, + }), + ), + }, + opening: opening.value, + delivery: admitted.value.delivery, + parsed: admitted.value.parsed as + | z.output + | undefined, + parseWholeInput: admitted.value.parseWholeInput as + | (() => Result< + z.output, + AnalysisInputError + >) + | undefined, + checked: read.checked as CliCheckedJsonInputs, + cliOptions: selected.cliOptionValues( + values, + ) as CliOptionValues, + }, + ), + selected.contract.outputSchema, + resultBinding, ); - const opening = admitOpening(selected, values); - if (!opening.ok) return projectAnalysisError(opening.error); - // A composed command also takes its sources' options; a control - // its result records from a source is set by that option. - const resultBinding = - description.evidenceTargets === undefined - ? selected.inputBinding - : { - ...selected.inputBinding, - flags: { - ...description.evidenceTargets.sourceFlags, - ...selected.inputBinding.flags, - }, - }; - return projectCliResult( - await run( - admitted.value.input as z.input, - { - signal, - operation: selected.contract.name, - callerInputs: selected.callerInputs(values), - sessionTarget: - description.sessionTarget === undefined - ? undefined - : (values[description.sessionTarget.key] as string), - evidenceTargets: - description.evidenceTargets === undefined - ? undefined - : { - source: description.evidenceTargets.source, - sourceFlags: description.evidenceTargets.sourceFlags, - targets: description.evidenceTargets.targets.map( - ({ field, key }) => ({ - field, - key, - target: values[key] as string, - }), - ), - }, - opening: opening.value, - delivery: admitted.value.delivery, - parsed: admitted.value.parsed as - | z.output - | undefined, - parseWholeInput: admitted.value.parseWholeInput as - | (() => Result< - z.output, - AnalysisInputError - >) - | undefined, - checked: read.checked as CliCheckedJsonInputs, - cliOptions: selected.cliOptionValues( - values, - ) as CliOptionValues, - }, - ), - selected.contract.outputSchema, - resultBinding, - ); - }), - ); + }), + ); + }, + } as never, + { + operations: distinctOperations( + [description, ...chosen.values()].flatMap( + contractDescriptionOperations, + ), + ), + source: { kind: "contract", description }, }, - } as never); - const registered = descriptions.get(cli) ?? []; - registered.push(description); - descriptions.set(cli, registered); + ); }; /** One contract input a routed command runs, with the inputs it takes. */ @@ -849,12 +866,13 @@ const commandShape = (description: ContractCliDescription) => ({ const schemaSignature = (schema: z.ZodType): string => JSON.stringify(z.toJSONSchema(schema, { unrepresentable: "any" })); -const routedDescriptions = new WeakMap(); - /** Route descriptions of commands registered through `registerRoutedCommand`. */ export const routedCommandDescriptions = ( cli: CliInstance, -): readonly ContractCliDescription[] => routedDescriptions.get(cli) ?? []; +): readonly ContractCliDescription[] => + cliCommands(cli).flatMap(({ source }) => + source.kind === "routed" ? source.descriptions : [], + ); /** * Register one CLI command whose input chooses the contract input it runs, @@ -920,100 +938,112 @@ export const registerRoutedCommand = ( Object.hasOwn(shapes[routes.indexOf(route)]!.options, key); // Only JSON inputs every route takes alike are decoded before routing. const sharedJson = sharedJsonInputs(name, routes); - cli.command(name, { - description: command.description, - args: z.object(Object.fromEntries(args)), - options: z.object(Object.fromEntries(options)), - run: ({ - args: given, - options: chosen, - }: { - readonly args: Readonly>; - readonly options: Readonly>; - }) => { - const values: Record = { ...chosen, ...given }; - const supplied = Object.keys(values).filter( - (key) => values[key] !== undefined, - ); - return withCommandCancellation((signal) => - logCliCommand(logger, name, async () => { - const shared = await readJsonInputs( - routes[0]!.description, - values, - signal, - sharedJson, - ); - if (!shared.ok) return shared.error; - let route = routes.at(-1)!; - for (const candidate of routes) - if ( - candidate.takes !== undefined && - supplied.every((key) => owns(candidate, key)) && - (await candidate.takes(shared.value)) - ) { - route = candidate; - break; - } - const { description } = route; - const refused = supplied.filter((key) => !owns(route, key)); - if (refused.length > 0) - return projectAnalysisError( - new AnalysisInputError( - description.contract.name, - undefined, - refused.map((key) => ({ - path: [key], - reason: "invalid_value" as const, - message: `--${kebabCase(key)} requires ${owners.get(key)!.requirement}; the given input selects ${route.requirement}, which does not take it.`, - })), - ), + registerCliCommand( + cli, + name, + { + description: command.description, + args: z.object(Object.fromEntries(args)), + options: z.object(Object.fromEntries(options)), + run: ({ + args: given, + options: chosen, + }: { + readonly args: Readonly>; + readonly options: Readonly>; + }) => { + const values: Record = { ...chosen, ...given }; + const supplied = Object.keys(values).filter( + (key) => values[key] !== undefined, + ); + return withCommandCancellation((signal) => + logCliCommand(logger, name, async () => { + const shared = await readJsonInputs( + routes[0]!.description, + values, + signal, + sharedJson, ); - const options = description.admitDeliveryOptions(shared.value); - if (!options.ok) return projectAnalysisError(options.error); - const read = await readJsonInputs( - description, - shared.value, - signal, - ownJsonInputs(description, sharedJson), - ); - if (!read.ok) return read.error; - const admitted = description.admit(read.value); - if (!admitted.ok) - return projectCliInputFields( - projectAnalysisError(admitted.error), + if (!shared.ok) return shared.error; + let route = routes.at(-1)!; + for (const candidate of routes) + if ( + candidate.takes !== undefined && + supplied.every((key) => owns(candidate, key)) && + (await candidate.takes(shared.value)) + ) { + route = candidate; + break; + } + const { description } = route; + const refused = supplied.filter((key) => !owns(route, key)); + if (refused.length > 0) + return projectAnalysisError( + new AnalysisInputError( + description.contract.name, + undefined, + refused.map((key) => ({ + path: [key], + reason: "invalid_value" as const, + message: `--${kebabCase(key)} requires ${owners.get(key)!.requirement}; the given input selects ${route.requirement}, which does not take it.`, + })), + ), + ); + const options = description.admitDeliveryOptions(shared.value); + if (!options.ok) return projectAnalysisError(options.error); + const read = await readJsonInputs( + description, + shared.value, + signal, + ownJsonInputs(description, sharedJson), + ); + if (!read.ok) return read.error; + const admitted = description.admit(read.value); + if (!admitted.ok) + return projectCliInputFields( + projectAnalysisError(admitted.error), + description.inputBinding, + ); + const opening = admitOpening(description, values); + if (!opening.ok) return projectAnalysisError(opening.error); + return projectCliResult( + await route.run(admitted.value.input, { + signal, + operation: description.contract.name, + callerInputs: description.callerInputs(values), + sessionTarget: + description.sessionTarget === undefined + ? undefined + : (values[description.sessionTarget.key] as string), + evidenceTargets: undefined, + opening: opening.value, + delivery: admitted.value.delivery, + parsed: admitted.value.parsed, + parseWholeInput: admitted.value.parseWholeInput, + checked: { ...shared.checked, ...read.checked }, + cliOptions: description.cliOptionValues( + withCliOnlyDefaults(description, values), + ), + }), + description.contract.outputSchema, description.inputBinding, ); - const opening = admitOpening(description, values); - if (!opening.ok) return projectAnalysisError(opening.error); - return projectCliResult( - await route.run(admitted.value.input, { - signal, - operation: description.contract.name, - callerInputs: description.callerInputs(values), - sessionTarget: - description.sessionTarget === undefined - ? undefined - : (values[description.sessionTarget.key] as string), - evidenceTargets: undefined, - opening: opening.value, - delivery: admitted.value.delivery, - parsed: admitted.value.parsed, - parseWholeInput: admitted.value.parseWholeInput, - checked: { ...shared.checked, ...read.checked }, - cliOptions: description.cliOptionValues( - withCliOnlyDefaults(description, values), - ), - }), - description.contract.outputSchema, - description.inputBinding, - ); - }), - ); + }), + ); + }, + } as never, + { + operations: distinctOperations( + routes.flatMap(({ description }) => + contractDescriptionOperations(description), + ), + ), + source: { + kind: "routed", + descriptions: routes.map(({ description }) => description), + }, }, - } as never); - const registered = routedDescriptions.get(cli) ?? []; - registered.push(...routes.map(({ description }) => description)); - routedDescriptions.set(cli, registered); + ); }; /** @@ -1080,16 +1110,13 @@ export interface ContractDocumentContext< readonly opening: Readonly>; } -const documentDescriptions = new WeakMap< - CliInstance, - ContractCliDocumentDescription[] ->(); - /** Commands registered on this CLI through `registerContractDocumentCommand`. */ export const contractDocumentCommandDescriptions = ( cli: CliInstance, ): readonly ContractCliDocumentDescription[] => - documentDescriptions.get(cli) ?? []; + cliCommands(cli).flatMap(({ source }) => + source.kind === "document" ? [source.description] : [], + ); /** * A document field the projection omits or takes as an option is refused @@ -1263,94 +1290,103 @@ export const registerContractDocumentCommand = < ...description.cliOnlyOptions, ].map(({ key, schema }) => [key, schema]), ); - cli.command(description.command, { - description: description.description, - args: z.object({ - ...(description.sessionTarget === undefined + registerCliCommand( + cli, + description.command, + { + description: description.description, + args: z.object({ + ...(description.sessionTarget === undefined + ? {} + : { + [description.sessionTarget.key]: description.sessionTarget.schema, + }), + [description.key]: jsonInputArgument( + description.documentDescription, + description.content, + ), + }), + ...(Object.keys(options).length === 0 ? {} - : { - [description.sessionTarget.key]: description.sessionTarget.schema, + : { options: z.object(options) }), + run: ({ + args, + options: values, + }: { + readonly args: Readonly>; + readonly options: Readonly>; + }) => + withCommandCancellation((signal) => + logCliCommand(logger, description.command, async () => { + // Delivery options are checked before the document is read. + const delivery = description.admitDelivery(values); + if (!delivery.ok) return projectAnalysisError(delivery.error); + const opening = admitOpening(description, { ...values, ...args }); + if (!opening.ok) return projectAnalysisError(opening.error); + const decoded = await parseCliJsonInput( + args[description.key]!, + contract.name, + signal, + ); + if (!decoded.ok) return decoded.error; + // A document that is not an object has no fields to refuse; the + // contract refuses it. + const refused = + typeof decoded.value === "object" && decoded.value !== null + ? refusedDocumentFieldError( + contract.name, + description.documentRefusals, + decoded.value, + ) + : undefined; + if (refused !== undefined) return projectAnalysisError(refused); + const document = resolveCliJsonPaths( + decoded.value, + description.callerPaths, + ); + let admitted: + | Result, AnalysisInputError> + | undefined; + const parseWholeInput = () => + (admitted ??= (() => { + const parsed = contract.inputSchema.safeParse(document); + return parsed.success + ? ok(parsed.data as z.output) + : err( + analysisInputErrorFromIssues( + contract.name, + parsed.error.issues, + decoded.value, + ), + ); + })()); + return run(document, { + signal, + operation: contract.name, + spelled: decoded.value, + parsed: undefined, + parseWholeInput, + frame: description.content, + delivery: delivery.value, + opening: opening.value, + sessionTarget: + description.sessionTarget === undefined + ? undefined + : args[description.sessionTarget.key], + cliOptions: description.cliOptionValues( + values, + ) as CliOptionValues, + }); }), - [description.key]: jsonInputArgument( - description.documentDescription, - description.content, - ), - }), - ...(Object.keys(options).length === 0 - ? {} - : { options: z.object(options) }), - run: ({ - args, - options: values, - }: { - readonly args: Readonly>; - readonly options: Readonly>; - }) => - withCommandCancellation((signal) => - logCliCommand(logger, description.command, async () => { - // Delivery options are checked before the document is read. - const delivery = description.admitDelivery(values); - if (!delivery.ok) return projectAnalysisError(delivery.error); - const opening = admitOpening(description, { ...values, ...args }); - if (!opening.ok) return projectAnalysisError(opening.error); - const decoded = await parseCliJsonInput( - args[description.key]!, - contract.name, - signal, - ); - if (!decoded.ok) return decoded.error; - // A document that is not an object has no fields to refuse; the - // contract refuses it. - const refused = - typeof decoded.value === "object" && decoded.value !== null - ? refusedDocumentFieldError( - contract.name, - description.documentRefusals, - decoded.value, - ) - : undefined; - if (refused !== undefined) return projectAnalysisError(refused); - const document = resolveCliJsonPaths( - decoded.value, - description.callerPaths, - ); - let admitted: - | Result, AnalysisInputError> - | undefined; - const parseWholeInput = () => - (admitted ??= (() => { - const parsed = contract.inputSchema.safeParse(document); - return parsed.success - ? ok(parsed.data as z.output) - : err( - analysisInputErrorFromIssues( - contract.name, - parsed.error.issues, - decoded.value, - ), - ); - })()); - return run(document, { - signal, - operation: contract.name, - spelled: decoded.value, - parsed: undefined, - parseWholeInput, - frame: description.content, - delivery: delivery.value, - opening: opening.value, - sessionTarget: - description.sessionTarget === undefined - ? undefined - : args[description.sessionTarget.key], - cliOptions: description.cliOptionValues( - values, - ) as CliOptionValues, - }); - }), - ), - } as never); - const registered = documentDescriptions.get(cli) ?? []; - registered.push(description); - documentDescriptions.set(cli, registered); + ), + } as never, + { + // A document's fields are set in the document, not by flags. + operations: contractDescriptionOperations({ + contract: description.contract, + sessionTarget: description.sessionTarget, + }), + source: { kind: "document", description }, + }, + ); }; diff --git a/src/cli/desktopCaptureCommands.ts b/src/cli/desktopCaptureCommands.ts index 1c3fcf1a41..210f95d2c2 100644 --- a/src/cli/desktopCaptureCommands.ts +++ b/src/cli/desktopCaptureCommands.ts @@ -32,6 +32,7 @@ import { import { createDesktopCaptureProvider } from "../desktop/DesktopCaptureProvider.js"; import { SessionRequestQueue } from "../desktop/DesktopSessionRequests.js"; import { withCommandCancellation } from "./commandCancellation.js"; +import { registerCliCommand } from "./commandRegistry.js"; import type { CliInstance } from "./types.js"; import { writeCliProgressLine } from "./cliProgress.js"; import { errorMessage } from "../kernel/errorMessage.js"; @@ -306,7 +307,7 @@ const registerDesktopExportCommand = ( logger: Logger, environment: NodeJS.ProcessEnv, ): void => { - cli.command(CLI_COMMANDS.exportDesktopApplication, { + registerCliCommand(cli, CLI_COMMANDS.exportDesktopApplication, { description: "Export a desktop application capture folder as an agentenv computer app bundle: class, env.toml, skill and seed", args: z.object({ @@ -422,7 +423,7 @@ const registerDesktopTaskCommand = ( logger: Logger, environment: NodeJS.ProcessEnv, ): void => { - cli.command(CLI_COMMANDS.describeDesktopApplicationTask, { + registerCliCommand(cli, CLI_COMMANDS.describeDesktopApplicationTask, { description: "Describe how a desktop application capture's files changed from the seed checkpoint to the end, with suggested checks and a task draft to complete for export-desktop-application --task", args: z.object({ @@ -468,7 +469,7 @@ const registerDesktopStateCommand = ( logger: Logger, environment: NodeJS.ProcessEnv, ): void => { - cli.command(CLI_COMMANDS.inspectDesktopApplicationState, { + registerCliCommand(cli, CLI_COMMANDS.inspectDesktopApplicationState, { description: "Read a desktop application capture folder into the application's state: roles, typed JSON views of each version and kinds of change", args: z.object({ @@ -520,7 +521,7 @@ export const registerDesktopCaptureCommands = ( registerDesktopStateCommand(cli, logger, environment); registerDesktopExportCommand(cli, logger, environment); registerDesktopTaskCommand(cli, logger, environment); - cli.command(CLI_COMMANDS.captureDesktopApplication, { + registerCliCommand(cli, CLI_COMMANDS.captureDesktopApplication, { description: "Launch a Linux desktop application, watch it while it is used and record its windows and state at checkpoints read from stdin", options: captureOptions, diff --git a/src/cli/environmentCommands.ts b/src/cli/environmentCommands.ts index 8d9a671e9e..4664b9d353 100644 --- a/src/cli/environmentCommands.ts +++ b/src/cli/environmentCommands.ts @@ -40,6 +40,7 @@ import { TEMPLATE_RULES } from "../domain/analysisView/environmentManifestRules. import { inspectWebNetworkCaptureInputSchema } from "../domain/webNetworkCapture.js"; import { withCommandCancellation } from "./commandCancellation.js"; import { finishCliEvidenceCommand } from "./cliEvidenceCallerPath.js"; +import { registerCliCommand } from "./commandRegistry.js"; import type { CliInstance } from "./types.js"; import { cliDecimalField, publishArgvInput } from "./options.js"; @@ -482,7 +483,7 @@ const registerBuildCommand = ( logger: Logger, environment: Readonly, ): void => { - cli.command(CLI_COMMANDS.environmentBuild, { + registerCliCommand(cli, CLI_COMMANDS.environmentBuild, { description: "Build an agent environment bundle from a recorded capture in one offline step: inspect a HAR (or read capture Evidence), project the environment manifest, derive the state, report which tools the environment answers from state, which replay and why each write is withheld, then write the bundle environment-export writes", args: z.object({ @@ -607,7 +608,7 @@ const compareEnvironmentCommand = async ( /** Register the comparison of an environment with probe captures of its application. */ const registerCompareCommand = (cli: CliInstance, logger: Logger): void => { - cli.command(CLI_COMMANDS.environmentCompare, { + registerCliCommand(cli, CLI_COMMANDS.environmentCompare, { description: "Compare an environment with probe captures of the application it was captured from: each probe is one call sequence recorded against a freshly reset application, answered by the environment from a reset state, with agreement reported per step, tool and probe", args: z.object({ manifest: manifestArgument }), @@ -633,7 +634,7 @@ const registerCompareCommand = (cli: CliInstance, logger: Logger): void => { /** Register the one-shot bundle export command. */ const registerExportCommand = (cli: CliInstance, logger: Logger): void => { - cli.command(CLI_COMMANDS.environmentExport, { + registerCliCommand(cli, CLI_COMMANDS.environmentExport, { description: "Export an environment manifest and its capture Evidence as an agent environment bundle folder the agentenv framework runs with agent-env run", args: z.object({ @@ -678,7 +679,7 @@ export const registerEnvironmentCommands = ( registerBuildCommand(cli, logger, environment); registerExportCommand(cli, logger); registerCompareCommand(cli, logger); - cli.command(CLI_COMMANDS.environmentServe, { + registerCliCommand(cli, CLI_COMMANDS.environmentServe, { description: "Serve an environment manifest as an agent environment over streamable HTTP until SIGINT or SIGTERM: read tools, and write tools whose effect the capture confirmed, answer from the state the capture observed, derived at startup, or every tool replays retained capture records with --replay-only or when the state is unavailable", args: z.object({ manifest: manifestArgument }), diff --git a/src/cli/guidanceCommands.ts b/src/cli/guidanceCommands.ts index 8903e62ce1..fcea407406 100644 --- a/src/cli/guidanceCommands.ts +++ b/src/cli/guidanceCommands.ts @@ -13,6 +13,7 @@ import { CLI_COMMANDS } from "../contracts/cliCommandNames.js"; import { logCliCommand } from "../cliLogging.js"; import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import type { Logger } from "pino"; +import { registerCliCommand } from "./commandRegistry.js"; import type { CliInstance } from "./types.js"; import { cliDecimalField } from "./options.js"; import { ownCliProcessResource } from "./cliResources.js"; @@ -51,7 +52,7 @@ export const registerGuidanceCommands = ( logger: Logger, resources: CliGuidanceResources = processGuidanceResources, ): void => { - cli.command(CLI_COMMANDS.guidance, { + registerCliCommand(cli, CLI_COMMANDS.guidance, { description: "Search or read the installed REA workflow guidance", args: z.object({}), options: z diff --git a/src/cli/options.ts b/src/cli/options.ts index 3f9844ac80..95efec333e 100644 --- a/src/cli/options.ts +++ b/src/cli/options.ts @@ -1,16 +1,7 @@ import { z } from "zod"; -import { localPathStringSchema } from "../domain/localPath.js"; -import { - executableFormatHintSchema, - type ExecutableFormatHint, -} from "../domain/dosCom.js"; +import type { ExecutableFormatHint } from "../domain/dosCom.js"; import type { BinaryArchitecture } from "../domain/binaryTargetTypes.js"; -import { - binaryArchitectureSchema, - rawBinaryEntryPointSchema, -} from "../domain/rawBinary.js"; -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"; @@ -173,40 +164,6 @@ const NATIVE_OPEN_HELP = { snapshot: "Load and update a local analysis snapshot", } as const; -export const providerSelectionOption = analysisProviderSelectorSchema - .optional() - .describe(NATIVE_OPEN_HELP.provider); - -/** Optional path to the local analysis snapshot loaded or updated by a command. */ -export const snapshotSelectionOption = localPathStringSchema - .optional() - .describe(NATIVE_OPEN_HELP.snapshot); - -/** - * Explicit interpretation for headerless native executable formats. Flash - * dumps take their offsets on the artifact commands instead. - */ -const formatSelectionOption = executableFormatHintSchema - .exclude(["esp-flash-image"]) - .optional() - .describe(NATIVE_OPEN_HELP.format); - -export const architectureSelectionOption = binaryArchitectureSchema - .optional() - .describe(NATIVE_OPEN_HELP.architecture); - -export const entryPointSelectionOption = rawBinaryEntryPointSchema - .optional() - .describe(NATIVE_OPEN_HELP.entryPoint); - -/** Shared CLI flags that bind a native target interpretation. */ -export const nativeOpenOptionFields = { - "target-format": formatSelectionOption, - architecture: architectureSelectionOption, - "entry-point": entryPointSelectionOption, - 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 diff --git a/src/cli/processCommands.ts b/src/cli/processCommands.ts index d66b961394..0916ed655f 100644 --- a/src/cli/processCommands.ts +++ b/src/cli/processCommands.ts @@ -14,6 +14,7 @@ import { SESSION_TOOL_CONTRACTS } from "../contracts/sessionToolContracts.js"; import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import { contractNamed } from "./contractCliDescription.js"; import { registerContractCommand } from "./contractCommand.js"; +import { registerCliCommand } from "./commandRegistry.js"; import type { CliInstance } from "./types.js"; import { logCliCommand } from "../cliLogging.js"; import type { Logger } from "pino"; @@ -27,7 +28,7 @@ export const registerProcessCommands = ( logger: Logger, environment: Readonly>, ): void => { - cli.command(CLI_COMMANDS.captureProcess, { + registerCliCommand(cli, CLI_COMMANDS.captureProcess, { description: "Capture one caller-selected process scenario", args: z.object({ scenario: localPathStringSchema.describe("Scenario JSON path"), diff --git a/src/cli/reverseEngineeringCommands.ts b/src/cli/reverseEngineeringCommands.ts index 99b78b6e66..d68bf92e98 100644 --- a/src/cli/reverseEngineeringCommands.ts +++ b/src/cli/reverseEngineeringCommands.ts @@ -18,6 +18,7 @@ import { ok } from "../domain/result.js"; import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import { OBJDUMP_ARTIFACT_OPERATIONS } from "../domain/reverseEngineering.js"; import { logCliCommand } from "../cliLogging.js"; +import { registerCliCommand } from "./commandRegistry.js"; import type { CliInstance } from "./types.js"; import { withCommandCancellation } from "./commandCancellation.js"; import { CLI_COMMANDS } from "../contracts/cliCommandNames.js"; @@ -232,7 +233,7 @@ export const registerReverseEngineeringCommands = ( ), ), ); - cli.command(CLI_COMMANDS.debugWithGdb, { + registerCliCommand(cli, CLI_COMMANDS.debugWithGdb, { description: "Run one unrestricted GDB console command in an ephemeral MI session; provide an inferior TTY so a live target can be safely detached", args: z.object({ @@ -308,7 +309,7 @@ export const registerReverseEngineeringCommands = ( }), ), }); - cli.command(CLI_COMMANDS.debugWithRizin, { + registerCliCommand(cli, CLI_COMMANDS.debugWithRizin, { description: "Run one unrestricted Rizin debugger command in an ephemeral session", args: z.object({ diff --git a/src/cli/setupCommands.ts b/src/cli/setupCommands.ts index 24ec867ca5..84b10acdd7 100644 --- a/src/cli/setupCommands.ts +++ b/src/cli/setupCommands.ts @@ -33,6 +33,7 @@ import { PRODUCT_IDENTITY } from "../identity.js"; import { logCliCommand } from "../cliLogging.js"; import { CLI_COMMANDS } from "../contracts/cliCommandNames.js"; import type { Logger } from "pino"; +import { registerCliCommand } from "./commandRegistry.js"; import type { CliInstance } from "./types.js"; import { SUPPORTED_CLIENT_DEFINITIONS } from "../application/SupportedClients.js"; @@ -56,7 +57,7 @@ const registerSetupCommand = ( logger: Logger, environment: Readonly, ): void => { - cli.command(CLI_COMMANDS.setup, { + registerCliCommand(cli, CLI_COMMANDS.setup, { description: "Configure agent integrations and optional analysis providers", outputPolicy: "agent-only", options: z.object({ @@ -143,7 +144,7 @@ const registerDoctorCommand = ( logger: Logger, environment: Readonly, ): void => { - cli.command(CLI_COMMANDS.doctor, { + registerCliCommand(cli, CLI_COMMANDS.doctor, { description: "Check whether REA is ready", options: z.object({ target: localPathStringSchema @@ -187,7 +188,7 @@ const registerMaintenanceCommands = ( logger: Logger, environment: Readonly, ): void => { - cli.command(CLI_COMMANDS.uninstall, { + registerCliCommand(cli, CLI_COMMANDS.uninstall, { description: "Remove REA-owned agent configuration and skill files", options: z.object({ purgeData: z @@ -215,7 +216,7 @@ const registerMaintenanceCommands = ( isUninstallFailure, ), }); - cli.command(CLI_COMMANDS.update, { + registerCliCommand(cli, CLI_COMMANDS.update, { description: "Update this REA installation and verify the installed release", run: ({ formatExplicit }) => diff --git a/src/cli/utilityCommands.ts b/src/cli/utilityCommands.ts index 30e480bac4..7d2a72e0bd 100644 --- a/src/cli/utilityCommands.ts +++ b/src/cli/utilityCommands.ts @@ -28,6 +28,7 @@ import { isCliOperationFailure, logCliCommand } from "../cliLogging.js"; import { CLI_COMMANDS, cliCommandFor } from "../contracts/cliCommandNames.js"; import { localPathStringSchema } from "../domain/localPath.js"; import type { Logger } from "pino"; +import { registerCliCommand } from "./commandRegistry.js"; import type { CliInstance } from "./types.js"; import { registerNativeCallCommands } from "./nativeCallCommands.js"; import { NATIVE_TOOL_CONTRACTS } from "../contracts/native/nativeToolContracts.js"; @@ -109,7 +110,7 @@ const registerCapabilityCommands = ( CLI_COMMANDS.capabilities, CLI_COMMANDS.providers, ] as const) { - cli.command(command, { + registerCliCommand(cli, command, { description: command === "capabilities" ? "List provider capabilities and side effects" @@ -252,7 +253,7 @@ const registerReferenceSourceCommand = ( logger: Logger, environment: Readonly>, ): void => { - cli.command(CLI_COMMANDS.importReferenceSource, { + registerCliCommand(cli, CLI_COMMANDS.importReferenceSource, { description: "Import a source tree as historical reference only", args: z.object({ root: localPathStringSchema.describe( diff --git a/src/cliEvidenceCommands.ts b/src/cliEvidenceCommands.ts index e096d8a0e1..12ad614842 100644 --- a/src/cliEvidenceCommands.ts +++ b/src/cliEvidenceCommands.ts @@ -2,7 +2,8 @@ import { withCommandCancellation } from "./cli/commandCancellation.js"; import { parseCliJsonInput } from "./cli/cliJsonInput.js"; import { analysisInputErrorFromIssues } from "./domain/inputIssueProjection.js"; import { bundleComparisonInputSchema } from "./domain/bundleComparison.js"; -import { Cli } from "incur"; +import { registerCliCommand } from "./cli/commandRegistry.js"; +import type { CliInstance } from "./cli/types.js"; import { z } from "zod"; import { @@ -20,10 +21,10 @@ import { localPathStringSchema } from "./domain/localPath.js"; /** Register caller-path Evidence commands. */ export const registerEvidenceCommands = ( - cli: ReturnType, + cli: CliInstance, logger: Logger, ): void => { - cli.command(CLI_COMMANDS.evidenceImport, { + registerCliCommand(cli, CLI_COMMANDS.evidenceImport, { description: "Validate a standalone Evidence bundle and count records and Unknown revisions; does not retain them in an MCP session", args: z.object({ @@ -37,7 +38,7 @@ export const registerEvidenceCommands = ( }), ), }); - cli.command(CLI_COMMANDS.evidenceExport, { + registerCliCommand(cli, CLI_COMMANDS.evidenceExport, { description: "Validate and atomically export canonical Evidence JSON", args: z.object({ source: localPathStringSchema.describe( @@ -61,7 +62,7 @@ export const registerEvidenceCommands = ( }), ), }); - cli.command(CLI_COMMANDS.compare, { + registerCliCommand(cli, CLI_COMMANDS.compare, { description: "Compare two canonical Evidence bundles by record identity; use compare-artifacts for artifact inventory contents", args: z.object({ diff --git a/tests/boundary/cli/cliCommandRegistry.test.ts b/tests/boundary/cli/cliCommandRegistry.test.ts new file mode 100644 index 0000000000..2e7e6970a9 --- /dev/null +++ b/tests/boundary/cli/cliCommandRegistry.test.ts @@ -0,0 +1,114 @@ +import { describe, expect, it } from "vitest"; + +import { createCli } from "../../../src/cli.js"; +import { cliCommands } from "../../../src/cli/commandRegistry.js"; +import { visitRegisteredCommands } from "../../../src/cli/visitRegisteredCommands.js"; + +const cli = createCli({}); +const entries = cliCommands(cli); +const entry = (name: string) => { + const found = entries.find((candidate) => candidate.name === name); + if (found === undefined) throw new Error(`${name} is not registered`); + return found; +}; + +describe("REA's CLI command table", () => { + it("holds every dispatched command, in registration order, with the served definition", () => { + const dispatched: { path: string; command: object }[] = []; + visitRegisteredCommands(cli, (command, path) => + dispatched.push({ path, command }), + ); + expect(entries.map(({ name }) => name)).toEqual( + dispatched.map(({ path }) => path), + ); + // Shell owners rewrite inputs and handlers in place; the table sees them. + for (const [index, { command }] of dispatched.entries()) + expect(entries[index]!.definition).toBe(command); + }); + + it("names the operations a direct-analysis command runs and the flag of each field", () => { + expect(entry("function").operations).toEqual([ + { name: "analyze_function", flags: expect.any(Object) }, + { + name: "open_binary", + flags: { + format: "--target-format", + architecture: "--architecture", + entry_point: "--entry-point", + provider_id: "--provider", + snapshot_path: "--snapshot", + }, + }, + ]); + // `--kind procedures` chooses another operation. + expect(entry("search").operations.map(({ name }) => name)).toEqual([ + "search_strings", + "open_binary", + "search_procedures", + ]); + expect(entry("decompile").operations.map(({ name }) => name)).toEqual([ + "procedure_pseudo_code", + "open_binary", + ]); + // The overview route opens its target the same way. + expect( + entry("analyze").operations.find(({ name }) => name === "open_binary") + ?.flags, + ).toMatchObject({ snapshot_path: "--snapshot" }); + }); + + it("records each route of a routed command and each contract command's own flags", () => { + expect(entry("analyze").operations.map(({ name }) => name)).toEqual([ + "analyze_javascript_application", + "binary_overview", + "open_binary", + ]); + expect(entry("analyze").source.kind).toBe("routed"); + expect(entry("inspect-byte-entropy").operations).toEqual([ + { + name: "inspect_byte_entropy", + flags: { + block_size: "--block-size", + offset: "--offset", + length: "--length", + }, + }, + ]); + }); + + it("flags every contract field an option sets: grouped fields and named selectors", () => { + const flags = (command: string, operation: string) => + entry(command).operations.find(({ name }) => name === operation)?.flags; + // One JSON option supplies each field of its group; the group's CLI key + // is not a contract field. + const jni = flags( + "inspect-android-jni-bindings", + "inspect_android_jni_bindings", + ); + expect(jni).toMatchObject({ + class_name: "--query", + method_names: "--query", + descriptors: "--query", + abis: "--query", + library_paths: "--query", + }); + expect(jni).not.toHaveProperty("query"); + // A positional selector is also set by its named option. + expect(flags("function", "analyze_function")).toMatchObject({ + procedure: "--procedure", + }); + expect(flags("decompile", "procedure_pseudo_code")).toMatchObject({ + procedure: "--procedure", + }); + expect(flags("search", "search_strings")).toMatchObject({ + pattern: "--pattern", + }); + }); + + it("lists host commands without operations", () => { + for (const name of ["setup", "doctor", "guidance", "capture-process"]) { + expect(entry(name).source).toEqual({ kind: "host" }); + expect(entry(name).operations).toEqual([]); + } + }); +}); diff --git a/tests/boundary/cli/completions.test.ts b/tests/boundary/cli/completions.test.ts index 6bd5047f87..9db94b9bb6 100644 --- a/tests/boundary/cli/completions.test.ts +++ b/tests/boundary/cli/completions.test.ts @@ -3,11 +3,14 @@ import { Cli } from "incur"; import { z } from "zod"; import { expect, it } from "vitest"; +import { registerCliCommand } from "../../../src/cli/commandRegistry.js"; import { createCliCompletions } from "../../../src/cli/completions.js"; +import type { CliInstance } from "../../../src/cli/types.js"; import { workspaceCliTest } from "../../support/cli/workspaceCliFixture.js"; -const registry = () => - Cli.create("rea", { sync: false }).command("instructions", { +const registry = () => { + const cli = Cli.create("rea", { sync: false }) as unknown as CliInstance; + registerCliCommand(cli, "instructions", { options: z.object({ procedure: z.string().optional(), targetFormat: z.enum(["dos-com", "raw-binary"]).optional(), @@ -16,6 +19,8 @@ const registry = () => throw new Error("Completion must not execute a command"); }, }); + return cli; +}; const complete = (words: string[], index = words.length - 1) => { let text = ""; const callback = createCliCompletions(registry(), {