refactor(cli): project WASM inspection and firmware commands from their contracts (#10648)

* refactor(cli): project WASM inspection and firmware commands from their contracts

The contract command description gains lists of caller paths and optional object fields flattened into one option per member. inspect-wasm-artifact, inspect-firmware-regions and extract-firmware are derived from their contracts. extract-firmware now records the caller's output_directory spelling in Evidence, like every other caller-path field.

* refactor(cli): project Apple bundle commands onto a declared session target (#10656)

Session-scoped operations take their target from the MCP session, so the CLI's target positional is not a contract field. The contract command description declares a session target: the CLI takes it as the first positional, opens it through runProviderAnalysis as the hand-written commands did, and passes the rest of the contract input. Input issues reported after argv parsing name renamed fields by their CLI key. inspect-keyed-archive, trace-dylib-resolution, inspect-asset-catalog and decode-interface-builder are the pilot; trace-dylib-resolution --root now admits only the roots its contract admits.
This commit is contained in:
morluto authored and GitHub committed 2026-11-15 17:45:33 +08:00
1 parent 26520bd290
commit a761efda70
9 files changed
+592 -404

No files matched your search

+108 -159
View File
@@ -12,15 +12,21 @@ import {
import { withCommandCancellation } from "./commandCancellation.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { ARTIFACT_GRAPH_PROVIDER } from "../domain/investigationProviders.js";
import { keyedArchiveInputSchema } from "../domain/apple/keyedArchive.js";
import { dylibResolutionInputSchema } from "../domain/apple/dylibResolution.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 { artifactExtractionInputSchema } from "../contracts/artifactToolContracts.js";
import {
ARTIFACT_TOOL_CONTRACTS,
artifactExtractionInputSchema,
} from "../contracts/artifactToolContracts.js";
import { contractNamed } from "./contractCliDescription.js";
import {
registerContractCommand,
runOnSessionTarget,
} from "./contractCommand.js";
import type { DirectAnalysis } from "../composition/directAnalysis.js";
import { createArtifactExtractionDestination } from "../application/artifacts/ArtifactExtractionDestination.js";
@@ -30,11 +36,6 @@ import { CLI_COMMANDS } from "../cliCommandNames.js";
import type { Logger } from "pino";
import type { CliInstance } from "./types.js";
const keyedArchiveInputBinding = {
operation: "inspect_keyed_archive",
fields: { path: "archive" },
} as const;
const artifactLimitsOption = producerLimitsOption(
artifactReaderLimitsInputSchema,
"artifact-limits",
@@ -50,157 +51,7 @@ export const registerArtifactCommands = (
registerInspectionCommand(cli, logger, runProviderAnalysis);
registerExtractionCommand(cli, logger, runProviderAnalysis);
registerArtifactComparisonCommand(cli, logger);
registerInterfaceBuilderCommand(cli, logger, runProviderAnalysis);
registerAssetCatalogCommand(cli, logger, runProviderAnalysis);
registerDylibResolutionCommand(cli, logger, runProviderAnalysis);
cli.command(CLI_COMMANDS.inspectKeyedArchive, {
description:
"Inspect a Foundation keyed archive as an object-reference graph",
args: z.object({
path: localPathStringSchema.describe(
"Foundation plist archive or Apple app bundle",
),
archive: keyedArchiveInputSchema.shape.path.describe(
"Relative archive path when the target is a bundle",
),
}),
options: z.object({
root: keyedArchiveInputSchema.shape.root.describe(
"Named $top archive root",
),
// Decimal tokens only: numeric coercion would read "" as 0 and accept
// "0x10" or "1e2".
offset: cliDecimalField(keyedArchiveInputSchema.shape.offset).describe(
"First original object-table index",
),
limit: cliDecimalField(keyedArchiveInputSchema.shape.limit).describe(
"Maximum object-table entries to return",
),
}),
run: ({ args, options }) =>
logCliCommand(logger, CLI_COMMANDS.inspectKeyedArchive, () =>
runProviderAnalysis(
args.path,
keyedArchiveInputBinding.operation,
{
path: args.archive,
offset: options.offset,
limit: options.limit,
...(options.root === undefined ? {} : { root: options.root }),
},
logger,
).then((result) =>
projectCliAnalysisResult(result, keyedArchiveInputBinding),
),
),
});
};
const registerDylibResolutionCommand = (
cli: CliInstance,
logger: Logger,
runProviderAnalysis: DirectAnalysis["runProviderAnalysis"],
): void => {
cli.command(CLI_COMMANDS.traceDylibResolution, {
description:
"Trace dyld load-path resolution for a Mach-O or every executable in an app bundle",
args: z.object({
path: localPathStringSchema.describe(
"Mach-O file or Apple .app bundle path",
),
}),
options: z.object({
root: dylibResolutionInputSchema.shape.roots.describe(
"Process root relative to the bundle or the Mach-O's directory (repeatable)",
),
architecture: z
.enum(["arm64", "arm64e", "x86_64"])
.optional()
.describe("Trace only this slice of each root"),
}),
run: ({ args, options }) =>
logCliCommand(logger, CLI_COMMANDS.traceDylibResolution, () =>
runProviderAnalysis(
args.path,
"trace_dylib_resolution",
{
...(options.root === undefined ? {} : { roots: options.root }),
...(options.architecture === undefined
? {}
: { architecture: options.architecture }),
},
logger,
).then(projectCliAnalysisResult),
),
});
};
const registerAssetCatalogCommand = (
cli: CliInstance,
logger: Logger,
runProviderAnalysis: DirectAnalysis["runProviderAnalysis"],
): void => {
cli.command(CLI_COMMANDS.inspectAssetCatalog, {
description: "Inspect compiled Apple asset catalog metadata",
args: z.object({
path: localPathStringSchema.describe("Apple .app bundle path"),
}),
options: z.object({
offset: cliDecimalField(z.number().int().min(0).default(0)).describe(
"First metadata record",
),
limit: cliDecimalField(
z.number().int().min(1).max(10_000).default(1_000),
).describe("Maximum records to return"),
}),
run: ({ args, options }) =>
logCliCommand(logger, CLI_COMMANDS.inspectAssetCatalog, () =>
runProviderAnalysis(
args.path,
"inspect_asset_catalog",
{ offset: options.offset, limit: options.limit },
logger,
).then(projectCliAnalysisResult),
),
});
};
const registerInterfaceBuilderCommand = (
cli: CliInstance,
logger: Logger,
runProviderAnalysis: DirectAnalysis["runProviderAnalysis"],
): void => {
cli.command(CLI_COMMANDS.decodeInterfaceBuilder, {
description:
"Decode compiled storyboard and nib archives from an app bundle",
args: z.object({
path: localPathStringSchema.describe("Apple .app bundle path"),
}),
options: z.object({
maxDocuments: cliDecimalField(
z.number().int().min(1).max(64).default(64),
).describe("Maximum archives to decode"),
maxObjects: cliDecimalField(
z.number().int().min(1).max(20_000).default(20_000),
).describe("Maximum graph objects"),
maxConnections: cliDecimalField(
z.number().int().min(1).max(40_000).default(40_000),
).describe("Maximum decoded connections"),
}),
run: ({ args, options }) =>
logCliCommand(logger, "decode-interface-builder", () =>
runProviderAnalysis(
args.path,
"decode_interface_builder",
{
max_documents: options.maxDocuments,
max_objects: options.maxObjects,
max_connections: options.maxConnections,
},
logger,
).then(projectCliAnalysisResult),
),
});
registerAppleBundleCommands(cli, logger, runProviderAnalysis);
};
/** Options that read a dump as an ESP flash image with caller inputs. */
@@ -355,3 +206,101 @@ const registerInspectionCommand = (
),
});
};
/**
* Apple bundle resource commands. Each operation runs on the bundle or
* Mach-O an MCP session holds open, so the CLI opens it as the session
* target and passes the rest of the contract input.
*/
const registerAppleBundleCommands = (
cli: CliInstance,
logger: Logger,
runProviderAnalysis: DirectAnalysis["runProviderAnalysis"],
): void => {
const run = runOnSessionTarget(runProviderAnalysis, logger);
const contract = <
Name extends (typeof ARTIFACT_TOOL_CONTRACTS)[number]["name"],
>(
name: Name,
) => contractNamed(ARTIFACT_TOOL_CONTRACTS, name);
registerContractCommand(
cli,
logger,
contract("inspect_keyed_archive"),
{
command: CLI_COMMANDS.inspectKeyedArchive,
description:
"Inspect a Foundation keyed archive as an object-reference graph",
sessionTarget: {
description: "Foundation plist archive or Apple app bundle",
},
positionals: ["path"],
fields: {
path: {
name: "archive",
description: "Relative archive path when the target is a bundle",
},
root: { description: "Named $top archive root" },
offset: { description: "First original object-table index" },
limit: { description: "Maximum object-table entries to return" },
},
},
run,
);
registerContractCommand(
cli,
logger,
contract("trace_dylib_resolution"),
{
command: CLI_COMMANDS.traceDylibResolution,
description:
"Trace dyld load-path resolution for a Mach-O or every executable in an app bundle",
sessionTarget: { description: "Mach-O file or Apple .app bundle path" },
fields: {
roots: {
name: "root",
description:
"Process root relative to the bundle or the Mach-O's directory (repeatable)",
},
architecture: { description: "Trace only this slice of each root" },
},
},
run,
);
registerContractCommand(
cli,
logger,
contract("inspect_asset_catalog"),
{
command: CLI_COMMANDS.inspectAssetCatalog,
description: "Inspect compiled Apple asset catalog metadata",
sessionTarget: { description: "Apple .app bundle path" },
fields: {
offset: { description: "First metadata record" },
limit: { description: "Maximum records to return" },
},
},
run,
);
registerContractCommand(
cli,
logger,
contract("decode_interface_builder"),
{
command: CLI_COMMANDS.decodeInterfaceBuilder,
description:
"Decode compiled storyboard and nib archives from an app bundle",
sessionTarget: { description: "Apple .app bundle path" },
fields: {
max_documents: { description: "Maximum archives to decode" },
max_objects: { description: "Maximum graph objects" },
max_connections: { description: "Maximum decoded connections" },
},
omit: {
detail:
"One-shot output is complete Evidence; this command has no summary delivery",
},
},
run,
);
};
+11 -6
View File
@@ -26,6 +26,7 @@ import { BYTE_ENTROPY_PROVIDER } from "../domain/investigationProviders.js";
import { BINARY_DIAGNOSTICS_TOOL_CONTRACTS } from "../contracts/native/binaryDiagnosticsToolContracts.js";
import { contractNamed } from "./contractCliDescription.js";
import {
callerTargetPath,
deliverWithService,
inspectWithService,
registerContractCommand,
@@ -331,10 +332,12 @@ export const registerBinaryDiagnosticsCommands = (
"One-shot output is complete Evidence; this command has no summary delivery",
},
},
async (input, { signal, callerInputs }) => {
const result = await layout.inspectAndClose(input, { signal });
async (input, context) => {
const result = await layout.inspectAndClose(input, {
signal: context.signal,
});
return result.ok
? withEvidenceCallerInputPath(result.value, callerInputs.path)
? withEvidenceCallerInputPath(result.value, callerTargetPath(context))
: projectAnalysisError(result.error);
},
);
@@ -361,10 +364,12 @@ export const registerBinaryDiagnosticsCommands = (
},
},
},
async (input, { signal, callerInputs }) => {
const result = await recorded.inspectAndClose(input, { signal });
async (input, context) => {
const result = await recorded.inspectAndClose(input, {
signal: context.signal,
});
return result.ok
? withEvidenceCallerInputPath(result.value, callerInputs.path)
? withEvidenceCallerInputPath(result.value, callerTargetPath(context))
: projectAnalysisError(result.error);
},
);
+148 -18
View File
@@ -2,6 +2,7 @@ import { z } from "zod";
import type { AnalysisInputError } from "../domain/analysisErrorCore.js";
import type { AnalysisViewRequest } from "../domain/analysisView/analysisViewRequest.js";
import type { CallerInputPaths } from "../domain/evidence.js";
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
import { localPathStringSchema } from "../domain/localPath.js";
import { err, ok, type Result } from "../domain/result.js";
@@ -63,9 +64,10 @@ export interface CliContractProjection<
/** Fields taken as positional arguments, in argv order. */
readonly positionals?: readonly Field[];
/**
* Absolute-path fields the caller may spell relative to the working
* directory. The CLI admits a nonempty, NUL-free, well-formed path, then
* resolves it with `absoluteCallerPath` before the contract sees it.
* Absolute-path fields, or lists of them, the caller may spell relative to
* the working directory. The CLI admits each nonempty, NUL-free,
* well-formed path, then resolves it with `absoluteCallerPath` before the
* contract sees it.
*/
readonly callerPaths?: readonly Field[];
/**
@@ -85,6 +87,20 @@ 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;
readonly flatten?: {
readonly [Key in Field]?: Readonly<Record<string, CliFieldProjection>>;
};
readonly fields?: { readonly [Key in Field]?: CliFieldProjection };
/**
* Optional fields this one-shot command does not expose, each with the
@@ -135,6 +151,14 @@ export type CliOptionValues<CliOptions extends CliOptionShape> = {
};
/** A bare flag that sets a nullable contract field to null. */
export interface CliSessionTarget {
/** Help for the target positional. */
readonly description: string;
}
/** The CLI key of a session target, which no contract field supplies. */
const SESSION_TARGET_KEY = "path";
export interface CliNullFlag {
readonly key: string;
readonly description: string;
@@ -206,6 +230,8 @@ export interface ContractCliParameter {
readonly runtimeJson: string | undefined;
/** The bare flag that sets this nullable field to null, if any. */
readonly nullFlag: string | undefined;
/** The member of the object field this option supplies, if flattened. */
readonly member: string | undefined;
}
/** The contract input and delivery one invocation selected. */
@@ -258,11 +284,26 @@ export interface ContractCliDescription {
/** Each caller-path field as the caller spelled it, before resolution. */
readonly callerInputs: (
values: Readonly<Record<string, unknown>>,
) => Readonly<Record<string, string>>;
) => CallerInputPaths;
/** The parsed values of the projection's CLI-only options. */
readonly cliOptionValues: (
values: Readonly<Record<string, unknown>>,
) => Readonly<Record<string, unknown>>;
/**
* 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;
/**
* Contract fields the CLI spells differently, so input issues reported
* after argv parsing can name the CLI key.
*/
readonly inputBinding: {
readonly operation: string;
readonly fields: Readonly<Record<string, string>>;
};
/** The command adds `--detail` and `--evidence_output`. */
readonly evidenceDelivery: boolean;
/**
@@ -558,6 +599,7 @@ export const describeContractCommand = <
...jsonTextFields,
...Object.keys(runtimeJsonFields),
...Object.keys(nullFlags),
...Object.keys(projection.flatten ?? {}),
...Object.keys(fieldProjections),
...Object.keys(omitted),
])
@@ -601,9 +643,11 @@ export const describeContractCommand = <
: analysisEvidenceDeliveryOptions.detail;
else if (jsonText) schema = jsonTextField(declared, kebabCase(key));
else if (callerPath) {
schema = admitsOmission(declared)
? localPathStringSchema.optional()
: localPathStringSchema;
const admitted =
core(declared) instanceof z.ZodArray
? z.array(localPathStringSchema)
: localPathStringSchema;
schema = admitsOmission(declared) ? admitted.optional() : admitted;
if (declared.description !== undefined)
schema = schema.describe(declared.description);
} else {
@@ -630,14 +674,61 @@ export const describeContractCommand = <
viewSelection,
runtimeJson,
nullFlag,
member: undefined,
};
};
const flattened: Readonly<
Record<string, Readonly<Record<string, CliFieldProjection>> | undefined>
> = projection.flatten ?? {};
const memberParameters = (field: string): ContractCliParameter[] => {
const declared = shape[field]!;
const object = core(declared);
const members = flattened[field]!;
if (!(object instanceof z.ZodObject) || !admitsOmission(declared))
throw new Error(`${contract.name}.${field} is not an optional object`);
const memberShape = object.shape as Record<string, z.ZodType>;
if (
Object.keys(members).toSorted().join() !==
Object.keys(memberShape).toSorted().join()
)
throw new Error(`${contract.name}.${field} flattens other members`);
return Object.entries(memberShape).map(([member, memberDeclared]) => {
const projected = members[member]!;
assertArgvField(contract.name, `${field}.${member}`, memberDeclared);
let schema = cliDecimalShape({ field: memberDeclared.optional() }).field;
const description = projected.description ?? memberDeclared.description;
if (description !== undefined) schema = schema.describe(description);
const value = core(memberDeclared);
return {
field,
key: projected.name ?? camelCase(member),
positional: false,
alias: projected.alias,
description,
schema,
booleanFlag: value instanceof z.ZodBoolean,
repeatable: value instanceof z.ZodArray,
decimal: value instanceof z.ZodNumber,
callerPath: false,
delivery: false,
jsonText: false,
viewSelection: false,
runtimeJson: undefined,
nullFlag: undefined,
member,
};
});
};
const parameters = [
...positionals,
...Object.keys(shape).filter(
(field) => !positionals.includes(field) && !Object.hasOwn(omitted, field),
),
].map(parameter);
].flatMap((field) =>
flattened[field] === undefined
? [parameter(field)]
: memberParameters(field),
);
const cliOptions: CliOptionShape = projection.cliOptions ?? {};
const cliOnlyOptions: readonly CliOnlyOption[] = [
...Object.values(nullFlags).flatMap((flag) =>
@@ -663,11 +754,17 @@ export const describeContractCommand = <
description: schema.description,
schema,
}));
const sessionTargetKeys =
projection.sessionTarget === undefined ? [] : [SESSION_TARGET_KEY];
const keys = new Set([
...sessionTargetKeys,
...parameters.map(({ key }) => key),
...cliOnlyOptions.map(({ key }) => key),
]);
if (keys.size !== parameters.length + cliOnlyOptions.length)
if (
keys.size !==
sessionTargetKeys.length + parameters.length + cliOnlyOptions.length
)
throw new Error(`${contract.name} projects two fields to one CLI key`);
const cliOptionDependencies = Object.fromEntries(
Object.entries(projection.cliOptionDependencies ?? {}).filter(
@@ -678,20 +775,36 @@ export const describeContractCommand = <
for (const dependency of [key, ...required])
if (!keys.has(dependency))
throw new Error(`${contract.name} has no CLI option ${dependency}`);
const keyOf = new Map(parameters.map(({ field, key }) => [field, key]));
const keyOf = new Map(
parameters.flatMap(({ field, key, member }) =>
member === undefined ? [[field, key] as const] : [],
),
);
const rename = (field: string): string => keyOf.get(field) ?? field;
const toContractInput = (
values: Readonly<Record<string, unknown>>,
): Record<string, unknown> => {
const input: Record<string, unknown> = {};
for (const { field, key, callerPath, delivery } of parameters) {
for (const { field, key, callerPath, delivery, member } of parameters) {
const value = values[key];
if (value === undefined || delivery) continue;
input[field] =
callerPath && typeof value === "string"
? absoluteCallerPath(value)
: value;
if (value === undefined || delivery || member !== undefined) continue;
input[field] = !callerPath
? value
: Array.isArray(value)
? value.map((path: string) => absoluteCallerPath(path))
: absoluteCallerPath(value as string);
}
// Any member given supplies the whole object, absent members included,
// so the contract names the missing companion.
for (const field of Object.keys(flattened)) {
const members = parameters.filter(
(candidate) => candidate.field === field,
);
if (members.some(({ key }) => values[key] !== undefined))
input[field] = Object.fromEntries(
members.map(({ member, key }) => [member, values[key]]),
);
}
for (const { field, nullFlag } of parameters)
if (nullFlag !== undefined && values[nullFlag] === true)
@@ -777,8 +890,8 @@ export const describeContractCommand = <
Object.fromEntries(
parameters.flatMap(({ field, key, callerPath }) => {
const value = values[key];
return callerPath && typeof value === "string"
? [[field, value]]
return callerPath && value !== undefined
? [[field, value as string | readonly string[]]]
: [];
}),
),
@@ -788,6 +901,23 @@ export const describeContractCommand = <
values[key] === undefined ? [] : [[key, values[key]]],
),
),
sessionTarget:
projection.sessionTarget === undefined
? undefined
: {
key: SESSION_TARGET_KEY,
schema: localPathStringSchema.describe(
projection.sessionTarget.description,
),
},
inputBinding: {
operation: contract.name,
fields: Object.fromEntries(
parameters.flatMap(({ field, key, member }) =>
member === undefined && key !== field ? [[field, key]] : [],
),
),
},
evidenceDelivery,
admit: (values) =>
admitInvocation(
+65 -12
View File
@@ -4,7 +4,9 @@ import type { Logger } from "pino";
import { logCliCommand } from "../cliLogging.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
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 { finishCliEvidenceCommand } from "./cliEvidenceCallerPath.js";
@@ -39,7 +41,14 @@ export interface ContractCommandContext<
/** The contract name, which is the canonical operation. */
readonly operation: string;
/** Each caller-path field as the caller spelled it, before resolution. */
readonly callerInputs: Readonly<Record<string, string>>;
readonly callerInputs: CallerInputPaths;
/**
* The session target as the caller spelled it, for a projection with
* `sessionTarget`; undefined otherwise.
*/
readonly sessionTarget: string | undefined;
/** Contract fields the CLI spells differently, for input issue paths. */
readonly inputBinding: ContractCliDescription["inputBinding"];
/** The admitted delivery, for a projection with `evidenceDelivery`. */
readonly delivery: CliEvidenceDeliveryChoice | undefined;
/** The projection's CLI-only options, whose effect the handler owns. */
@@ -55,22 +64,30 @@ export interface EvidenceInspectionService {
close(): Promise<void>;
}
/** The caller's spelling of the selected target `path`. */
export const callerTargetPath = ({
operation,
callerInputs,
}: ContractCommandContext): string => {
const { path } = callerInputs;
if (typeof path !== "string")
throw new Error(`${operation} has no caller path field named path`);
return path;
};
/**
* The caller's spelling of `path`, and of each other caller-path field keyed
* by its contract field name.
*/
const callerSpellings = ({
operation,
callerInputs,
}: ContractCommandContext): {
const callerSpellings = (
context: ContractCommandContext,
): {
readonly path: string;
readonly others: CallerInputPaths | undefined;
} => {
const { path, ...others } = callerInputs;
if (path === undefined)
throw new Error(`${operation} has no caller path field named path`);
const { path: _path, ...others } = context.callerInputs;
return {
path,
path: callerTargetPath(context),
others: Object.keys(others).length === 0 ? undefined : others,
};
};
@@ -95,6 +112,34 @@ export const inspectWithService =
).then(projectCliAnalysisResult);
};
/**
* 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.
*/
export const runOnSessionTarget =
(
runProviderAnalysis: DirectAnalysis["runProviderAnalysis"],
logger: Logger,
) =>
(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<Record<string, JsonValue>>,
logger,
context.signal,
).then((result) => projectCliAnalysisResult(result, context.inputBinding));
};
/** Operations `runProviderAnalysis` runs on an opened session target. */
type SessionTargetOperation = Parameters<
DirectAnalysis["runProviderAnalysis"]
>[1];
/**
* Run an analysis that selects no target path through a closeable service
* and finish its cleanup.
@@ -193,9 +238,12 @@ export const registerContractCommand = <
) => Promise<Value>,
): void => {
const description = describeContractCommand(contract, projection);
const positionals = description.parameters.filter(
({ positional }) => positional,
);
const positionals = [
...(description.sessionTarget === undefined
? []
: [description.sessionTarget]),
...description.parameters.filter(({ positional }) => positional),
];
const alias = Object.fromEntries(
description.parameters.flatMap(({ key, alias: short, positional }) =>
short === undefined || positional ? [] : [[key, short]],
@@ -230,6 +278,11 @@ export const registerContractCommand = <
signal,
operation: contract.name,
callerInputs: description.callerInputs(values),
sessionTarget:
description.sessionTarget === undefined
? undefined
: (values[description.sessionTarget.key] as string),
inputBinding: description.inputBinding,
delivery: admitted.value.delivery,
cliOptions: description.cliOptionValues(
values,
+57 -103
View File
@@ -1,19 +1,19 @@
import { FIRMWARE_OPERATION_ENGINES } from "../contracts/firmware/firmwareToolRequirements.js";
import { projectCliAnalysisResult } from "./projectCliAnalysisResult.js";
import { z } from "incur";
import { FirmwareAnalysisService } from "../application/firmware/FirmwareAnalysisService.js";
import { createFirmwareAnalysisProvider } from "../composition/firmware.js";
import { CLI_COMMANDS } from "../cliCommandNames.js";
import { logCliCommand } from "../cliLogging.js";
import { firmwareInputSchemas } from "../domain/firmware/firmwareAnalysis.js";
import { cliDecimalField } from "./options.js";
import { localPathStringSchema } from "../domain/localPath.js";
import type { FirmwareOperation } from "../domain/firmware/firmwareAnalysis.js";
import type { Logger } from "pino";
import { FirmwareAnalysisService } from "../application/firmware/FirmwareAnalysisService.js";
import { CLI_COMMANDS } from "../cliCommandNames.js";
import { createFirmwareAnalysisProvider } from "../composition/firmware.js";
import { FIRMWARE_TOOL_CONTRACTS } from "../contracts/firmware/firmwareToolContracts.js";
import { FIRMWARE_OPERATION_ENGINES } from "../contracts/firmware/firmwareToolRequirements.js";
import type { FirmwareOperation } from "../domain/firmware/firmwareAnalysis.js";
import { contractNamed } from "./contractCliDescription.js";
import {
inspectWithService,
registerContractCommand,
} from "./contractCommand.js";
import type { CliInstance } from "./types.js";
import { withCommandCancellation } from "./commandCancellation.js";
import { absoluteCallerPath } from "../filesystem/callerPath.js";
import { finishCliEvidenceCommand } from "./cliEvidenceCallerPath.js";
const FIRMWARE_PATH_HELP = "Local firmware path; never executed";
/** One-shot firmware CLI commands backed by the same workflows as MCP. */
export const registerFirmwareCommands = (
@@ -24,97 +24,51 @@ export const registerFirmwareCommands = (
const service = new FirmwareAnalysisService(
createFirmwareAnalysisProvider(environment),
);
const extractInput = firmwareInputSchemas.extract_firmware.shape;
const range = extractInput.range.unwrap().shape;
const execute = (
name: string,
operation: FirmwareOperation,
input: unknown,
callerPath: string,
) =>
withCommandCancellation((signal) =>
logCliCommand(logger, name, () =>
finishCliEvidenceCommand(
callerPath,
() => service.execute(operation, input, { signal }),
service,
FIRMWARE_OPERATION_ENGINES[operation],
operation,
signal,
).then(projectCliAnalysisResult),
),
const run = (operation: FirmwareOperation) =>
inspectWithService(
() => ({
inspect: (input, options) => service.execute(operation, input, options),
close: () => service.close(),
}),
FIRMWARE_OPERATION_ENGINES[operation],
);
const path = localPathStringSchema.describe(
"Local firmware path; never executed",
registerContractCommand(
cli,
logger,
contractNamed(FIRMWARE_TOOL_CONTRACTS, "inspect_firmware_regions"),
{
command: CLI_COMMANDS.inspectFirmwareRegions,
description:
"Inspect firmware signature candidates without extracting them",
positionals: ["path"],
callerPaths: ["path"],
fields: { path: { description: FIRMWARE_PATH_HELP } },
},
run("inspect_firmware_regions"),
);
cli.command(CLI_COMMANDS.inspectFirmwareRegions, {
description:
"Inspect firmware signature candidates without extracting them",
args: z.object({ path }),
options: z.object({
analysisTimeoutMs: cliDecimalField(extractInput.analysis_timeout_ms),
}),
run: ({ args, options }) =>
execute(
CLI_COMMANDS.inspectFirmwareRegions,
"inspect_firmware_regions",
// CLI paths are operator-relative; resolve before shared validation.
{
path: absoluteCallerPath(args.path),
...(options.analysisTimeoutMs === undefined
? {}
: { analysis_timeout_ms: options.analysisTimeoutMs }),
registerContractCommand(
cli,
logger,
contractNamed(FIRMWARE_TOOL_CONTRACTS, "extract_firmware"),
{
command: CLI_COMMANDS.extractFirmware,
description:
"Extract selected firmware bytes and return verified files and provenance",
positionals: ["path", "output_directory"],
callerPaths: ["path", "output_directory"],
flatten: {
range: {
offset: { description: "Selected byte offset; requires length" },
length: { description: "Selected byte length; requires offset" },
},
args.path,
),
});
cli.command(CLI_COMMANDS.extractFirmware, {
description:
"Extract selected firmware bytes and return verified files and provenance",
args: z.object({
path,
outputDirectory: localPathStringSchema.describe(
"Absent output directory; parent must exist",
),
}),
options: z.object({
offset: cliDecimalField(
range.offset
.optional()
.describe("Selected byte offset; requires length"),
),
length: cliDecimalField(
range.length
.optional()
.describe("Selected byte length; requires offset"),
),
maxDepth: cliDecimalField(extractInput.max_depth),
maxOutputBytes: cliDecimalField(extractInput.max_output_bytes),
maxOutputFiles: cliDecimalField(extractInput.max_output_files),
publicationTimeoutMs: cliDecimalField(
extractInput.publication_timeout_ms,
),
analysisTimeoutMs: cliDecimalField(extractInput.analysis_timeout_ms),
}),
run: ({ args, options }) =>
execute(
CLI_COMMANDS.extractFirmware,
"extract_firmware",
{
path: absoluteCallerPath(args.path),
output_directory: absoluteCallerPath(args.outputDirectory),
...(options.offset === undefined && options.length === undefined
? {}
: { range: { offset: options.offset, length: options.length } }),
max_depth: options.maxDepth,
max_output_bytes: options.maxOutputBytes,
max_output_files: options.maxOutputFiles,
publication_timeout_ms: options.publicationTimeoutMs,
...(options.analysisTimeoutMs === undefined
? {}
: { analysis_timeout_ms: options.analysisTimeoutMs }),
},
fields: {
path: { description: FIRMWARE_PATH_HELP },
output_directory: {
description: "Absent output directory; parent must exist",
},
args.path,
),
});
},
},
run("extract_firmware"),
);
};
+31 -94
View File
@@ -1,5 +1,4 @@
import { projectCliAnalysisResult } from "./projectCliAnalysisResult.js";
import { localPathStringSchema } from "../domain/localPath.js";
import { compareWasmInterfaces } from "../application/wasm/WasmInterfaceComparisonService.js";
import { parseCliJsonInput } from "../cliJsonInput.js";
import { CLI_COMMANDS } from "../cliCommandNames.js";
@@ -7,19 +6,16 @@ import { z } from "incur";
import { wasmArtifactModule } from "../composition/wasm.js";
import { logCliCommand } from "../cliLogging.js";
import type { Logger } from "pino";
import { cliDecimalField } from "./options.js";
import type { CliInstance } from "./types.js";
import { withCommandCancellation } from "./commandCancellation.js";
import { absoluteCallerPath } from "../filesystem/callerPath.js";
import { finishCliEvidenceCommand } from "./cliEvidenceCallerPath.js";
import {
inspectWithService,
registerContractCommand,
} from "./contractCommand.js";
import {
evidenceBundleOption,
runEvidenceInputCommand,
} from "./evidenceInputCommand.js";
import {
inspectWasmArtifactInputSchema,
wasmArtifactPathsSchema,
} from "../domain/wasm/wasmArtifact.js";
/** Resolve all caller-selected artifact paths through the shared workflow. */
export const registerWasmCommands = (
@@ -66,90 +62,31 @@ export const registerWasmCommands = (
),
});
const service = wasmArtifactModule.create(environment);
cli.command(wasmArtifactModule.cliCommand, {
description: "Inspect an explicit local WASM artifact with WABT",
args: z.object({
path: localPathStringSchema.describe("Local WASM artifact"),
}),
options: z.object({
commandTimeoutMs: cliDecimalField(
inspectWasmArtifactInputSchema.shape.command_timeout_ms,
),
maxInterfaceBytes: cliDecimalField(
inspectWasmArtifactInputSchema.shape.max_interface_bytes,
),
maxArtifactPaths: cliDecimalField(
inspectWasmArtifactInputSchema.shape.max_artifact_paths,
),
maxInputBytes: cliDecimalField(
inspectWasmArtifactInputSchema.shape.max_input_bytes,
),
maxToolBytes: cliDecimalField(
inspectWasmArtifactInputSchema.shape.max_tool_bytes,
),
maxOutputBytes: cliDecimalField(
inspectWasmArtifactInputSchema.shape.max_output_bytes,
),
glue_paths: wasmArtifactPathsSchema(localPathStringSchema)
.optional()
.describe("Selected local JavaScript glue paths"),
candidate_paths: wasmArtifactPathsSchema(localPathStringSchema)
.optional()
.describe("Explicit local WASM candidates"),
}),
run: ({ args, options }) =>
withCommandCancellation((signal) =>
logCliCommand(logger, wasmArtifactModule.cliCommand, () =>
finishCliEvidenceCommand(
args.path,
() =>
service.inspect(
{
path: absoluteCallerPath(args.path),
...(options.commandTimeoutMs === undefined
? {}
: { command_timeout_ms: options.commandTimeoutMs }),
...(options.maxInterfaceBytes === undefined
? {}
: { max_interface_bytes: options.maxInterfaceBytes }),
...(options.maxArtifactPaths === undefined
? {}
: { max_artifact_paths: options.maxArtifactPaths }),
...(options.maxInputBytes === undefined
? {}
: { max_input_bytes: options.maxInputBytes }),
...(options.maxToolBytes === undefined
? {}
: { max_tool_bytes: options.maxToolBytes }),
...(options.maxOutputBytes === undefined
? {}
: { max_output_bytes: options.maxOutputBytes }),
glue_paths: options.glue_paths?.map((path) =>
absoluteCallerPath(path),
),
candidate_paths: options.candidate_paths?.map((path) =>
absoluteCallerPath(path),
),
},
{ signal },
),
service,
"wabt-artifact",
"inspect_wasm_artifact",
signal,
options.glue_paths === undefined &&
options.candidate_paths === undefined
? undefined
: {
...(options.glue_paths === undefined
? {}
: { glue_paths: options.glue_paths }),
...(options.candidate_paths === undefined
? {}
: { candidate_paths: options.candidate_paths }),
},
).then(projectCliAnalysisResult),
),
),
});
registerContractCommand(
cli,
logger,
wasmArtifactModule.contract,
{
command: wasmArtifactModule.cliCommand,
description: "Inspect an explicit local WASM artifact with WABT",
positionals: ["path"],
callerPaths: ["path", "glue_paths", "candidate_paths"],
fields: {
path: { description: "Local WASM artifact" },
glue_paths: {
name: "glue_paths",
description: "Selected local JavaScript glue paths",
},
candidate_paths: {
name: "candidate_paths",
description: "Explicit local WASM candidates",
},
},
omit: {
detail:
"One-shot output is complete Evidence; this command has no summary delivery",
},
},
inspectWithService(() => service, "wabt-artifact"),
);
};
@@ -121,6 +121,14 @@ const expectedAdmission = (
if (parameter.callerPath) {
// A caller path is validated as typed: an empty value never becomes the
// working directory. A nonempty value is resolved, then the contract rules.
if (Array.isArray(value))
return (
value.every((path) => typeof path === "string" && path !== "") &&
admits(
contractField,
value.map((path: string) => absoluteCallerPath(path)),
)
);
if (typeof value !== "string") return admits(contractField, value);
return value !== "" && admits(contractField, absoluteCallerPath(value));
}
@@ -143,6 +151,20 @@ const registeredField = (
const contractShape = (description: ContractCliDescription) =>
description.fields;
/** The contract schema one parameter supplies: a field, or a flattened member. */
const suppliedField = (
description: ContractCliDescription,
parameter: ContractCliParameter,
): z.ZodType => {
const field = contractShape(description)[parameter.field]!;
if (parameter.member === undefined) return field;
let object: z.ZodType = field;
while (object instanceof z.ZodOptional) object = object.unwrap() as z.ZodType;
return (
(object as z.ZodObject).shape[parameter.member] as z.ZodType
).optional();
};
/** A caller-relative target, or the first probe the argument admits. */
const requiredValue = (
description: ContractCliDescription,
@@ -150,7 +172,7 @@ const requiredValue = (
): unknown =>
parameter.callerPath
? "rel/target"
: probes(contractShape(description)[parameter.field]!).find(
: probes(suppliedField(description, parameter)).find(
(value) =>
value !== undefined &&
admits(registeredField(description, parameter), value),
@@ -217,6 +239,13 @@ describe("CLI commands projected from tool contracts", () => {
"decode-signal-recording",
"inspect-packet-fields",
"inspect-packet-capture",
"inspect-wasm-artifact",
"inspect-firmware-regions",
"extract-firmware",
"inspect-keyed-archive",
"trace-dylib-resolution",
"inspect-asset-catalog",
"decode-interface-builder",
]),
);
});
@@ -226,7 +255,7 @@ describe("CLI commands projected from tool contracts", () => {
(_command, description) => {
expect(
[
...description.parameters.map(({ field }) => field),
...new Set(description.parameters.map(({ field }) => field)),
...Object.keys(description.omitted),
]
.toSorted()
@@ -239,11 +268,14 @@ describe("CLI commands projected from tool contracts", () => {
const optionKeys = Object.keys(
(command.options as z.ZodObject | undefined)?.shape ?? {},
);
expect(argKeys).toEqual(
description.parameters
expect(argKeys).toEqual([
...(description.sessionTarget === undefined
? []
: [description.sessionTarget.key]),
...description.parameters
.filter(({ positional }) => positional)
.map(({ key }) => key),
);
]);
expect(optionKeys.toSorted()).toEqual(
[
...description.parameters
@@ -261,13 +293,19 @@ describe("CLI commands projected from tool contracts", () => {
const mismatches: string[] = [];
for (const parameter of description.parameters) {
const cliField = registeredField(description, parameter);
const contractField = contractShape(description)[parameter.field]!;
const contractField = suppliedField(description, parameter);
// Incur's help reads flag and choice types only through `optional`.
expect(cliField, parameter.key).not.toBeInstanceOf(z.ZodExactOptional);
if (parameter.callerPath) {
// Only the absolute-path rule is relaxed, and only by resolution.
expect(admits(contractField, "rel/x"), parameter.field).toBe(false);
expect(admits(contractField, absoluteCallerPath("rel/x"))).toBe(true);
const spelled = (path: string) =>
parameter.repeatable ? [path] : path;
expect(admits(contractField, spelled("rel/x")), parameter.field).toBe(
false,
);
expect(
admits(contractField, spelled(absoluteCallerPath("rel/x"))),
).toBe(true);
}
if (parameter.runtimeJson !== undefined) {
// JSON text decoded when the command runs; see below.
@@ -320,7 +358,9 @@ describe("CLI commands projected from tool contracts", () => {
}
},
);
});
describe("Registration refusals of contract commands", () => {
it.each([
["an object", z.object({ value: z.string() }).optional()],
["a record", z.record(z.string(), z.string()).optional()],
@@ -512,6 +552,115 @@ describe("Null-limit flags of contract commands", () => {
);
});
const flattening = each.filter(([, description]) =>
description.parameters.some(({ member }) => member !== undefined),
);
describe("Flattened object fields of contract commands", () => {
it.each(flattening)(
"%s supplies the whole object when any member is given",
(_command, description) => {
const members = description.parameters.filter(
({ member }) => member !== undefined,
);
const field = members[0]!.field;
expect(
field in description.toContractInput(argvValues(description, {})),
).toBe(false);
for (const given of members) {
const input = description.toContractInput(
argvValues(description, { [given.key]: 1 }),
);
expect(Object.keys(input[field] as object).toSorted()).toEqual(
members.map(({ member }) => member).toSorted(),
);
expect((input[field] as Record<string, unknown>)[given.member!]).toBe(
1,
);
}
},
);
it("refuses to flatten part of an object or a non-object field", () => {
const contract = {
name: "probe",
inputSchema: z.object({
range: z.object({ a: z.number(), b: z.number() }).optional(),
value: z.string().optional(),
}),
};
expect(() =>
describeContractCommand(contract, {
command: "probe",
description: "Probe",
flatten: { range: { a: {} } },
}),
).toThrow("probe.range flattens other members");
expect(() =>
describeContractCommand(contract, {
command: "probe",
description: "Probe",
flatten: { range: { a: {}, b: {} }, value: { a: {} } },
}),
).toThrow("probe.value is not an optional object");
});
});
const sessionTargeted = each.filter(
([, description]) => description.sessionTarget !== undefined,
);
describe("Session targets of contract commands", () => {
it.each(sessionTargeted)(
"%s takes the session target first and keeps it out of the contract input",
(_command, description) => {
const target = description.sessionTarget!;
const command = registered.get(description.command)!;
const args = (command.args as z.ZodObject).shape;
expect(Object.keys(args)[0]).toBe(target.key);
for (const value of ["rel/app", "/abs/app"])
expect(admits(args[target.key] as z.ZodType, value)).toBe(true);
for (const value of [undefined, "", "a\0b"])
expect(admits(args[target.key] as z.ZodType, value)).toBe(false);
const values = {
...argvValues(description, {}),
[target.key]: "rel/app",
};
expect(Object.values(description.toContractInput(values))).not.toContain(
"rel/app",
);
expect(description.callerInputs(values)).toEqual({});
},
);
it.each(sessionTargeted)(
"%s names each renamed contract field by its CLI key in input issues",
(_command, description) => {
expect(description.inputBinding.operation).toBe(
description.contract.name,
);
for (const { field, key, member } of description.parameters)
if (member === undefined)
expect(description.inputBinding.fields[field]).toBe(
key === field ? undefined : key,
);
},
);
it("refuses a session target beside a contract field keyed path", () => {
expect(() =>
describeContractCommand(
{ name: "probe", inputSchema: z.object({ path: z.string() }) },
{
command: "probe",
description: "Probe",
sessionTarget: { description: "Target" },
},
),
).toThrow("probe projects two fields to one CLI key");
});
});
const delivering = each.filter(
([, description]) => description.evidenceDelivery,
);
@@ -202,9 +202,9 @@ describe("CLI advertised input schemas", () => {
expect(options?.safeParse({}).success).toBe(true);
expect(validate({})).toBe(true);
expect(options?.safeParse({ commandTimeoutMs: undefined }).success).toBe(
false,
);
// Argv omits an absent option rather than passing undefined, so the
// contract's own default applies.
expect(options?.parse({})).not.toHaveProperty("commandTimeoutMs");
for (const commandTimeoutMs of [1, 30_000, 2_147_483_647]) {
expect(options?.safeParse({ commandTimeoutMs }).success).toBe(true);
expect(validate({ commandTimeoutMs })).toBe(true);
+12 -1
View File
@@ -51,13 +51,24 @@ const expectRootInputError = async (
environment: ENVIRONMENT,
});
expect(rejected.exitCode).toBe(1);
// The contract's root syntax is checked at argv parsing; facts about the
// selected file are checked by the analysis. Both name the CLI option.
if (reason === "invalid_format") {
expect(rejected.json).toMatchObject({
code: "VALIDATION_ERROR",
fieldErrors: [
{ path: "root.0", message: expect.stringContaining(message) },
],
});
return;
}
expect(rejected.json).toMatchObject({
error: "Analysis failed",
code: "invalid_request",
details: {
issues: [
{
path: ["roots", 0],
path: ["root", 0],
reason,
message: expect.stringContaining(message),
},