From fc6a9604a175f3456c99025e142817fdc70d3961 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:25:34 +0800 Subject: [PATCH] refactor(cli): project JSON-document workflow commands from their contracts (#10668) * refactor(cli): project JSON-document workflow commands from their contracts * test(cli): include WASM interface and native matching documents in the JSON-input guard --- src/cli/analysisViewCommands.ts | 100 +++++---- src/cli/applicationCommands.ts | 105 ++++------ src/cli/artifactComparisonCommand.ts | 101 ++++----- src/cli/contractCliDescription.ts | 136 ++++++++++++- src/cli/contractCommand.ts | 100 +++++++++ src/cli/electronCommands.ts | 192 ++++++++---------- src/cli/managedCommands.ts | 157 +++++++------- src/cli/managedProjectGraphCommand.ts | 58 ------ src/cli/nativeFunctionMatchingCommands.ts | 153 +++++++------- src/cli/wasmCommands.ts | 71 +++---- tests/boundary/cli/analysisViewCli.test.ts | 2 +- .../cli/cliContractCommandParity.test.ts | 155 +++++++++++++- tests/boundary/cli/jsonInputSchema.test.ts | 10 + tests/boundary/cli/jsonInputStatus.test.ts | 24 +-- .../boundary/filesystem/cliJsonInput.test.ts | 2 +- 15 files changed, 794 insertions(+), 572 deletions(-) delete mode 100644 src/cli/managedProjectGraphCommand.ts diff --git a/src/cli/analysisViewCommands.ts b/src/cli/analysisViewCommands.ts index d28fd097a0..e6e4615093 100644 --- a/src/cli/analysisViewCommands.ts +++ b/src/cli/analysisViewCommands.ts @@ -4,12 +4,13 @@ import { inspectAnalysisView } from "../application/analysisView/AnalysisViewSer import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js"; import { ANALYSIS_VIEW_PROVIDER } from "../domain/investigationProviders.js"; import { inspectEvidenceBundleCommand } from "../application/EvidenceBundleCommands.js"; +import { ANALYSIS_VIEW_TOOL_CONTRACTS } from "../contracts/analysisViewToolContracts.js"; import { getEvidenceBundleInputSchema, importEvidenceBundleInputSchema, } from "../contracts/sessionToolSchemas.js"; import { CLI_COMMANDS } from "../cliCommandNames.js"; -import { parseCliJsonInput, resolveCliJsonPaths } from "../cliJsonInput.js"; +import { parseCliJsonInput } from "../cliJsonInput.js"; import { logCliCommand } from "../cliLogging.js"; import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js"; @@ -17,9 +18,10 @@ import type { Logger } from "pino"; import type { CliInstance } from "./types.js"; import { localPathStringSchema } from "../domain/localPath.js"; import { withCommandCancellation } from "./commandCancellation.js"; +import { contractNamed } from "./contractCliDescription.js"; +import { registerContractDocumentCommand } from "./contractCommand.js"; import { finishAnalysisCommand } from "./finishAnalysisCommand.js"; import { jsonInputArgument } from "./jsonInputArgument.js"; -import { inspectAnalysisViewInputSchema } from "../domain/analysisView/analysisViewRequest.js"; const inspectEvidenceBundleCliInputSchema = getEvidenceBundleInputSchema.safeExtend({ @@ -76,57 +78,49 @@ export const registerAnalysisViewCommands = ( }), ), }); - cli.command(CLI_COMMANDS.inspectAnalysisView, { - description: - "Project a selected view of completed Evidence JSON for a supported analysis operation. For inventory rows, use --format csv or --format tsv with --filter-output normalized_result.items and --columns logical_path,artifact_id (if those fields are included in the view).", - args: z.object({ - inputJson: jsonInputArgument( - "Inline workflow JSON or JSON file path", - inspectAnalysisViewInputSchema, - ), - }), - options: z.object({ - evidenceBundle: localPathStringSchema - .optional() - .describe( - "Read the exact retained-evidence source ID from this local Evidence bundle without reopening the target; omit for inline Evidence", - ), - }), - run: ({ args, options }) => - withCommandCancellation((signal) => - logCliCommand(logger, CLI_COMMANDS.inspectAnalysisView, async () => { - const input = await parseCliJsonInput( - args.inputJson, - CLI_COMMANDS.inspectAnalysisView, + registerContractDocumentCommand( + cli, + logger, + contractNamed(ANALYSIS_VIEW_TOOL_CONTRACTS, "inspect_analysis_view"), + { + command: CLI_COMMANDS.inspectAnalysisView, + description: + "Project a selected view of completed Evidence JSON for a supported analysis operation. For inventory rows, use --format csv or --format tsv with --filter-output normalized_result.items and --columns logical_path,artifact_id (if those fields are included in the view).", + document: "Inline workflow JSON or JSON file path", + // An evidence-file path is resolved against the operator's working directory. + callerPaths: [["source", "path"]], + cliOptions: { + evidenceBundle: localPathStringSchema + .optional() + .describe( + "Read the exact retained-evidence source ID from this local Evidence bundle without reopening the target; omit for inline Evidence", + ), + }, + }, + async (document, { signal, operation, cliOptions }) => { + const resources = new ArtifactResourceScope(); + const bundlePath = cliOptions.evidenceBundle; + const result = await finishAnalysisCommand( + () => + inspectAnalysisView(document, undefined, { signal, - ); - if (!input.ok) return input.error; - // An evidence-file path is resolved against the operator's working directory. - const value = resolveCliJsonPaths(input.value, [["source", "path"]]); - const resources = new ArtifactResourceScope(); - const bundlePath = options.evidenceBundle; - const result = await finishAnalysisCommand( - () => - inspectAnalysisView(value, undefined, { - signal, - resources, - ...(bundlePath === undefined - ? {} - : { evidenceBundlePath: bundlePath }), - }), resources, - ANALYSIS_VIEW_PROVIDER.id, - "inspect_analysis_view", - signal, - ); - // Preserve the inline command's existing error label without copying - // the authenticated completed Evidence or its partial observation. - return result.ok - ? result.value - : bundlePath === undefined - ? { error: "Application workflow failed", ...result.error } - : result.error; - }), - ), - }); + ...(bundlePath === undefined + ? {} + : { evidenceBundlePath: bundlePath }), + }), + resources, + ANALYSIS_VIEW_PROVIDER.id, + operation, + signal, + ); + // Preserve the inline command's existing error label without copying + // the authenticated completed Evidence or its partial observation. + return result.ok + ? result.value + : bundlePath === undefined + ? { error: "Application workflow failed", ...result.error } + : result.error; + }, + ); }; diff --git a/src/cli/applicationCommands.ts b/src/cli/applicationCommands.ts index 4bd145a2d5..ea87380266 100644 --- a/src/cli/applicationCommands.ts +++ b/src/cli/applicationCommands.ts @@ -13,17 +13,12 @@ import type { Logger } from "pino"; import { registerSourceToBundleCommand } from "./sourceToBundleCommand.js"; import { registerStaticObservedEndpointsCommand } from "./staticObservedEndpointsCommand.js"; import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js"; -import { getEvidenceInputContract } from "../domain/evidenceInputContract.js"; -import { applicationInventoryProjectionInputSchema } from "../domain/mobileApplicationGraphProjection.js"; -import { - compareApplicationVersionsRequestSchema, - compareJavaScriptExportShapesRequestSchema, - traceApplicationFeatureRequestSchema, - traceJavaScriptSemanticsRequestSchema, -} from "../contracts/javascript/applicationWorkflowInputContracts.js"; import { reconstructionCoverageRequestSchema } from "../domain/reconstructionCoverageInput.js"; import { reconstructionObligationLedgerRequestSchema } from "../application/ReconstructionObligationLedgerRequest.js"; import { jsonInputArgument } from "./jsonInputArgument.js"; +import { APPLICATION_TOOL_CONTRACTS } from "../contracts/applicationToolContracts.js"; +import { contractNamed } from "./contractCliDescription.js"; +import { registerContractDocumentCommand } from "./contractCommand.js"; import type { EvidenceLookup } from "../application/EvidenceInputResolver.js"; import type { Evidence } from "../domain/evidence.js"; import type { Result } from "../domain/result.js"; @@ -31,25 +26,19 @@ import { evidenceBundleOption, runEvidenceInputCommand, } from "./evidenceInputCommand.js"; -import { withCommandCancellation } from "./commandCancellation.js"; type CliInstance = ReturnType; -const traceApplicationFeatureDocumentSchema = getEvidenceInputContract( - traceApplicationFeatureRequestSchema, -).frameSchema; -const traceJavaScriptSemanticsDocumentSchema = getEvidenceInputContract( - traceJavaScriptSemanticsRequestSchema, -).frameSchema; -const compareApplicationVersionsDocumentSchema = getEvidenceInputContract( - compareApplicationVersionsRequestSchema, -).frameSchema; -const compareJavaScriptExportShapesDocumentSchema = getEvidenceInputContract( - compareJavaScriptExportShapesRequestSchema, -).frameSchema; -const applicationInventoryDocumentSchema = getEvidenceInputContract( - applicationInventoryProjectionInputSchema, -).frameSchema; +/** Application workflows whose CLI input is one Evidence-carrying JSON document. */ +type EvidenceWorkflowOperation = + | "trace_application_feature" + | "trace_javascript_semantics" + | "compare_application_versions" + | "compare_javascript_export_shapes" + | "project_android_application_graph" + | "project_apple_application_graph" + | "project_harmony_application_graph"; + const workflowJsonDescription = "Inline workflow JSON or JSON file path"; /** Register CLI equivalents of provider-neutral application graph workflows. */ @@ -62,7 +51,9 @@ export const registerApplicationCommands = ( logger, name: CLI_COMMANDS.traceApplicationFeature, operation: "trace_application_feature", - documentSchema: traceApplicationFeatureDocumentSchema, + omit: { + view: "A one-shot command retains no session Evidence for a selected view; save the complete trace and query it with inspect-analysis-view", + }, description: "Trace a typed seed through authenticated application Evidence JSON", workflow: async (input, lookup, signal) => { @@ -77,7 +68,6 @@ export const registerApplicationCommands = ( logger, name: CLI_COMMANDS.traceJavaScriptSemantics, operation: "trace_javascript_semantics", - documentSchema: traceJavaScriptSemanticsDocumentSchema, description: "Trace bounded static semantic relations through authenticated application Evidence", workflow: async (input, lookup, signal) => { @@ -94,7 +84,6 @@ export const registerApplicationCommands = ( logger, name: CLI_COMMANDS.compareApplicationVersions, operation: "compare_application_versions", - documentSchema: compareApplicationVersionsDocumentSchema, description: "Compare two authenticated JavaScript Application Graph versions", workflow: async (input, lookup, signal) => { @@ -116,7 +105,6 @@ export const registerApplicationCommands = ( logger, name: CLI_COMMANDS.compareJavaScriptExportShapes, operation: "compare_javascript_export_shapes", - documentSchema: compareJavaScriptExportShapesDocumentSchema, description: "Compare exact static JavaScript export return shapes without execution", workflow: async (input, lookup, signal) => { @@ -135,7 +123,6 @@ export const registerApplicationCommands = ( logger, name: CLI_COMMANDS.projectAndroidApplicationGraph, operation: "project_android_application_graph", - documentSchema: applicationInventoryDocumentSchema, description: "Project authenticated APK inventory Evidence into an Android application graph", workflow: async (input, lookup, signal) => { @@ -152,7 +139,6 @@ export const registerApplicationCommands = ( logger, name: CLI_COMMANDS.projectAppleApplicationGraph, operation: "project_apple_application_graph", - documentSchema: applicationInventoryDocumentSchema, description: "Project authenticated IPA or macOS app inventory Evidence into an Apple application graph", workflow: async (input, lookup, signal) => { @@ -167,7 +153,6 @@ export const registerApplicationCommands = ( logger, name: CLI_COMMANDS.projectHarmonyApplicationGraph, operation: "project_harmony_application_graph", - documentSchema: applicationInventoryDocumentSchema, description: "Project authenticated HarmonyOS HAP, HSP, or App Pack inventory Evidence into an application graph", workflow: async (input, lookup, signal) => { @@ -282,45 +267,41 @@ const registerEvidenceJsonCommand = ({ name, operation, description, - documentSchema, + omit, workflow, }: { readonly cli: CliInstance; readonly logger: Logger; readonly name: string; - readonly operation: string; + readonly operation: EvidenceWorkflowOperation; readonly description: string; - readonly documentSchema: z.ZodType; + readonly omit?: Readonly>; readonly workflow: ( input: unknown, lookup: EvidenceLookup | undefined, signal: AbortSignal, ) => Promise>; -}): void => { - cli.command(name, { - description, - args: z.object({ - inputJson: jsonInputArgument(workflowJsonDescription, documentSchema), - }), - options: z.object({ evidenceBundle: evidenceBundleOption }), - run: ({ args, options }) => - withCommandCancellation((signal) => - logCliCommand(logger, name, async () => { - const input = await parseCliJsonInput(args.inputJson, name, signal); - if (!input.ok) return input.error; - const result = await runEvidenceInputCommand( - operation, - options.evidenceBundle, - signal, - (lookup) => workflow(input.value, lookup, signal), - ); - return result.ok - ? result.value - : { - error: "Application workflow failed", - ...result.error, - }; - }), - ), - }); -}; +}): void => + registerContractDocumentCommand( + cli, + logger, + contractNamed(APPLICATION_TOOL_CONTRACTS, operation), + { + command: name, + description, + document: workflowJsonDescription, + ...(omit === undefined ? {} : { omit }), + cliOptions: { evidenceBundle: evidenceBundleOption }, + }, + async (input, { signal, cliOptions }) => { + const result = await runEvidenceInputCommand( + operation, + cliOptions.evidenceBundle, + signal, + (lookup) => workflow(input, lookup, signal), + ); + return result.ok + ? result.value + : { error: "Application workflow failed", ...result.error }; + }, + ); diff --git a/src/cli/artifactComparisonCommand.ts b/src/cli/artifactComparisonCommand.ts index 0149d2aa5a..64e090f6d9 100644 --- a/src/cli/artifactComparisonCommand.ts +++ b/src/cli/artifactComparisonCommand.ts @@ -1,4 +1,3 @@ -import { z } from "incur"; import type { Logger } from "pino"; import { @@ -6,70 +5,56 @@ import { resolveArtifactComparisonSources, } from "../application/artifacts/ArtifactComparisonEvidence.js"; import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js"; -import { artifactComparisonInputSchema } from "../contracts/artifactComparisonContracts.js"; +import { SESSION_TOOL_CONTRACTS } from "../contracts/sessionToolContracts.js"; import { CLI_COMMANDS } from "../cliCommandNames.js"; -import { parseCliJsonInput, resolveCliJsonPaths } from "../cliJsonInput.js"; -import { logCliCommand } from "../cliLogging.js"; import { ARTIFACT_COMPARISON_PROVIDER } from "../domain/comparisonEvidenceIdentity.js"; -import { withCommandCancellation } from "./commandCancellation.js"; +import { contractNamed } from "./contractCliDescription.js"; +import { registerContractDocumentCommand } from "./contractCommand.js"; import { finishAnalysisCommand } from "./finishAnalysisCommand.js"; -import { jsonInputArgument } from "./jsonInputArgument.js"; import type { CliInstance } from "./types.js"; -const OPERATION = "compare_artifacts"; - /** Compare artifact inventories through the same source owners and workflow as MCP. */ export const registerArtifactComparisonCommand = ( cli: CliInstance, logger: Logger, -): void => { - const name = CLI_COMMANDS.compareArtifacts; - cli.command(name, { - description: - 'Compare two artifact inventories, including FIT and legacy uImage firmware components, named as {left, right}: complete Evidence or {kind:"evidence-file",path,evidence_id?}. A one-shot command retains no session Evidence for retained-evidence references.', - args: z.object({ - inputJson: jsonInputArgument( - "Inline workflow JSON or JSON file path", - artifactComparisonInputSchema, - ), - }), - run: ({ args }) => - withCommandCancellation((signal) => - logCliCommand(logger, name, async () => { - const input = await parseCliJsonInput( - args.inputJson, - OPERATION, - signal, +): void => + registerContractDocumentCommand( + cli, + logger, + contractNamed(SESSION_TOOL_CONTRACTS, "compare_artifacts"), + { + command: CLI_COMMANDS.compareArtifacts, + description: + 'Compare two artifact inventories, including FIT and legacy uImage firmware components, named as {left, right}: complete Evidence or {kind:"evidence-file",path,evidence_id?}. A one-shot command retains no session Evidence for retained-evidence references.', + document: "Inline workflow JSON or JSON file path", + // Evidence-file paths are resolved against the operator's working directory. + callerPaths: [ + ["left", "path"], + ["right", "path"], + ], + }, + async (document, { signal, operation }) => { + const resources = new ArtifactResourceScope(); + const result = await finishAnalysisCommand( + async () => { + const sources = await resolveArtifactComparisonSources( + document, + undefined, + { signal, resources }, ); - if (!input.ok) return input.error; - // Evidence-file paths are resolved against the operator's working directory. - const value = resolveCliJsonPaths(input.value, [ - ["left", "path"], - ["right", "path"], - ]); - const resources = new ArtifactResourceScope(); - const result = await finishAnalysisCommand( - async () => { - const sources = await resolveArtifactComparisonSources( - value, - undefined, - { signal, resources }, - ); - if (!sources.ok) return sources; - const compared = compareArtifactEvidence(sources.value); - return compared.ok - ? { ok: true as const, value: compared.value.evidence } - : compared; - }, - resources, - ARTIFACT_COMPARISON_PROVIDER.id, - OPERATION, - signal, - ); - return result.ok - ? result.value - : { error: "Application workflow failed", ...result.error }; - }), - ), - }); -}; + if (!sources.ok) return sources; + const compared = compareArtifactEvidence(sources.value); + return compared.ok + ? { ok: true as const, value: compared.value.evidence } + : compared; + }, + resources, + ARTIFACT_COMPARISON_PROVIDER.id, + operation, + signal, + ); + return result.ok + ? result.value + : { error: "Application workflow failed", ...result.error }; + }, + ); diff --git a/src/cli/contractCliDescription.ts b/src/cli/contractCliDescription.ts index 354d34ab9a..10577d91e7 100644 --- a/src/cli/contractCliDescription.ts +++ b/src/cli/contractCliDescription.ts @@ -12,6 +12,7 @@ import { cliEvidenceDeliveryInputError, } from "./analysisEvidenceDelivery.js"; import { parseCliJsonOption } from "./cliJsonOption.js"; +import { getEvidenceInputContract } from "../domain/evidenceInputContract.js"; import { safeParseJson } from "../domain/safeJson.js"; import { cliDecimalShape } from "./options.js"; @@ -34,8 +35,14 @@ export interface ProjectedContract { | z.ZodDiscriminatedUnion; } +/** A contract whose whole input a CLI command takes as one JSON document. */ +export interface DocumentContract { + readonly name: Name; + readonly inputSchema: z.ZodType; +} + /** A contract input field name. */ -export type ContractField = keyof z.input< +export type ContractField = keyof z.input< Contract["inputSchema"] > & string; @@ -87,17 +94,17 @@ export interface CliContractProjection< * and the limit are mutually exclusive. */ readonly nullFlags?: { readonly [Key in Field]?: CliNullFlag }; - /** - * Optional object fields taken as one option per member, keyed by contract - * field and then member. Any member given supplies the whole object, so the - * contract reports a missing companion member. - */ /** * The operation analyzes the target an MCP session holds open, so the * target is not a contract field. The CLI takes it as the first positional, * `path`, and opens it before the operation runs on the contract input. */ readonly sessionTarget?: CliSessionTarget; + /** + * Optional object fields taken as one option per member, keyed by contract + * field and then member. Any member given supplies the whole object, so the + * contract reports a missing companion member. + */ readonly flatten?: { readonly [Key in Field]?: Readonly>; }; @@ -150,7 +157,7 @@ export type CliOptionValues = { readonly [Key in keyof CliOptions]: z.output; }; -/** A bare flag that sets a nullable contract field to null. */ +/** The target an operation runs on, which an MCP session holds open. */ export interface CliSessionTarget { /** Help for the target positional. */ readonly description: string; @@ -159,6 +166,7 @@ export interface CliSessionTarget { /** The CLI key of a session target, which no contract field supplies. */ const SESSION_TARGET_KEY = "path"; +/** A bare flag that sets a nullable contract field to null. */ export interface CliNullFlag { readonly key: string; readonly description: string; @@ -318,7 +326,7 @@ export interface ContractCliDescription { /** One contract from a contract group, keeping its exact schema types. */ export const contractNamed = < - Contracts extends readonly ProjectedContract[], + Contracts extends readonly { readonly name: string }[], Name extends Contracts[number]["name"], >( contracts: Contracts, @@ -552,6 +560,118 @@ const inputFields = ( ); }; +/** + * The CLI spelling of a contract whose whole input is one JSON document: + * inline JSON, a JSON file path, or `-` for standard input. + */ +export interface CliDocumentProjection< + Field extends string, + CliOptions extends CliOptionShape = CliOptionShape, +> { + readonly command: string; + readonly description: string; + /** Help for the document argument. */ + readonly document: string; + /** + * Property paths of caller paths inside the document. Each nonblank string + * there that is not a URL is resolved against the working directory. + */ + readonly callerPaths?: readonly (readonly string[])[]; + /** + * Optional top-level fields this one-shot command does not admit, each with + * the reason; `--schema` leaves them out of the document. + */ + readonly omit?: { readonly [Key in Field]?: string }; + /** Options no contract field owns, keyed by their CLI key. */ + readonly cliOptions?: CliOptions; +} + +/** A complete, framework-neutral CLI command whose input is one JSON document. */ +export interface ContractCliDocumentDescription { + readonly command: string; + readonly description: string; + readonly contract: DocumentContract; + /** The argument key, which no option shares. */ + readonly key: string; + /** Help for the document argument. */ + readonly documentDescription: string; + /** + * What the document admits as `--schema` advertises it: the contract input + * without omitted fields, with each Evidence carrier left to its owner. + */ + readonly content: z.ZodType; + /** Property paths of caller paths inside the document. */ + readonly callerPaths: readonly (readonly string[])[]; + /** Contract fields the command does not admit, with the reason. */ + readonly omitted: Readonly>; + readonly cliOnlyOptions: readonly CliOnlyOption[]; + /** The parsed values of the projection's CLI-only options. */ + readonly cliOptionValues: ( + values: Readonly>, + ) => Readonly>; +} + +/** The CLI key of a JSON input document. */ +const DOCUMENT_KEY = "inputJson"; + +/** + * Describe a contract command that takes its whole input as one JSON + * document. The handler admits the decoded document with the contract's + * owner, which borrows Evidence carriers rather than parsing them here. + */ +export const describeContractDocumentCommand = < + Contract extends DocumentContract, + CliOptions extends CliOptionShape = CliOptionShape, +>( + contract: Contract, + projection: CliDocumentProjection, CliOptions>, +): ContractCliDocumentDescription => { + const omitted: Readonly> = Object.fromEntries( + Object.entries(projection.omit ?? {}).filter( + (entry): entry is [string, string] => typeof entry[1] === "string", + ), + ); + let admitted: z.ZodType = contract.inputSchema; + if (Object.keys(omitted).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)) + if (!Object.hasOwn(shape, field) || !admitsOmission(shape[field]!)) + throw new Error(`${contract.name}.${field} is not an optional field`); + admitted = schema.omit( + Object.fromEntries( + Object.keys(omitted).map((field) => [field, true]), + ) as never, + ); + } + const cliOptions: CliOptionShape = projection.cliOptions ?? {}; + if (Object.hasOwn(cliOptions, DOCUMENT_KEY)) + throw new Error(`${contract.name} projects two fields to one CLI key`); + return { + command: projection.command, + description: projection.description, + contract, + key: DOCUMENT_KEY, + documentDescription: projection.document, + content: getEvidenceInputContract(admitted).frameSchema, + callerPaths: projection.callerPaths ?? [], + omitted, + cliOnlyOptions: Object.entries(cliOptions).map(([key, schema]) => ({ + key, + description: schema.description, + schema, + })), + cliOptionValues: (values) => + Object.fromEntries( + Object.keys(cliOptions).flatMap((key) => + values[key] === undefined ? [] : [[key, values[key]]], + ), + ), + }; +}; + /** Derive the CLI parameters of one contract from its input schema and projection. */ export const describeContractCommand = < Contract extends ProjectedContract, diff --git a/src/cli/contractCommand.ts b/src/cli/contractCommand.ts index 5eb2f55214..4c972c645a 100644 --- a/src/cli/contractCommand.ts +++ b/src/cli/contractCommand.ts @@ -12,8 +12,14 @@ import { deliverCliAnalysisEvidence } from "./analysisEvidenceDelivery.js"; import { finishCliEvidenceCommand } from "./cliEvidenceCallerPath.js"; import { finishAnalysisCommand } from "./finishAnalysisCommand.js"; import { withCommandCancellation } from "./commandCancellation.js"; +import { parseCliJsonInput, resolveCliJsonPaths } from "../cliJsonInput.js"; +import { jsonInputArgument } from "./jsonInputArgument.js"; import { describeContractCommand, + describeContractDocumentCommand, + type CliDocumentProjection, + type DocumentContract, + type ContractCliDocumentDescription, type CliContractProjection, type CliEvidenceDeliveryChoice, type CliOptionShape, @@ -296,3 +302,97 @@ export const registerContractCommand = < registered.push(description); descriptions.set(cli, registered); }; + +/** What a JSON-document command's handler receives besides the document. */ +export interface ContractDocumentContext< + CliOptions extends Readonly> = Readonly< + Record + >, +> { + readonly signal: AbortSignal; + /** The contract name, which is the canonical operation. */ + readonly operation: string; + /** The document as decoded, before its caller paths were resolved. */ + readonly spelled: unknown; + /** The projection's CLI-only options, whose effect the handler owns. */ + readonly cliOptions: CliOptions; +} + +const documentDescriptions = new WeakMap< + CliInstance, + ContractCliDocumentDescription[] +>(); + +/** Commands registered on this CLI through `registerContractDocumentCommand`. */ +export const contractDocumentCommandDescriptions = ( + cli: CliInstance, +): readonly ContractCliDocumentDescription[] => + documentDescriptions.get(cli) ?? []; + +/** + * Register one CLI command whose whole contract input is one JSON document. + * The handler receives the decoded document with its caller paths made + * absolute, and admits it with the contract's owner. + */ +export const registerContractDocumentCommand = < + Contract extends DocumentContract, + Value, + CliOptions extends CliOptionShape = Record, +>( + cli: CliInstance, + logger: Logger, + contract: Contract, + projection: CliDocumentProjection, CliOptions>, + run: ( + document: unknown, + context: ContractDocumentContext>, + ) => Promise, +): void => { + const description = describeContractDocumentCommand(contract, projection); + const options = Object.fromEntries( + description.cliOnlyOptions.map(({ key, schema }) => [key, schema]), + ); + cli.command(description.command, { + description: description.description, + args: z.object({ + [description.key]: jsonInputArgument( + description.documentDescription, + description.content, + ), + }), + ...(Object.keys(options).length === 0 + ? {} + : { options: z.object(options) }), + run: ({ + args, + options: values, + }: { + readonly args: Readonly>; + readonly options: Readonly>; + }) => + withCommandCancellation((signal) => + logCliCommand(logger, description.command, async () => { + const decoded = await parseCliJsonInput( + args[description.key]!, + contract.name, + signal, + ); + if (!decoded.ok) return decoded.error; + return run( + resolveCliJsonPaths(decoded.value, description.callerPaths), + { + signal, + operation: contract.name, + spelled: decoded.value, + cliOptions: description.cliOptionValues( + values, + ) as CliOptionValues, + }, + ); + }), + ), + } as never); + const registered = documentDescriptions.get(cli) ?? []; + registered.push(description); + documentDescriptions.set(cli, registered); +}; diff --git a/src/cli/electronCommands.ts b/src/cli/electronCommands.ts index acd3505317..dbe3932bde 100644 --- a/src/cli/electronCommands.ts +++ b/src/cli/electronCommands.ts @@ -16,8 +16,9 @@ import { listElectronTargetsInputSchema, } from "../domain/javascript/electronObservation.js"; import { electronActiveObservationInputSchema } from "../domain/javascript/electronActiveObservation.js"; -import { reconcileJavaScriptRuntimeRequestSchema } from "../contracts/javascript/applicationWorkflowInputContracts.js"; -import { getEvidenceInputContract } from "../domain/evidenceInputContract.js"; +import { ELECTRON_TOOL_CONTRACTS } from "../contracts/javascript/electronToolContracts.js"; +import { contractNamed } from "./contractCliDescription.js"; +import { registerContractDocumentCommand } from "./contractCommand.js"; import { AnalysisInputError } from "../domain/analysisErrorCore.js"; import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import { projectInputIssues } from "../domain/inputIssueProjection.js"; @@ -26,7 +27,7 @@ import type { Logger } from "pino"; import { cliDomainInput } from "./domainInput.js"; import { CLI_COMMANDS } from "../cliCommandNames.js"; import { createElectronFuseService } from "../composition/electronFuses.js"; -import { parseCliJsonInput, resolveCliJsonPaths } from "../cliJsonInput.js"; +import { parseCliJsonInput } from "../cliJsonInput.js"; import { electronPageInspectionOptions, javascriptApplicationOptions, @@ -44,7 +45,6 @@ import { evidenceBundleOption, runEvidenceInputCommand, } from "./evidenceInputCommand.js"; -import { jsonInputArgument } from "./jsonInputArgument.js"; /** Register CLI equivalents of the Electron MCP tools. */ export const registerElectronCommands = ( @@ -116,120 +116,90 @@ const registerElectronActiveCommand = ( ) => ElectronActiveObservationPort; }, ): void => { - cli.command(CLI_COMMANDS.captureElectronScenario, { - description: "Run one owned Electron scenario with cancellable actions", - args: z.object({ - inputJson: jsonInputArgument( - "Inline JSON or a JSON file matching capture_electron_scenario", - electronActiveObservationInputSchema, - ), - }), - run: ({ args }) => - withCommandCancellation((signal) => - logCliCommand( - logger, - CLI_COMMANDS.captureElectronScenario, - async () => { - const input = await parseCliJsonInput( - args.inputJson, - "capture_electron_scenario", - signal, - ); - if (!input.ok) return input.error; - const parsed = electronActiveObservationInputSchema.safeParse( - resolveCliJsonPaths(input.value, [ - ["executable_path"], - ["application_path"], - ["application_root"], - ]), - ); - if (!parsed.success) - return inputError( - "capture_electron_scenario", - parsed.error.issues, - input.value, - ); - const { captureElectronScenario } = - await import("../application/javascript/ElectronActiveObservationService.js"); - const provider = - options.createActiveProvider === undefined - ? await import("../composition/electronScenario.js").then( - ({ createElectronScenarioProvider }) => - createElectronScenarioProvider(environment), - ) - : options.createActiveProvider(environment); - const result = await finishAnalysisCommand( - () => captureElectronScenario(provider, parsed.data, { signal }), - { - close: async () => { - await provider.close?.(); - }, - }, - provider.identity().id, - "capture_electron_scenario", - signal, - ); - return result.ok - ? result.value - : { error: "Electron analysis failed", ...result.error }; + registerContractDocumentCommand( + cli, + logger, + contractNamed(ELECTRON_TOOL_CONTRACTS, "capture_electron_scenario"), + { + command: CLI_COMMANDS.captureElectronScenario, + description: "Run one owned Electron scenario with cancellable actions", + document: "Inline JSON or a JSON file matching capture_electron_scenario", + callerPaths: [ + ["executable_path"], + ["application_path"], + ["application_root"], + ], + }, + async (document, { signal, operation, spelled }) => { + const parsed = electronActiveObservationInputSchema.safeParse(document); + if (!parsed.success) + return inputError(operation, parsed.error.issues, spelled); + const { captureElectronScenario } = + await import("../application/javascript/ElectronActiveObservationService.js"); + const provider = + options.createActiveProvider === undefined + ? await import("../composition/electronScenario.js").then( + ({ createElectronScenarioProvider }) => + createElectronScenarioProvider(environment), + ) + : options.createActiveProvider(environment); + const result = await finishAnalysisCommand( + () => captureElectronScenario(provider, parsed.data, { signal }), + { + close: async () => { + await provider.close?.(); }, - ), - ), - }); + }, + provider.identity().id, + operation, + signal, + ); + return result.ok + ? result.value + : { error: "Electron analysis failed", ...result.error }; + }, + ); }; const registerJavaScriptRuntimeReconciliationCommand = ( cli: ReturnType, logger: Logger, -): void => { - cli.command(CLI_COMMANDS.reconcileJavaScriptRuntime, { - description: - "Reconcile static application and passive runtime Evidence JSON", - args: z.object({ - inputJson: jsonInputArgument( +): void => + registerContractDocumentCommand( + cli, + logger, + contractNamed(ELECTRON_TOOL_CONTRACTS, "reconcile_javascript_runtime"), + { + command: CLI_COMMANDS.reconcileJavaScriptRuntime, + description: + "Reconcile static application and passive runtime Evidence JSON", + document: "Inline JSON or a JSON file path matching reconcile_javascript_runtime", - getEvidenceInputContract(reconcileJavaScriptRuntimeRequestSchema) - .frameSchema, - ), - }), - options: z.object({ evidenceBundle: evidenceBundleOption }), - run: ({ args, options }) => - withCommandCancellation((signal) => - logCliCommand( - logger, - CLI_COMMANDS.reconcileJavaScriptRuntime, - async () => { - const input = await parseCliJsonInput( - args.inputJson, - "reconcile_javascript_runtime", - signal, - ); - if (!input.ok) return input.error; - const { reconcileJavaScriptRuntimeEvidence } = - await import("../application/javascript/JavaScriptRuntimeReconciliationService.js"); - const result = await runEvidenceInputCommand( - "reconcile_javascript_runtime", - options.evidenceBundle, - signal, - async (lookup) => { - const reconciled = reconcileJavaScriptRuntimeEvidence( - input.value, - lookup, - { signal }, - ); - return reconciled.ok - ? { ok: true, value: reconciled.value.evidence } - : reconciled; - }, - ); - return result.ok - ? result.value - : { error: "Application workflow failed", ...result.error }; - }, - ), - ), - }); -}; + cliOptions: { evidenceBundle: evidenceBundleOption }, + }, + async (document, { signal, operation, cliOptions }) => { + const { reconcileJavaScriptRuntimeEvidence } = + await import("../application/javascript/JavaScriptRuntimeReconciliationService.js"); + const result = await runEvidenceInputCommand( + operation, + cliOptions.evidenceBundle, + signal, + async (lookup) => { + const reconciled = reconcileJavaScriptRuntimeEvidence( + document, + lookup, + { signal }, + ); + return reconciled.ok + ? { ok: true, value: reconciled.value.evidence } + : reconciled; + }, + ); + return result.ok + ? result.value + : { error: "Application workflow failed", ...result.error }; + }, + ); const registerElectronObservationCommands = ( cli: ReturnType, diff --git a/src/cli/managedCommands.ts b/src/cli/managedCommands.ts index f6be42f30a..ce1c4c00b8 100644 --- a/src/cli/managedCommands.ts +++ b/src/cli/managedCommands.ts @@ -4,9 +4,13 @@ import { z } from "incur"; import { compareManagedMemberPaths } from "../application/managed/ManagedMemberComparisonService.js"; import { executeManagedNativeBoundaries } from "../application/managed/ManagedNativeVerificationService.js"; import { importManagedReconstructionEvidence } from "../application/managed/ManagedReconstructionService.js"; +import { projectManagedApplicationGraphEvidence } from "../application/managed/ManagedApplicationGraphService.js"; +import type { EvidenceLookup } from "../application/EvidenceInputResolver.js"; +import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "../contracts/managed/managedWorkflowToolContracts.js"; +import { contractNamed } from "./contractCliDescription.js"; +import { registerContractDocumentCommand } from "./contractCommand.js"; import type { DirectAnalysis } from "../composition/directAnalysis.js"; import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js"; -import { parseCliJsonInput } from "../cliJsonInput.js"; import { MANAGED_STATIC_PROVIDER } from "../domain/investigationProviders.js"; import { ok } from "../domain/result.js"; import { @@ -17,12 +21,7 @@ import { CLI_COMMANDS } from "../cliCommandNames.js"; import { logCliCommand } from "../cliLogging.js"; import type { Logger } from "pino"; import type { CliInstance } from "./types.js"; -import { registerProjectManagedApplicationGraph } from "./managedProjectGraphCommand.js"; import { managedMembersInputSchema } from "../contracts/managed/managedToolContracts.js"; -import { managedReconstructionImportRequestSchema } from "../domain/managed/managedReconstruction.js"; -import { managedNativeVerificationRequestSchema } from "../domain/managed/managedNativeVerificationSchemas.js"; -import { getEvidenceInputContract } from "../domain/evidenceInputContract.js"; -import { jsonInputArgument } from "./jsonInputArgument.js"; import { localPathStringSchema } from "../domain/localPath.js"; import { withCommandCancellation } from "./commandCancellation.js"; import { finishAnalysisCommand } from "./finishAnalysisCommand.js"; @@ -62,9 +61,7 @@ export const registerManagedCommands = ( registerInspectManagedMembers(cli, logger, runProviderAnalysis); registerInspectManagedNativeBoundaries(cli, logger, runProviderAnalysis); registerCompareManagedMembers(cli, logger); - registerImportManagedReconstruction(cli, logger); - registerVerifyManagedNativeBoundaries(cli, logger); - registerProjectManagedApplicationGraph(cli, logger); + registerManagedWorkflowCommands(cli, logger); }; const registerInspectManagedArtifact = ( @@ -236,86 +233,76 @@ const registerCompareManagedMembers = ( }); }; -const registerImportManagedReconstruction = ( - cli: CliInstance, - logger: Logger, -): void => { - cli.command(CLI_COMMANDS.importManagedReconstruction, { +/** Managed Evidence workflows, each taking its contract input as one JSON document. */ +const MANAGED_WORKFLOWS = [ + { + name: "import_managed_reconstruction", + command: CLI_COMMANDS.importManagedReconstruction, description: "Import decompiler-produced managed reconstruction against exact static member evidence", - args: z.object({ - inputJson: jsonInputArgument( - "Inline managed reconstruction JSON or JSON file path", - getEvidenceInputContract(managedReconstructionImportRequestSchema) - .frameSchema, - ), - }), - options: z.object({ evidenceBundle: evidenceBundleOption }), - run: ({ args, options }) => - withCommandCancellation((signal) => - logCliCommand(logger, "import-managed-reconstruction", async () => { - const input = await parseCliJsonInput( - args.inputJson, - "import-managed-reconstruction", - signal, - ); - if (!input.ok) return input.error; - return runEvidenceInputCommand( - "import_managed_reconstruction", - options.evidenceBundle, - signal, - (lookup) => - Promise.resolve( - importManagedReconstructionEvidence(input.value, lookup, { - signal, - }), - ), - ).then(projectCliAnalysisResult); - }), - ), - }); -}; + document: "Inline managed reconstruction JSON or JSON file path", + workflow: ( + input: unknown, + lookup: EvidenceLookup | undefined, + signal: AbortSignal, + ) => importManagedReconstructionEvidence(input, lookup, { signal }), + }, + { + name: "verify_managed_native_boundaries", + command: CLI_COMMANDS.verifyManagedNativeBoundaries, + description: + "Verify managed P/Invoke declarations against authenticated native Evidence", + document: "Inline managed/native verification JSON or JSON file path", + workflow: ( + input: unknown, + lookup: EvidenceLookup | undefined, + signal: AbortSignal, + ) => { + const result = executeManagedNativeBoundaries(input, lookup, { signal }); + return result.ok ? ok(result.value.evidence) : result; + }, + }, + { + name: "project_managed_application_graph", + command: CLI_COMMANDS.projectManagedApplicationGraph, + description: + "Project authenticated managed static Evidence into an application graph", + document: "Inline managed application graph JSON or JSON file path", + workflow: ( + input: unknown, + lookup: EvidenceLookup | undefined, + signal: AbortSignal, + ) => projectManagedApplicationGraphEvidence(input, lookup, { signal }), + }, +] as const; -const registerVerifyManagedNativeBoundaries = ( +const registerManagedWorkflowCommands = ( cli: CliInstance, logger: Logger, ): void => { - cli.command(CLI_COMMANDS.verifyManagedNativeBoundaries, { - description: - "Verify managed P/Invoke declarations against authenticated native Evidence", - args: z.object({ - inputJson: jsonInputArgument( - "Inline managed/native verification JSON or JSON file path", - getEvidenceInputContract(managedNativeVerificationRequestSchema) - .frameSchema, - ), - }), - options: z.object({ evidenceBundle: evidenceBundleOption }), - run: ({ args, options }) => - withCommandCancellation((signal) => - logCliCommand(logger, "verify-managed-native-boundaries", async () => { - const input = await parseCliJsonInput( - args.inputJson, - "verify-managed-native-boundaries", - signal, - ); - if (!input.ok) return input.error; - return runEvidenceInputCommand( - "verify_managed_native_boundaries", - options.evidenceBundle, - signal, - (lookup) => { - const result = executeManagedNativeBoundaries( - input.value, - lookup, - { signal }, - ); - return Promise.resolve( - result.ok ? ok(result.value.evidence) : result, - ); - }, - ).then(projectCliAnalysisResult); - }), - ), - }); + for (const { + name, + command, + description, + document, + workflow, + } of MANAGED_WORKFLOWS) + registerContractDocumentCommand( + cli, + logger, + contractNamed(MANAGED_WORKFLOW_TOOL_CONTRACTS, name), + { + command, + description, + document, + cliOptions: { evidenceBundle: evidenceBundleOption }, + }, + (input, { signal, operation, cliOptions }) => + runEvidenceInputCommand( + operation, + cliOptions.evidenceBundle, + signal, + (lookup) => Promise.resolve(workflow(input, lookup, signal)), + ).then(projectCliAnalysisResult), + ); }; diff --git a/src/cli/managedProjectGraphCommand.ts b/src/cli/managedProjectGraphCommand.ts deleted file mode 100644 index 8e1838f2e4..0000000000 --- a/src/cli/managedProjectGraphCommand.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { z } from "incur"; - -import { projectManagedApplicationGraphEvidence } from "../application/managed/ManagedApplicationGraphService.js"; -import { CLI_COMMANDS } from "../cliCommandNames.js"; -import { parseCliJsonInput } from "../cliJsonInput.js"; -import { logCliCommand } from "../cliLogging.js"; -import { projectCliAnalysisResult } from "./projectCliAnalysisResult.js"; -import { withCommandCancellation } from "./commandCancellation.js"; -import { - evidenceBundleOption, - runEvidenceInputCommand, -} from "./evidenceInputCommand.js"; -import type { Logger } from "pino"; -import { managedApplicationGraphReferenceInputSchema } from "../domain/managed/managedApplicationGraph.js"; -import { getEvidenceInputContract } from "../domain/evidenceInputContract.js"; -import { jsonInputArgument } from "./jsonInputArgument.js"; -import type { CliInstance } from "./types.js"; - -/** Register managed static-Evidence application graph projection. */ -export const registerProjectManagedApplicationGraph = ( - cli: CliInstance, - logger: Logger, -): void => { - cli.command(CLI_COMMANDS.projectManagedApplicationGraph, { - description: - "Project authenticated managed static Evidence into an application graph", - args: z.object({ - inputJson: jsonInputArgument( - "Inline managed application graph JSON or JSON file path", - getEvidenceInputContract(managedApplicationGraphReferenceInputSchema) - .frameSchema, - ), - }), - options: z.object({ evidenceBundle: evidenceBundleOption }), - run: ({ args, options }) => - withCommandCancellation((signal) => - logCliCommand(logger, "project-managed-application-graph", async () => { - const input = await parseCliJsonInput( - args.inputJson, - "project-managed-application-graph", - signal, - ); - if (!input.ok) return input.error; - return runEvidenceInputCommand( - "project_managed_application_graph", - options.evidenceBundle, - signal, - (lookup) => - Promise.resolve( - projectManagedApplicationGraphEvidence(input.value, lookup, { - signal, - }), - ), - ).then(projectCliAnalysisResult); - }), - ), - }); -}; diff --git a/src/cli/nativeFunctionMatchingCommands.ts b/src/cli/nativeFunctionMatchingCommands.ts index 1ee0d0ae76..fb1918c37d 100644 --- a/src/cli/nativeFunctionMatchingCommands.ts +++ b/src/cli/nativeFunctionMatchingCommands.ts @@ -3,18 +3,18 @@ import type { Logger } from "pino"; import { matchNativeFunctionsFromBundles } from "../application/native/NativeFunctionMatchingService.js"; import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js"; import { matchNativeFunctionsInputSchema } from "../contracts/native/functionMatchingContracts.js"; +import { SESSION_TOOL_CONTRACTS } from "../contracts/sessionToolContracts.js"; import { FUNCTION_COMPARISON_PROVIDER } from "../domain/comparisonEvidenceIdentity.js"; import { CLI_COMMANDS } from "../cliCommandNames.js"; -import { parseCliJsonInput } from "../cliJsonInput.js"; -import { logCliCommand } from "../cliLogging.js"; import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js"; import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import type { Evidence } from "../domain/evidence.js"; -import { withCommandCancellation } from "./commandCancellation.js"; import { cliEvidenceDeliveryInputError, publishCliAnalysisEvidence, } from "./analysisEvidenceDelivery.js"; +import { contractNamed } from "./contractCliDescription.js"; +import { registerContractDocumentCommand } from "./contractCommand.js"; import { finishAnalysisCommand } from "./finishAnalysisCommand.js"; import type { CliInstance } from "./types.js"; import { parseNativeMatchingAllowance } from "../config/nativeMatchingAllowance.js"; @@ -25,83 +25,74 @@ export const registerNativeFunctionMatchingCommands = ( cli: CliInstance, logger: Logger, environment: Readonly, -): void => { - cli.command(CLI_COMMANDS.matchNativeFunctions, { - description: - "Match two observed native function inventories without executing targets", - args: z.object({ - input: z - .string() - .describe( - "JSON or JSON file: left/right inventories, optional observations and detail", - ), - }), - options: z.object({ - source_bundle: z - .array(localPathStringSchema) - .default([]) - .describe( - "Canonical source Evidence bundle for retained references; repeat for each input", - ), - evidence_output: localPathStringSchema - .optional() - .describe( - "Save full matching Evidence and selected sources; required for default summary; never overwrites", - ), - }), - run: ({ args, options }) => - withCommandCancellation((signal) => - logCliCommand(logger, CLI_COMMANDS.matchNativeFunctions, async () => { - const input = await parseCliJsonInput( - args.input, - "match_native_functions", - signal, - ); - if (!input.ok) return input.error; - const parsed = matchNativeFunctionsInputSchema.safeParse(input.value); - if (!parsed.success) - return projectAnalysisError( - analysisInputErrorFromIssues( - "match_native_functions", - parsed.error.issues, - input.value, - ), - ); - const delivery = { - providerId: FUNCTION_COMPARISON_PROVIDER.id, - operation: "match_native_functions", - signal, - detail: parsed.data.detail, - evidenceOutput: options.evidence_output, - }; - const invalid = cliEvidenceDeliveryInputError(delivery); - if (invalid !== undefined) return projectAnalysisError(invalid); - const allowance = parseNativeMatchingAllowance(environment); - if (!allowance.ok) return projectAnalysisError(allowance.error); - const resources = new ArtifactResourceScope(); - let sources: readonly Evidence[] = []; - const complete = await finishAnalysisCommand( - async () => { - const result = await matchNativeFunctionsFromBundles( - parsed.data, - options.source_bundle, - resources, - { signal, representationAllowance: allowance.value }, - ); - if (!result.ok) return result; - sources = result.value.sources; - return { ok: true as const, value: result.value.evidence }; - }, +): void => + registerContractDocumentCommand( + cli, + logger, + contractNamed(SESSION_TOOL_CONTRACTS, "match_native_functions"), + { + command: CLI_COMMANDS.matchNativeFunctions, + description: + "Match two observed native function inventories without executing targets", + document: + "JSON or JSON file: left/right inventories, optional observations and detail", + cliOptions: { + source_bundle: z + .array(localPathStringSchema) + .default([]) + .describe( + "Canonical source Evidence bundle for retained references; repeat for each input", + ), + evidence_output: localPathStringSchema + .optional() + .describe( + "Save full matching Evidence and selected sources; required for default summary; never overwrites", + ), + }, + }, + async (document, { signal, operation, cliOptions }) => { + const parsed = matchNativeFunctionsInputSchema.safeParse(document); + if (!parsed.success) + return projectAnalysisError( + analysisInputErrorFromIssues( + operation, + parsed.error.issues, + document, + ), + ); + const delivery = { + providerId: FUNCTION_COMPARISON_PROVIDER.id, + operation, + signal, + detail: parsed.data.detail, + evidenceOutput: cliOptions.evidence_output, + }; + const invalid = cliEvidenceDeliveryInputError(delivery); + if (invalid !== undefined) return projectAnalysisError(invalid); + const allowance = parseNativeMatchingAllowance(environment); + if (!allowance.ok) return projectAnalysisError(allowance.error); + const resources = new ArtifactResourceScope(); + let sources: readonly Evidence[] = []; + const complete = await finishAnalysisCommand( + async () => { + const result = await matchNativeFunctionsFromBundles( + parsed.data, + cliOptions.source_bundle, resources, - delivery.providerId, - delivery.operation, - signal, + { signal, representationAllowance: allowance.value }, ); - return publishCliAnalysisEvidence(complete, { - ...delivery, - sourceEvidence: sources, - }); - }), - ), - }); -}; + if (!result.ok) return result; + sources = result.value.sources; + return { ok: true as const, value: result.value.evidence }; + }, + resources, + delivery.providerId, + delivery.operation, + signal, + ); + return publishCliAnalysisEvidence(complete, { + ...delivery, + sourceEvidence: sources, + }); + }, + ); diff --git a/src/cli/wasmCommands.ts b/src/cli/wasmCommands.ts index c7349a7d84..2cddba6df9 100644 --- a/src/cli/wasmCommands.ts +++ b/src/cli/wasmCommands.ts @@ -1,16 +1,14 @@ import { projectCliAnalysisResult } from "./projectCliAnalysisResult.js"; import { compareWasmInterfaces } from "../application/wasm/WasmInterfaceComparisonService.js"; -import { parseCliJsonInput } from "../cliJsonInput.js"; import { CLI_COMMANDS } from "../cliCommandNames.js"; -import { z } from "incur"; import { wasmArtifactModule } from "../composition/wasm.js"; -import { logCliCommand } from "../cliLogging.js"; +import { COMPARE_WASM_INTERFACES_CONTRACT } from "../contracts/wasm/wasmComparisonContracts.js"; import type { Logger } from "pino"; import type { CliInstance } from "./types.js"; -import { withCommandCancellation } from "./commandCancellation.js"; import { inspectWithService, registerContractCommand, + registerContractDocumentCommand, } from "./contractCommand.js"; import { evidenceBundleOption, @@ -23,44 +21,35 @@ export const registerWasmCommands = ( logger: Logger, environment: Readonly, ): void => { - cli.command(CLI_COMMANDS.compareWasmInterfaces, { - description: - "Compare core WASM interfaces from two exact inspection Evidence records", - args: z.object({ - input: z - .string() - .describe( - "Inline JSON or input file containing left/right Evidence or retained references and required scope", - ), - }), - options: z.object({ evidenceBundle: evidenceBundleOption }), - run: ({ args, options }) => - withCommandCancellation(async (signal) => - logCliCommand(logger, CLI_COMMANDS.compareWasmInterfaces, async () => { - const input = await parseCliJsonInput( - args.input, - "compare_wasm_interfaces", - signal, + registerContractDocumentCommand( + cli, + logger, + COMPARE_WASM_INTERFACES_CONTRACT, + { + command: CLI_COMMANDS.compareWasmInterfaces, + description: + "Compare core WASM interfaces from two exact inspection Evidence records", + document: + "Inline JSON or input file containing left/right Evidence or retained references and required scope", + cliOptions: { evidenceBundle: evidenceBundleOption }, + }, + (document, { signal, operation, cliOptions }) => + runEvidenceInputCommand( + operation, + cliOptions.evidenceBundle, + signal, + async (lookup) => { + const result = await compareWasmInterfaces( + document, + { signal }, + lookup, ); - if (!input.ok) return input.error; - return runEvidenceInputCommand( - "compare_wasm_interfaces", - options.evidenceBundle, - signal, - async (lookup) => { - const result = await compareWasmInterfaces( - input.value, - { signal }, - lookup, - ); - return result.ok - ? { ok: true, value: result.value.evidence } - : result; - }, - ).then(projectCliAnalysisResult); - }), - ), - }); + return result.ok + ? { ok: true, value: result.value.evidence } + : result; + }, + ).then(projectCliAnalysisResult), + ); const service = wasmArtifactModule.create(environment); registerContractCommand( cli, diff --git a/tests/boundary/cli/analysisViewCli.test.ts b/tests/boundary/cli/analysisViewCli.test.ts index 60dc7cc75e..65918f5ad5 100644 --- a/tests/boundary/cli/analysisViewCli.test.ts +++ b/tests/boundary/cli/analysisViewCli.test.ts @@ -1100,7 +1100,7 @@ cliTest("rejects malformed JSON before projection", async ({ cli }) => { expect(result.json).toMatchObject({ code: "invalid_request", category: "invalid_input", - details: { operation: "inspect-analysis-view" }, + details: { operation: "inspect_analysis_view" }, }); }); diff --git a/tests/boundary/cli/cliContractCommandParity.test.ts b/tests/boundary/cli/cliContractCommandParity.test.ts index 8a9b9503a2..f893c7ebd6 100644 --- a/tests/boundary/cli/cliContractCommandParity.test.ts +++ b/tests/boundary/cli/cliContractCommandParity.test.ts @@ -4,10 +4,15 @@ import { describe, expect, it } from "vitest"; import { createCli } from "../../../src/cli.js"; import { describeContractCommand, + describeContractDocumentCommand, type ContractCliDescription, type ContractCliParameter, } from "../../../src/cli/contractCliDescription.js"; -import { contractCommandDescriptions } from "../../../src/cli/contractCommand.js"; +import { + contractCommandDescriptions, + contractDocumentCommandDescriptions, +} from "../../../src/cli/contractCommand.js"; +import { jsonInputContentSchema } from "../../../src/cli/jsonInputArgument.js"; import { visitRegisteredCommands, type RegisteredCommand, @@ -713,3 +718,151 @@ describe("Evidence delivery of contract commands", () => { ).toThrow("probe.detail differs between input branches"); }); }); + +const documents = contractDocumentCommandDescriptions(cli).map( + (description) => [description.command, description] as const, +); + +/** The JSON Schemas a property path can reach, through unions. */ +const reachable = ( + schema: Record, + path: readonly string[], +): Record[] => { + // A typed schema keeps its own type; `allOf` there only adds constraints. + const branches = + schema.type !== undefined + ? [] + : ["anyOf", "oneOf", "allOf"].flatMap((keyword) => + Array.isArray(schema[keyword]) + ? (schema[keyword] as Record[]) + : [], + ); + if (branches.length > 0) + return branches.flatMap((branch) => reachable(branch, path)); + const [head, ...rest] = path; + if (head === undefined) return [schema]; + const properties = schema.properties as + | Record> + | undefined; + const next = properties?.[head]; + return next === undefined ? [] : reachable(next, rest); +}; + +describe("JSON-document contract commands", () => { + it("registers the migrated document commands", () => { + expect(documents.map(([command]) => command)).toEqual( + expect.arrayContaining([ + "compare-wasm-interfaces", + "import-managed-reconstruction", + "verify-managed-native-boundaries", + "project-managed-application-graph", + "trace-application-feature", + "trace-javascript-semantics", + "compare-application-versions", + "compare-javascript-export-shapes", + "project-android-application-graph", + "project-apple-application-graph", + "project-harmony-application-graph", + "reconcile-javascript-runtime", + "capture-electron-scenario", + "compare-artifacts", + "inspect-analysis-view", + "match-native-functions", + ]), + ); + }); + + it.each(documents)( + "%s takes one JSON document whose --schema is its contract input", + (_command, description) => { + const command = registered.get(description.command)!; + const args = (command.args as z.ZodObject).shape; + expect(Object.keys(args)).toEqual([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. + const input = inputJsonSchema(description.contract.inputSchema); + const fields = new Set( + reachable(input, []).flatMap((branch) => + Object.keys( + (branch.properties as Record | undefined) ?? {}, + ), + ), + ); + for (const field of fields) + expect( + reachable(content, [field]).length > 0 || + Object.hasOwn(description.omitted, field), + field, + ).toBe(true); + for (const field of Object.keys(description.omitted)) + expect(reachable(content, [field]), field).toEqual([]); + expect( + Object.keys( + (command.options as z.ZodObject | undefined)?.shape ?? {}, + ).toSorted(), + ).toEqual(description.cliOnlyOptions.map(({ key }) => key).toSorted()); + }, + ); + + it.each(documents.filter(([, { callerPaths }]) => callerPaths.length > 0))( + "%s resolves only caller paths its contract declares as strings", + (_command, description) => { + const input = inputJsonSchema(description.contract.inputSchema); + for (const path of description.callerPaths) { + const targets = reachable(input, path); + expect(targets.length, path.join(".")).toBeGreaterThan(0); + for (const target of targets) + expect(target.type, path.join(".")).toBe("string"); + } + }, + ); + + it("refuses omissions the document cannot make and options that shadow it", () => { + const contract = { + name: "probe", + inputSchema: z.object({ + required: z.string(), + optional: z.string().optional(), + }), + }; + const projection = { + command: "probe", + description: "Probe", + document: "Probe JSON", + }; + expect(() => + describeContractDocumentCommand(contract, { + ...projection, + omit: { required: "never" }, + }), + ).toThrow("probe.required is not an optional field"); + expect(() => + describeContractDocumentCommand( + { + name: "probe", + inputSchema: z.union([ + z.object({ a: z.string().optional() }), + z.object({ b: z.string() }), + ]), + }, + { ...projection, omit: { a: "never" } }, + ), + ).toThrow("probe omits fields from a union input"); + expect(() => + describeContractDocumentCommand(contract, { + ...projection, + cliOptions: { inputJson: z.string().optional() }, + }), + ).toThrow("probe projects two fields to one CLI key"); + const described = describeContractDocumentCommand(contract, { + ...projection, + omit: { optional: "Not one-shot" }, + }); + expect( + Object.keys(inputJsonSchema(described.content).properties as object), + ).toEqual(["required"]); + }); +}); diff --git a/tests/boundary/cli/jsonInputSchema.test.ts b/tests/boundary/cli/jsonInputSchema.test.ts index d9697381fd..11478550bf 100644 --- a/tests/boundary/cli/jsonInputSchema.test.ts +++ b/tests/boundary/cli/jsonInputSchema.test.ts @@ -30,6 +30,8 @@ import { managedApplicationGraphReferenceInputSchema } from "../../../src/domain import { managedNativeVerificationRequestSchema } from "../../../src/domain/managed/managedNativeVerificationSchemas.js"; import { managedReconstructionImportRequestSchema } from "../../../src/domain/managed/managedReconstruction.js"; import { nativeCallObservationInputSchema } from "../../../src/domain/native/nativeCallObservation.js"; +import { matchNativeFunctionsInputSchema } from "../../../src/contracts/native/functionMatchingContracts.js"; +import { COMPARE_WASM_INTERFACES_CONTRACT } from "../../../src/contracts/wasm/wasmComparisonContracts.js"; import { jsonInputArgument, jsonInputContentSchema, @@ -130,6 +132,14 @@ const documents = [ command: CLI_COMMANDS.compareArtifacts, schema: artifactComparisonInputSchema, }, + { + command: CLI_COMMANDS.compareWasmInterfaces, + schema: frame(COMPARE_WASM_INTERFACES_CONTRACT.inputSchema), + }, + { + command: CLI_COMMANDS.matchNativeFunctions, + schema: frame(matchNativeFunctionsInputSchema), + }, { command: CLI_COMMANDS.captureBrowserScenario, schema: browserScenarioSchema, diff --git a/tests/boundary/cli/jsonInputStatus.test.ts b/tests/boundary/cli/jsonInputStatus.test.ts index bdbec616f5..0dd9b0b3e5 100644 --- a/tests/boundary/cli/jsonInputStatus.test.ts +++ b/tests/boundary/cli/jsonInputStatus.test.ts @@ -7,22 +7,22 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { cliTest } from "../../support/cli/cliFixture.js"; const JSON_COMMANDS = [ - ["inspect-analysis-view", "inspect-analysis-view"], - ["trace-application-feature", "trace-application-feature"], - ["trace-javascript-semantics", "trace-javascript-semantics"], - ["compare-application-versions", "compare-application-versions"], + ["inspect-analysis-view", "inspect_analysis_view"], + ["trace-application-feature", "trace_application_feature"], + ["trace-javascript-semantics", "trace_javascript_semantics"], + ["compare-application-versions", "compare_application_versions"], ["compare-source-to-bundle", "compare-source-to-bundle"], - ["compare-javascript-export-shapes", "compare-javascript-export-shapes"], + ["compare-javascript-export-shapes", "compare_javascript_export_shapes"], [ "build-reconstruction-obligation-ledger", "build-reconstruction-obligation-ledger", ], ["evaluate-reconstruction-coverage", "evaluate-reconstruction-coverage"], - ["project-android-application-graph", "project-android-application-graph"], - ["project-apple-application-graph", "project-apple-application-graph"], - ["import-managed-reconstruction", "import-managed-reconstruction"], - ["verify-managed-native-boundaries", "verify-managed-native-boundaries"], - ["project-managed-application-graph", "project-managed-application-graph"], + ["project-android-application-graph", "project_android_application_graph"], + ["project-apple-application-graph", "project_apple_application_graph"], + ["import-managed-reconstruction", "import_managed_reconstruction"], + ["verify-managed-native-boundaries", "verify_managed_native_boundaries"], + ["project-managed-application-graph", "project_managed_application_graph"], ["capture-browser-scenario", "capture_browser_scenario"], ["capture-electron-scenario", "capture_electron_scenario"], ["reconcile-javascript-runtime", "reconcile_javascript_runtime"], @@ -80,7 +80,7 @@ describe("compiled CLI JSON input failure status", () => { input_path: input, input_reason: kind === "file" ? "invalid-json" : "read-failed", ...(kind === "file" - ? { details: { operation: "compare-javascript-export-shapes" } } + ? { details: { operation: "compare_javascript_export_shapes" } } : {}), }); expect(result.stderr).toBe(""); @@ -160,7 +160,7 @@ describe("compiled CLI JSON input diagnostic preservation", () => { code: "invalid_request", category: "invalid_input", details: { - operation: "compare-javascript-export-shapes", + operation: "compare_javascript_export_shapes", issues: [{ path: [], reason: "invalid_format", expected: "JSON" }], }, }); diff --git a/tests/boundary/filesystem/cliJsonInput.test.ts b/tests/boundary/filesystem/cliJsonInput.test.ts index b569757680..64a365a960 100644 --- a/tests/boundary/filesystem/cliJsonInput.test.ts +++ b/tests/boundary/filesystem/cliJsonInput.test.ts @@ -319,7 +319,7 @@ describe("CLI JSON input", () => { code: "access_denied", category: "unavailable", details: { - operation: "inspect-analysis-view", + operation: "inspect_analysis_view", path, system_code: "EACCES", boundary: "filesystem-read",