Files
reverse-engineering-anything/tests/boundary/cli/cliContractCommandParity.test.ts
T
morluto 897784042a fix(native)!: report a target-selected plist against the target, not the unsent path input (#10798)
* fix(native): report a target-selected plist against the target, not the unsent path input

inspect_plist resolved a plist that the open target itself selects with the same origin as a caller's path input, so an unreadable target plist was reported as an input issue on path even when the caller never sent path. The selection now records a target origin, and unreadablePlist reports it as a BinaryTargetError for the target. The inspect-plist CLI command is projected from its contract, so its --relative-path issues are named by the CLI key.

* refactor(cli)!: route analyze to the contract its target selects (#10808)

* refactor(cli): route analyze to the contract its target selects

analyze hand-declared both lanes: native open options for binary_overview and the JavaScript integrity policy and source selection for analyze_javascript_application, with its own routing and refusals. registerTargetRoutedCommand now projects each route from its contract, takes the union of their options, runs the first route that owns every given option and takes the target, and refuses options the chosen route does not own by their CLI key. Omitted union fields, including a root discriminator, no longer need an argv projection.

* fix(cli): give a routed command's chosen route its CLI-only option defaults

Routing strips option defaults so an omitted option routes no target. Contract fields regain theirs on admission, but CLI-only options have no later parse, so a defaulted one reached the handler as undefined. The chosen route's omitted CLI-only options now receive their defaults before the handler runs.

* refactor(cli): deliver decompile and inspect-macho Evidence by the contract's detail (#10813)

* refactor(cli): deliver decompile and inspect-macho Evidence by the contract's detail

decompile and inspect-macho omitted the contract's detail field and always printed complete Evidence. Both now declare evidenceDelivery, adding --detail and --evidence_output from the contract. Publishing a result never used the provider id it required, so publication takes no provider and runOnSessionTarget no longer needs one to deliver.

* refactor(cli): project managed artifact and native-boundary inspectors from their contracts (#10816)

inspect-managed-artifact and inspect-managed-native-boundaries re-declared the managed budget fields by hand. Both now register from their contracts on a session target, and inspect-managed-artifact gains --detail and --evidence_output from its detail field.

* fix(cli): name every contract command's input issues by their CLI key

Commands applied their CLI field binding only where a session-target or
direct handler returned an undelivered result. With evidenceDelivery,
decompile publishes through the shared delivery, which returned a
provider failure unprojected, so an issue about the procedure would be
reported at ["procedure"] instead of the advertised positional
"address". Handlers that run a service or publish themselves never
applied it: inspect-il2cpp-metadata reported ["generic_instances"],
inspect-go-binary ["max_string_literals"] and inspect-apple-ips
["join_path"] rather than the CLI keys other commands report.

The contract command now projects whatever its handler returns through
the binding it owns, for plain and target-routed commands alike, and
the handler context no longer carries the binding.

* fix(analysis-view): summarize pseudocode that selected an independent fresh decompile

The pseudocode view parsed its parent's parameters with a selection
schema that admitted only procedure and document. A procedure_pseudo_code
observation made with analysis independent_fresh records that field, so
its summary view refused the parent. Through the CLI's new summary
delivery, `decompile --analysis independent_fresh --detail summary
--evidence_output <file>` would fail after a successful decompile and
never save the bundle; an inline inspect_analysis_view of such Evidence
failed the same way.

The selection schema now admits the analysis the contract offers, and
the contract reads that enum from the same owner.

* test(cli): restore the worker's exit status after synthetic contract command runs

logCliCommand sets process.exitCode on a refused or failed command. The
synthetic routed and input-field harnesses ran in the cli-boundary
project's shared workers (isolate: false) and left that status for later
tests. Each invocation now restores the previous status.

* refactor(cli)!: deliver inspect-managed-members Evidence through the shared --evidence_output (#10845)

inspect-managed-members was the last command with its own Evidence
delivery: a hand-written registration passed --detail and
--evidence-bundle to runProviderAnalysis, whose members-only delivery
variant re-checked heap headroom and published through
deliverAnalysisEvidence. Every other producer writes its bundle with
--evidence_output through publishCliAnalysisEvidence, and elsewhere on
the CLI --evidence-bundle names an input bundle to read.

The command now registers from the inspect_managed_members contract on
a session target with evidenceDelivery, like inspect-managed-artifact;
--type is the contract's type_names. runProviderAnalysis loses its
delivery parameter and its two refusals, and deliverAnalysisEvidence,
now unused, is deleted. Its lifecycle tests drive publishEvidenceDelivery
directly or the CLI delivery; the managed-only headroom pre-check tests
are removed, since the shared delivery deliberately does not
re-authenticate immutable Evidence and keeps the writer's check for
mutable sources.

BREAKING CHANGE: `rea inspect-managed-members --evidence-bundle <path>`
is now `--evidence_output <path>`; the old flag is refused as an unknown
flag. With `--detail summary`, stdout is now
`{"summary": <summary Evidence>, "evidence_bundle": {"path", "bytes"}}`
instead of the summary Evidence alone, and a publication failure is the
shared delivery's error projection without the `error` label or
`input_path`. A summary without a destination names `evidence_output`
in its issue path. Migrate by renaming the flag and reading
`.summary`. Compatibility is not kept: one spelling cannot mean "read
this bundle" on view and workflow commands and "write this bundle" on
one producer.

* refactor(cli): project analyze-javascript-application and analyze's JavaScript route from one contract projection

analyze-javascript-application declared its options by hand, mapped
about twelve option names to contract fields itself, parsed its delivery
separately and resolved its own caller path. analyze's JavaScript route,
projected from the same contract, omitted every field but the path,
source selection and integrity policy, so the two commands for one
contract offered different options.

Both now use javaScriptApplicationCliProjection and
runJavaScriptApplicationCommand: the path positional, --artifact-format,
--source-path, and the two options that accept a JSON file
(--source-paths-json, --semantic-precision), with contract delivery.
analyze therefore takes the JavaScript budgets, --artifact-format,
--semantic-precision and --detail/--evidence_output/--view for
JavaScript targets, and refuses them by CLI key for native targets.
javascriptApplicationOptions is deleted.

The command's missing-target refusal now names its CLI key, "path",
as every contract command does.

* refactor(cli): project the apktool commands from their contracts (#10878)

* refactor(cli): project the apktool commands from their contracts

* refactor(cli): project the Flutter commands from their contracts (#10882)

* refactor(cli): project the Flutter commands from their contracts

* refactor(cli): project the JEB commands from their contracts (#10888)

* refactor(cli): project the JEB commands from their contracts

* refactor(cli): project the Android package, class, method and reference commands from their contracts (#10893)

* refactor(cli): compose compare-managed-members from its contract over two inspected targets (#10914)

* refactor(cli): compose compare-managed-members from its contract over two inspected targets

The contract command builder takes Evidence targets: required contract
fields that each take the Evidence a source contract produces for one
positional target, with the source's options admitted for every target.
compare-managed-members now inspects each path through the typed managed
runner, as inspect-managed-members does, and compares the records as MCP
compare_managed_members does. A failing candidate names its argument and
retains the baseline's Evidence; a cancellation as the comparison settles
retains the comparison. The path-only comparison service is removed.

* fix(cli): drain queued interrupts before a composed command settles

Select snapshot faults by file identity, guard real permission denial to
hosts that enforce it, and release retained owners when a test fails.

* refactor(cli): project the ADB commands from their contracts (#10934)

Each ADB command is registered from its ADB_TOOL_CONTRACTS entry through
registerContractCommand, keeping its positionals, flags and kebab-case path
keys. start-adb-activity keeps its repeatable --extra type:key:value option,
which supplies the contract's extras.

* refactor(cli): project Frida discovery from its contracts and share Frida request mapping with MCP (#10951)

list-frida-devices and list-frida-processes are registered from their
contracts, with each remote member as its own option, and admit the request
MCP would send. instrument-with-frida keeps its argv but builds and admits
the instrument_with_frida contract input. One application owner maps Frida
contract inputs to service requests for both adapters.

* refactor(cli): finalize the Evidence-target composition through runOwned

runOnEvidenceTargets turned a completed comparison into a cancellation by reading the abort signal by hand, which main's architecture guard now refuses outside runOwned. The composition now finalizes through runOwned: its close drains queued interrupts (it owns no resource), and a cancellation observed as it settles keeps the completed Evidence as the partial observation, as before.

* fix(errors)!: keep every completed argument's observation beside a composite failure's own partial (#10961)

* fix(errors): keep every completed argument's observation beside a composite failure's own partial

* test(errors): cover argument observations through cleanup composition and the partial-free fallback

* test(errors): settle the cleanup through its owner's release in the argument-observation case

* refactor(cli): project instrument-with-frida through the contract builder (#10962)

* refactor(cli): project instrument-with-frida through the contract builder with CLI-only positionals and handler-filled fields

* fix(cli): keep omitted flattened members omitted so partial capture limits keep their Evidence

* refactor(cli): project the CDP page-target browser commands from their contracts (#10976)

* refactor(cli): project the CDP page-target browser commands from their contracts

* refactor(cli): project inspect-web-page from its contract with a branch-selecting flag

* test(cli): enroll the browser commands in the parity registration check and refuse unenrolled argv fixtures

* refactor(cli): project the V8 Inspector and Electron commands from their contracts (#10977)

* refactor(cli): project the V8 Inspector runtime commands from their contracts

* test(cli): enroll the V8 Inspector runtime commands in the parity registration check

* refactor(cli): project the Electron page observation commands from their contracts (#10987)

* refactor(cli): project the Electron page observation commands from their contracts

* test(cli): enroll the Electron page observation commands in the parity registration check

* refactor(cli): project inspect-electron-fuses from its contract with the shared caller-path rule

The command now registers through registerContractCommand with `path` as a
caller path, so the builder's absoluteCallerPath owns relative-path
anchoring and the command's own absoluteElectronFusePath copy is removed.
inspectWithService records the caller's spelling as caller_input_path.

The named file is unchanged: every `..` is kept for the filesystem, and
Win32 resolves as before. The recorded selected_path drops `.` segments
and repeated separators (`App.app/./` -> `App.app/`), and an empty path is
now refused at argv parsing (VALIDATION_ERROR) like every other
caller-path command.

* test(cli): derive contract-built commands from the builder registries instead of a hand list

Every command named after a public tool contract must register through a contract builder unless it is in a shrinking list of hand registrations, and the renamed contract commands are listed exactly, so an earlier migration that reverts fails instead of dropping out of the parity cases. The JSON-document command hand list is covered by the same check and removed.

* test(cli): drop the empty inspect-electron-fuses path mismatch the CLI now refuses

* refactor(cli): project compare-web-screenshots and analyze-web-bundle from their contracts with builder JSON inputs (#11012)

* refactor(cli): project compare-web-screenshots from its contract with builder JSON inputs read from inline text or a file

The contract command builder gains jsonInputs: structured fields taken as inline JSON or a JSON file path (- reads stdin), read when the command runs and admitted with the contract input before any target is opened. Inline text that is not JSON is refused under its CLI key; a file that cannot be read keeps its own failure. compare-web-screenshots takes both artifacts this way, replacing its hand-written JSON argument parsing.

* refactor(cli): project analyze-web-bundle from its contract

analyze-web-bundle now registers through registerContractCommand with Evidence and view delivery, semantic_precision as a builder JSON input, and source_map_limits flattened onto the existing --source-map-* flags. Page-inspection extras stay omitted, and script sources stay on as the contract default. The superseded javascriptRouteDelivery options, passive browser scope options, observation duration helper and fetched source-map option set are removed.

* refactor(cli): take semantic_precision of JavaScript application analysis as a builder JSON input

analyze-javascript-application and the analyze route read --semantic-precision through the contract builder's jsonInputs instead of a CLI-only option decoded in the handler, so the decoded budgets are admitted with the contract input before analysis.

* refactor(cli): route compare-web-captures to the contract input shape its documents select (#11027)

* refactor(cli): route compare-web-captures to the contract input shape its documents select

* fix(cli): keep routed defaults advertised and reuse the admitted capture parse

* fix(cli): keep explicit routed options distinct from advertised defaults

* refactor(cli): project inspect-ntfs-journal from its contract (#11043)

* refactor(cli): project inspect-ntfs-journal from its contract

* refactor(cli): project the pcap commands from their contracts (#11045)

* refactor(cli): project the pcap commands from their contracts

* refactor(cli): project inspect-playwright-trace, the Cutter commands and execute-rizin-command from their contracts (#11046)

* refactor(cli): project inspect-playwright-trace from its contract

* refactor(cli): project the Cutter commands from their contracts (#11047)

* refactor(cli): project the Cutter commands from their contracts

* refactor(cli): project execute-rizin-command from its contract (#11048)

* fix(cli): refuse a selected page without summary delivery before opening the target

* refactor(cli): project export-web-scripts and trace-web-module-imports from their contracts (#11053)

* refactor(cli): project export-web-scripts and trace-web-module-imports from their contracts

* fix(cli): describe export-web-scripts paths as resolved against the working directory

* refactor(cli): project the web runtime and JavaScript recovery commands from their contracts (#11084)

* refactor(cli): project the web runtime commands from their contracts

* refactor(cli): project recover-javascript-sources from its contract

* refactor(cli): select a contract input branch by its literal field and project guided-workflows (#11085)

* refactor(cli): select a contract input branch by its literal field and project guided-workflows

* fix(cli): refuse delivery options before reading JSON inputs

* fix(cli): keep branch-only defaults to their branch and name admission issues by CLI key

A branch-only field no longer carries its default into the shared options, so another branch never receives it; the selected branch applies the default on parse. Contract admission failures are projected to CLI keys like handler failures. CLI defaults are typed only on top-level fields, the one place that applies them.

* refactor(cli): project compare-process-captures from its contract, checking each capture before reading the next (#11114)

* refactor(cli): project compare-process-captures from its contract, checking each capture before reading the next

The contract builder gains jsonInputChecks: each check runs on a decoded JSON input as soon as it is read, in argv order, so a refused input stops the command before the next is read; the handler receives what each check admitted. compare-process-captures authenticates the left capture before reading the right and the right before the trace specification, then compares the authenticated facts. It now also takes inline JSON, stdin and --max-capture-age-ms like MCP. Empty JSON input text is refused at argv. A JSON input whose final file close fails is reported as cleanup_incomplete naming the file instead of an unclassified failure. compareProcessEvidenceFiles and its trace-spec parser are removed.

* fix(cli): retry a refused JSON input close and keep the read's refusal beside incomplete cleanup

parseCliJsonInput gives the file's owner a resource scope, so a transient close refusal is retried before the command fails. A close that still fails reports cleanup_incomplete composed with the read's own refusal. Routed commands refuse routes that check a shared JSON input differently, since it is checked before the route is chosen.

* refactor(cli): project inspect-web-network-capture from its contract with nested protobuf options

The contract builder flattens a nested optional object member in turn (protobuf.schema), resolves a flattened caller-path member and reports it as spelled under its dotted path in callerInputs, keeps a flattened member's contract default out of argv so an omitted member stays omitted, and takes an array of numbers as repeated decimal tokens within its bounds. inspect-web-network-capture registers from its contract with the same option names; Evidence keeps the capture and descriptor paths as the caller spelled them. CLI input issues name the capturePath argument.

* fix(cli): name a selector field by its own option in admission issues

A selector parameter's positional may share another key (decompile's procedure positional is address), so mapping the field to its positional key renamed selection issues that already name the option, such as a missing or conflicting --procedure. Map a selector field to its option.

* fix(cli): retain a JSON input file whose close fails and keep why its read stopped

parseCliJsonInput dropped its per-read scope after the owner's close retry failed, so the handle lost its owner, and a read or cancellation failure recorded before the close was replaced by the cleanup failure. The read's scope now stays with the CLI process until final CLI cleanup retries it, and the recorded outcome is translated once into the primary failure with the cleanup attached. The module moves into src/cli so it can register with the CLI process owner without a layer cycle.

* refactor(cli): project inspect-with-objdump and inspect-api-contract from their contracts (#11142)

* refactor(cli): project inspect-with-objdump, list-objdump-architectures and inspect-api-contract from their contracts

The contract builder selects input branches by a field that is a literal in
one branch and an enum in another, takes the default of the one branch that
admits omission, and lets a command take a subset of a union's branches by
their discriminating values, fixing the field when one value is selected.

* refactor(cli): project trace-web-source-location from its contract with flattened positional objects (#11167)

* refactor(cli): project trace-web-source-location from its contract with flattened positional objects

The contract builder flattens required objects as well as optional ones; a
flattened field listed in positionals takes its members as positionals in
member order. The hand-written source-map limit options and the separate CLI
delivery schema are removed.

* fix(cli): refuse to flatten a required object without a required member

* fix(cli): refuse a malformed Evidence-input document before reading the selected bundle

runEvidenceInputCommand admits the document with its transport frame before
it reads --evidence-bundle, so every Evidence-input command refuses a
malformed document first, as compare-static-and-observed-endpoints already
did by hand.

* test(cli): expect a selector field to be named by its option in input issues

* fix(cli): report a refused view before the delivery rule it would trip

Refusing delivery options before JSON inputs are read checked --evidence_output before the view's own schema, so a summary view naming an unknown field reported only the missing bundle. Admit the view with the contract's view field first, as full admission does.

* refactor(cli): project inspect-android-jni-bindings from its contract with a grouped --query option (#11196)

* refactor(cli): project inspect-android-jni-bindings from its contract with a grouped --query option

A projection's fieldGroups take several optional top-level contract fields as the members of one JSON object option. The text is decoded when the command runs, refused with the group's message when it is not a JSON object, a member that is not one of the group's fields is refused by its path, and the contract admits each member as its field. inspect-android-jni-bindings keeps its --query selection through a group and now registers through the contract builder, so the hand-registered contract command list is empty; the superseded parseCliAnalysisEvidenceDelivery and androidJniDeliverySchema are removed.

* fix(cli): refuse an object rule that names a grouped field

A grouped field is a JSON member, not an option, so a contract rule such as dependentRequired naming it would be advertised over an option that does not exist. Registration now refuses that combination.

* fix(cli): describe the --view and --maxCaptureAgeMs options of projected commands

A projected view field kept no help because the contract's own description was skipped and none replaced it, and compare-process-captures exposed max_capture_age_ms without help. The canonical CLI catalog test refused both. The view option now takes the same help in both builders.

* refactor(cli): derive the CLI command inventory from the contract registry (#11248)

A contract now declares `cli: true` when the CLI exposes it as the command
named by its kebab-case name. The primary CLI inventory (CLI_COMMAND_NAMES,
now owned by catalogIdentity.ts) is derived from those declarations plus the
commands no contract names, and a contract projection omits `command`: the
builder names the command from the contract and refuses a contract that does
not declare one. CLI_COMMANDS keeps only the 32 commands no contract names;
the 164 contract-named entries and the copied MCP-only list in
cliToolCoverage.test.ts are removed.

* fix(managed): keep decoded members when only their loaded literals exceed capacity

A capacity failure while decoding #US literals discarded the member facts already decoded, because the shared representation budget threw through the whole inspection. Literals carry their own coverage, so the inspection is retried without them and reports user_strings as partial with the capacity issue. compare-managed-members, which now runs full inspections, keeps comparing members it used to read with literals disabled.

* test(cli): expect builder-admitted issues by CLI key and option help with its default

Builder admission of compare-web-captures, compare-web-screenshots and analyze-web-bundle names input issues by the CLI key (beforeJson, afterJson, normalizationJson, endpoint), and --integrity-policy help states its default. Four test files still expected the contract field names and the old help, so they failed on the stack.

* test(cli): read each refused browser input's CLI path directly now that every case names one

Every invalid browser input now carries its CLI key, so the fallback branch narrowed to never and failed the TypeScript compiler's typecheck.

* chore(verify): carry the moved cliJsonInput baseline entry into its per-guard file

Rebased on main after #11316 split the guard baselines and #11181 threaded the launch environment into the web bundle command; the contract-built analyze-web-bundle command now passes that environment to the browser provider.

* refactor(cli): hand whole-input contract handlers the admitted parse instead of parsing again (#11301)

* refactor(cli): hand whole-input contract handlers the admitted parse instead of parsing again

* refactor(cli): parse an argv whole input only when the handler reads it

Admission parsed every argv whole-input command eagerly, so handlers that
hand the raw input to a service (inspectWithService) parsed it twice.
parseWholeInput now parses on the first admittedContractInput call and
reuses the result; run-time JSON and view delivery still parse at
admission. The test counts whole-schema evaluations.

* refactor(cli): hand JSON-document handlers the admitted parse of their document (#11332)

observe-native-calls, capture-electron-scenario and match-native-functions
parsed their resolved document against the contract schema in the handler.
registerContractDocumentCommand now gives each document handler
parseWholeInput, a memoized parse of the resolved document as the whole
contract input whose refusal names the caller's spelling, so
admittedContractInput serves argv and document commands alike. A handler
whose document is not the whole input never calls it, so it adds no parse.

* fix(cli): admit checked JSON inputs through their checks only

compare-process-captures walked and copied both capture records again in
the whole-input parse after their checks had admitted them. Admission now
parses the remaining fields with the contract and hands the handler the
checked documents uncopied. The managed summary example names
--evidence_output.
2026-11-16 03:22:24 +08:00

1964 lines
66 KiB
TypeScript

import { Parser, z } from "incur";
import { describe, expect, it } from "vitest";
import { createCli } from "../../../src/cli.js";
import {
contractNamed,
describeContractCommand,
describeOperationChoices,
describeContractDocumentCommand,
type ContractCliDescription,
type ContractCliParameter,
} from "../../../src/cli/contractCliDescription.js";
import { BROWSER_TOOL_CONTRACTS } from "../../../src/contracts/browserToolContracts.js";
import { passiveNetworkCapture } from "../../fixtures/passiveNetworkCapture.js";
import {
contractCommandDescriptions,
contractInputBranch,
contractDocumentCommandDescriptions,
routedCommandDescriptions,
} from "../../../src/cli/contractCommand.js";
import { jsonInputContentSchema } from "../../../src/cli/jsonInputArgument.js";
import {
visitRegisteredCommands,
type RegisteredCommand,
} from "../../../src/cli/visitRegisteredCommands.js";
import { absoluteCallerPath } from "../../../src/filesystem/callerPath.js";
import {
TOOL_CONTRACTS,
toolContract,
} from "../../../src/contracts/toolContracts.js";
const DECIMAL_TOKEN = /^[0-9]+$/u;
const cli = createCli({});
const registered = new Map<string, RegisteredCommand>();
visitRegisteredCommands(cli, (command, path) => {
registered.set(path, command);
});
// A routed command contributes one description per contract it runs.
const descriptions = [
...contractCommandDescriptions(cli),
...routedCommandDescriptions(cli),
];
const inputJsonSchema = (field: z.ZodType): Record<string, unknown> =>
z.toJSONSchema(field, { io: "input", unrepresentable: "any" });
/** Values at and around each advertised bound, plus spellings argv can carry. */
const probes = (field: z.ZodType): readonly unknown[] => {
const json = inputJsonSchema(field);
const values: unknown[] = [
undefined,
null,
"",
"\0",
"a\0b",
"\uD800",
"x",
"rel/x",
"/abs/x",
true,
false,
-1,
0,
1,
1.5,
64,
4096,
2 ** 31,
2 ** 53,
[],
["x"],
[""],
["a\0b"],
"0",
"1",
"010",
"0x10",
"1e3",
"+1",
" 1",
"-1",
"1.5",
"{}",
"[]",
"null",
"{",
'{"input_bytes":1}',
'{"input_bytes":0}',
'{"unknown":1}',
];
for (const bound of ["minimum", "maximum", "minLength", "maxLength"]) {
const value = json[bound];
if (typeof value !== "number") continue;
const near = [value - 1, value, value + 1];
values.push(...near, ...near.filter((n) => n >= 0).map(String));
if (bound.endsWith("Length"))
values.push(...near.filter((n) => n >= 0).map((n) => "x".repeat(n)));
}
if (Array.isArray(json.enum)) values.push(...json.enum, `${json.enum[0]}!`);
return values;
};
/** The field admits a number, possibly alongside null. */
const isNumeric = (field: z.ZodType): boolean => {
const json = inputJsonSchema(field);
const branches = Array.isArray(json.anyOf)
? (json.anyOf as Record<string, unknown>[])
: [json];
return branches.some(({ type }) => type === "integer" || type === "number");
};
/** Argv omission is an absent key, never an explicit undefined. */
const admits = (field: z.ZodType, value: unknown): boolean =>
value === undefined
? z.object({ value: field }).safeParse({}).success
: field.safeParse(value).success;
/** What the contract admits for one value the caller typed on the CLI. */
const expectedAdmission = (
parameter: ContractCliParameter,
contractField: z.ZodType,
value: unknown,
): boolean => {
// The named option may supply a selector in place of the positional.
if (parameter.selectorOption !== undefined && value === undefined)
return true;
// An omitted option takes its CLI default, which the contract admits.
if (parameter.cliDefault !== undefined && value === undefined) return true;
if (parameter.jsonText) {
// JSON text is decoded once, then the contract field admits the value.
if (typeof value !== "string")
return admits(contractField, value) && value === undefined;
let decoded: unknown;
try {
decoded = JSON.parse(value);
} catch {
return false;
}
return admits(contractField, decoded) && decoded !== undefined;
}
if (parameter.nullFlag !== undefined && value === null)
// Null is spelled by the bare flag, never by the limit option.
return false;
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));
}
if (typeof value === "string" && isNumeric(contractField))
return DECIMAL_TOKEN.test(value) && admits(contractField, Number(value));
return admits(contractField, value);
};
const registeredField = (
description: ContractCliDescription,
parameter: ContractCliParameter,
): z.ZodType => {
const command = registered.get(description.command)!;
const group = (
parameter.positional ? command.args : command.options
) as z.ZodObject;
return group.shape[parameter.key] as z.ZodType;
};
const contractShape = (description: ContractCliDescription) =>
description.fields;
/**
* Contract fields the handler supplies: each Evidence target's from its
* source, and each handler field from CLI-only values.
*/
const handlerSuppliedFields = (
description: ContractCliDescription,
): string[] => [
...(description.evidenceTargets?.targets ?? []).map(({ field }) => field),
...description.handlerFields,
];
/**
* The contract schema one parameter supplies: a field, a flattened member,
* or a field group's optional object of its fields.
*/
const suppliedField = (
description: ContractCliDescription,
parameter: ContractCliParameter,
): z.ZodType => {
const shape = contractShape(description);
if (parameter.group !== undefined)
return z
.strictObject(
Object.fromEntries(
parameter.group.map((field) => [field, shape[field]!]),
),
)
.optional();
const field = shape[parameter.field]!;
if (parameter.member === undefined) return field;
// A member is omittable when it or any enclosing object is.
let supplied: z.ZodType = field;
let omittable = false;
for (const member of parameter.member) {
omittable ||= admits(supplied, undefined);
while (
supplied instanceof z.ZodOptional ||
supplied instanceof z.ZodExactOptional
)
supplied = supplied.unwrap() as z.ZodType;
supplied = (supplied as z.ZodObject).shape[member] as z.ZodType;
}
return omittable ? supplied.optional() : supplied;
};
/**
* Argv takes a transformed field's inbound text, as tools/list advertises
* it; the contract transforms it on admission. CLI help may word the field
* differently, and the contract applies its own default.
*/
const expectInboundView = (
key: string,
cliField: z.ZodType,
contractField: z.ZodType,
): void => {
const inbound = (schema: z.ZodType) => {
const {
default: _default,
description: _description,
...view
} = z.toJSONSchema(schema, { io: "input" }) as Record<string, unknown>;
return view;
};
expect(inbound(cliField), key).toEqual(inbound(contractField));
expect(admits(cliField, undefined), key).toBe(
admits(contractField, undefined),
);
};
/** Each positional caller path is resolved, and kept as typed in callerInputs. */
const expectResolvedPositionalPaths = (
description: ContractCliDescription,
values: Readonly<Record<string, unknown>>,
input: Readonly<Record<string, unknown>>,
): void => {
for (const parameter of description.parameters) {
if (!parameter.callerPath || !parameter.positional) continue;
// A flattened member is resolved inside its object.
const path = [parameter.field, ...(parameter.member ?? [])];
const resolved = path.reduce<unknown>(
(value, key) => (value as Record<string, unknown>)[key],
input,
);
expect(resolved).toBe(absoluteCallerPath("rel/target"));
expect(description.callerInputs(values)[path.join(".")]).toBe("rel/target");
}
};
/** A caller-relative target, or the first probe the argument admits. */
const requiredValue = (
description: ContractCliDescription,
parameter: ContractCliParameter,
): unknown =>
parameter.callerPath
? "rel/target"
: probes(suppliedField(description, parameter)).find(
(value) =>
value !== undefined &&
admits(registeredField(description, parameter), value),
);
/** Parsed option values plus admitted positionals and required options. */
const argvValues = (
description: ContractCliDescription,
options: Readonly<Record<string, unknown>>,
): Record<string, unknown> => {
const positional: ReadonlySet<string> = new Set(
description.parameters
.filter((parameter) => parameter.positional)
.map(({ key }) => key),
);
// A required selector is supplied positionally.
const required = description.parameters.filter(
(parameter) =>
(parameter.selectorOption === undefined
? !admits(registeredField(description, parameter), undefined)
: parameter.selectorOption.required) &&
!Object.hasOwn(options, parameter.key),
);
const filled = Object.fromEntries(
required.map((parameter) => [
parameter.key,
requiredValue(description, parameter),
]),
);
return {
...Object.fromEntries(
Object.entries(options).filter(([key]) => positional.has(key)),
),
...(registered.get(description.command)!.options as z.ZodObject).parse({
...Object.fromEntries(
Object.entries(options).filter(([key]) => !positional.has(key)),
),
...Object.fromEntries(
required
.filter(({ positional }) => !positional)
.map(({ key }) => [key, filled[key]]),
),
}),
...Object.fromEntries(
required
.filter(({ positional }) => positional)
.map(({ key }) => [key, filled[key]]),
),
};
};
const processComparisonExample = toolContract("compare_process_captures")
.examples[0]!.input as { readonly left: unknown; readonly right: unknown };
const screenshotExample = toolContract("compare_web_screenshots").examples[0]!
.input as { readonly before: unknown; readonly after: unknown };
const captureDiff = contractNamed(
BROWSER_TOOL_CONTRACTS,
"compare_web_captures",
);
const scenarioExample = captureDiff.examples[0]!.input as {
readonly before_scenario: unknown;
readonly after_scenario: unknown;
};
/**
* Argv for each input shape of a command routed by document content, keyed
* by the shape its route projects; a passive capture and a scenario capture
* cannot both satisfy one fixture.
*/
const ROUTE_ARGV: ReadonlyMap<
unknown,
Readonly<Record<string, unknown>>
> = new Map<unknown, Readonly<Record<string, unknown>>>([
[
contractInputBranch(captureDiff, "before").inputSchema,
{
beforeJson: JSON.stringify({ inspection: passiveNetworkCapture() }),
afterJson: JSON.stringify({ inspection: passiveNetworkCapture() }),
},
],
[
contractInputBranch(captureDiff, "before_scenario").inputSchema,
{
beforeJson: JSON.stringify(scenarioExample.before_scenario),
afterJson: JSON.stringify(scenarioExample.after_scenario),
},
],
]);
/**
* Argv for commands whose contract rules need more than one value per
* required field: a selector choice, a pattern grammar or a change to make.
*/
const ARGV_SATISFYING_RULES: Readonly<
Record<string, Readonly<Record<string, unknown>>>
> = {
"annotate-native-function": { name: "renamed" },
"search-bytes": { pattern: "41 ??" },
"cutter-command": { sessionId: "00000000-0000-4000-8000-000000000001" },
"inspect-native-data-type": { type: "/struct" },
"capture-native-ui-scenario": {
steps: '[{"kind":"wait","milliseconds":0}]',
},
// The handler selects the local device when the caller selects none.
"list-frida-processes": { deviceId: "local" },
// The contract transforms the endpoint text it admits.
"list-browser-targets": { endpoint: "http://127.0.0.1:9222" },
"observe-web-session": { endpoint: "http://127.0.0.1:9222" },
"inspect-web-page": { endpoint: "http://127.0.0.1:9222" },
"list-electron-targets": { endpoint: "http://127.0.0.1:9222" },
"inspect-electron-page": { endpoint: "http://127.0.0.1:9222" },
"discover-webmcp-tools": { endpoint: "http://127.0.0.1:9222" },
"capture-web-screenshot": { endpoint: "http://127.0.0.1:9222" },
"observe-web-execution": { endpoint: "http://127.0.0.1:9222" },
"inspect-web-event-listeners": { endpoint: "http://127.0.0.1:9222" },
"analyze-web-bundle": { endpoint: "http://127.0.0.1:9222" },
"list-javascript-runtime-targets": { endpoint: "http://127.0.0.1:9229" },
"observe-javascript-runtime": { endpoint: "http://127.0.0.1:9229" },
// Each side must be a self-verifying screenshot artifact.
"compare-web-screenshots": {
beforeJson: JSON.stringify(screenshotExample.before),
afterJson: JSON.stringify(screenshotExample.after),
},
// Each side must be process capture Evidence.
"compare-process-captures": {
left: JSON.stringify(processComparisonExample.left),
right: JSON.stringify(processComparisonExample.right),
},
};
const each = descriptions.map(
(description) => [description.command, description] as const,
);
/** Every command the contract builders registered, from their registry. */
const contractBuilt: ReadonlySet<string> = new Set(
[...descriptions, ...contractDocumentCommandDescriptions(cli)].map(
({ command }) => command,
),
);
/** Contract-built commands whose name differs from their contract's. */
const RENAMED_CONTRACT_COMMANDS = [
"analyze",
"decompile",
"function",
"inspect",
"instructions",
"list-objdump-architectures",
"search",
"trace",
"validate-browser-scenario",
];
const commandName = (contract: string): string => contract.replaceAll("_", "-");
// Derived from the registries, so a command that stops registering through a
// contract builder fails here rather than silently leaving the parity cases.
it("builds every contract-named command from its contract", () => {
const named = new Set(TOOL_CONTRACTS.map(({ name }) => commandName(name)));
expect(
[...named]
.filter((name) => registered.has(name) && !contractBuilt.has(name))
.toSorted(),
).toEqual([]);
expect(
[...contractBuilt].filter((name) => !named.has(name)).toSorted(),
).toEqual(RENAMED_CONTRACT_COMMANDS);
});
// The CLI resolves a relative caller path against the working directory, so
// its help must not inherit an MCP description that requires an absolute one.
it("describes every caller path without requiring an absolute path", () => {
expect(
descriptions.flatMap(({ command, parameters }) =>
parameters
.filter(
({ callerPath, description }) =>
callerPath && /\babsolute\b/iu.test(description ?? ""),
)
.map(({ key }) => `${command} ${key}`),
),
).toEqual([]);
});
// An argv fixture names a contract-built command, so it cannot outlive its registration.
it("keeps every argv fixture on a contract-built command", () => {
expect(
Object.keys(ARGV_SATISFYING_RULES).filter(
(name) => !contractBuilt.has(name),
),
).toEqual([]);
});
describe("CLI commands projected from tool contracts", () => {
it.each(each)(
"%s exposes every contract field or declares its omission",
(_command, description) => {
expect(
[
...new Set(
description.parameters.flatMap(
({ field, group }) => group ?? [field],
),
),
...Object.keys(description.omitted),
...Object.keys(description.fixedFields),
...handlerSuppliedFields(description),
]
.toSorted()
.join(),
).toBe(Object.keys(contractShape(description)).toSorted().join());
const command = registered.get(description.command)!;
const argKeys = Object.keys(
(command.args as z.ZodObject | undefined)?.shape ?? {},
);
const optionKeys = Object.keys(
(command.options as z.ZodObject | undefined)?.shape ?? {},
);
expect(argKeys).toEqual([
...(description.sessionTarget === undefined
? []
: [description.sessionTarget.key]),
...(description.evidenceTargets?.targets ?? []).map(({ key }) => key),
...description.parameters
.filter(({ positional }) => positional)
.map(({ key }) => key),
...description.cliPositionals.map(({ key }) => key),
]);
// A routed command takes the union of its routes' options.
const routes = descriptions.filter(
({ command: name }) => name === description.command,
);
expect(optionKeys.toSorted()).toEqual(
[
...new Set(
routes.flatMap((route) => [
...route.parameters
.filter(({ positional }) => !positional)
.map(({ key }) => key),
...(route.sessionTarget?.options ?? []).map(({ key }) => key),
...(route.evidenceTargets?.options ?? []).map(({ key }) => key),
...route.cliOnlyOptions.map(({ key }) => key),
...route.parameters.flatMap(({ selectorOption }) =>
[selectorOption, selectorOption?.alternative].flatMap(
(option) => (option === undefined ? [] : [option.key]),
),
),
]),
),
].toSorted(),
);
},
);
it.each(each)(
"%s admits exactly what its contract admits",
(_command, description) => {
const mismatches: string[] = [];
for (const parameter of description.parameters) {
const cliField = registeredField(description, parameter);
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.
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.inbound) {
expectInboundView(parameter.key, cliField, contractField);
continue;
}
if (parameter.runtimeJson !== undefined) {
// JSON text decoded when the command runs; see below. Argv
// requires the text of a required field.
expect(admits(cliField, undefined), parameter.key).toBe(
admits(contractField, undefined),
);
for (const value of ["{", "{}"])
expect(admits(cliField, value), parameter.key).toBe(true);
// Empty text is neither JSON nor a JSON input's file path.
expect(admits(cliField, ""), parameter.key).toBe(
!parameter.jsonInput,
);
continue;
}
for (const value of probes(contractField)) {
const expected = expectedAdmission(parameter, contractField, value);
if (admits(cliField, value) !== expected)
mismatches.push(
`${parameter.key}=${JSON.stringify(value)} expected ${String(expected)}`,
);
}
}
expect(mismatches).toEqual([]);
},
);
it.each(each)(
"%s takes each boolean contract field as a bare flag",
(_command, description) => {
for (const parameter of description.parameters) {
if (parameter.positional || !parameter.booleanFlag) continue;
const options = z.object({
[parameter.key]: registeredField(description, parameter),
});
const flag = `--${parameter.key.replaceAll(/[A-Z]/gu, (c) => `-${c.toLowerCase()}`)}`;
expect(Parser.parse([flag], { options }).options, flag).toEqual({
[parameter.key]: true,
});
}
},
);
it.each(each)(
"%s maps parsed argv to an admitted contract input",
(command, description) => {
const values = argvValues(
description,
ROUTE_ARGV.get(description.contract.inputSchema) ??
ARGV_SATISFYING_RULES[command] ??
{},
);
// Runtime JSON text is decoded as admission does.
for (const { key, runtimeJson } of description.parameters)
if (runtimeJson !== undefined && typeof values[key] === "string")
values[key] = JSON.parse(values[key]) as unknown;
const input = description.toContractInput(values);
const targets = new Set(handlerSuppliedFields(description));
const admitted =
targets.size === 0
? description.contract.inputSchema
: z.object(
Object.fromEntries(
Object.entries(contractShape(description)).filter(
([field]) => !targets.has(field),
),
),
);
expect(admitted.safeParse(input).error).toBe(undefined);
expectResolvedPositionalPaths(description, values, input);
},
);
});
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()],
["a union", z.union([z.string(), z.boolean()]).optional()],
["a pipe", z.string().pipe(z.string()).optional()],
["an array of objects", z.array(z.object({})).optional()],
["an array of booleans", z.array(z.boolean()).optional()],
["a tuple", z.tuple([z.string()]).optional()],
])("refuses to describe a field that is %s", (_kind, field) => {
expect(() =>
describeContractCommand(
{ name: "probe", inputSchema: z.object({ field }) },
{ command: "probe", description: "Probe" },
),
).toThrow("probe.field has no argv projection");
});
it("takes an array of numbers as repeated decimal tokens within its bounds", () => {
const [parameter] = describeContractCommand(
{
name: "probe",
inputSchema: z.object({
ordinals: z.array(z.int().nonnegative()).min(1).max(2).optional(),
}),
},
{ command: "probe", description: "Probe" },
).parameters;
const schema = parameter!.schema;
expect(parameter!.repeatable).toBe(true);
expect(schema.parse(["0", "7"])).toEqual([0, 7]);
expect(schema.parse(undefined)).toBeUndefined();
for (const refused of [["0x1"], ["-1"], [], ["1", "2", "3"]])
expect(schema.safeParse(refused).success, String(refused)).toBe(false);
});
it("refuses an input constraint the CLI schema cannot carry", () => {
expect(() =>
describeContractCommand(
{
name: "probe",
inputSchema: z
.object({ value: z.string().optional() })
.meta({ not: { required: ["value"] } }),
},
{ command: "probe", description: "Probe" },
),
).toThrow("probe input keyword not has no CLI projection");
});
});
describe("CLI-only options of contract commands", () => {
it.each(each)(
"%s keeps its CLI-only options out of the contract input",
(_command, description) => {
const cliKeys = description.cliOnlyOptions.map(({ key }) => key);
const values = Object.fromEntries(cliKeys.map((key) => [key, "set"]));
const input = description.toContractInput(values);
for (const key of cliKeys) {
expect(Object.values(input), key).not.toContain("set");
expect(Object.keys(description.fields), key).not.toContain(key);
}
},
);
it("takes CLI-only positionals after the contract's and leaves handler fields to the handler", () => {
const contract = {
name: "probe",
inputSchema: z.object({
mode: z.enum(["a", "b"]),
id: z.number().optional(),
kind: z.enum(["x", "y"]),
value: z.string().optional(),
}),
};
const described = describeContractCommand(contract, {
command: "probe",
description: "Probe",
positionals: ["mode"],
cliOptions: { target: z.string().min(1) },
cliPositionals: ["target"],
handlerFields: ["id", "kind"],
});
expect(described.parameters.map(({ field }) => field)).toEqual([
"mode",
"value",
]);
expect(described.cliPositionals.map(({ key }) => key)).toEqual(["target"]);
expect(described.cliOnlyOptions).toEqual([]);
expect(described.handlerFields).toEqual(["id", "kind"]);
expect(
described.toContractInput({ mode: "a", target: "7", value: "v" }),
).toEqual({ mode: "a", value: "v" });
expect(described.cliOptionValues({ mode: "a", target: "7" })).toEqual({
target: "7",
});
expect(() =>
describeContractCommand(contract, {
command: "probe",
description: "Probe",
cliPositionals: ["missing" as never],
}),
).toThrow("probe has no CLI option missing");
expect(() =>
describeContractCommand(contract, {
command: "probe",
description: "Probe",
handlerFields: ["kind"],
fields: { kind: { name: "k" } },
}),
).toThrow("probe.kind is filled by the handler");
expect(() =>
describeContractCommand(contract, {
command: "probe",
description: "Probe",
handlerFields: ["absent" as never],
}),
).toThrow("probe has no input field absent");
});
it("refuses CLI-only options that collide with or depend on unknown keys", () => {
const contract = {
name: "probe",
inputSchema: z.object({ value: z.string().optional() }),
};
expect(() =>
describeContractCommand(contract, {
command: "probe",
description: "Probe",
cliOptions: { value: z.string().optional() },
}),
).toThrow("probe projects two fields to one CLI key");
expect(() =>
describeContractCommand(contract, {
command: "probe",
description: "Probe",
cliOptions: { extra: z.string().optional() },
cliOptionDependencies: { extra: ["missing"] },
}),
).toThrow("probe has no CLI option missing");
const described = describeContractCommand(contract, {
command: "probe",
description: "Probe",
cliOptions: { extra: z.string().optional() },
cliOptionDependencies: { extra: ["value"] },
});
expect(described.optionConstraints).toEqual({
dependentRequired: { extra: ["value"] },
});
expect(described.cliOptionValues({ value: "a", extra: "b" })).toEqual({
extra: "b",
});
expect(described.toContractInput({ value: "a", extra: "b" })).toEqual({
value: "a",
});
});
});
const decodingAtRunTime = each.filter(([, description]) =>
description.parameters.some(({ runtimeJson }) => runtimeJson !== undefined),
);
describe("JSON decoded when contract commands run", () => {
it.each(decodingAtRunTime)(
"%s refuses text that is not JSON before analysis",
(_command, description) => {
for (const parameter of description.parameters) {
// The command reads a JSON input before admission and refuses it
// there; the CLI tests cover that refusal.
if (parameter.runtimeJson === undefined || parameter.jsonInput)
continue;
const malformed = description.admit(
argvValues(description, {
detail: "summary",
evidence_output: "out.json",
[parameter.key]: "{",
}),
);
expect(malformed.ok, parameter.key).toBe(false);
if (!malformed.ok)
expect(malformed.error.issues).toEqual([
expect.objectContaining({
path: [parameter.key],
reason: "invalid_format",
message: parameter.runtimeJson,
}),
]);
}
},
);
it.each(decodingAtRunTime)(
"%s admits what its contract admits once decoded",
(_command, description) => {
const mismatches: string[] = [];
const details = description.evidenceDelivery
? (["complete", "summary"] as const)
: [undefined];
for (const parameter of description.parameters) {
if (parameter.runtimeJson === undefined) continue;
for (const detail of details)
for (const text of ["{}", "[]", "null", '{"unknown":1}', '["x"]']) {
const values = argvValues(description, {
...(detail === undefined
? {}
: { detail, evidence_output: "out.json" }),
[parameter.key]: text,
});
// The command hands admission a JSON input already decoded.
if (parameter.jsonInput)
values[parameter.key] = JSON.parse(text) as unknown;
const decoded = JSON.parse(text) as unknown;
const { group } = parameter;
// A field group supplies the members of a JSON object, each one
// of its fields; other JSON is refused before the contract.
const supplied =
group === undefined
? { [parameter.field]: decoded }
: typeof decoded === "object" &&
decoded !== null &&
!Array.isArray(decoded) &&
Object.keys(decoded).every((key) => group.includes(key))
? decoded
: undefined;
const expected =
supplied !== undefined &&
description.contract.inputSchema.safeParse({
...description.toContractInput({
...values,
[parameter.key]: undefined,
}),
...(detail === undefined ? {} : { detail }),
...supplied,
}).success;
const admitted = description.admit(values).ok;
// A checked JSON input is admitted by its check, which the
// command runs as soon as the input is read, and may be
// stricter than the contract; the contract admits the rest.
const check = parameter.checkJsonInput?.(decoded);
const refusedByCheck = check !== undefined && !check.ok;
if (expected ? !admitted : admitted && !refusedByCheck)
mismatches.push(
`${parameter.key} ${String(detail)} ${text} expected ${String(expected)}`,
);
}
}
expect(mismatches).toEqual([]);
},
);
});
const nullFlagged = each.filter(([, description]) =>
description.parameters.some(({ nullFlag }) => nullFlag !== undefined),
);
describe("Null-limit flags of contract commands", () => {
it.each(nullFlagged)(
"%s spells null with its flag and refuses the flag with a limit",
(_command, description) => {
const parameter = description.parameters.find(
({ nullFlag }) => nullFlag !== undefined,
)!;
const flag = parameter.nullFlag!;
expect(description.cliOnlyOptions.map(({ key }) => key)).toContain(flag);
expect(admits(contractShape(description)[parameter.field]!, null)).toBe(
true,
);
const all = argvValues(description, { [flag]: true });
expect(description.toContractInput(all)[parameter.field]).toBeNull();
expect(
description.contract.inputSchema.safeParse(
description.toContractInput(all),
).error,
).toBe(undefined);
expect(description.checkOptions?.(all)).toEqual([]);
const both = { ...all, [parameter.key]: 1 };
expect(description.checkOptions?.(both)).toEqual([
expect.objectContaining({
path: [flag],
message: `${flag} and ${parameter.key} are mutually exclusive`,
}),
]);
expect(description.optionConstraints?.not).toEqual({
required: [flag, parameter.key],
properties: { [flag]: { const: true } },
});
const bounded = argvValues(description, { [parameter.key]: 1 });
expect(description.toContractInput(bounded)[parameter.field]).toBe(1);
},
);
});
const flattening = each.filter(([, description]) =>
description.parameters.some(({ member }) => member !== undefined),
);
describe("Flattened object fields of contract commands", () => {
it.each(flattening)(
"%s supplies the object with only the given members",
(_command, description) => {
// A required object is always supplied, so only optional ones apply.
const fields = new Set(
description.parameters.flatMap(({ field, member }) =>
member === undefined ||
!contractShape(description)[field]!.safeParse(undefined).success
? []
: [field],
),
);
for (const field of fields) {
const members = description.parameters.filter(
(parameter) =>
parameter.field === field && parameter.member !== undefined,
);
expect(
field in description.toContractInput(argvValues(description, {})),
).toBe(false);
for (const given of members) {
const value = requiredValue(description, given);
const input = description.toContractInput(
argvValues(description, { [given.key]: value }),
);
// An omitted member stays omitted, never an explicit undefined;
// a nested member supplies each enclosing object with only itself.
let object = input[field] as Record<string, unknown>;
for (const member of given.member!.slice(0, -1)) {
expect(Object.keys(object)).toEqual([member]);
object = object[member] as Record<string, unknown>;
}
expect(Object.keys(object)).toEqual([given.member!.at(-1)]);
expect(object[given.member!.at(-1)!]).toEqual(
given.callerPath ? absoluteCallerPath(value as string) : value,
);
}
}
},
);
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 object");
});
it("takes a required object's members as positionals in member order", () => {
const inputSchema = z.strictObject({
name: z.string(),
position: z.strictObject({ line: z.int(), column: z.int() }),
limits: z.strictObject({ bytes: z.int().optional() }).optional(),
});
const described = describeContractCommand(
{ name: "probe", inputSchema },
{
command: "probe",
description: "Probe",
positionals: ["name", "position"],
flatten: {
position: { line: {}, column: { name: "col" } },
limits: { bytes: {} },
},
},
);
expect(
described.parameters.map(({ key, positional }) => [key, positional]),
).toEqual([
["name", true],
["line", true],
["col", true],
["bytes", false],
]);
const [, line] = described.parameters;
expect(line!.schema.safeParse(undefined).success).toBe(false);
expect(line!.schema.safeParse("2").success).toBe(true);
expect(described.toContractInput({ name: "n", line: 2, col: 0 })).toEqual({
name: "n",
position: { line: 2, column: 0 },
});
expect(() =>
describeContractCommand(
{ name: "probe", inputSchema },
{
command: "probe",
description: "Probe",
positionals: ["limits"],
flatten: { limits: { bytes: {} } },
},
),
).toThrow("probe.limits is an optional positional object");
expect(() =>
describeContractCommand(
{
name: "probe",
inputSchema: z.strictObject({
position: z.strictObject({ line: z.int().optional() }),
}),
},
{
command: "probe",
description: "Probe",
positionals: ["position"],
flatten: { position: { line: {} } },
},
),
).toThrow("probe.position.line is an optional positional");
// Omitting every member would drop a required object argv cannot spell.
expect(() =>
describeContractCommand(
{
name: "probe",
inputSchema: z.strictObject({
limits: z.strictObject({ bytes: z.int().optional() }),
}),
},
{
command: "probe",
description: "Probe",
flatten: { limits: { bytes: {} } },
},
),
).toThrow("probe.limits has no required member");
});
});
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(
Object.values(description.callerInputs(values)).flat(),
).not.toContain("rel/app");
},
);
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,
);
// A selector field is named by its own option, which selection
// issues already use; its positional may share another key.
for (const {
field,
key,
member,
selectorOption,
} of description.parameters)
if (member === undefined) {
const named = selectorOption?.key ?? key;
expect(description.inputBinding.fields[field]).toBe(
named === field ? undefined : named,
);
}
},
);
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 openingKeys = (description: ContractCliDescription) =>
description.sessionTarget!.options.map(({ key }) => key);
describe("Opening options of session-targeted contract commands", () => {
it.each(
sessionTargeted.filter(
([, description]) => description.sessionTarget!.options.length > 0,
),
)(
"%s keeps opening options out of the contract input",
(_command, description) => {
for (const key of openingKeys(description))
expect(Object.keys(description.fields), key).not.toContain(key);
expect(
description.sessionTarget!.admitOpening(description.contract.name, {}),
).toEqual({ ok: true, value: {} });
},
);
it.each(
sessionTargeted.filter(([, description]) =>
openingKeys(description).includes("entry-point"),
),
)(
"%s admits a native target interpretation with open_binary",
(_command, description) => {
const target = description.sessionTarget!;
const snapshot = openingKeys(description).includes("snapshot");
const values = {
...argvValues(
description,
ARGV_SATISFYING_RULES[description.command] ?? {},
),
[target.key]: "rel/app",
"target-format": "raw-binary",
architecture: "x86",
"entry-point": "0x100",
provider: "ghidra",
...(snapshot ? { snapshot: "rel/snapshot.json" } : {}),
};
expect(Object.values(description.toContractInput(values))).not.toContain(
"0x100",
);
// The snapshot is admitted resolved and passed on as typed.
expect(target.admitOpening(description.contract.name, values)).toEqual({
ok: true,
value: {
format: "raw-binary",
architecture: "x86",
entry_point: "0x100",
provider_id: "ghidra",
...(snapshot ? { snapshot_path: "rel/snapshot.json" } : {}),
},
});
// The pairing rule refuses before the target opens and names CLI keys.
const unpaired = target.admitOpening(description.contract.name, {
[target.key]: "rel/app",
"target-format": "raw-binary",
architecture: "x86",
});
expect(unpaired.ok).toBe(false);
if (!unpaired.ok)
expect(unpaired.error.issues).toEqual([
expect.objectContaining({
path: ["entry-point"],
message: expect.stringMatching(/requires architecture/u),
}),
]);
const format = target.options.find(({ key }) => key === "target-format")!;
expect(admits(format.schema, "raw-binary")).toBe(true);
expect(admits(format.schema, "esp-flash-image")).toBe(false);
},
);
it.each(
sessionTargeted.filter(([, description]) =>
openingKeys(description).includes("flashOffset"),
),
)(
"%s admits ESP flash options with the opening contract and keeps them out of the contract input",
(_command, description) => {
const target = description.sessionTarget!;
const values = {
...argvValues(description, {}),
[target.key]: "rel/app",
targetFormat: "esp-flash-image",
flashOffset: "0x1000",
};
for (const { key } of target.options)
expect(Object.keys(description.fields), key).not.toContain(key);
expect(Object.values(description.toContractInput(values))).not.toContain(
"0x1000",
);
expect(target.admitOpening(description.contract.name, values)).toEqual({
ok: true,
value: { format: "esp-flash-image", flash_offset: "0x1000" },
});
expect(target.admitOpening(description.contract.name, {})).toEqual({
ok: true,
value: {},
});
// The opening contract's pairing rule names the CLI key.
const unpaired = target.admitOpening(description.contract.name, {
[target.key]: "rel/app",
flashOffset: "0x1000",
});
expect(unpaired.ok).toBe(false);
if (!unpaired.ok)
expect(unpaired.error.issues).toEqual([
expect.objectContaining({
path: ["flashOffset"],
message: expect.stringMatching(/only with format=esp-flash-image/u),
}),
]);
// Only the projected values of an opening field are admitted.
const format = target.options.find(({ key }) => key === "targetFormat")!;
expect(admits(format.schema, "esp-flash-image")).toBe(true);
expect(admits(format.schema, "raw-binary")).toBe(false);
},
);
});
describe("Opening fields a session target projects", () => {
it("refuses opening fields the opening contract cannot supply", () => {
const opening = {
name: "open",
inputSchema: z.object({
path: z.string(),
mode: z.enum(["a", "b"]).optional(),
required: z.string(),
}),
};
const describeOpening = (
fields: Record<string, { values?: [string]; callerPath?: true }>,
) =>
describeContractCommand(
{ name: "probe", inputSchema: z.object({}) },
{
command: "probe",
description: "Probe",
sessionTarget: {
description: "Target",
open: { contract: opening, fields },
},
},
);
expect(() => describeOpening({ missing: {} })).toThrow(
"open has no option field missing",
);
expect(() => describeOpening({ path: {} })).toThrow(
"open has no option field path",
);
expect(() => describeOpening({ required: {} })).toThrow(
"open.required is required",
);
expect(() => describeOpening({ mode: { values: ["c"] } })).toThrow(
"open.mode does not admit c",
);
expect(() => describeOpening({ mode: { callerPath: true } })).toThrow(
"open.mode is not a path",
);
});
});
/** Summary selections for contracts whose summary requires a view. */
const SUMMARY_SELECTIONS: Readonly<
Record<string, Readonly<Record<string, unknown>>>
> = {
"analyze-web-bundle": {
view: '{"kind":"web-bundle","collection":"endpoints"}',
},
};
const delivering = each.filter(
([, description]) => description.evidenceDelivery,
);
describe("Evidence delivery of contract commands", () => {
it.each(delivering)(
"%s refuses summary delivery without --evidence_output before analysis",
(command, description) => {
const satisfying = {
...ARGV_SATISFYING_RULES[command],
...SUMMARY_SELECTIONS[command],
};
const refused = description.admit(
argvValues(description, { ...satisfying, detail: "summary" }),
);
expect(refused.ok).toBe(false);
if (!refused.ok)
expect(refused.error.issues.map(({ path }) => path)).toEqual([
["evidence_output"],
]);
expect(
description.admit(
argvValues(description, {
...satisfying,
detail: "summary",
evidence_output: "out.json",
}),
).ok,
).toBe(true);
},
);
it("refuses a union input whose branches differ outside the delivery", () => {
const inputSchema = z.discriminatedUnion("detail", [
z.object({
detail: z.literal("complete").optional(),
limit: z.number().optional(),
}),
z.object({
detail: z.literal("summary"),
limit: z.number().max(1).optional(),
}),
]);
expect(() =>
describeContractCommand(
{ name: "probe", inputSchema },
{ command: "probe", description: "Probe", evidenceDelivery: true },
),
).toThrow("probe.limit differs between input branches");
expect(() =>
describeContractCommand(
{ name: "probe", inputSchema },
{ command: "probe", description: "Probe" },
),
).toThrow("probe.limit differs between input branches");
});
it("selects an input branch with a literal in one branch and an enum in another", () => {
const inputSchema = z.union([
z.strictObject({ format: z.literal("json").default("json") }),
z.strictObject({ format: z.enum(["sdl", "graphql"]) }),
]);
const [format] = describeContractCommand(
{ name: "probe", inputSchema },
{ command: "probe", description: "Probe" },
).parameters;
expect(format!.schema.parse(undefined)).toBe("json");
expect(format!.schema.safeParse("graphql").success).toBe(true);
expect(format!.schema.safeParse("xml").success).toBe(false);
});
it("takes the input branches a command selects and fixes a single selected value", () => {
const path = z.string();
const inputSchema = z.discriminatedUnion("operation", [
z.strictObject({ operation: z.enum(["a", "b"]), path }),
z.strictObject({
operation: z.literal("c"),
path,
symbol: z.string().optional(),
}),
z.strictObject({ operation: z.literal("d") }),
]);
const describe = (values: readonly [string, ...string[]]) =>
describeContractCommand(
{ name: "probe", inputSchema },
{
command: "probe",
description: "Probe",
inputBranches: { field: "operation", values },
},
);
const artifact = describe(["a", "b", "c"]);
expect(artifact.parameters.map(({ key }) => key)).toEqual([
"operation",
"path",
"symbol",
]);
const operation = artifact.parameters[0]!.schema;
expect(operation.safeParse("c").success).toBe(true);
expect(operation.safeParse("d").success).toBe(false);
expect(artifact.parameters[1]!.schema.safeParse(undefined).success).toBe(
false,
);
const fixed = describe(["d"]);
expect(fixed.parameters).toEqual([]);
expect(fixed.toContractInput({})).toEqual({ operation: "d" });
expect(inputSchema.safeParse(fixed.toContractInput({})).success).toBe(true);
expect(() => describe(["a"])).toThrow(
"probe.operation would narrow an input branch",
);
expect(() => describe(["e"])).toThrow(
"probe.operation selects no branch for a value",
);
expect(() =>
describeContractCommand(
{ name: "probe", inputSchema: z.object({ operation: z.string() }) },
{
command: "probe",
description: "Probe",
inputBranches: { field: "operation", values: ["a"] },
},
),
).toThrow("probe has one input branch");
});
});
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<string, unknown>,
path: readonly string[],
): Record<string, unknown>[] => {
// 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<string, unknown>[])
: [],
);
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<string, Record<string, unknown>>
| undefined;
const next = properties?.[head];
return next === undefined ? [] : reachable(next, rest);
};
describe("JSON-document contract commands", () => {
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.sessionTarget === undefined
? []
: [description.sessionTarget.key]),
description.key,
]);
const advertised = (args[description.key] as z.ZodType).meta();
expect(advertised?.contentMediaType).toBe("application/json");
const content = advertised?.contentSchema as Record<string, unknown>;
expect(content).toEqual(jsonInputContentSchema(description.content));
// Every contract field reaches the document unless omitted with a
// reason or taken as an option beside it.
const input = inputJsonSchema(description.contract.inputSchema);
const fields = new Set(
reachable(input, []).flatMap((branch) =>
Object.keys(
(branch.properties as Record<string, unknown> | undefined) ?? {},
),
),
);
for (const field of fields)
expect(
reachable(content, [field]).length > 0 ||
Object.hasOwn(description.omitted, field) ||
Object.hasOwn(description.flagged, field),
field,
).toBe(true);
for (const field of [
...Object.keys(description.omitted),
...Object.keys(description.flagged),
])
expect(reachable(content, [field]), field).toEqual([]);
const options = [
...description.deliveryOptions,
...description.cliOnlyOptions,
].map(({ key }) => key);
for (const key of Object.values(description.flagged))
expect(options, key).toContain(key);
expect(
Object.keys(
(command.options as z.ZodObject | undefined)?.shape ?? {},
).toSorted(),
).toEqual(options.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"]);
});
});
describe("JSON-document delivery options", () => {
const contract = {
name: "probe",
inputSchema: z.object({
required: z.string(),
optional: z.string().optional(),
}),
};
const projection = {
command: "probe",
description: "Probe",
document: "Probe JSON",
};
it("takes detail and view beside the document and admits them before the handler", () => {
expect(() =>
describeContractDocumentCommand(contract, {
...projection,
evidenceDelivery: true,
}),
).toThrow("probe.detail is not an optional field");
const delivered = {
name: "probe",
inputSchema: contract.inputSchema.extend({
detail: z.enum(["complete", "summary"]).default("complete"),
view: z.object({ offset: z.number() }).optional(),
}),
};
expect(() =>
describeContractDocumentCommand(delivered, {
...projection,
viewDelivery: { invalidJson: "view must be JSON" },
}),
).toThrow("probe view delivery requires evidenceDelivery");
expect(() =>
describeContractDocumentCommand(delivered, {
...projection,
evidenceDelivery: true,
omit: { detail: "never" },
}),
).toThrow("probe.detail is both omitted and an option");
expect(() =>
describeContractDocumentCommand(delivered, {
...projection,
evidenceDelivery: true,
cliOptions: { evidence_output: z.string().optional() },
}),
).toThrow("probe projects two fields to one CLI key");
const flagged = describeContractDocumentCommand(delivered, {
...projection,
evidenceDelivery: true,
viewDelivery: { invalidJson: "view must be JSON" },
});
expect(
Object.keys(inputJsonSchema(flagged.content).properties as object),
).toEqual(["required", "optional"]);
expect(flagged.admitDelivery({ detail: "complete" })).toEqual({
ok: true,
value: { detail: "complete", evidenceOutput: undefined },
});
expect(
flagged.admitDelivery({
detail: "summary",
evidence_output: "out.json",
view: '{"offset":2}',
}),
).toEqual({
ok: true,
value: {
detail: "summary",
evidenceOutput: "out.json",
view: { offset: 2 },
},
});
for (const values of [
{ detail: "complete", view: '{"offset":2}' },
{ detail: "summary", evidence_output: "out.json", view: "{" },
{
detail: "summary",
evidence_output: "out.json",
view: '{"offset":"2"}',
},
{ detail: "summary" },
])
expect(flagged.admitDelivery(values).ok, JSON.stringify(values)).toBe(
false,
);
});
});
const selecting = each.flatMap(([command, description]) =>
description.parameters.flatMap((parameter) =>
parameter.selectorOption === undefined
? []
: [[command, description, parameter, parameter.selectorOption] as const],
),
);
describe("Positional selectors with a named option", () => {
it.each(selecting)(
"%s takes its selector positionally or by its named option",
(_command, description, parameter, option) => {
const command = registered.get(description.command)!;
const named = (command.options as z.ZodObject).shape[option.key];
expect(admits(named as z.ZodType, undefined)).toBe(true);
expect(admits(named as z.ZodType, "-dash")).toBe(true);
// A required selector is refused when neither spelling is given,
// including where only the CLI requires it.
expect(option.required).toBe(
option.required ||
!admits(description.fields[parameter.field]!, undefined),
);
const { required } = option;
const admit = (values: Record<string, unknown>) =>
description.admit({
[description.sessionTarget?.key ?? "path"]: "rel/app",
...values,
});
const selected = (values: Record<string, unknown>) => {
const result = admit(values);
return result.ok ? result.value.input[parameter.field] : result.error;
};
expect(selected({ [parameter.key]: "main" })).toBe("main");
expect(selected({ [option.valueKey]: "-main" })).toBe("-main");
expect(selected({ [parameter.key]: "m", [option.valueKey]: "m" })).toBe(
"m",
);
const issues = (values: Record<string, unknown>) => {
const result = admit(values);
return result.ok ? [] : result.error.issues;
};
expect(issues({ [parameter.key]: "a", [option.valueKey]: "b" })).toEqual([
expect.objectContaining({
path: [option.key],
reason: "invalid_value",
}),
]);
if (required)
expect(issues({})).toEqual([
expect.objectContaining({
path: [option.key],
reason: "missing_argument",
}),
]);
if (option.kind === "native")
// The named spelling is kept when both name one native address.
expect(
selected({ [parameter.key]: "0x1a", [option.valueKey]: "0x1A" }),
).toBe("0x1A");
},
);
const alternatives = selecting.flatMap(
([command, description, parameter, option]) =>
option.alternative === undefined
? []
: [[command, description, parameter, option.alternative] as const],
);
it.each(alternatives)(
"%s maps its alternative selector option onto the same field",
(_command, description, parameter, alternative) => {
const option = parameter.selectorOption!;
const admit = (values: Record<string, unknown>) =>
description.admit({
[description.sessionTarget?.key ?? "path"]: "rel/app",
...values,
});
const alone = admit({ [alternative.valueKey]: "0x10" });
expect(alone.ok && alone.value.input[parameter.field]).toBe(
alternative.selects("0x10"),
);
const agreeing = admit({
[alternative.valueKey]: "0x10",
[option.valueKey]: alternative.selects("0x10"),
});
expect(agreeing.ok).toBe(true);
for (const conflicting of [
{ [alternative.valueKey]: "0x10", [parameter.key]: "main" },
{ [alternative.valueKey]: "0x10", [option.valueKey]: "main" },
]) {
const result = admit(conflicting);
expect(result.ok ? [] : result.error.issues).toEqual([
expect.objectContaining({
path: [alternative.key],
reason: "invalid_value",
}),
]);
}
},
);
it("refuses a selector whose contract admits an empty value", () => {
expect(() =>
describeContractCommand(
{ name: "probe", inputSchema: z.object({ text: z.string() }) },
{
command: "probe",
description: "Probe",
positionals: ["text"],
selectorOptions: { text: { name: "text", description: "Text" } },
},
),
).toThrow("probe.text admits an empty selector");
});
it("refuses a selector option on a field that is not a positional text selector", () => {
const describeSelector = (
positionals: readonly ("text" | "count")[],
field: "text" | "count",
) =>
describeContractCommand(
{
name: "probe",
inputSchema: z.object({ text: z.string(), count: z.number() }),
},
{
command: "probe",
description: "Probe",
positionals,
selectorOptions: { [field]: { name: "named", description: "Named" } },
},
);
expect(() => describeSelector([], "text")).toThrow(
"probe.text is not a positional selector",
);
expect(() => describeSelector(["count"], "count")).toThrow(
"probe.count is not a text selector",
);
});
});
describe("Operation choices selected by an option", () => {
it("refuses an operation choice whose contract projects other options", () => {
const projection = {
command: "probe",
description: "Probe",
operationBy: {
option: "kind",
contracts: {
other: {
name: "other",
inputSchema: z.object({ text: z.string(), extra: z.string() }),
},
},
},
};
const base = describeContractCommand(
{ name: "probe", inputSchema: z.object({ text: z.string() }) },
projection,
);
expect(() => describeOperationChoices(base, projection)).toThrow(
"other does not project to probe's options",
);
});
it("refuses an operation choice whose contract projects other option rules", () => {
const projection = {
command: "probe",
description: "Probe",
operationBy: {
option: "kind",
contracts: {
other: {
name: "other",
inputSchema: z
.object({ text: z.string(), limit: z.number().optional() })
.meta({ dependentRequired: { limit: ["text"] } }),
},
},
},
};
const base = describeContractCommand(
{
name: "probe",
inputSchema: z.object({
text: z.string(),
limit: z.number().optional(),
}),
},
projection,
);
expect(() => describeOperationChoices(base, projection)).toThrow(
"other does not project to probe's options",
);
});
});
describe("Contract command field groups", () => {
const contract = {
name: "group_probe",
inputSchema: z.strictObject({
path: z.string(),
name: z.string().optional(),
tags: z.array(z.string()).optional(),
}),
};
const grouped = (
fields: readonly [
"name" | "tags" | "path",
...("name" | "tags" | "path")[],
],
) =>
describeContractCommand(contract, {
command: "group-probe",
description: "Probe",
positionals: ["path"],
fieldGroups: {
query: {
fields,
description: "JSON selection",
invalidJson: "query must be a JSON selection object.",
},
},
});
it("supplies each member of one JSON object option as its contract field", () => {
const description = grouped(["name", "tags"]);
expect(description.parameters.map(({ key }) => key)).toEqual([
"path",
"query",
]);
const admitted = description.admit({
path: "/x",
query: '{"name":"a","tags":["b"]}',
});
expect(admitted.ok && admitted.value.input).toEqual({
path: "/x",
name: "a",
tags: ["b"],
});
expect(description.admit({ path: "/x" }).ok).toBe(true);
});
it.each([
["[]", ["query"], "invalid_format"],
['{"path":"/y"}', ["query", "path"], undefined],
['{"name":1}', ["name"], undefined],
])("refuses the group %s", (text, path, reason) => {
const admitted = grouped(["name", "tags"]).admit({
path: "/x",
query: text,
});
expect(admitted.ok).toBe(false);
if (admitted.ok) return;
expect(admitted.error.issues[0]).toMatchObject({
path,
...(reason === undefined ? {} : { reason }),
});
});
it("refuses a group member an object rule names", () => {
expect(() =>
describeContractCommand(
{
name: "group_probe",
inputSchema: contract.inputSchema.meta({
dependentRequired: { name: ["tags"] },
}),
},
{
command: "group-probe",
description: "Probe",
positionals: ["path"],
fieldGroups: {
query: {
fields: ["name", "tags"],
description: "x",
invalidJson: "x",
},
},
},
),
).toThrow("group_probe.name is grouped but named by an input rule");
});
it("refuses a required or twice-projected group member", () => {
expect(() => grouped(["path"])).toThrow(
"group_probe.path is projected twice",
);
expect(() =>
describeContractCommand(contract, {
command: "group-probe",
description: "Probe",
fieldGroups: {
query: { fields: ["path"], description: "x", invalidJson: "x" },
},
}),
).toThrow("group_probe.path is a required group member");
});
});