From d5a942177fad030d3caf0f8d39856c116e3e5cda Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Tue, 17 Nov 2026 05:42:07 +0800 Subject: [PATCH] feat(errors): carry related parameters and operations and derive CLI flags and commands (#11777) * feat(errors): carry related parameters and operations and derive CLI flags and commands * fix(cli,errors): preserve operation-selector flags in CLI hints and clarify snapshot load/save --- .../cli-option-text-outside-cli.json | 5 - src/application/EvidenceBundleFiles.ts | 3 +- src/cli/commandRegistry.ts | 50 +++++ src/cli/contractCommand.ts | 20 +- src/cli/projectCliAnalysisResult.ts | 204 ++++++++++++++++-- src/cli/runCliCommand.ts | 14 +- src/cliLogging.ts | 13 ++ src/domain/analysisErrorPresentation.ts | 78 ++++++- src/domain/analysisErrorProjection.ts | 3 +- src/ghidra/GhidraFileOffsetFailure.ts | 12 +- src/ghidra/GhidraProvider.behavior.test.ts | 12 +- src/ghidra/GhidraProviderClient.ts | 18 +- ...avaScriptAnalysisWorker.inspection.test.ts | 2 + .../analysis/JavaScriptAnalysisWorker.ts | 3 +- src/providers/AnalysisClientFailure.test.ts | 13 +- src/providers/AnalysisClientFailure.ts | 1 + tests/boundary/cli/cliCommandRegistry.test.ts | 12 +- .../cli/projectCliAnalysisResult.test.ts | 151 +++++++++++++ tests/boundary/cli/rawBinaryCli.test.ts | 89 +++++++- .../filesystem/appleBundleTargets.test.ts | 2 + .../filesystem/targetDiagnostics.test.ts | 13 +- tests/boundary/mcp/artifactMcp.test.ts | 5 +- .../ghidraDecompileDeadlineLifetime.test.ts | 6 + tests/boundary/mcp/wasmArtifactMcp.test.ts | 14 +- .../mcp/workflowSnapshotReplayMcp.test.ts | 4 +- 25 files changed, 679 insertions(+), 68 deletions(-) diff --git a/scripts/verify/baselines/cli-option-text-outside-cli.json b/scripts/verify/baselines/cli-option-text-outside-cli.json index 424a449e91..b5aa727cf5 100644 --- a/scripts/verify/baselines/cli-option-text-outside-cli.json +++ b/scripts/verify/baselines/cli-option-text-outside-cli.json @@ -1,10 +1,5 @@ { - "src/application/EvidenceBundleFiles.ts": 1, "src/application/decompileDirectory/decompileAll.ts": 1, - "src/domain/analysisErrorPresentation.ts": 6, "src/dotnet/ManagedMemberRecovery.ts": 1, - "src/ghidra/GhidraFileOffsetFailure.ts": 1, - "src/ghidra/GhidraProviderClient.ts": 5, - "src/javascript/analysis/JavaScriptAnalysisWorker.ts": 1, "src/kuna/KunaProjectReader.ts": 1 } diff --git a/src/application/EvidenceBundleFiles.ts b/src/application/EvidenceBundleFiles.ts index 969afd4940..a45c40a5bf 100644 --- a/src/application/EvidenceBundleFiles.ts +++ b/src/application/EvidenceBundleFiles.ts @@ -160,8 +160,9 @@ export const authenticateEvidenceBundleValue = ( path: absoluteCallerPath(path), cause: failure.cause, detectedKind: "analysis-snapshot", + related: { operations: ["open_binary", "export_evidence_bundle"] }, userMessage: - "This JSON appears to be an analysis snapshot rather than an Evidence bundle. Its snapshot content has not been validated. To restore it, use a matching target, provider and analysis profile: call open_binary with snapshot_path set to this file, or pass --snapshot to a compatible CLI analysis command (which loads and updates the snapshot). Alternatively, supply a bundle from export_evidence_bundle.", + "This JSON appears to be an analysis snapshot rather than an Evidence bundle. Its snapshot content has not been validated. To restore it, use a matching target, provider and analysis profile: call open_binary with snapshot_path set to this file to load the snapshot, and close_binary with snapshot_path to save updated state. Alternatively, supply a bundle from export_evidence_bundle.", }), ); return err( diff --git a/src/cli/commandRegistry.ts b/src/cli/commandRegistry.ts index 5f162f5b4b..76977d3669 100644 --- a/src/cli/commandRegistry.ts +++ b/src/cli/commandRegistry.ts @@ -1,5 +1,6 @@ import type { z } from "zod"; +import { cliCommandFor } from "../contracts/cliCommandNames.js"; import type { ContractCliDescription, ContractCliDocumentDescription, @@ -17,6 +18,11 @@ export interface CliCommandOperation { * delivery fields have no flag. */ readonly flags: Readonly>; + /** + * The CLI selector option and value that chooses this operation when the + * command defaults to another contract, such as `"--kind procedures"`. + */ + readonly selector?: string | undefined; } type Inputs = Schema extends z.ZodObject @@ -132,12 +138,14 @@ export const contractDescriptionOperations = ( readonly contract: { readonly name: string }; readonly evidenceTargets?: ContractCliDescription["evidenceTargets"]; }, + options: { readonly selector?: string | undefined } = {}, ): readonly CliCommandOperation[] => { const { sessionTarget, evidenceTargets } = description; return [ { name: description.contract.name, flags: description.inputBinding?.flags ?? {}, + ...(options.selector === undefined ? {} : { selector: options.selector }), }, ...(sessionTarget?.opening === undefined ? [] @@ -193,3 +201,45 @@ export const commandOwnOperations = ( } return operations; }; + +/** + * The CLI command spelling (`rea `) that runs a contract operation, + * or undefined when no CLI command answers it. Prefers the canonical + * single-contract command, then a contract command whose own operations start + * with or include it, then any other registered command whose own operations + * include it. + */ +export const cliCommandForOperation = ( + operation: string, + entries: readonly CliCommandEntry[], + cliName: string, + recordedCommands?: Readonly>, +): string | undefined => { + const canonical = cliCommandFor(operation); + let contractPrimary: string | undefined; + let contractSecondary: string | undefined; + let otherMatch: string | undefined; + for (const entry of entries) { + const own = commandOwnOperations(entry); + const matched = own.find(({ name }) => name === operation); + if (matched === undefined) continue; + const command = + matched.selector === undefined + ? entry.name + : `${entry.name} ${matched.selector}`; + if (entry.name === canonical) return `${cliName} ${command}`; + if (entry.source.kind === "contract") { + if (own[0]?.name === operation) contractPrimary ??= command; + else contractSecondary ??= command; + } else { + otherMatch ??= command; + } + } + if ( + recordedCommands !== undefined && + Object.hasOwn(recordedCommands, canonical) + ) + return `${cliName} ${canonical}`; + const selected = contractPrimary ?? contractSecondary ?? otherMatch; + return selected === undefined ? undefined : `${cliName} ${selected}`; +}; diff --git a/src/cli/contractCommand.ts b/src/cli/contractCommand.ts index f74cabe50d..bb1e504922 100644 --- a/src/cli/contractCommand.ts +++ b/src/cli/contractCommand.ts @@ -686,11 +686,13 @@ export const registerContractCommand = < 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 operations = contractDescriptionOperations(selected); const resultBinding = description.evidenceTargets === undefined - ? selected.inputBinding + ? { ...selected.inputBinding, operations } : { ...selected.inputBinding, + operations, flags: { ...description.evidenceTargets.sourceFlags, ...selected.inputBinding.flags, @@ -746,11 +748,14 @@ export const registerContractCommand = < }, } as never, { - operations: distinctOperations( - [description, ...chosen.values()].flatMap( - contractDescriptionOperations, + operations: distinctOperations([ + ...contractDescriptionOperations(description), + ...[...chosen.entries()].flatMap(([value, choice]) => + contractDescriptionOperations(choice, { + selector: `--${optionFlagName(projection.operationBy!.option)} ${String(value)}`, + }), ), - ), + ]), source: { kind: "contract", description }, }, ); @@ -1027,7 +1032,10 @@ export const registerRoutedCommand = ( ), }), description.contract.outputSchema, - description.inputBinding, + { + ...description.inputBinding, + operations: contractDescriptionOperations(description), + }, ); }), ); diff --git a/src/cli/projectCliAnalysisResult.ts b/src/cli/projectCliAnalysisResult.ts index d875bf3ec3..7126e29948 100644 --- a/src/cli/projectCliAnalysisResult.ts +++ b/src/cli/projectCliAnalysisResult.ts @@ -3,12 +3,31 @@ import type { z } from "zod"; import { recordedControlSchemas } from "../domain/analysisSettingDefinitions.js"; import type { JsonValue } from "../domain/jsonValue.js"; import type { Result } from "../domain/result.js"; +import { + cliCommandForOperation, + type CliCommandEntry, + type CliCommandOperation, +} from "./commandRegistry.js"; interface CliInputFieldBinding { readonly operation: string; readonly fields: Readonly>; /** Each contract field, or `field.member`, the command takes as a flag. */ readonly flags: Readonly>; + /** + * Operations the selected command route runs, including its session-target + * opener and Evidence-target source. When supplied, recovery flags fall back + * across these operations when an error omits `details.operation` or names + * its opener. + */ + readonly operations?: readonly CliCommandOperation[] | undefined; +} + +export interface CliCommandOutputProjectionContext { + readonly operations: readonly CliCommandOperation[]; + readonly commands: readonly CliCommandEntry[]; + readonly cliName?: string | undefined; + readonly recordedCommands?: Readonly> | undefined; } /** Flatten a finalized outcome only when returning the command's JSON output. */ @@ -21,6 +40,20 @@ export const isObject = ( ): value is Record => value !== null && typeof value === "object" && !Array.isArray(value); +const orderedOperations = ( + operations: readonly CliCommandOperation[], + errorOperation: JsonValue | undefined, +): readonly CliCommandOperation[] => { + if (typeof errorOperation !== "string" || operations.length <= 1) + return operations; + const matching = operations.filter(({ name }) => name === errorOperation); + if (matching.length === 0) return operations; + return [ + ...matching, + ...operations.filter(({ name }) => name !== errorOperation), + ]; +}; + /** * Name a contract command's input fields by their CLI spelling in its * output: a direct failure, a delivered failure or a refused publication. @@ -36,10 +69,23 @@ export const projectCliInputFields = ( binding: CliInputFieldBinding, ): Output => { const error = output as JsonValue; - if (!isObject(error) || !isObject(error.details)) return output; + if ( + !isObject(error) || + typeof error.code !== "string" || + !isObject(error.details) + ) + return output; + const operations = + binding.operations === undefined + ? [{ name: binding.operation, flags: binding.flags }] + : orderedOperations(binding.operations, error.details.operation); const issues = renamedIssues(error, error.details, binding); - const limit = flaggedLimit(error.details.limit, binding); - const relatedFlags = relatedCliFlags(error.details, binding); + const limit = flaggedLimit(error.details.limit, operations); + const relatedFlags = + binding.operations === undefined && + error.details.operation !== binding.operation + ? undefined + : relatedCliFlagsFromOperations(error.details, operations); if (issues === undefined && limit === undefined && relatedFlags === undefined) return output; return { @@ -56,28 +102,132 @@ export const projectCliInputFields = ( }; /** - * The option of each field this command's failure names for its recovery, - * keyed by contract field, or undefined when it takes none of them. Fields - * of another operation are that command's to render. + * Render `cli_flag`, `related_cli_flags`, and `related_cli_commands` on any + * CLI command's error output from its registered operations and the CLI's + * command registry. Preserves existing route-specific bindings and untouched + * references. */ -const relatedCliFlags = ( - details: Record, - binding: CliInputFieldBinding, -): Record | undefined => { +export const projectCliCommandOutput = ( + output: Output, + context: CliCommandOutputProjectionContext, +): Output => { + const candidate = output as JsonValue; + if (!isObject(candidate)) return output; + if (typeof candidate.code === "string" && isObject(candidate.details)) + return projectErrorRecord(candidate, context) as Output; if ( - details.operation !== binding.operation || - !Array.isArray(details.related_parameters) + isObject(candidate.error) && + typeof candidate.error.code === "string" && + isObject(candidate.error.details) + ) { + const nested = projectErrorRecord(candidate.error, context); + return nested === candidate.error + ? output + : ({ ...candidate, error: nested } as Output); + } + return output; +}; + +const projectErrorRecord = ( + error: Record, + context: CliCommandOutputProjectionContext, +): Record => { + const { details } = error; + if (!isObject(details)) return error; + const operations = orderedOperations(context.operations, details.operation); + const limit = + isObject(details.limit) && Object.hasOwn(details.limit, "cli_flag") + ? undefined + : flaggedLimit(details.limit, operations); + const relatedFlags = Object.hasOwn(details, "related_cli_flags") + ? undefined + : relatedCliFlagsFromOperations(details, operations); + const relatedCommands = Object.hasOwn(details, "related_cli_commands") + ? undefined + : relatedCliCommands(details, context); + const secondaryFailures = projectedSecondaryFailures( + details.secondary_failures, + context, + ); + if ( + limit === undefined && + relatedFlags === undefined && + relatedCommands === undefined && + secondaryFailures === undefined ) + return error; + return { + ...error, + details: { + ...details, + ...(limit === undefined ? {} : { limit }), + ...(relatedFlags === undefined + ? {} + : { related_cli_flags: relatedFlags }), + ...(relatedCommands === undefined + ? {} + : { related_cli_commands: relatedCommands }), + ...(secondaryFailures === undefined + ? {} + : { secondary_failures: secondaryFailures }), + }, + }; +}; + +const projectedSecondaryFailures = ( + secondary: JsonValue | undefined, + context: CliCommandOutputProjectionContext, +): JsonValue[] | undefined => { + if (!Array.isArray(secondary) || secondary.length === 0) return undefined; + let changed = false; + const mapped = secondary.map((item) => { + if (!isObject(item) || typeof item.code !== "string") return item; + const next = projectErrorRecord(item, context); + if (next !== item) changed = true; + return next; + }); + return changed ? mapped : undefined; +}; + +/** + * The option of each field a failure names for its recovery, keyed by contract + * field, or undefined when the command takes none of them. + */ +const relatedCliFlagsFromOperations = ( + details: Record, + operations: readonly CliCommandOperation[], +): Record | undefined => { + if (!Array.isArray(details.related_parameters) || operations.length === 0) return undefined; const flags: Record = {}; for (const parameter of details.related_parameters) { if (typeof parameter !== "string") continue; - const flag = cliFlagFor(parameter, binding); + const flag = cliFlagForOperations(parameter, operations); if (flag !== undefined) flags[parameter] = flag; } return Object.keys(flags).length === 0 ? undefined : flags; }; +const relatedCliCommands = ( + details: Record, + context: CliCommandOutputProjectionContext, +): Record | undefined => { + if (!Array.isArray(details.related_operations)) return undefined; + const cliName = context.cliName ?? "rea"; + const commands: Record = {}; + for (const operation of details.related_operations) { + if (typeof operation !== "string") continue; + const command = cliCommandForOperation( + operation, + context.commands, + cliName, + context.recordedCommands, + ); + if (command !== undefined) commands[operation] = command; + } + return Object.keys(commands).length === 0 ? undefined : commands; +}; + /** Issue paths renamed to CLI keys, or undefined when none changes. */ const renamedIssues = ( error: Record, @@ -128,13 +278,29 @@ const limitParameter = (limit: JsonValue | undefined): string | undefined => * parameter path names the flag: a flattened member option, else the option * of the whole field (such as `--producer-limits` JSON). */ -const cliFlagFor = ( +const cliFlagForFlags = ( parameter: string, - binding: CliInputFieldBinding, + flags: Readonly>, ): string | undefined => { const segments = parameter.split("."); for (let length = segments.length; length > 0; length -= 1) { - const flag = binding.flags[segments.slice(0, length).join(".")]; + const flag = flags[segments.slice(0, length).join(".")]; + if (flag !== undefined) return flag; + } + return undefined; +}; + +const cliFlagFor = ( + parameter: string, + binding: Pick, +): string | undefined => cliFlagForFlags(parameter, binding.flags); + +const cliFlagForOperations = ( + parameter: string, + operations: readonly CliCommandOperation[], +): string | undefined => { + for (const operation of operations) { + const flag = cliFlagForFlags(parameter, operation.flags); if (flag !== undefined) return flag; } return undefined; @@ -143,11 +309,13 @@ const cliFlagFor = ( /** The reported per-call control with the flag that sets it. */ const flaggedLimit = ( limit: JsonValue | undefined, - binding: CliInputFieldBinding, + operations: readonly CliCommandOperation[], ): Record | undefined => { const parameter = limitParameter(limit); const flag = - parameter === undefined ? undefined : cliFlagFor(parameter, binding); + parameter === undefined + ? undefined + : cliFlagForOperations(parameter, operations); return flag === undefined || !isObject(limit) ? undefined : { ...limit, cli_flag: flag }; diff --git a/src/cli/runCliCommand.ts b/src/cli/runCliCommand.ts index 58fbb1ad2f..64de4660ca 100644 --- a/src/cli/runCliCommand.ts +++ b/src/cli/runCliCommand.ts @@ -17,8 +17,11 @@ import { type CliCommandFailure, } from "./argumentErrors.js"; import { parseCliArgv } from "./argvParser.js"; -import { cliCommand } from "./commandRegistry.js"; +import { cliCommand, cliCommands } from "./commandRegistry.js"; import { withCliEvidencePublication } from "./cliEvidencePublication.js"; +import { rebindLoggedCliFailure } from "../cliLogging.js"; +import { RECORDED_CLI_COMMAND_REGISTRATIONS } from "../recordedCliCommandRegistrations.js"; +import { projectCliCommandOutput } from "./projectCliAnalysisResult.js"; import { cliResultControls, withCliResultControls, @@ -122,10 +125,17 @@ export const runCliCommand = async ( } await withCliEvidencePublication(() => withCliResultControls(async () => { - const value = await entry.definition.run({ + const rawValue = await entry.definition.run({ ...parsed.value, formatExplicit: controls.formatExplicit, }); + const value = projectCliCommandOutput(rawValue, { + operations: entry.operations, + commands: cliCommands(cli), + cliName: cli.name, + recordedCommands: RECORDED_CLI_COMMAND_REGISTRATIONS, + }); + rebindLoggedCliFailure(rawValue, value); if (!output.handled) await output.write(value, { command: entry.name, diff --git a/src/cliLogging.ts b/src/cliLogging.ts index bb7698b618..a9ada75910 100644 --- a/src/cliLogging.ts +++ b/src/cliLogging.ts @@ -96,6 +96,19 @@ export const cliOperationFailureIdentity = ( ): CliFailureIdentity | undefined => isRecord(value) ? loggedFailures.get(value)?.identity : undefined; +/** Keep failure classification and recovery identity when a CLI wrapper projects an error record. */ +export const rebindLoggedCliFailure = ( + previous: unknown, + next: unknown, +): void => { + if (previous === next || !isRecord(previous) || !isRecord(next)) return; + if (!loggedFailures.has(previous)) return; + loggedFailures.set( + next, + inferCliOperationFailure(next) ?? loggedFailures.get(previous), + ); +}; + /** Log one CLI command with duration and a stable success or failure status. */ export const logCliCommand = async ( logger: Logger, diff --git a/src/domain/analysisErrorPresentation.ts b/src/domain/analysisErrorPresentation.ts index fc5c408153..baa820f063 100644 --- a/src/domain/analysisErrorPresentation.ts +++ b/src/domain/analysisErrorPresentation.ts @@ -42,6 +42,7 @@ import { type AnalysisContinuingCallerGuidance, type AnalysisError, type AnalysisErrorTag, + type AnalysisRelatedInputs, domainErrorTag, ProviderOwnedAnalysisError, } from "./analysisErrorBase.js"; @@ -172,7 +173,7 @@ export const analysisErrorRemediationAction = ( error instanceof BinaryTargetError && error.constraint === "directory_requires_file" ) - return `For a JavaScript/Electron application directory, call analyze_javascript_application with input_path or run \`rea analyze \`. For binary analysis, select its executable file or an Apple bundle directory (${OPENABLE_APPLE_BUNDLE_TYPES_TEXT}).`; + return `For a JavaScript/Electron application directory, call analyze_javascript_application with input_path. For binary analysis, select its executable file or an Apple bundle directory (${OPENABLE_APPLE_BUNDLE_TYPES_TEXT}).`; if ( error instanceof BinaryTargetError && error.constraint === "bundle_type_unsupported" @@ -184,7 +185,7 @@ export const analysisErrorRemediationAction = ( error.constraint === "bundle_program_missing") && error.infoPlist !== undefined ) - return `Read ${error.infoPlist} with inspect_plist (\`rea inspect-plist \`) to review its CFBundleExecutable, then select an existing program file directly.`; + return `Read ${error.infoPlist} with inspect_plist to review its CFBundleExecutable, then select an existing program file directly.`; if ( error instanceof BinaryTargetError && (error.constraint === "bundle_info_plist_missing" || @@ -197,7 +198,7 @@ export const analysisErrorRemediationAction = ( error instanceof BinaryTargetError && error.constraint === "load_selection_rejected" ) - return "Correct the reported load argument (--target-format, --architecture, or --entry-point on the CLI; format, architecture, or entry_point through MCP) and retry."; + return "Correct the reported load argument (format, architecture, or entry_point) and retry."; if ( error instanceof BinaryTargetError && error.constraint === "file_format_rejected" @@ -207,7 +208,7 @@ export const analysisErrorRemediationAction = ( error instanceof BinaryTargetError && error.constraint === "wasm_requires_static_inspection" ) - return `For static inspection, call inspect_wasm_artifact with ${JSON.stringify({ path: error.path })} or run \`rea inspect-wasm-artifact --format json\`. This separate lane requires caller-supplied WABT 1.0.42 via absolute REA_WABT_BIN_DIRECTORY; check its availability in binary_session. REA does not execute WASM or install tools, and the header alone does not establish that the complete module is valid.`; + return `For static inspection, call inspect_wasm_artifact with ${JSON.stringify({ path: error.path })}. This separate lane requires caller-supplied WABT 1.0.42 via absolute REA_WABT_BIN_DIRECTORY; check its availability in binary_session. REA does not execute WASM or install tools, and the header alone does not establish that the complete module is valid.`; if ( error instanceof AnalysisAccessDeniedError || (error instanceof BinaryTargetError && error.systemCode !== undefined) @@ -465,7 +466,7 @@ const outcomeUserMessage = (error: AnalysisError): string => { return `${error.message}. Static WebAssembly inspection uses a separate optional WABT lane, not a native analysis engine.`; if (error instanceof BinaryTargetError) return error.constraint === "directory_requires_file" - ? `open_binary accepts files and Apple bundle directories (${OPENABLE_APPLE_BUNDLE_TYPES_TEXT}). This target is another directory; JavaScript/Electron application directories can be analyzed directly with analyze_javascript_application or \`rea analyze \`.` + ? `open_binary accepts files and Apple bundle directories (${OPENABLE_APPLE_BUNDLE_TYPES_TEXT}). This target is another directory; JavaScript/Electron application directories can be analyzed directly with analyze_javascript_application.` : error.constraint === undefined ? `${error.message}. Check that the path exists, is readable, and points to a supported file.` : `${error.message}.`; @@ -564,12 +565,77 @@ const artifactMessage = ({ details.calculatedSha256 !== null ? `Declared ASAR integrity for unpacked entry ${details.logicalPath} contradicts its companion file; packaging tools commonly sign or strip unpacked native binaries after writing the archive.` : "Artifact bytes contradict declared integrity." - } If expected, rerun ${operation === "inventory_artifact" ? "inspect_artifact" : operation} with integrity_policy=record-and-continue (CLI: --integrity-policy record-and-continue) to retain observed bytes as untrusted; otherwise get a fresh copy.`; + } If expected, rerun ${operation === "inventory_artifact" ? "inspect_artifact" : operation} with integrity_policy=record-and-continue to retain observed bytes as untrusted; otherwise get a fresh copy.`; if (reason === "format" || reason === "integrity") return "Artifact is invalid or has changed. Get a fresh copy and try again."; return "Artifact could not be read or written. Check file access and try again."; }; +const mergeRelatedList = ( + left: readonly string[] | undefined, + right: readonly string[] | undefined, +): readonly string[] | undefined => { + const merged = [...new Set([...(left ?? []), ...(right ?? [])])]; + return merged.length === 0 ? undefined : merged; +}; + +const presentedRelatedInputs = ( + error: AnalysisError, +): AnalysisRelatedInputs | undefined => { + if (error instanceof BinaryTargetError) { + if (error.constraint === "directory_requires_file") + return { operations: ["analyze_javascript_application"] }; + if (error.remediationAction !== undefined) return undefined; + if ( + (error.constraint === "bundle_executable_undeclared" || + error.constraint === "bundle_program_missing") && + error.infoPlist !== undefined + ) + return { operations: ["inspect_plist"] }; + if (error.constraint === "load_selection_rejected") + return { parameters: ["format", "architecture", "entry_point"] }; + if (error.constraint === "wasm_requires_static_inspection") + return { operations: ["inspect_wasm_artifact"] }; + } + if ( + error instanceof ArtifactOperationError && + error.reason === "integrity" && + error.artifactDetails !== undefined && + INTEGRITY_POLICY_OPERATIONS.has(error.operation) + ) + return { + parameters: ["integrity_policy"], + ...(error.operation === "inventory_artifact" + ? { operations: ["inspect_artifact"] } + : {}), + }; + return undefined; +}; + +/** + * Contract fields and operations that the shared error presentation names for + * recovery, combined with any producer-bound `error.related`. + */ +export const analysisErrorRelatedInputs = ( + error: AnalysisError, +): AnalysisRelatedInputs | undefined => { + error = resolvedAnalysisError(error); + const presented = presentedRelatedInputs(error); + const parameters = mergeRelatedList( + error.related?.parameters, + presented?.parameters, + ); + const operations = mergeRelatedList( + error.related?.operations, + presented?.operations, + ); + if (parameters === undefined && operations === undefined) return undefined; + return { + ...(parameters === undefined ? {} : { parameters }), + ...(operations === undefined ? {} : { operations }), + }; +}; + const evidenceFileMessage = ({ operation, reason, diff --git a/src/domain/analysisErrorProjection.ts b/src/domain/analysisErrorProjection.ts index e4035ff0ed..79eccf047e 100644 --- a/src/domain/analysisErrorProjection.ts +++ b/src/domain/analysisErrorProjection.ts @@ -10,6 +10,7 @@ import { isImmutableJsonSnapshot } from "./immutableJson.js"; import { analysisErrorCategory, UNRETAINED_EVIDENCE_EXPORT_GUIDANCE, + analysisErrorRelatedInputs, analysisErrorRemediationAction, analysisErrorUserMessage, assertKnownAnalysisError, @@ -448,7 +449,7 @@ const projectError = ( ...(refusal === undefined ? {} : { refusal: analysisRefusalDetails(refusal) }), - ...relatedInputDetails(primary.related), + ...relatedInputDetails(analysisErrorRelatedInputs(primary)), ...(!options.secondary || secondary.size === 0 ? {} : { diff --git a/src/ghidra/GhidraFileOffsetFailure.ts b/src/ghidra/GhidraFileOffsetFailure.ts index 6ba217da57..4c81639dee 100644 --- a/src/ghidra/GhidraFileOffsetFailure.ts +++ b/src/ghidra/GhidraFileOffsetFailure.ts @@ -26,8 +26,7 @@ export const ghidraFileOffsetOutcome = ( ? FILE_OFFSET_OUTCOMES[code as keyof typeof FILE_OFFSET_OUTCOMES] : undefined; -const LOAD_IMAGE = - "inspect_native_load_image (CLI: `rea inspect-native-load-image --provider ghidra --json`)"; +const LOAD_IMAGE = "inspect_native_load_image"; const UNCHANGED = "Do not repeat the unchanged call."; const SELECT_MAPPED = `Review Ghidra's memory blocks and source-file mappings with ${LOAD_IMAGE}, then select an address inside an initialized mapping of the admitted file. ${UNCHANGED}`; @@ -55,6 +54,15 @@ export const ghidraFileOffsetUnavailable = ( operation, { ...options, + related: { + ...options.related, + operations: [ + ...new Set([ + ...(options.related?.operations ?? []), + "inspect_native_load_image", + ]), + ], + }, userMessage: `${reason.trim().replace(/\.$/u, "")}. REA establishes no single exact original-file offset for this well-formed address and does not derive or choose one.`, remediationAction: REMEDIATION[outcome], conformsToInputContract: true, diff --git a/src/ghidra/GhidraProvider.behavior.test.ts b/src/ghidra/GhidraProvider.behavior.test.ts index e6d731d1c5..7441928b92 100644 --- a/src/ghidra/GhidraProvider.behavior.test.ts +++ b/src/ghidra/GhidraProvider.behavior.test.ts @@ -1780,6 +1780,9 @@ describe("Ghidra procedure lookup projection", () => { code: "invalid_request", message, details: { + related_operations: code.startsWith("file_offset_") + ? ["inspect_native_load_image"] + : ["list_procedures", "search_procedures"], issues: [ { path: ["procedure"], @@ -1792,6 +1795,7 @@ describe("Ghidra procedure lookup projection", () => { expect(projected).not.toHaveProperty("recovery"); expect(projected.remediation.action).toContain(remedy); expect(projected.remediation.action).toContain(qualification); + expect(projected.remediation.action).not.toContain("(CLI:"); expect(projected.remediation.action).not.toContain( "REA_GHIDRA_PROJECT_PATH", ); @@ -1913,6 +1917,7 @@ describe("Ghidra file-offset outcome projection", () => { retryable: false, details: { operation: "address_to_file_offset", + related_operations: ["inspect_native_load_image"], issues: [ { path: ["address"], @@ -1930,6 +1935,7 @@ describe("Ghidra file-offset outcome projection", () => { expect(projected.remediation.action).toContain( "inspect_native_load_image", ); + expect(projected.remediation.action).not.toContain("(CLI:"); expect(projected.remediation.action).not.toContain("schema"); expect(projected.remediation.action).not.toContain("tools/list"); await client.close(); @@ -2106,10 +2112,14 @@ describe("Ghidra decompiler failure projection", () => { code: "execution_failure", retryable: false, message: `${message}. Only the decompiler failed for this procedure. ${GHIDRA_SESSION_RETAINED}`, - details: { diagnostics: { remote_code: code } }, + details: { + related_operations: ["analyze_function"], + diagnostics: { remote_code: code }, + }, }); expect(projected.message).not.toContain("rea doctor"); expect(projected.remediation.action).toContain("analyze_function"); + expect(projected.remediation.action).not.toContain("rea function"); expect(projected.remediation.action).toContain( "facet_availability.pseudocode", ); diff --git a/src/ghidra/GhidraProviderClient.ts b/src/ghidra/GhidraProviderClient.ts index 84f2feca31..6feae16078 100644 --- a/src/ghidra/GhidraProviderClient.ts +++ b/src/ghidra/GhidraProviderClient.ts @@ -1472,31 +1472,37 @@ const projectPrimarySessionError = ( failure.remoteCode === "file_offset_ambiguous") ) { let recovery: string; + let relatedOperations: readonly string[]; switch (failure.remoteCode) { case "file_offset_unmapped": recovery = - "Use inspect_native_load_image (CLI: `rea inspect-native-load-image --provider ghidra --json`) to inspect the admitted file's loaded mappings, then select an offset with an observed mapping. A missing mapping does not prove the file contains no relevant data."; + "Use inspect_native_load_image to inspect the admitted file's loaded mappings, then select an offset with an observed mapping. A missing mapping does not prove the file contains no relevant data."; + relatedOperations = ["inspect_native_load_image"]; break; case "file_offset_ambiguous": recovery = "Choose a space-qualified analysis address from the reported mappings, such as ram:0x1000. A bare 0x... selector falls back to file-offset lookup and can report this ambiguity again. Use inspect_native_load_image to inspect the loaded mappings and Ghidra's observed default address space; REA does not select one automatically."; + relatedOperations = ["inspect_native_load_image"]; break; case "procedure_ambiguous": recovery = "Choose an explicit procedure entry address from the reported candidates. Use list_procedures or search_procedures to inspect the current Ghidra inventory."; + relatedOperations = ["list_procedures", "search_procedures"]; break; default: recovery = - "Use list_procedures or search_procedures (CLI: `rea search --kind procedures --provider ghidra --json`) to inspect the current Ghidra inventory and choose an observed name or address. An absent entry does not prove the function is absent from the artifact." + + "Use list_procedures or search_procedures to inspect the current Ghidra inventory and choose an observed name or address. An absent entry does not prove the function is absent from the artifact." + (source === "existing-project" ? " The selected project's previous analysis completeness is unknown. To explicitly request a separate fresh import, start a new REA process without REA_GHIDRA_PROJECT_PATH and REA_GHIDRA_PROGRAM_NAME; that analysis will not include the selected project's annotations or other edits." : "") + ` ${ghidraFunctionSeedRecovery(source)}`; + relatedOperations = ["list_procedures", "search_procedures"]; } return new AnalysisInputError( operation, { ...context, + related: { operations: relatedOperations }, userMessage: failure.message, conformsToInputContract: true, remediationAction: recovery, @@ -1531,6 +1537,7 @@ const projectPrimarySessionError = ( if (failure.kind === "remote" && failure.remoteCode === "decompile_failed") return new ProviderAdapterError("ghidra", operation, { ...context, + related: { operations: ["analyze_function"] }, ...ghidraRequestOutcome( failure, "Only the decompiler failed for this procedure.", @@ -1538,7 +1545,7 @@ const projectPrimarySessionError = ( source, ), remediationAction: - "Call analyze_function (CLI: `rea function`) for the same procedure. It returns assembly, callers, callees, references and basic blocks from the Ghidra listing and records this decompiler failure under facet_availability.pseudocode. Repeating the unchanged decompile request is not expected to succeed.", + "Call analyze_function for the same procedure. It returns assembly, callers, callees, references and basic blocks from the Ghidra listing and records this decompiler failure under facet_availability.pseudocode. Repeating the unchanged decompile request is not expected to succeed.", }); // A request-level deadline, not a provider failure: other operations stay // available. Only a continuing caller can reuse the session, and only when @@ -1568,6 +1575,7 @@ const projectPrimarySessionError = ( limits.ghidraDecompileTimeoutSeconds, undefined, ), + related: { operations: ["analyze_function"] }, userMessage: outcome.userMessage, remediationAction: recovery.remediationAction, continuingCallerGuidance: { @@ -1910,9 +1918,9 @@ export const ghidraDecompileTimeoutRecovery = ( seconds < MAX_GHIDRA_DECOMPILE_TIMEOUT_SECONDS ? `Set REA_GHIDRA_DECOMPILE_TIMEOUT_SECONDS above ${String(seconds)} seconds (maximum ${String(MAX_GHIDRA_DECOMPILE_TIMEOUT_SECONDS)}), or unset it to leave decompilation unbounded,` : `REA_GHIDRA_DECOMPILE_TIMEOUT_SECONDS is already at its maximum of ${String(seconds)} seconds; unset it to leave decompilation unbounded` - } in the environment of a new REA invocation, then rerun the command. That invocation starts a new Ghidra session and ${ghidraSessionRestart(source)}. Use \`rea function\` for this procedure's listing facts without pseudocode.`, + } in the environment of a new REA invocation, then rerun the command. That invocation starts a new Ghidra session and ${ghidraSessionRestart(source)}. Use analyze_function for this procedure's listing facts without pseudocode.`, continuingRemediationAction: - "Use analyze_function (CLI: `rea function`) for listing facts. Call update_analysis_settings with setting ghidra.decompile_timeout_seconds and action set to raise the per-function deadline for the next operation on this Program. For CLI or future REA processes, set REA_GHIDRA_DECOMPILE_TIMEOUT_SECONDS. Set the MCP tool-call deadline to cover startup and the full call; earlier cancellation closes the session. `rea setup` estimates deadlines for new Codex/Kimi registrations and preserves existing positive values; edit existing deadlines yourself.", + "Use analyze_function for listing facts. Call update_analysis_settings with setting ghidra.decompile_timeout_seconds and action set to raise the per-function deadline for the next operation on this Program. For CLI or future REA processes, set REA_GHIDRA_DECOMPILE_TIMEOUT_SECONDS. Set the MCP tool-call deadline to cover startup and the full call; earlier cancellation closes the session. `rea setup` estimates deadlines for new Codex/Kimi registrations and preserves existing positive values; edit existing deadlines yourself.", }); /** diff --git a/src/javascript/analysis/JavaScriptAnalysisWorker.inspection.test.ts b/src/javascript/analysis/JavaScriptAnalysisWorker.inspection.test.ts index cce2f5a83d..eb8e86b7e3 100644 --- a/src/javascript/analysis/JavaScriptAnalysisWorker.inspection.test.ts +++ b/src/javascript/analysis/JavaScriptAnalysisWorker.inspection.test.ts @@ -239,6 +239,8 @@ it.each(["cancelled", "physical"] as const)( const error = primaryAnalysisError(result.error.error); const deadline = { _tag: "AnalysisTimeoutError", + related: { parameters: ["source_paths"] }, + remediationAction: expect.not.stringContaining("--source-path"), limit: expect.objectContaining({ setting: "javascript.analysis_timeout_ms", effective_value: 20, diff --git a/src/javascript/analysis/JavaScriptAnalysisWorker.ts b/src/javascript/analysis/JavaScriptAnalysisWorker.ts index 4e869e5429..3d668b8a64 100644 --- a/src/javascript/analysis/JavaScriptAnalysisWorker.ts +++ b/src/javascript/analysis/JavaScriptAnalysisWorker.ts @@ -1245,10 +1245,11 @@ export class JavaScriptAnalysisWorker { this.limits.timeoutMs, this.limits.timeoutSource, ), + related: { parameters: ["source_paths"] }, ...(withCapturedOutput ? { capturedOutput: this.#captured() } : {}), userMessage: `JavaScript source analysis reached its ${String(this.limits.timeoutMs)}ms per-source server/provider deadline (analysis_timeout_ms), not the MCP client deadline.`, remediationAction: - "Reuse accessible partial_observation Evidence to avoid recomputation; reading it is not a prerequisite for a corrected retry. Increase analysis_timeout_ms on the next call. Alternatively, reduce semantic limits or select exact inventoried source_paths (CLI: --source-path on that command). Omit source_paths to analyze all sources; an empty array is invalid. detail: summary reduces response size, not analysis work. Allow execution, cleanup and delivery headroom in the MCP client tool deadline; increasing that client deadline alone does not change this server budget. Resolve any reported incomplete cleanup before retrying.", + "Reuse accessible partial_observation Evidence to avoid recomputation; reading it is not a prerequisite for a corrected retry. Increase analysis_timeout_ms on the next call. Alternatively, reduce semantic limits or select exact inventoried source_paths. Omit source_paths to analyze all sources; an empty array is invalid. detail: summary reduces response size, not analysis work. Allow execution, cleanup and delivery headroom in the MCP client tool deadline; increasing that client deadline alone does not change this server budget. Resolve any reported incomplete cleanup before retrying.", }); } #workerExitFailure( diff --git a/src/providers/AnalysisClientFailure.test.ts b/src/providers/AnalysisClientFailure.test.ts index 0671d081dc..5fa036149c 100644 --- a/src/providers/AnalysisClientFailure.test.ts +++ b/src/providers/AnalysisClientFailure.test.ts @@ -161,7 +161,15 @@ it("keeps the structured limit when a resource refusal changes operation", () => "transport", "status exceeded the ceiling", { max_request_bytes: 8192 }, - { remediationAction: "Raise the ceiling.", retryable: false, limit }, + { + remediationAction: "Raise the ceiling.", + retryable: false, + limit, + related: { + parameters: ["max_output_bytes"], + operations: ["analyze_function"], + }, + }, ); const attributed = analysisClientFailureForOperation( source, @@ -174,9 +182,12 @@ it("keeps the structured limit when a resource refusal changes operation", () => expect(attributed.operation).toBe("binary_overview"); expect(attributed.retryable).toBe(false); expect(attributed.limit).toEqual(source.limit); + expect(attributed.related).toEqual(source.related); expect(projectAnalysisError(attributed)).toMatchObject({ code: "resource_constraint", details: { + related_parameters: ["max_output_bytes"], + related_operations: ["analyze_function"], limit: { setting: "bridge.max_request_bytes", effective_value: 8192, diff --git a/src/providers/AnalysisClientFailure.ts b/src/providers/AnalysisClientFailure.ts index 34a8493ade..a3f2d473e2 100644 --- a/src/providers/AnalysisClientFailure.ts +++ b/src/providers/AnalysisClientFailure.ts @@ -46,6 +46,7 @@ export const analysisClientFailureContext = ( return { cause, ...(cause.limit === undefined ? {} : { limit: cause.limit }), + ...(cause.related === undefined ? {} : { related: cause.related }), ...(cause.continuingCallerGuidance === undefined ? {} : { continuingCallerGuidance: cause.continuingCallerGuidance }), diff --git a/tests/boundary/cli/cliCommandRegistry.test.ts b/tests/boundary/cli/cliCommandRegistry.test.ts index 7138361294..a127add6a6 100644 --- a/tests/boundary/cli/cliCommandRegistry.test.ts +++ b/tests/boundary/cli/cliCommandRegistry.test.ts @@ -27,10 +27,14 @@ describe("REA's CLI command table", () => { }, ]); // `--kind procedures` chooses another operation. - expect(entry("search").operations.map(({ name }) => name)).toEqual([ - "search_strings", - "open_binary", - "search_procedures", + expect(entry("search").operations).toEqual([ + { name: "search_strings", flags: expect.any(Object) }, + { name: "open_binary", flags: expect.any(Object) }, + { + name: "search_procedures", + flags: expect.any(Object), + selector: "--kind procedures", + }, ]); expect(entry("decompile").operations.map(({ name }) => name)).toEqual([ "procedure_pseudo_code", diff --git a/tests/boundary/cli/projectCliAnalysisResult.test.ts b/tests/boundary/cli/projectCliAnalysisResult.test.ts index f81d543d65..e607b6943b 100644 --- a/tests/boundary/cli/projectCliAnalysisResult.test.ts +++ b/tests/boundary/cli/projectCliAnalysisResult.test.ts @@ -11,8 +11,13 @@ import { freezeJsonSnapshot } from "../../../src/domain/immutableJson.js"; import { ownedJsonObjectSchema } from "../../../src/domain/jsonValue.js"; import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js"; import { err, ok } from "../../../src/domain/result.js"; +import { createCli } from "../../../src/cli.js"; +import { cliCommand, cliCommands } from "../../../src/cli/commandRegistry.js"; +import { BinaryTargetError } from "../../../src/domain/configurationErrors.js"; +import { ArtifactOperationError } from "../../../src/domain/artifactOperationError.js"; import { projectCliAnalysisResult, + projectCliCommandOutput, projectCliInputFields, } from "../../../src/cli/projectCliAnalysisResult.js"; @@ -183,3 +188,149 @@ it("names related fields and operations by contract identity and renders only th projectAnalysisError(new AnalysisInputError("inspect_plist")).details ?? {}, ).not.toHaveProperty("related_parameters"); }); + +it("renders related_cli_flags and related_cli_commands from the CLI command registry across command shapes", () => { + const cli = createCli(); + const entries = cliCommands(cli); + const inspectEntry = cliCommand(cli, "inspect"); + const compareEntry = cliCommand(cli, "compare"); + const inspectArtifactEntry = cliCommand(cli, "inspect-artifact"); + if ( + inspectEntry === undefined || + compareEntry === undefined || + inspectArtifactEntry === undefined + ) + throw new Error("Expected registered CLI commands"); + + // Open-path BinaryTargetError has no details.operation; flags come from the + // running command's open_binary bindings, while MCP projection stays flag-free. + const loadRejected = projectAnalysisError( + new BinaryTargetError("/tmp/image.bin", "unaligned entry", { + constraint: "load_selection_rejected", + }), + ); + expect(loadRejected.details).toMatchObject({ + related_parameters: ["format", "architecture", "entry_point"], + }); + expect(loadRejected.details).not.toHaveProperty("related_cli_flags"); + expect(JSON.stringify(loadRejected)).not.toContain("--target-format"); + + const cliLoadRejected = projectCliCommandOutput( + { error: "Analysis failed", ...loadRejected }, + { operations: inspectEntry.operations, commands: entries }, + ); + expect(cliLoadRejected).toMatchObject({ + error: "Analysis failed", + details: { + related_parameters: ["format", "architecture", "entry_point"], + related_cli_flags: { + format: "--target-format", + architecture: "--architecture", + entry_point: "--entry-point", + }, + }, + }); + + // Artifact integrity errors omit details.operation when artifactDetails are present. + const integrityFailure = projectAnalysisError( + new ArtifactOperationError("inspect_artifact", "integrity", { + logicalPath: "main.js", + unpacked: false, + declaredSha256: "a".repeat(64), + calculatedSha256: "b".repeat(64), + }), + ); + expect(integrityFailure.details).toMatchObject({ + related_parameters: ["integrity_policy"], + }); + expect(JSON.stringify(integrityFailure)).not.toContain("--integrity-policy"); + expect( + projectCliCommandOutput(integrityFailure, { + operations: inspectArtifactEntry.operations, + commands: entries, + }), + ).toMatchObject({ + details: { + related_cli_flags: { integrity_policy: "--integrity-policy" }, + }, + }); + + // Operation references resolve canonical contract commands and aliased direct + // commands while omitting MCP-only operations such as list_procedures and open_binary. + const operationRefs = projectAnalysisError( + new AnalysisInputError("procedure_pseudo_code", { + related: { + operations: [ + "analyze_function", + "procedure_pseudo_code", + "search_procedures", + "inspect_plist", + "inspect_wasm_artifact", + "inspect_native_load_image", + "analyze_javascript_application", + "list_procedures", + "open_binary", + ], + }, + }), + ); + expect( + projectCliCommandOutput(operationRefs, { + operations: inspectEntry.operations, + commands: entries, + }), + ).toMatchObject({ + details: { + related_cli_commands: { + analyze_function: "rea function", + procedure_pseudo_code: "rea decompile", + search_procedures: "rea search --kind procedures", + inspect_plist: "rea inspect-plist", + inspect_wasm_artifact: "rea inspect-wasm-artifact", + inspect_native_load_image: "rea inspect-native-load-image", + analyze_javascript_application: "rea analyze-javascript-application", + }, + }, + }); + + // In one-shot mode where only the running registrar was loaded, recorded + // canonical commands from other registrars still resolve. + expect( + projectCliCommandOutput( + projectAnalysisError( + new BinaryTargetError("/tmp/module.wasm", "wasm module", { + constraint: "wasm_requires_static_inspection", + }), + ), + { + operations: inspectEntry.operations, + commands: [inspectEntry], + recordedCommands: { "inspect-wasm-artifact": "wasm" }, + }, + ), + ).toMatchObject({ + details: { + related_operations: ["inspect_wasm_artifact"], + related_cli_commands: { + inspect_wasm_artifact: "rea inspect-wasm-artifact", + }, + }, + }); + + // Non-contract host commands that bind contract operations render flags too. + const compareFailure = projectAnalysisError( + new AnalysisInputError("compare_bundles", { + related: { parameters: ["record_pairs"] }, + }), + ); + expect( + projectCliCommandOutput( + { error: compareFailure }, + { operations: compareEntry.operations, commands: entries }, + ), + ).toMatchObject({ + error: { + details: { related_cli_flags: { record_pairs: "--record_pairs" } }, + }, + }); +}); diff --git a/tests/boundary/cli/rawBinaryCli.test.ts b/tests/boundary/cli/rawBinaryCli.test.ts index 7988ac195c..8a831cb91a 100644 --- a/tests/boundary/cli/rawBinaryCli.test.ts +++ b/tests/boundary/cli/rawBinaryCli.test.ts @@ -1,4 +1,4 @@ -import { writeFile } from "node:fs/promises"; +import { mkdir, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { expect } from "vitest"; @@ -122,7 +122,15 @@ cliTest( expect(result.exitCode).toBe(1); expect(result.json).toMatchObject({ code: "invalid_request", - details: { reason: expect.stringContaining("6502 address width") }, + details: { + reason: expect.stringContaining("6502 address width"), + related_parameters: ["format", "architecture", "entry_point"], + related_cli_flags: { + format: "--target-format", + architecture: "--architecture", + entry_point: "--entry-point", + }, + }, }); }, ); @@ -138,7 +146,7 @@ cliTest.for([ await writeFile(path, Buffer.from(bytes, "hex")); const result = await cli.run({ arguments: [ - "inspect", + "analyze", path, "--target-format", "raw-binary", @@ -155,7 +163,14 @@ cliTest.for([ expect(result.exitCode).toBe(1); expect(result.json).toMatchObject({ code: "invalid_request", - details: { reason: expect.stringContaining(reason) }, + details: { + reason: expect.stringContaining(reason), + related_cli_flags: { + format: "--target-format", + architecture: "--architecture", + entry_point: "--entry-point", + }, + }, }); }, ); @@ -193,3 +208,69 @@ cliTest( ); }, ); + +cliTest( + "renders related_cli_commands across registrars when target opening directs to another lane", + async ({ cli }) => { + const root = await createTestTempDirectory("rea-open-related-cli-"); + const env = { HOME: root, XDG_CONFIG_HOME: root, XDG_CACHE_HOME: root }; + + const wasmPath = join(root, "module.wasm"); + await writeFile(wasmPath, Buffer.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0])); + const wasm = await cli.run({ + arguments: ["inspect", wasmPath, "--json"], + environment: env, + }); + expect(wasm.exitCode).toBe(1); + expect(wasm.json).toMatchObject({ + code: "target_unavailable", + details: { + constraint: "wasm_requires_static_inspection", + related_operations: ["inspect_wasm_artifact"], + related_cli_commands: { + inspect_wasm_artifact: "rea inspect-wasm-artifact", + }, + }, + }); + + const plainDirectory = join(root, "plain-js-dir"); + await mkdir(plainDirectory); + const directory = await cli.run({ + arguments: ["inspect", plainDirectory, "--json"], + environment: env, + }); + expect(directory.exitCode).toBe(1); + expect(directory.json).toMatchObject({ + code: "target_unavailable", + details: { + constraint: "directory_requires_file", + related_operations: ["analyze_javascript_application"], + related_cli_commands: { + analyze_javascript_application: "rea analyze-javascript-application", + }, + }, + }); + + const bundle = join(root, "Codeless.app", "Contents"); + await mkdir(bundle, { recursive: true }); + await writeFile( + join(bundle, "Info.plist"), + '', + ); + const missingExec = await cli.run({ + arguments: ["inspect", join(root, "Codeless.app"), "--json"], + environment: env, + }); + expect(missingExec.exitCode).toBe(1); + expect(missingExec.json).toMatchObject({ + code: "target_unavailable", + details: { + constraint: "bundle_executable_undeclared", + related_operations: ["inspect_plist"], + related_cli_commands: { + inspect_plist: "rea inspect-plist", + }, + }, + }); + }, +); diff --git a/tests/boundary/filesystem/appleBundleTargets.test.ts b/tests/boundary/filesystem/appleBundleTargets.test.ts index 0be42e15f5..aa4961e3d9 100644 --- a/tests/boundary/filesystem/appleBundleTargets.test.ts +++ b/tests/boundary/filesystem/appleBundleTargets.test.ts @@ -230,9 +230,11 @@ describe("Apple bundle directories that fail closed", () => { expect(projected.details).toMatchObject({ constraint: "bundle_executable_undeclared", info_plist: plist, + related_operations: ["inspect_plist"], }); expect(projected.remediation.action).toContain(plist); expect(projected.remediation.action).toContain("inspect_plist"); + expect(projected.remediation.action).not.toContain("rea inspect-plist"); }); it("names the Info.plist when the declared program file is absent", async () => { diff --git a/tests/boundary/filesystem/targetDiagnostics.test.ts b/tests/boundary/filesystem/targetDiagnostics.test.ts index 6f41c6e6dd..46b82771c9 100644 --- a/tests/boundary/filesystem/targetDiagnostics.test.ts +++ b/tests/boundary/filesystem/targetDiagnostics.test.ts @@ -89,10 +89,14 @@ describe("target route diagnostics", () => { details: { path: await realpath(path), constraint: "wasm_requires_static_inspection", + related_operations: ["inspect_wasm_artifact"], }, }); expect(projected.message).toContain("WebAssembly"); expect(projected.remediation.action).toContain("inspect_wasm_artifact"); + expect(projected.remediation.action).not.toContain( + "rea inspect-wasm-artifact", + ); expect(projected.remediation.action).toContain("REA_WABT_BIN_DIRECTORY"); expect(projected.remediation.action).toContain("WABT 1.0.42"); expect(await systemDoctorHost().inspectTarget?.(path)).toMatchObject({ @@ -160,10 +164,13 @@ describe("target route diagnostics", () => { details: { path: await realpath(directory), constraint: "directory_requires_file", + related_operations: ["analyze_javascript_application"], }, }); expect(projected.message).toContain("analyze_javascript_application"); + expect(projected.message).not.toContain("rea analyze"); expect(projected.remediation.action).toContain("input_path"); + expect(projected.remediation.action).not.toContain("rea analyze"); const doctor = systemDoctorHost(); expect(await doctor.inspectTarget?.(directory)).toMatchObject({ name: "target", @@ -245,13 +252,13 @@ describe("raw-binary load rejection diagnostics", () => { /raw-binary.*arm.*entry_point.*0x1.*4.byte.*align/i, ), constraint: "load_selection_rejected", + related_parameters: ["format", "architecture", "entry_point"], }, remediation: { - action: expect.stringMatching( - /--target-format.*--architecture.*--entry-point.*entry_point/i, - ), + action: expect.stringMatching(/format.*architecture.*entry_point/i), }, }); + expect(projected.remediation.action).not.toContain("--target-format"); }); it("projects an x86 entry beyond the address width as caller input", async () => { diff --git a/tests/boundary/mcp/artifactMcp.test.ts b/tests/boundary/mcp/artifactMcp.test.ts index f802ef16af..930be4f829 100644 --- a/tests/boundary/mcp/artifactMcp.test.ts +++ b/tests/boundary/mcp/artifactMcp.test.ts @@ -184,14 +184,13 @@ it.for([ .digest("hex"), unpacked, integrity_check: "declared-digest", + related_parameters: ["integrity_policy"], }, retryable: false, remediation: { action: projected.error.message }, }, }); - expect(projected.error.message).toContain( - "--integrity-policy record-and-continue", - ); + expect(projected.error.message).not.toContain("--integrity-policy"); if (unpacked) expect(projected.error.message).toMatch( /unpacked entry main\.js.*companion file/iu, diff --git a/tests/boundary/mcp/ghidraDecompileDeadlineLifetime.test.ts b/tests/boundary/mcp/ghidraDecompileDeadlineLifetime.test.ts index 227411928b..9a40aedff8 100644 --- a/tests/boundary/mcp/ghidraDecompileDeadlineLifetime.test.ts +++ b/tests/boundary/mcp/ghidraDecompileDeadlineLifetime.test.ts @@ -121,8 +121,12 @@ it("tells a finished CLI invocation to rerun with the launch setting, not to reu details: { diagnostics: { remote_code: "decompile_timed_out" }, limit: invocationLimit, + related_operations: ["analyze_function"], }, }); + expect(projected.remediation).toMatchObject({ + action: expect.not.stringContaining("rea function"), + }); const { message } = cliFailure.parse(projected); expect(message.startsWith(BRIDGE_MESSAGE)).toBe(true); expect(message).not.toContain(GHIDRA_SESSION_RETAINED); @@ -155,6 +159,7 @@ it("keeps same-session and runtime-update guidance for a continuing MCP connecti .continuingRemediationAction, }, details: { + related_operations: ["analyze_function"], limit: { ...enforcedLimit, applies_at: "next_operation", @@ -162,6 +167,7 @@ it("keeps same-session and runtime-update guidance for a continuing MCP connecti }, }, }); + expect(timedOut.remediation.action).not.toContain("rea function"); expect(timedOut.details?.limit).not.toHaveProperty("environment"); expect(timedOut.message.startsWith(BRIDGE_MESSAGE)).toBe(true); expect(timedOut.message.endsWith(` ${GHIDRA_SESSION_RETAINED}`)).toBe(true); diff --git a/tests/boundary/mcp/wasmArtifactMcp.test.ts b/tests/boundary/mcp/wasmArtifactMcp.test.ts index d6ec7fd9cb..8abed1a21c 100644 --- a/tests/boundary/mcp/wasmArtifactMcp.test.ts +++ b/tests/boundary/mcp/wasmArtifactMcp.test.ts @@ -128,13 +128,19 @@ it.each(["bin", "hop"])( error: { code: "target_unavailable", category: "unsupported_target", - details: { constraint: "wasm_requires_static_inspection" }, + details: { + constraint: "wasm_requires_static_inspection", + related_operations: ["inspect_wasm_artifact"], + }, }, }); + expect(failure.error.details).not.toHaveProperty("related_cli_commands"); + expect(failure.error.remediation.action).not.toContain( + "rea inspect-wasm-artifact", + ); const [, recoveryName, serializedInput] = - failure.error.remediation.action.match( - /call (\w+) with (\{.*\}) or run/, - ) ?? []; + failure.error.remediation.action.match(/call (\w+) with (\{[^}]*\})\./) ?? + []; expect(recoveryName).toBe(name); const recoveryInput = z .object({ path: z.literal(path) }) diff --git a/tests/boundary/mcp/workflowSnapshotReplayMcp.test.ts b/tests/boundary/mcp/workflowSnapshotReplayMcp.test.ts index fbf9a454b0..19a8d5ae66 100644 --- a/tests/boundary/mcp/workflowSnapshotReplayMcp.test.ts +++ b/tests/boundary/mcp/workflowSnapshotReplayMcp.test.ts @@ -787,11 +787,13 @@ const expectSnapshotImportGuidance = async (mcp: Client, path: string) => { operation: "read", reason: "wrong-kind", detected_kind: "analysis-snapshot", + related_operations: ["open_binary", "export_evidence_bundle"], }, }); expect(error.remediation.action).toContain("open_binary"); + expect(error.remediation.action).toContain("close_binary"); expect(error.remediation.action).toContain("snapshot_path"); - expect(error.remediation.action).toContain("--snapshot"); + expect(error.remediation.action).not.toContain("--snapshot"); expect((await readFile(path)).equals(before)).toBe(true); };