diff --git a/.oxlintrc.json b/.oxlintrc.json index 886194eda5..d4fa277521 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -139,6 +139,23 @@ "files": ["src/filesystem/Owned*.ts"], "rules": { "rea/no-raw-file-handle-close": "off" } }, + { + "files": ["src/cli*.ts", "src/cli/**/*.ts"], + "rules": { + "no-restricted-imports": [ + "error", + { + "patterns": [ + { + "group": ["**/contracts/toolContracts.js"], + "allowTypeImports": true, + "message": "CLI startup registers every command without loading the complete tool catalog (tests/boundary/cli/cliStartupImports.test.ts). Import the command's own contract group instead." + } + ] + } + ] + } + }, { "files": ["src/domain/javascript/javascriptSemanticTraversal.ts"], "rules": { "rea/no-babel-visitor-keys": "off" } diff --git a/src/cli/artifactCommands.ts b/src/cli/artifactCommands.ts index 6a2a0f0e5a..a83dba471e 100644 --- a/src/cli/artifactCommands.ts +++ b/src/cli/artifactCommands.ts @@ -1,28 +1,10 @@ -import { - espFlashAddressSchema, - parseEspFlashAddress, -} from "../domain/firmware/espFlashSelection.js"; -import type { ArtifactTargetSelection } from "../application/DirectAnalysis.js"; -import { projectCliAnalysisResult } from "./projectCliAnalysisResult.js"; -import { - analysisEvidenceDeliveryOptions, - cliEvidenceDeliveryInputError, - publishCliAnalysisEvidence, -} from "./analysisEvidenceDelivery.js"; -import { withCommandCancellation } from "./commandCancellation.js"; -import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; +import { ARTIFACT_TOOL_CONTRACTS } from "../contracts/artifactToolContracts.js"; +import { OPEN_BINARY_TOOL_CONTRACT } from "../contracts/sessionToolContracts.js"; import { ARTIFACT_GRAPH_PROVIDER } from "../domain/investigationProviders.js"; -import { localPathStringSchema } from "../domain/localPath.js"; -import { z } from "incur"; -import { cliDecimalField } from "./options.js"; -import { producerLimitsOption } from "./producerLimitsOption.js"; -import { artifactReaderLimitsInputSchema } from "../domain/artifactReaderLimits.js"; - import { - ARTIFACT_TOOL_CONTRACTS, - artifactExtractionInputSchema, -} from "../contracts/artifactToolContracts.js"; -import { contractNamed } from "./contractCliDescription.js"; + contractNamed, + type CliSessionTarget, +} from "./contractCliDescription.js"; import { registerContractCommand, runOnSessionTarget, @@ -31,180 +13,110 @@ import { import type { DirectAnalysis } from "../composition/directAnalysis.js"; import { createArtifactExtractionDestination } from "../application/artifacts/ArtifactExtractionDestination.js"; import { registerArtifactComparisonCommand } from "./artifactComparisonCommand.js"; -import { logCliCommand } from "../cliLogging.js"; import { CLI_COMMANDS } from "../cliCommandNames.js"; import type { Logger } from "pino"; import type { CliInstance } from "./types.js"; -const artifactLimitsOption = producerLimitsOption( - artifactReaderLimitsInputSchema, - "artifact-limits", -).describe( - "JSON artifact producer admissions: bun, dotnet_bundle, node_sea, godot, and expanded_bytes. Omitted fields keep defaults; changes apply on the next call without restart. Independent of summary/paging and client delivery limits.", -); - export const registerArtifactCommands = ( cli: CliInstance, logger: Logger, runProviderAnalysis: DirectAnalysis["runProviderAnalysis"], ): void => { - registerInspectionCommand(cli, logger, runProviderAnalysis); - registerExtractionCommand(cli, logger, runProviderAnalysis); + registerInventoryCommands(cli, logger, runProviderAnalysis); registerArtifactComparisonCommand(cli, logger); registerAppleBundleCommands(cli, logger, runProviderAnalysis); }; -/** Options that read a dump as an ESP flash image with caller inputs. */ -const espFlashSelectionOptions = { - targetFormat: z - .enum(["esp-flash-image"]) - .optional() - .describe( - "Read the target as an ESP flash dump; required with --flash-offset or --partition-table-offset", - ), - flashOffset: espFlashAddressSchema - .optional() - .describe("Flash address (0xhex) of the dump's first byte"), - partitionTableOffset: espFlashAddressSchema - .optional() - .describe( - "Flash address (0xhex, a multiple of 0x1000) of the partition table; disables the table scan", - ), -}; +/** + * The artifact as an MCP client opens it: an ESP flash dump is selected with + * `open_binary`'s format and flash fields. + */ +const artifactTarget = { + description: "Application or package path", + open: { + contract: OPEN_BINARY_TOOL_CONTRACT, + fields: { + format: { + name: "targetFormat", + values: ["esp-flash-image"], + description: + "Read the target as an ESP flash dump; required with --flash-offset or --partition-table-offset", + }, + flash_offset: { + description: "Flash address (0xhex) of the dump's first byte", + }, + partition_table_offset: { + description: + "Flash address (0xhex, a multiple of 0x1000) of the partition table; disables the table scan", + }, + }, + }, +} as const satisfies CliSessionTarget; -const espFlashTargetSelection = (options: { - readonly targetFormat?: "esp-flash-image" | undefined; - readonly flashOffset?: string | undefined; - readonly partitionTableOffset?: string | undefined; -}): ArtifactTargetSelection => ({ - ...(options.targetFormat === undefined - ? {} - : { formatHint: options.targetFormat }), - ...(options.flashOffset === undefined && - options.partitionTableOffset === undefined - ? {} - : { - espFlash: { - ...(options.flashOffset === undefined - ? {} - : { flashOffset: parseEspFlashAddress(options.flashOffset) }), - ...(options.partitionTableOffset === undefined - ? {} - : { - partitionTableOffset: parseEspFlashAddress( - options.partitionTableOffset, - ), - }), +const artifactFields = { + artifact_limits: { + description: + "JSON artifact producer admissions: bun, dotnet_bundle, node_sea, godot, and expanded_bytes. Omitted fields keep defaults; changes apply on the next call without restart. Independent of summary/paging and client delivery limits.", + }, + integrity_policy: { + description: "Behavior when declared artifact integrity does not match", + }, +} as const; + +/** Inventory and extraction run on the artifact the CLI opens. */ +const registerInventoryCommands = ( + cli: CliInstance, + logger: Logger, + runProviderAnalysis: DirectAnalysis["runProviderAnalysis"], +): void => { + const run = runOnSessionTarget( + runProviderAnalysis, + logger, + ARTIFACT_GRAPH_PROVIDER.id, + ); + registerContractCommand( + cli, + logger, + contractNamed(ARTIFACT_TOOL_CONTRACTS, "inspect_artifact"), + { + command: CLI_COMMANDS.inspectArtifact, + description: + "Inspect one artifact and return all available observations and next probes", + sessionTarget: artifactTarget, + jsonText: ["artifact_limits"], + fields: artifactFields, + evidenceDelivery: true, + }, + run, + ); + registerContractCommand( + cli, + logger, + contractNamed(ARTIFACT_TOOL_CONTRACTS, "extract_artifact"), + { + command: CLI_COMMANDS.extractArtifact, + description: + "Extract all or selected regular artifact contents safely; DMG extraction is unavailable", + sessionTarget: artifactTarget, + jsonText: ["artifact_limits"], + fields: { + ...artifactFields, + occurrence_ids: { + name: "occurrenceId", + description: + "Inventory occurrence ID to extract (repeatable); omit to extract all regular entries", }, - }), -}); - -const registerExtractionCommand = ( - cli: CliInstance, - logger: Logger, - runProviderAnalysis: DirectAnalysis["runProviderAnalysis"], -): void => { - cli.command(CLI_COMMANDS.extractArtifact, { - description: - "Extract all or selected regular artifact contents safely; DMG extraction is unavailable", - args: z.object({ - path: localPathStringSchema.describe("Application or package path"), - }), - options: z.object({ - // Incur needs an ordinary optional; keep the owning contract's metadata. - artifactLimits: artifactLimitsOption, - outputRoot: artifactExtractionInputSchema.shape.output_root - .unwrap() - .optional() - .meta(artifactExtractionInputSchema.shape.output_root.meta() ?? {}), - occurrenceId: artifactExtractionInputSchema.shape.occurrence_ids - .unwrap() - .optional() - .describe( - "Inventory occurrence ID to extract (repeatable); omit to extract all regular entries", - ), - integrityPolicy: z - .enum(["fail", "record-and-continue"]) - .default("fail") - .describe("Behavior when declared artifact integrity does not match"), - ...espFlashSelectionOptions, - }), - run: ({ args, options }) => - logCliCommand(logger, "extract-artifact", () => - runProviderAnalysis( - args.path, - "extract_artifact", - { - integrity_policy: options.integrityPolicy, - ...(options.artifactLimits === undefined - ? {} - : { artifact_limits: options.artifactLimits }), - output_root: createArtifactExtractionDestination( - options.outputRoot, - ), - ...(options.occurrenceId === undefined - ? {} - : { occurrence_ids: options.occurrenceId }), - }, - logger, - undefined, - undefined, - espFlashTargetSelection(options), - ).then(projectCliAnalysisResult), + }, + }, + (input, context) => + run( + { + ...input, + output_root: createArtifactExtractionDestination(input.output_root), + }, + context, ), - }); -}; - -const registerInspectionCommand = ( - cli: CliInstance, - logger: Logger, - runProviderAnalysis: DirectAnalysis["runProviderAnalysis"], -): void => { - cli.command(CLI_COMMANDS.inspectArtifact, { - description: - "Inspect one artifact and return all available observations and next probes", - args: z.object({ - path: localPathStringSchema.describe("Application or package path"), - }), - options: z.object({ - ...analysisEvidenceDeliveryOptions, - artifactLimits: artifactLimitsOption, - integrityPolicy: z - .enum(["fail", "record-and-continue"]) - .default("fail") - .describe("Behavior when declared artifact integrity does not match"), - ...espFlashSelectionOptions, - }), - run: ({ args, options }) => - logCliCommand(logger, "inspect-artifact", () => - withCommandCancellation(async (signal) => { - const delivery = { - providerId: ARTIFACT_GRAPH_PROVIDER.id, - operation: "inspect_artifact", - signal, - detail: options.detail, - evidenceOutput: options.evidence_output, - }; - const inputError = cliEvidenceDeliveryInputError(delivery); - if (inputError !== undefined) return projectAnalysisError(inputError); - const complete = await runProviderAnalysis( - args.path, - "inspect_artifact", - { - integrity_policy: options.integrityPolicy, - ...(options.artifactLimits === undefined - ? {} - : { artifact_limits: options.artifactLimits }), - }, - logger, - signal, - undefined, - espFlashTargetSelection(options), - ); - return publishCliAnalysisEvidence(complete, delivery); - }), - ), - }); + ); }; /** diff --git a/src/cli/contractCliDescription.ts b/src/cli/contractCliDescription.ts index c7b3259d1d..5687346d38 100644 --- a/src/cli/contractCliDescription.ts +++ b/src/cli/contractCliDescription.ts @@ -162,6 +162,53 @@ export type CliOptionValues = { export interface CliSessionTarget { /** Help for the target positional. */ readonly description: string; + /** + * Fields of the contract an MCP client opens the target with, taken as + * options. They are admitted by that contract's input, with the target as + * its `path`, before the target is opened. + */ + readonly open?: CliTargetOpening; +} + +/** The opening contract's fields a command takes as options. */ +export interface CliTargetOpening { + readonly contract: { + readonly name: string; + readonly inputSchema: z.ZodObject; + }; + readonly fields: Readonly>; +} + +/** How one opening field is spelled on the CLI. */ +export interface CliOpeningFieldProjection extends CliFieldProjection { + /** The values this command admits: a subset of the field's enum. */ + readonly values?: readonly [string, ...string[]]; +} + +/** An option that supplies one field of the opening contract. */ +export interface ContractCliOpeningOption { + readonly field: string; + readonly key: string; + readonly description: string | undefined; + readonly schema: z.ZodType; +} + +/** The described session target of a contract command. */ +export interface ContractCliSessionTarget { + /** The positional key, taken before every other positional. */ + readonly key: string; + readonly schema: z.ZodType; + /** Options that supply fields of the opening contract. */ + readonly options: readonly ContractCliOpeningOption[]; + /** + * The opening fields the parsed options select, in contract spelling, + * admitted by the opening contract with the target as its `path`. + * Issues name CLI keys. + */ + readonly admitOpening: ( + operation: string, + values: Readonly>, + ) => Result>, AnalysisInputError>; } /** The CLI key of a session target, which no contract field supplies. */ @@ -302,9 +349,7 @@ export interface ContractCliDescription { * The session target positional, taken before the contract positionals, * when the operation runs on a target the CLI opens; undefined otherwise. */ - readonly sessionTarget: - | { readonly key: string; readonly schema: z.ZodType } - | undefined; + readonly sessionTarget: ContractCliSessionTarget | undefined; /** * Contract fields the CLI spells differently, so input issues reported * after argv parsing can name the CLI key. @@ -585,6 +630,24 @@ export interface CliDocumentProjection< readonly omit?: { readonly [Key in Field]?: string }; /** Options no contract field owns, keyed by their CLI key. */ readonly cliOptions?: CliOptions; + /** + * The operation runs on the target an MCP session holds open. The CLI takes + * it as the `path` positional before the document. + */ + readonly sessionTarget?: CliSessionTarget; + /** + * The contract's optional `detail` field is taken as `--detail` beside the + * document, with `--evidence_output`: the command delivers complete + * Evidence or a summary saved beside a bundle. The document refuses + * `detail`. + */ + readonly evidenceDelivery?: true; + /** + * With `evidenceDelivery`, the contract's optional `view` field is taken as + * `--view` JSON text beside the document and admitted by the contract + * field's schema before the handler runs. The document refuses `view`. + */ + readonly viewDelivery?: CliViewDelivery; } /** A complete, framework-neutral CLI command whose input is one JSON document. */ @@ -605,6 +668,24 @@ export interface ContractCliDocumentDescription { readonly callerPaths: readonly (readonly string[])[]; /** Contract fields the command does not admit, with the reason. */ readonly omitted: Readonly>; + /** Contract fields taken as options beside the document, keyed by field. */ + readonly flagged: Readonly>; + /** + * The refusal of each top-level document field the command does not take + * in the document: omitted fields and fields taken as options. + */ + readonly documentRefusals: Readonly>; + /** The session target positional, taken before the document, if any. */ + readonly sessionTarget: ContractCliSessionTarget | undefined; + /** Options that select Evidence delivery, for `evidenceDelivery`. */ + readonly deliveryOptions: readonly CliOnlyOption[]; + /** + * The delivery the parsed options select, admitted before the handler + * runs; undefined without `evidenceDelivery`. + */ + readonly admitDelivery: ( + values: Readonly>, + ) => Result; readonly cliOnlyOptions: readonly CliOnlyOption[]; /** The parsed values of the projection's CLI-only options. */ readonly cliOptionValues: ( @@ -681,6 +762,162 @@ const admitDocumentCallerPath = ( /** The CLI key of a JSON input document. */ const DOCUMENT_KEY = "inputJson"; +/** + * Describe the target positional and the options that supply fields of its + * opening contract. Each option admits its field's own schema, narrowed to + * the projected values. + */ +const describeSessionTarget = ( + target: CliSessionTarget | undefined, +): ContractCliSessionTarget | undefined => { + if (target === undefined) return undefined; + const opening = target.open; + const opener = opening?.contract.name ?? ""; + const shape = (opening?.contract.inputSchema.shape ?? {}) as Record< + string, + z.ZodType + >; + const options: readonly ContractCliOpeningOption[] = Object.entries( + opening?.fields ?? {}, + ).map(([field, projected]) => { + const declared = shape[field]; + if (declared === undefined || field === SESSION_TARGET_KEY) + throw new Error(`${opener} has no option field ${field}`); + if (!admitsOmission(declared)) + throw new Error(`${opener}.${field} is required`); + let schema: z.ZodType; + if (projected.values === undefined) { + assertArgvField(opener, field, declared); + schema = cliDecimalShape({ field: argvOptional(declared) }).field; + } else { + for (const value of projected.values) + if (!declared.safeParse(value).success) + throw new Error(`${opener}.${field} does not admit ${value}`); + schema = z.enum(projected.values).optional(); + } + const description = projected.description ?? declared.description; + if (description !== undefined) schema = schema.describe(description); + return { + field, + key: projected.name ?? camelCase(field), + description, + schema, + }; + }); + const keyOf = new Map(options.map(({ field, key }) => [field, key])); + return { + key: SESSION_TARGET_KEY, + schema: localPathStringSchema.describe(target.description), + options, + admitOpening: (operation, values) => { + if (opening === undefined) return ok({}); + const selected = Object.fromEntries( + options.flatMap(({ field, key }) => + values[key] === undefined ? [] : [[field, values[key]]], + ), + ); + // The target itself was admitted as the positional. + if (Object.keys(selected).length === 0) return ok({}); + const candidate = { + ...selected, + [SESSION_TARGET_KEY]: absoluteCallerPath( + values[SESSION_TARGET_KEY] as string, + ), + }; + const admitted = opening.contract.inputSchema.safeParse(candidate); + if (!admitted.success) + return err( + analysisInputErrorFromIssues( + operation, + admitted.error.issues.map((issue) => { + const [field, ...rest] = issue.path; + const key = + typeof field === "string" ? keyOf.get(field) : undefined; + return key === undefined + ? issue + : { ...issue, path: [key, ...rest] }; + }), + selected, + ), + ); + const data = admitted.data as Readonly>; + return ok( + Object.fromEntries( + Object.keys(selected).map((field) => [field, data[field]]), + ), + ); + }, + }; +}; + +/** + * The delivery `--detail`, `--evidence_output` and `--view` select beside a + * JSON document. The view is admitted by the contract's own `view` field; a + * page is selected from a retained summary, so it needs summary delivery. + */ +const admitDocumentDelivery = ( + operation: string, + viewDelivery: (CliViewDelivery & { readonly schema: z.ZodType }) | undefined, + values: Readonly>, +): Result => { + let view: AnalysisViewRequest | undefined; + if (viewDelivery !== undefined) { + const decoded = parseCliJsonOption( + operation, + "view", + values.view as string | undefined, + viewDelivery.invalidJson, + ); + if (!decoded.ok) return decoded; + if (decoded.value !== undefined) { + const candidate = { view: decoded.value }; + const parsed = z + .object({ view: viewDelivery.schema }) + .safeParse(candidate); + if (!parsed.success) + return err( + analysisInputErrorFromIssues( + operation, + parsed.error.issues, + candidate, + ), + ); + const selected = parsed.data.view as object; + view = ( + viewDelivery.kind === undefined + ? selected + : { kind: viewDelivery.kind, ...selected } + ) as AnalysisViewRequest; + } + } + const detail = + (values.detail as "complete" | "summary" | undefined) ?? + (view === undefined ? "complete" : "summary"); + if (view !== undefined && detail !== "summary") + return err( + analysisInputErrorFromIssues( + operation, + [ + { + code: "custom", + path: ["view"], + message: + "A selected page requires --detail summary and --evidence_output.", + input: values.view, + }, + ], + { detail, view }, + ), + ); + const delivery: CliEvidenceDeliveryChoice = { + detail, + evidenceOutput: values.evidence_output as string | undefined, + ...(view === undefined ? {} : { view }), + }; + const refused = cliEvidenceDeliveryInputError({ ...delivery, operation }); + return refused === undefined ? ok(delivery) : err(refused); +}; + /** * Describe a contract command that takes its whole input as one JSON * document. The handler admits the decoded document with the contract's @@ -698,27 +935,96 @@ export const describeContractDocumentCommand = < (entry): entry is [string, string] => typeof entry[1] === "string", ), ); + const evidenceDelivery = projection.evidenceDelivery === true; + const { viewDelivery } = projection; + if (viewDelivery !== undefined && !evidenceDelivery) + throw new Error(`${contract.name} view delivery requires evidenceDelivery`); + // Delivery fields keep their contract names as CLI keys. + const flagged: Readonly> = Object.fromEntries( + (evidenceDelivery + ? viewDelivery === undefined + ? ["detail"] + : ["detail", "view"] + : [] + ).map((field) => [field, field]), + ); + for (const field of Object.keys(flagged)) + if (Object.hasOwn(omitted, field)) + throw new Error( + `${contract.name}.${field} is both omitted and an option`, + ); + const removed = [...Object.keys(omitted), ...Object.keys(flagged)]; let admitted: z.ZodType = contract.inputSchema; - if (Object.keys(omitted).length > 0) { + let viewSchema: z.ZodType = z.never(); + if (removed.length > 0) { const schema = contract.inputSchema; if (!(schema instanceof z.ZodObject)) throw new Error(`${contract.name} omits fields from a union input`); const shape = schema.shape as Record; - for (const field of Object.keys(omitted)) + for (const field of removed) if (!Object.hasOwn(shape, field) || !admitsOmission(shape[field]!)) throw new Error(`${contract.name}.${field} is not an optional field`); + if (viewDelivery !== undefined) viewSchema = shape.view!; admitted = schema.omit( - Object.fromEntries( - Object.keys(omitted).map((field) => [field, true]), - ) as never, + Object.fromEntries(removed.map((field) => [field, true])) as never, ); } const callerPaths = projection.callerPaths ?? []; for (const path of callerPaths) admitted = admitDocumentCallerPath(admitted, path); const cliOptions: CliOptionShape = projection.cliOptions ?? {}; - if (Object.hasOwn(cliOptions, DOCUMENT_KEY)) + const deliveryOptions: readonly CliOnlyOption[] = Object.entries({ + ...(evidenceDelivery + ? { + detail: + viewDelivery?.viewSelectsSummary === true + ? analysisEvidenceDeliveryOptions.detail.unwrap().optional() + : analysisEvidenceDeliveryOptions.detail, + evidence_output: analysisEvidenceDeliveryOptions.evidence_output, + } + : {}), + ...(viewDelivery === undefined + ? {} + : { + view: z + .string() + .optional() + .describe( + viewDelivery.viewSelectsSummary === true + ? "JSON page selection; selects summary delivery, which requires --evidence_output" + : "JSON page selection; requires --detail summary and --evidence_output", + ), + }), + }).map(([key, schema]: [string, z.ZodType]) => ({ + key, + description: schema.description, + schema, + })); + const sessionTarget = describeSessionTarget(projection.sessionTarget); + const keys = [ + DOCUMENT_KEY, + ...(sessionTarget === undefined + ? [] + : [sessionTarget.key, ...sessionTarget.options.map(({ key }) => key)]), + ...Object.keys(cliOptions), + ...deliveryOptions.map(({ key }) => key), + ]; + if (new Set(keys).size !== keys.length) throw new Error(`${contract.name} projects two fields to one CLI key`); + const documentRefusals: Readonly> = { + ...Object.fromEntries( + Object.entries(omitted).map(([field, reason]) => [ + field, + `${field} is not accepted by this command: ${reason}`, + ]), + ), + ...Object.fromEntries( + Object.entries(flagged).map(([field, key]) => [ + field, + `${field} is not accepted in the document: pass --${key} beside it`, + ]), + ), + }; return { command: projection.command, description: projection.description, @@ -728,6 +1034,20 @@ export const describeContractDocumentCommand = < content: getEvidenceInputContract(admitted).frameSchema, callerPaths, omitted, + flagged, + documentRefusals, + deliveryOptions, + admitDelivery: (values) => + evidenceDelivery + ? admitDocumentDelivery( + contract.name, + viewDelivery === undefined + ? undefined + : { ...viewDelivery, schema: viewSchema }, + values, + ) + : ok(undefined), + sessionTarget, cliOnlyOptions: Object.entries(cliOptions).map(([key, schema]) => ({ key, description: schema.description, @@ -944,8 +1264,11 @@ export const describeContractCommand = < description: schema.description, schema, })); + const sessionTarget = describeSessionTarget(projection.sessionTarget); const sessionTargetKeys = - projection.sessionTarget === undefined ? [] : [SESSION_TARGET_KEY]; + sessionTarget === undefined + ? [] + : [sessionTarget.key, ...sessionTarget.options.map(({ key }) => key)]; const keys = new Set([ ...sessionTargetKeys, ...parameters.map(({ key }) => key), @@ -1091,15 +1414,7 @@ export const describeContractCommand = < values[key] === undefined ? [] : [[key, values[key]]], ), ), - sessionTarget: - projection.sessionTarget === undefined - ? undefined - : { - key: SESSION_TARGET_KEY, - schema: localPathStringSchema.describe( - projection.sessionTarget.description, - ), - }, + sessionTarget, inputBinding: { operation: contract.name, fields: Object.fromEntries( diff --git a/src/cli/contractCommand.ts b/src/cli/contractCommand.ts index af8bf03e64..f3bc1dd932 100644 --- a/src/cli/contractCommand.ts +++ b/src/cli/contractCommand.ts @@ -9,7 +9,12 @@ import type { DirectAnalysis } from "../composition/directAnalysis.js"; import type { CallerInputPaths, Evidence } from "../domain/evidence.js"; import type { JsonValue } from "../domain/jsonValue.js"; import type { Result } from "../domain/result.js"; -import { deliverCliAnalysisEvidence } from "./analysisEvidenceDelivery.js"; +import type { ArtifactAnalysisOperation } from "../contracts/artifactToolContracts.js"; +import { openBinaryTargetSelection } from "../contracts/sessionLifecycleInputs.js"; +import { + deliverCliAnalysisEvidence, + publishCliAnalysisEvidence, +} from "./analysisEvidenceDelivery.js"; import { finishCliEvidenceCommand } from "./cliEvidenceCallerPath.js"; import { finishAnalysisCommand } from "./finishAnalysisCommand.js"; import { withCommandCancellation } from "./commandCancellation.js"; @@ -26,6 +31,7 @@ import { type CliOptionShape, type CliOptionValues, type ContractCliDescription, + type ContractCliSessionTarget, type ContractField, type ProjectedContract, } from "./contractCliDescription.js"; @@ -54,6 +60,11 @@ export interface ContractCommandContext< * `sessionTarget`; undefined otherwise. */ readonly sessionTarget: string | undefined; + /** + * The session target's opening fields the caller selected, in the opening + * contract's spelling; empty without `sessionTarget.open`. + */ + readonly opening: Readonly>; /** Contract fields the CLI spells differently, for input issue paths. */ readonly inputBinding: ContractCliDescription["inputBinding"]; /** The admitted delivery, for a projection with `evidenceDelivery`. */ @@ -120,26 +131,54 @@ export const inspectWithService = }; /** - * Open the session target as an MCP session would hold it, run the contract - * operation on the remaining input, and name renamed fields by their CLI key - * in input issues. + * Open the session target as an MCP session would hold it, with the opening + * fields the caller selected, and run the contract operation on the + * remaining input. Input issues name renamed fields by their CLI key; a + * projection with `evidenceDelivery` delivers complete Evidence or a summary + * beside its bundle. */ export const runOnSessionTarget = ( runProviderAnalysis: DirectAnalysis["runProviderAnalysis"], logger: Logger, + providerId?: string, ) => - (input: object, context: ContractCommandContext) => { - if (context.sessionTarget === undefined) - throw new Error(`${context.operation} declares no session target`); - return runProviderAnalysis( - context.sessionTarget, - context.operation as SessionTargetOperation, - // Argv values are decoded text, and absent options are left out. - input as Readonly>, - logger, - context.signal, - ).then((result) => projectCliAnalysisResult(result, context.inputBinding)); + async (input: object, context: ContractCommandContext) => { + const { sessionTarget, operation, signal, delivery, opening } = context; + if (sessionTarget === undefined) + throw new Error(`${operation} declares no session target`); + // Argv values are decoded text, and absent options are left out. + const values = input as Readonly>; + const result = await (Object.keys(opening).length === 0 + ? runProviderAnalysis( + sessionTarget, + operation as SessionTargetOperation, + values, + logger, + signal, + ) + : runProviderAnalysis( + sessionTarget, + // Only artifact operations take an opening selection. + operation as ArtifactAnalysisOperation, + values, + logger, + signal, + undefined, + openBinaryTargetSelection(opening), + )); + if (delivery === undefined) + return projectCliAnalysisResult(result, context.inputBinding); + if (providerId === undefined) + throw new Error(`${operation} delivers Evidence without a provider`); + return publishCliAnalysisEvidence(result, { + providerId, + operation, + signal, + detail: delivery.detail, + evidenceOutput: delivery.evidenceOutput, + ...(delivery.view === undefined ? {} : { view: delivery.view }), + }); }; /** Operations `runProviderAnalysis` runs on an opened session target. */ @@ -195,6 +234,18 @@ export const deliverWithService = }); }; +/** The session target's opening fields, when the command declares any. */ +const admitOpening = ( + description: { + readonly contract: { readonly name: string }; + readonly sessionTarget: ContractCliSessionTarget | undefined; + }, + values: Readonly>, +): Result>, AnalysisError> => + description.sessionTarget === undefined + ? { ok: true, value: {} } + : description.sessionTarget.admitOpening(description.contract.name, values); + const descriptions = new WeakMap(); /** Commands registered on this CLI through `registerContractCommand`. */ @@ -208,6 +259,9 @@ const incurOptions = (description: ContractCliDescription): z.ZodType => { ...description.parameters .filter(({ positional }) => !positional) .map(({ key, schema }) => [key, schema] as const), + ...(description.sessionTarget?.options ?? []).map( + ({ key, schema }) => [key, schema] as const, + ), ...description.cliOnlyOptions.map( ({ key, schema }) => [key, schema] as const, ), @@ -281,6 +335,8 @@ export const registerContractCommand = < logCliCommand(logger, description.command, async () => { const admitted = description.admit(values); if (!admitted.ok) return projectAnalysisError(admitted.error); + const opening = admitOpening(description, values); + if (!opening.ok) return projectAnalysisError(opening.error); return run(admitted.value.input as z.input, { signal, operation: contract.name, @@ -289,6 +345,7 @@ export const registerContractCommand = < description.sessionTarget === undefined ? undefined : (values[description.sessionTarget.key] as string), + opening: opening.value, inputBinding: description.inputBinding, delivery: admitted.value.delivery, cliOptions: description.cliOptionValues( @@ -315,8 +372,26 @@ export interface ContractDocumentContext< readonly operation: string; /** The document as decoded, before its caller paths were resolved. */ readonly spelled: unknown; + /** + * The document's transport frame as `--schema` advertises it. A handler + * that reads other inputs first, such as an Evidence bundle, admits the + * document with it beforehand; Evidence carriers stay with their owner. + */ + readonly frame: z.ZodType; + /** The admitted delivery, for a projection with `evidenceDelivery`. */ + readonly delivery: CliEvidenceDeliveryChoice | undefined; /** The projection's CLI-only options, whose effect the handler owns. */ readonly cliOptions: CliOptions; + /** + * The session target as the caller spelled it, for a projection with + * `sessionTarget`; undefined otherwise. + */ + readonly sessionTarget: string | undefined; + /** + * The session target's opening fields the caller selected, in the opening + * contract's spelling; empty without `sessionTarget.open`. + */ + readonly opening: Readonly>; } const documentDescriptions = new WeakMap< @@ -331,20 +406,20 @@ export const contractDocumentCommandDescriptions = ( documentDescriptions.get(cli) ?? []; /** - * A document field the projection omits is refused with its reason rather - * than passed to an owner that would act on it. + * A document field the projection omits or takes as an option is refused + * with its reason rather than passed to an owner that would act on it. */ -const omittedDocumentFieldError = ( +const refusedDocumentFieldError = ( operation: string, - omitted: Readonly>, + refusals: Readonly>, document: object, ): AnalysisError | undefined => { - const issues = Object.entries(omitted) + const issues = Object.entries(refusals) .filter(([field]) => Object.hasOwn(document, field)) - .map(([field, reason]) => ({ + .map(([field, message]) => ({ code: "custom" as const, path: [field], - message: `${field} is not accepted by this command: ${reason}`, + message, input: (document as Readonly>)[field], })); return issues.length === 0 @@ -373,11 +448,20 @@ export const registerContractDocumentCommand = < ): void => { const description = describeContractDocumentCommand(contract, projection); const options = Object.fromEntries( - description.cliOnlyOptions.map(({ key, schema }) => [key, schema]), + [ + ...(description.sessionTarget?.options ?? []), + ...description.deliveryOptions, + ...description.cliOnlyOptions, + ].map(({ key, schema }) => [key, schema]), ); cli.command(description.command, { description: description.description, args: z.object({ + ...(description.sessionTarget === undefined + ? {} + : { + [description.sessionTarget.key]: description.sessionTarget.schema, + }), [description.key]: jsonInputArgument( description.documentDescription, description.content, @@ -395,6 +479,11 @@ export const registerContractDocumentCommand = < }) => 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, @@ -405,9 +494,9 @@ export const registerContractDocumentCommand = < // contract refuses it. const refused = typeof decoded.value === "object" && decoded.value !== null - ? omittedDocumentFieldError( + ? refusedDocumentFieldError( contract.name, - description.omitted, + description.documentRefusals, decoded.value, ) : undefined; @@ -418,6 +507,13 @@ export const registerContractDocumentCommand = < signal, operation: contract.name, spelled: decoded.value, + frame: description.content, + delivery: delivery.value, + opening: opening.value, + sessionTarget: + description.sessionTarget === undefined + ? undefined + : args[description.sessionTarget.key], cliOptions: description.cliOptionValues( values, ) as CliOptionValues, diff --git a/src/cli/nativeCallCommands.ts b/src/cli/nativeCallCommands.ts index b7055cc7eb..787902d7bc 100644 --- a/src/cli/nativeCallCommands.ts +++ b/src/cli/nativeCallCommands.ts @@ -1,20 +1,15 @@ import { projectCliAnalysisResult } from "./projectCliAnalysisResult.js"; -import { z } from "incur"; import type { DirectAnalysis } from "../composition/directAnalysis.js"; import { CLI_COMMANDS } from "../cliCommandNames.js"; -import { parseCliJsonInput } from "../cliJsonInput.js"; -import { logCliCommand } from "../cliLogging.js"; +import { NATIVE_TOOL_CONTRACTS } from "../contracts/native/nativeToolContracts.js"; import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js"; -import { jsonValueSchema } from "../domain/jsonValue.js"; -import { localPathStringSchema } from "../domain/localPath.js"; -import { nativeCallObservationInputSchema } from "../domain/native/nativeCallObservation.js"; +import type { JsonValue } from "../domain/jsonValue.js"; import type { Logger } from "pino"; import type { CliInstance } from "./types.js"; -import { jsonInputArgument } from "./jsonInputArgument.js"; - -const OPERATION = "observe_native_calls"; +import { contractNamed } from "./contractCliDescription.js"; +import { registerContractDocumentCommand } from "./contractCommand.js"; /** `observe-native-calls `: the MCP input object as JSON. */ export const registerNativeCallCommands = ( @@ -22,38 +17,39 @@ export const registerNativeCallCommands = ( logger: Logger, runProviderAnalysis: DirectAnalysis["runProviderAnalysis"], ): void => { - cli.command(CLI_COMMANDS.observeNativeCalls, { - description: - "Launch a Mach-O under LLDB and record entries into selected functions or Objective-C methods", - args: z.object({ - path: localPathStringSchema.describe("Mach-O or app path"), - inputJson: jsonInputArgument( + const contract = contractNamed(NATIVE_TOOL_CONTRACTS, "observe_native_calls"); + registerContractDocumentCommand( + cli, + logger, + contract, + { + command: CLI_COMMANDS.observeNativeCalls, + description: + "Launch a Mach-O under LLDB and record entries into selected functions or Objective-C methods", + sessionTarget: { description: "Mach-O or app path" }, + document: "Inline JSON or a JSON file path: breakpoints, arguments, environment, duration_ms, max_events, argument_registers, backtrace_frames, capture_limits", - nativeCallObservationInputSchema, - ), - }), - run: ({ args }) => - logCliCommand(logger, CLI_COMMANDS.observeNativeCalls, async () => { - const input = await parseCliJsonInput(args.inputJson, OPERATION); - if (!input.ok) return input.error; - const parsed = nativeCallObservationInputSchema.safeParse(input.value); - if (!parsed.success) - return { - error: "Analysis failed", - ...projectAnalysisError( - analysisInputErrorFromIssues( - OPERATION, - parsed.error.issues, - input.value, - ), + }, + async (document, { signal, operation, sessionTarget }) => { + const parsed = contract.inputSchema.safeParse(document); + if (!parsed.success) + return { + error: "Analysis failed", + ...projectAnalysisError( + analysisInputErrorFromIssues( + operation, + parsed.error.issues, + document, ), - }; - return runProviderAnalysis( - args.path, - OPERATION, - z.record(z.string(), jsonValueSchema).parse(parsed.data), - logger, - ).then(projectCliAnalysisResult); - }), - }); + ), + }; + return runProviderAnalysis( + sessionTarget!, + contract.name, + parsed.data as Readonly>, + logger, + signal, + ).then((result) => projectCliAnalysisResult(result)); + }, + ); }; diff --git a/src/cli/producerLimitsOption.ts b/src/cli/producerLimitsOption.ts index 638c3fac8f..bebd9fa9b7 100644 --- a/src/cli/producerLimitsOption.ts +++ b/src/cli/producerLimitsOption.ts @@ -1,28 +1,3 @@ -import { z } from "incur"; -import { safeParseJson } from "../domain/safeJson.js"; - /** CLI help for a producer's `producer_limits` JSON text. */ export const PRODUCER_LIMITS_HELP = "JSON producer budget overrides. Keys and units follow this operation's producer_limits contract; changes apply on this call without restart and preserve tighter inherited OS limits."; - -/** Incur passes object flags as text; validate the selected producer's exact policy. */ -export const producerLimitsOption = ( - schema: Schema, - flagName = "producer-limits", -) => - z - .string() - .transform((text, context) => { - const parsed = safeParseJson(text); - if (!parsed.ok) { - context.addIssue({ - code: "custom", - message: `${flagName} must be a JSON object`, - }); - return z.NEVER; - } - return parsed.value; - }) - .pipe(schema) - .optional() - .describe(PRODUCER_LIMITS_HELP); diff --git a/src/cli/staticObservedEndpointsCommand.ts b/src/cli/staticObservedEndpointsCommand.ts index 02445ec7ff..d7194f792d 100644 --- a/src/cli/staticObservedEndpointsCommand.ts +++ b/src/cli/staticObservedEndpointsCommand.ts @@ -1,131 +1,73 @@ -import { z } from "incur"; import type { Logger } from "pino"; import type { Evidence } from "../domain/evidence.js"; import type { CliInstance } from "./types.js"; import { CLI_COMMANDS } from "../cliCommandNames.js"; -import { parseCliJsonInput } from "../cliJsonInput.js"; -import { logCliCommand } from "../cliLogging.js"; -import { compareStaticObservedEndpointsFactsSchema } from "../contracts/javascript/applicationWorkflowInputContracts.js"; -import { jsonInputArgument } from "./jsonInputArgument.js"; -import { getEvidenceInputContract } from "../domain/evidenceInputContract.js"; -import { endpointComparisonViewRequestSchema } from "../domain/analysisView/endpointComparisonView.js"; -import { parseAnalysisInput } from "../application/AnalysisInput.js"; -import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; +import { APPLICATION_TOOL_CONTRACTS } from "../contracts/applicationToolContracts.js"; import { JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER } from "../domain/investigationProviders.js"; -import { withCommandCancellation } from "./commandCancellation.js"; +import { contractNamed } from "./contractCliDescription.js"; +import { registerContractDocumentCommand } from "./contractCommand.js"; import { evidenceBundleOption, runEvidenceInputCommand, } from "./evidenceInputCommand.js"; -import { - analysisEvidenceDeliveryOptions, - parseCliAnalysisEvidenceDelivery, - publishCliAnalysisEvidence, -} from "./analysisEvidenceDelivery.js"; - -const operation = "compare_static_and_observed_endpoints"; -const comparisonDocumentSchema = getEvidenceInputContract( - compareStaticObservedEndpointsFactsSchema, -).frameSchema; -const deliverySchema = z - .object({ - detail: analysisEvidenceDeliveryOptions.detail, - view: endpointComparisonViewRequestSchema.optional(), - }) - .superRefine((value, context) => { - if (value.view !== undefined && value.detail !== "summary") - context.addIssue({ - code: "custom", - path: ["view"], - message: - "A selected page requires --detail summary and --evidence_output.", - }); - }); -const commandOptions = z.object({ - evidenceBundle: evidenceBundleOption, - ...analysisEvidenceDeliveryOptions, - view: z - .string() - .optional() - .describe( - "JSON endpoint-comparison page; requires --detail summary and --evidence_output", - ), -}); - -const runComparison = async ( - inputJson: string, - options: z.output, - signal: AbortSignal, -) => { - const selected = parseCliAnalysisEvidenceDelivery( - operation, - options, - deliverySchema, - ); - if (!selected.ok) return projectAnalysisError(selected.error); - const delivery = { - providerId: JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER.id, - operation, - signal, - detail: selected.value.detail, - evidenceOutput: selected.value.evidenceOutput, - ...(selected.value.view === undefined ? {} : { view: selected.value.view }), - }; - const raw = await parseCliJsonInput(inputJson, operation, signal); - if (!raw.ok) return raw.error; - // The frame validates transport fields without cloning either Evidence before budget admission. - const input = parseAnalysisInput( - operation, - raw.value, - comparisonDocumentSchema, - signal, - ); - if (!input.ok) return projectAnalysisError(input.error); - let sources: readonly Evidence[] = []; - const result = await runEvidenceInputCommand( - operation, - options.evidenceBundle, - signal, - async (lookup) => { - const { compareStaticAndObservedEndpointsEvidence } = - await import("../application/javascript/StaticObservedEndpointComparisonService.js"); - const compared = await compareStaticAndObservedEndpointsEvidence( - { ...input.value, detail: options.detail }, - lookup, - { signal }, - ); - if (!compared.ok) return compared; - sources = compared.value.sources; - return { ok: true, value: compared.value.evidence }; - }, - ); - return publishCliAnalysisEvidence(result, { - ...delivery, - sourceEvidence: sources, - }); -}; +import { publishCliAnalysisEvidence } from "./analysisEvidenceDelivery.js"; +import { parseAnalysisInput } from "../application/AnalysisInput.js"; +import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; /** Reuse standard CLI publication so summaries keep their complete source closure on disk. */ export const registerStaticObservedEndpointsCommand = ( cli: CliInstance, logger: Logger, -): void => { - const name = CLI_COMMANDS.compareStaticAndObservedEndpoints; - cli.command(name, { - description: - "Compare static JavaScript endpoints and HAR Evidence JSON offline; --detail summary with --evidence_output saves full facts for selected inspect-analysis-view pages", - args: z.object({ - inputJson: jsonInputArgument( +): void => + registerContractDocumentCommand( + cli, + logger, + contractNamed( + APPLICATION_TOOL_CONTRACTS, + "compare_static_and_observed_endpoints", + ), + { + command: CLI_COMMANDS.compareStaticAndObservedEndpoints, + description: + "Compare static JavaScript endpoints and HAR Evidence JSON offline; --detail summary with --evidence_output saves full facts for selected inspect-analysis-view pages", + document: "Inline JSON or file containing application, capture and optional origin", - comparisonDocumentSchema, - ), - }), - options: commandOptions, - run: ({ args, options }) => - withCommandCancellation((signal) => - logCliCommand(logger, name, () => - runComparison(args.inputJson, options, signal), - ), - ), - }); -}; + evidenceDelivery: true, + viewDelivery: { invalidJson: "view must be valid JSON" }, + cliOptions: { evidenceBundle: evidenceBundleOption }, + }, + async (document, { signal, operation, delivery, cliOptions, frame }) => { + if (delivery === undefined) + throw new Error(`${operation} declares evidenceDelivery`); + // Refuse a malformed document before reading the Evidence bundle. + const framed = parseAnalysisInput(operation, document, frame, signal); + if (!framed.ok) return projectAnalysisError(framed.error); + let sources: readonly Evidence[] = []; + const result = await runEvidenceInputCommand( + operation, + cliOptions.evidenceBundle, + signal, + async (lookup) => { + const { compareStaticAndObservedEndpointsEvidence } = + await import("../application/javascript/StaticObservedEndpointComparisonService.js"); + const compared = await compareStaticAndObservedEndpointsEvidence( + document, + lookup, + { signal }, + ); + if (!compared.ok) return compared; + sources = compared.value.sources; + return { ok: true, value: compared.value.evidence }; + }, + ); + return publishCliAnalysisEvidence(result, { + providerId: JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER.id, + operation, + signal, + detail: delivery.detail, + evidenceOutput: delivery.evidenceOutput, + ...(delivery.view === undefined ? {} : { view: delivery.view }), + sourceEvidence: sources, + }); + }, + ); diff --git a/src/cliBrowserScenarioCommands.ts b/src/cliBrowserScenarioCommands.ts index 3f77b170dc..31fb134945 100644 --- a/src/cliBrowserScenarioCommands.ts +++ b/src/cliBrowserScenarioCommands.ts @@ -1,36 +1,35 @@ -import { Cli } from "incur"; -import { z } from "zod"; +import type { Logger } from "pino"; import { captureBrowserScenario } from "./application/BrowserScenarioCaptureService.js"; +import type { BrowserScenarioCapturePort } from "./application/BrowserScenarioCapturePort.js"; +import { publishCliAnalysisEvidence } from "./cli/analysisEvidenceDelivery.js"; +import { contractNamed } from "./cli/contractCliDescription.js"; +import { registerContractDocumentCommand } from "./cli/contractCommand.js"; import { finishAnalysisCommand } from "./cli/finishAnalysisCommand.js"; -import { withCommandCancellation } from "./cli/commandCancellation.js"; -import { - analysisEvidenceDeliveryOptions, - cliEvidenceDeliveryInputError, - publishCliAnalysisEvidence, -} from "./cli/analysisEvidenceDelivery.js"; +import type { CliInstance } from "./cli/types.js"; import { CLI_COMMANDS } from "./cliCommandNames.js"; -import { parseCliJsonInput, resolveCliJsonPaths } from "./cliJsonInput.js"; -import { logCliCommand } from "./cliLogging.js"; +import { BROWSER_SCENARIO_TOOL_CONTRACTS } from "./contracts/browserScenarioToolContracts.js"; import { projectAnalysisError } from "./domain/analysisErrorProjection.js"; -import { analysisInputErrorFromIssues } from "./domain/inputIssueProjection.js"; import { browserScenarioSchema, type BrowserScenario, } from "./domain/browserScenario.js"; -import { err, ok, type Result } from "./domain/result.js"; -import type { BrowserScenarioCapturePort } from "./application/BrowserScenarioCapturePort.js"; +import { analysisInputErrorFromIssues } from "./domain/inputIssueProjection.js"; import type { JsonValue } from "./domain/jsonValue.js"; -import { jsonInputArgument } from "./cli/jsonInputArgument.js"; -import type { Logger } from "pino"; +import { err, ok, type Result } from "./domain/result.js"; -const OPERATION = "capture_browser_scenario"; -const browserScenarioJsonDescription = +const contract = contractNamed( + BROWSER_SCENARIO_TOOL_CONTRACTS, + "capture_browser_scenario", +); +const PROVIDER_ID = "rea-playwright-browser-scenario"; +const document = "Inline browser scenario JSON, JSON file path, or '-' for stdin"; +const callerPaths = [["browser", "executable_path"]] as const; /** Register controlled browser execution and offline validation commands. */ export const registerBrowserScenarioCommands = ( - cli: ReturnType, + cli: CliInstance, logger: Logger, environment: Readonly>, options: { @@ -39,137 +38,113 @@ export const registerBrowserScenarioCommands = ( ) => BrowserScenarioCapturePort; } = {}, ): void => { - cli.command(CLI_COMMANDS.captureBrowserScenario, { - description: - "Run one bounded Playwright browser scenario and return Evidence", - args: z.object({ - inputJson: jsonInputArgument( - browserScenarioJsonDescription, - browserScenarioSchema, - ), - }), - options: z.object(analysisEvidenceDeliveryOptions), - run: ({ args, options: delivery }) => - withCommandCancellation((signal) => - logCliCommand(logger, CLI_COMMANDS.captureBrowserScenario, async () => { - const deliveryError = cliEvidenceDeliveryInputError({ - detail: delivery.detail, - evidenceOutput: delivery.evidence_output, - operation: OPERATION, - }); - if (deliveryError !== undefined) return cliError(deliveryError); - const scenario = await parseBrowserScenarioInput( - args.inputJson, - signal, - "Browser scenario capture failed", - ); - if (!scenario.ok) return scenario.error; - // Load Playwright only for this command, not during CLI startup. - const provider = - options.createProvider === undefined - ? await import("./composition/browserScenario.js").then( - ({ createBrowserScenarioProvider }) => - createBrowserScenarioProvider(environment), - ) - : options.createProvider(environment); - const result = await finishAnalysisCommand( - () => captureBrowserScenario(provider, scenario.value, { signal }), - { - close: async () => { - await provider?.close?.(); - }, - }, - "rea-playwright-browser-scenario", - OPERATION, - signal, - undefined, - { failureProjection: "initial" }, - ); - if (!result.ok) - return { - error: "Browser scenario capture failed", - ...result.error, - }; - return publishCliAnalysisEvidence(result, { - providerId: "rea-playwright-browser-scenario", - operation: OPERATION, - signal, - detail: delivery.detail, - evidenceOutput: delivery.evidence_output, - }); - }), - ), - }); - registerBrowserScenarioValidationCommand(cli, logger); -}; - -/** Validate the execution contract without provider or environment access. */ -const registerBrowserScenarioValidationCommand = ( - cli: ReturnType, - logger: Logger, -): void => { - cli.command(CLI_COMMANDS.validateBrowserScenario, { - description: - "Validate one browser scenario without launching or attaching to a browser", - args: z.object({ - inputJson: jsonInputArgument( - browserScenarioJsonDescription, - browserScenarioSchema, - ), - }), - run: ({ args }) => - withCommandCancellation((signal) => - logCliCommand( - logger, - CLI_COMMANDS.validateBrowserScenario, - async () => { - const scenario = await parseBrowserScenarioInput( - args.inputJson, - signal, - "Browser scenario validation failed", - ); - if (!scenario.ok) return scenario.error; - return { - valid: true, - actions: scenario.value.actions.length, - secrets: scenario.value.secrets.length, - }; + registerContractDocumentCommand( + cli, + logger, + contract, + { + command: CLI_COMMANDS.captureBrowserScenario, + description: + "Run one bounded Playwright browser scenario and return Evidence", + document, + callerPaths, + evidenceDelivery: true, + }, + async (input, { signal, operation, delivery, spelled }) => { + if (delivery === undefined) + throw new Error(`${operation} declares evidenceDelivery`); + const scenario = parseBrowserScenario( + input, + spelled, + "Browser scenario capture failed", + ); + if (!scenario.ok) return scenario.error; + // Load Playwright only for this command, not during CLI startup. + const provider = + options.createProvider === undefined + ? await import("./composition/browserScenario.js").then( + ({ createBrowserScenarioProvider }) => + createBrowserScenarioProvider(environment), + ) + : options.createProvider(environment); + const result = await finishAnalysisCommand( + () => captureBrowserScenario(provider, scenario.value, { signal }), + { + close: async () => { + await provider?.close?.(); }, - ), - ), - }); + }, + PROVIDER_ID, + operation, + signal, + undefined, + { failureProjection: "initial" }, + ); + if (!result.ok) + return { error: "Browser scenario capture failed", ...result.error }; + return publishCliAnalysisEvidence(result, { + providerId: PROVIDER_ID, + operation, + signal, + detail: delivery.detail, + evidenceOutput: delivery.evidenceOutput, + }); + }, + ); + // Validation admits the capture document without provider or environment + // access. + registerContractDocumentCommand( + cli, + logger, + contract, + { + command: CLI_COMMANDS.validateBrowserScenario, + description: + "Validate one browser scenario without launching or attaching to a browser", + document, + callerPaths, + omit: { + detail: + "validation runs no browser and delivers no Evidence; pass --detail to capture-browser-scenario", + }, + }, + async (input, { spelled }) => { + const scenario = parseBrowserScenario( + input, + spelled, + "Browser scenario validation failed", + ); + if (!scenario.ok) return scenario.error; + return { + valid: true, + actions: scenario.value.actions.length, + secrets: scenario.value.secrets.length, + }; + }, + ); }; -/** Keep caller-path normalization and canonical diagnostics identical for both commands. */ -const parseBrowserScenarioInput = async ( - inputJson: string, - signal: AbortSignal, +/** + * Both commands report the canonical scenario parser's field diagnostics, + * citing the document as the caller spelled it. + */ +const parseBrowserScenario = ( + input: unknown, + spelled: unknown, headline: string, -): Promise> => { - const input = await parseCliJsonInput(inputJson, OPERATION, signal); - if (!input.ok) return input; - const scenario = browserScenarioSchema.safeParse( - resolveCliJsonPaths(input.value, [["browser", "executable_path"]]), - ); +): Result => { + const scenario = browserScenarioSchema.safeParse(input); return scenario.success ? ok(scenario.data) - : err( - cliError( + : err({ + error: headline, + ...projectAnalysisError( analysisInputErrorFromIssues( - OPERATION, + contract.name, scenario.error.issues, - input.value, + spelled, { cause: scenario.error }, ), - headline, ), - ); + }); }; - -const cliError = ( - error: Parameters[0], - headline = "Browser scenario capture failed", -): JsonValue => ({ - error: headline, - ...projectAnalysisError(error), -}); diff --git a/src/contracts/sessionLifecycleInputs.ts b/src/contracts/sessionLifecycleInputs.ts index fda9712c6c..8eb35368d6 100644 --- a/src/contracts/sessionLifecycleInputs.ts +++ b/src/contracts/sessionLifecycleInputs.ts @@ -121,3 +121,42 @@ export const resetInvestigationInputSchema = z.strictObject({ .optional(), overwrite: z.boolean().default(false), }); + +/** + * The target interpretation an `open_binary` input selects, in the spelling + * every target open takes. MCP and CLI commands that open a target with these + * fields share this mapping. + */ +export const openBinaryTargetSelection = ( + input: Pick< + z.output, + | "format" + | "architecture" + | "entry_point" + | "flash_offset" + | "partition_table_offset" + >, +) => ({ + ...(input.format === undefined ? {} : { formatHint: input.format }), + ...(input.architecture === undefined + ? {} + : { architecture: input.architecture }), + ...(input.entry_point === undefined ? {} : { entryPoint: input.entry_point }), + ...(input.flash_offset === undefined && + input.partition_table_offset === undefined + ? {} + : { + espFlash: { + ...(input.flash_offset === undefined + ? {} + : { flashOffset: parseEspFlashAddress(input.flash_offset) }), + ...(input.partition_table_offset === undefined + ? {} + : { + partitionTableOffset: parseEspFlashAddress( + input.partition_table_offset, + ), + }), + }, + }), +}); diff --git a/src/contracts/sessionToolContracts.ts b/src/contracts/sessionToolContracts.ts index 02299d0d15..92ecd9822c 100644 --- a/src/contracts/sessionToolContracts.ts +++ b/src/contracts/sessionToolContracts.ts @@ -64,13 +64,20 @@ export const exportEvidenceBundleInputSchema = z.strictObject({ overwrite: z.boolean().default(false), }); +/** + * The contract an MCP client opens a target with. CLI commands that open their + * target take its fields as options; startup reads it here rather than through + * the complete catalog. + */ +export const OPEN_BINARY_TOOL_CONTRACT = session( + "open_binary", + "Open a validated local artifact or analysis database and bind its analysis provider. Switching target/provider can discard ephemeral Ghidra edits even if the later open fails; retained investigation Evidence does not restore them. Reopening the same target/profile retains the engine and edits. provider_id selects a provider or deterministic auto routing, with no failure fallback. Omitted format uses headers; format dos-com admits 1..65280 headerless bytes, while raw-binary requires architecture and entry_point and maps file offset 0 there. Optional snapshots must match target, provider and analysis profile; close/reopen before importing into a mutated engine. For Ghidra cross-process edits, set a private absolute REA_GHIDRA_CHECKPOINT_DIR at startup (stock ELF/PE/Mach-O on Linux/macOS); normal opens/closes restore/save metadata. Failed opens report selection_at_failure and target/provider at completion; use binary_session for current state. close_binary releases engine resources; reset_investigation clears retained records.", + openBinaryInputSchema, +); + /** Target lifecycle tools available only on the long-lived MCP adapter. */ export const SESSION_TOOL_CONTRACTS = [ - session( - "open_binary", - "Open a validated local artifact or analysis database and bind its analysis provider. Switching target/provider can discard ephemeral Ghidra edits even if the later open fails; retained investigation Evidence does not restore them. Reopening the same target/profile retains the engine and edits. provider_id selects a provider or deterministic auto routing, with no failure fallback. Omitted format uses headers; format dos-com admits 1..65280 headerless bytes, while raw-binary requires architecture and entry_point and maps file offset 0 there. Optional snapshots must match target, provider and analysis profile; close/reopen before importing into a mutated engine. For Ghidra cross-process edits, set a private absolute REA_GHIDRA_CHECKPOINT_DIR at startup (stock ELF/PE/Mach-O on Linux/macOS); normal opens/closes restore/save metadata. Failed opens report selection_at_failure and target/provider at completion; use binary_session for current state. close_binary releases engine resources; reset_investigation clears retained records.", - openBinaryInputSchema, - ), + OPEN_BINARY_TOOL_CONTRACT, session( "open_bundle_resources", "Open a local app bundle for read-only plist, Interface Builder, asset catalog, and keyed archive inspection without resolving or inventing its executable identity. This switches the shared session to a resource-only lane; executable analysis is unavailable until another target is opened.", diff --git a/src/server/registerSessionTools.ts b/src/server/registerSessionTools.ts index b943376b8a..e0996f14cc 100644 --- a/src/server/registerSessionTools.ts +++ b/src/server/registerSessionTools.ts @@ -1,5 +1,5 @@ import type { CapabilityAvailabilityProbes } from "../application/CapabilityAvailability.js"; -import { parseEspFlashAddress } from "../domain/firmware/espFlashSelection.js"; +import { openBinaryTargetSelection } from "../contracts/sessionLifecycleInputs.js"; import { registerNativeFunctionMatchingTool } from "./registerNativeFunctionMatchingTool.js"; import type { EvidenceMcpServer } from "./EvidenceMcpServer.js"; import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js"; @@ -225,32 +225,7 @@ const registerOpenLifecycleTool = ({ const opened = await logToolExecution(logger, openContract.name, () => session.open(input.path, { signal: context.mcpReq.signal, - ...(input.format === undefined ? {} : { formatHint: input.format }), - ...(input.architecture === undefined - ? {} - : { architecture: input.architecture }), - ...(input.entry_point === undefined - ? {} - : { entryPoint: input.entry_point }), - ...(input.flash_offset === undefined && - input.partition_table_offset === undefined - ? {} - : { - espFlash: { - ...(input.flash_offset === undefined - ? {} - : { - flashOffset: parseEspFlashAddress(input.flash_offset), - }), - ...(input.partition_table_offset === undefined - ? {} - : { - partitionTableOffset: parseEspFlashAddress( - input.partition_table_offset, - ), - }), - }, - }), + ...openBinaryTargetSelection(input), ...(input.provider_id === undefined ? {} : { providerId: input.provider_id }), diff --git a/tests/boundary/cli/cliContractCommandParity.test.ts b/tests/boundary/cli/cliContractCommandParity.test.ts index b4ab38ced1..087399c36e 100644 --- a/tests/boundary/cli/cliContractCommandParity.test.ts +++ b/tests/boundary/cli/cliContractCommandParity.test.ts @@ -286,6 +286,7 @@ describe("CLI commands projected from tool contracts", () => { ...description.parameters .filter(({ positional }) => !positional) .map(({ key }) => key), + ...(description.sessionTarget?.options ?? []).map(({ key }) => key), ...description.cliOnlyOptions.map(({ key }) => key), ].toSorted(), ); @@ -652,6 +653,88 @@ describe("Session targets of contract commands", () => { }, ); + it.each( + sessionTargeted.filter( + ([, description]) => description.sessionTarget!.options.length > 0, + ), + )( + "%s admits opening options with the opening contract and keeps them out of the contract input", + (_command, description) => { + const target = description.sessionTarget!; + const values = { + ...argvValues(description, {}), + [target.key]: "rel/app", + targetFormat: "esp-flash-image", + flashOffset: "0x1000", + }; + for (const { key } of target.options) + expect(Object.keys(description.fields), key).not.toContain(key); + expect(Object.values(description.toContractInput(values))).not.toContain( + "0x1000", + ); + expect(target.admitOpening(description.contract.name, values)).toEqual({ + ok: true, + value: { format: "esp-flash-image", flash_offset: "0x1000" }, + }); + expect(target.admitOpening(description.contract.name, {})).toEqual({ + ok: true, + value: {}, + }); + // The opening contract's pairing rule names the CLI key. + const unpaired = target.admitOpening(description.contract.name, { + [target.key]: "rel/app", + flashOffset: "0x1000", + }); + expect(unpaired.ok).toBe(false); + if (!unpaired.ok) + expect(unpaired.error.issues).toEqual([ + expect.objectContaining({ + path: ["flashOffset"], + message: expect.stringMatching(/only with format=esp-flash-image/u), + }), + ]); + // Only the projected values of an opening field are admitted. + const format = target.options.find(({ key }) => key === "targetFormat")!; + expect(admits(format.schema, "esp-flash-image")).toBe(true); + expect(admits(format.schema, "raw-binary")).toBe(false); + }, + ); + + it("refuses opening fields the opening contract cannot supply", () => { + const opening = { + name: "open", + inputSchema: z.object({ + path: z.string(), + mode: z.enum(["a", "b"]).optional(), + required: z.string(), + }), + }; + const describeOpening = (fields: Record) => + describeContractCommand( + { name: "probe", inputSchema: z.object({}) }, + { + command: "probe", + description: "Probe", + sessionTarget: { + description: "Target", + open: { contract: opening, fields }, + }, + }, + ); + expect(() => describeOpening({ missing: {} })).toThrow( + "open has no option field missing", + ); + expect(() => describeOpening({ path: {} })).toThrow( + "open has no option field path", + ); + expect(() => describeOpening({ required: {} })).toThrow( + "open.required is required", + ); + expect(() => describeOpening({ mode: { values: ["c"] } })).toThrow( + "open.mode does not admit c", + ); + }); + it("refuses a session target beside a contract field keyed path", () => { expect(() => describeContractCommand( @@ -770,6 +853,10 @@ describe("JSON-document contract commands", () => { "match-native-functions", "build-reconstruction-obligation-ledger", "evaluate-reconstruction-coverage", + "observe-native-calls", + "compare-static-and-observed-endpoints", + "capture-browser-scenario", + "validate-browser-scenario", ]), ); }); @@ -779,12 +866,18 @@ describe("JSON-document contract commands", () => { (_command, description) => { const command = registered.get(description.command)!; const args = (command.args as z.ZodObject).shape; - expect(Object.keys(args)).toEqual([description.key]); + expect(Object.keys(args)).toEqual([ + ...(description.sessionTarget === undefined + ? [] + : [description.sessionTarget.key]), + description.key, + ]); const advertised = (args[description.key] as z.ZodType).meta(); expect(advertised?.contentMediaType).toBe("application/json"); const content = advertised?.contentSchema as Record; expect(content).toEqual(jsonInputContentSchema(description.content)); - // Every contract field reaches the document unless omitted with a reason. + // Every contract field reaches the document unless omitted with a + // reason or taken as an option beside it. const input = inputJsonSchema(description.contract.inputSchema); const fields = new Set( reachable(input, []).flatMap((branch) => @@ -796,16 +889,26 @@ describe("JSON-document contract commands", () => { for (const field of fields) expect( reachable(content, [field]).length > 0 || - Object.hasOwn(description.omitted, field), + Object.hasOwn(description.omitted, field) || + Object.hasOwn(description.flagged, field), field, ).toBe(true); - for (const field of Object.keys(description.omitted)) + for (const field of [ + ...Object.keys(description.omitted), + ...Object.keys(description.flagged), + ]) expect(reachable(content, [field]), field).toEqual([]); + const options = [ + ...description.deliveryOptions, + ...description.cliOnlyOptions, + ].map(({ key }) => key); + for (const key of Object.values(description.flagged)) + expect(options, key).toContain(key); expect( Object.keys( (command.options as z.ZodObject | undefined)?.shape ?? {}, ).toSorted(), - ).toEqual(description.cliOnlyOptions.map(({ key }) => key).toSorted()); + ).toEqual(options.toSorted()); }, ); @@ -868,3 +971,93 @@ describe("JSON-document contract commands", () => { ).toEqual(["required"]); }); }); + +describe("JSON-document delivery options", () => { + const contract = { + name: "probe", + inputSchema: z.object({ + required: z.string(), + optional: z.string().optional(), + }), + }; + const projection = { + command: "probe", + description: "Probe", + document: "Probe JSON", + }; + + it("takes detail and view beside the document and admits them before the handler", () => { + expect(() => + describeContractDocumentCommand(contract, { + ...projection, + evidenceDelivery: true, + }), + ).toThrow("probe.detail is not an optional field"); + const delivered = { + name: "probe", + inputSchema: contract.inputSchema.extend({ + detail: z.enum(["complete", "summary"]).default("complete"), + view: z.object({ offset: z.number() }).optional(), + }), + }; + expect(() => + describeContractDocumentCommand(delivered, { + ...projection, + viewDelivery: { invalidJson: "view must be JSON" }, + }), + ).toThrow("probe view delivery requires evidenceDelivery"); + expect(() => + describeContractDocumentCommand(delivered, { + ...projection, + evidenceDelivery: true, + omit: { detail: "never" }, + }), + ).toThrow("probe.detail is both omitted and an option"); + expect(() => + describeContractDocumentCommand(delivered, { + ...projection, + evidenceDelivery: true, + cliOptions: { evidence_output: z.string().optional() }, + }), + ).toThrow("probe projects two fields to one CLI key"); + const flagged = describeContractDocumentCommand(delivered, { + ...projection, + evidenceDelivery: true, + viewDelivery: { invalidJson: "view must be JSON" }, + }); + expect( + Object.keys(inputJsonSchema(flagged.content).properties as object), + ).toEqual(["required", "optional"]); + expect(flagged.admitDelivery({ detail: "complete" })).toEqual({ + ok: true, + value: { detail: "complete", evidenceOutput: undefined }, + }); + expect( + flagged.admitDelivery({ + detail: "summary", + evidence_output: "out.json", + view: '{"offset":2}', + }), + ).toEqual({ + ok: true, + value: { + detail: "summary", + evidenceOutput: "out.json", + view: { offset: 2 }, + }, + }); + for (const values of [ + { detail: "complete", view: '{"offset":2}' }, + { detail: "summary", evidence_output: "out.json", view: "{" }, + { + detail: "summary", + evidence_output: "out.json", + view: '{"offset":"2"}', + }, + { detail: "summary" }, + ]) + expect(flagged.admitDelivery(values).ok, JSON.stringify(values)).toBe( + false, + ); + }); +}); diff --git a/tests/boundary/cli/jsonInputSchema.test.ts b/tests/boundary/cli/jsonInputSchema.test.ts index 0f26762d6c..8c5dc98f23 100644 --- a/tests/boundary/cli/jsonInputSchema.test.ts +++ b/tests/boundary/cli/jsonInputSchema.test.ts @@ -160,10 +160,12 @@ const documents: readonly { { command: CLI_COMMANDS.captureBrowserScenario, schema: browserScenarioSchema, + callerPaths: [["browser", "executable_path"]], }, { command: CLI_COMMANDS.validateBrowserScenario, schema: browserScenarioSchema, + callerPaths: [["browser", "executable_path"]], }, ] as const; diff --git a/tests/boundary/cli/jsonInputStatus.test.ts b/tests/boundary/cli/jsonInputStatus.test.ts index 7a17059890..83198d7ff2 100644 --- a/tests/boundary/cli/jsonInputStatus.test.ts +++ b/tests/boundary/cli/jsonInputStatus.test.ts @@ -125,6 +125,103 @@ describe("compiled CLI JSON document omissions", () => { }); expect(result.exitCode).toBe(1); }); + + // Delivery is chosen by options beside the document; a delivery field in + // the document names its option instead of being dropped or misread. + for (const [command, operation, field, message] of [ + [ + "compare-static-and-observed-endpoints", + "compare_static_and_observed_endpoints", + "detail", + "pass --detail beside it", + ], + [ + "compare-static-and-observed-endpoints", + "compare_static_and_observed_endpoints", + "view", + "pass --view beside it", + ], + [ + "capture-browser-scenario", + "capture_browser_scenario", + "detail", + "pass --detail beside it", + ], + [ + "validate-browser-scenario", + "capture_browser_scenario", + "detail", + "pass --detail to capture-browser-scenario", + ], + ] as const) + cliTest( + `${command} refuses ${field} inside the document`, + async ({ cli }) => { + const root = await createTestTempDirectory("rea-cli-json-flagged-"); + const result = await cli.run({ + arguments: [ + command, + JSON.stringify({ + [field]: field === "view" ? { collection: "matches" } : "summary", + }), + "--json", + ], + environment: { + HOME: root, + XDG_CONFIG_HOME: root, + XDG_CACHE_HOME: root, + }, + }); + expect(result.json).toMatchObject({ + code: "invalid_request", + category: "invalid_input", + details: { + operation, + issues: [ + { path: [field], message: expect.stringContaining(message) }, + ], + }, + }); + expect(result.exitCode).toBe(1); + }, + ); +}); + +describe("compiled CLI JSON document admission order", () => { + // The document frame is checked before any Evidence bundle is read, so a + // missing bundle cannot hide document errors. + cliTest( + "compare-static-and-observed-endpoints refuses a malformed document before reading its bundle", + async ({ cli }) => { + const root = await createTestTempDirectory("rea-cli-json-frame-"); + const result = await cli.run({ + arguments: [ + "compare-static-and-observed-endpoints", + "{}", + "--evidence-bundle", + join(root, "missing.bundle.json"), + "--json", + ], + environment: { + HOME: root, + XDG_CONFIG_HOME: root, + XDG_CACHE_HOME: root, + }, + }); + expect(result.json).toMatchObject({ + code: "invalid_request", + details: { + operation: "compare_static_and_observed_endpoints", + issues: expect.arrayContaining([ + expect.objectContaining({ path: ["application"] }), + expect.objectContaining({ path: ["capture"] }), + ]), + }, + }); + expect(JSON.stringify(result.json)).not.toContain("missing.bundle.json"); + expect(result.exitCode).toBe(1); + }, + ); }); describe("compiled CLI JSON document caller paths", () => { @@ -161,6 +258,39 @@ describe("compiled CLI JSON document caller paths", () => { ); }); +describe("compiled CLI session-target JSON documents", () => { + cliTest( + "observe-native-calls refuses an invalid document before opening its target", + async ({ cli }) => { + const root = await createTestTempDirectory("rea-cli-json-target-"); + const result = await cli.run({ + arguments: [ + "observe-native-calls", + join(root, "missing-target"), + JSON.stringify({ breakpoints: "main" }), + "--json", + ], + environment: { + HOME: root, + XDG_CONFIG_HOME: root, + XDG_CACHE_HOME: root, + }, + }); + expect(result.json).toMatchObject({ + error: "Analysis failed", + code: "invalid_request", + details: { + operation: "observe_native_calls", + issues: expect.arrayContaining([ + expect.objectContaining({ path: ["breakpoints"] }), + ]), + }, + }); + expect(result.exitCode).toBe(1); + }, + ); +}); + describe("compiled CLI JSON input diagnostic preservation", () => { for (const [format, flags] of [ ["JSON", ["--json"]],