mirror of
https://github.com/morluto/rea.git
synced 2026-11-17 04:04:25 +00:00
refactor(cli): derive contract-backed command options from the tool contract (#10571)
* refactor(cli): derive contract-backed command options from the tool contract Each contract-backed CLI command restated its contract's input fields as hand-written incur options and mapped them back to snake_case input with conditional spreads. Nothing checked that the two schemas agreed. Add registerContractCommand: a per-command projection names only what the CLI spells differently (positionals, caller-relative path fields, option renames, CLI help wording, omitted optional fields with a reason). Option schemas, decimal argv tokens and the contract's cross-field rules are derived from the contract input schema, and parsed options map back to the contract input mechanically. Migrate inspect-sqlite-database and the thirteen flat binary-diagnostics inspectors. Their --schema output is unchanged apart from property order, and help lists options in contract order. Delete the SQLite superRefine that mirrored the contract and the per-command spreads. Add a parity test: every projected command exposes each contract field or declares its omission, and each field admits exactly what the contract admits for empty, NUL, relative-path, bound and numeric-spelling probes. * refactor(cli): refuse unprojected contract input forms at registration Address review findings on the contract projection: - Bind inspect-sqlite-database to its contract by name instead of catalog position. - Accept only field forms argv can carry (string, number, boolean, enum, and arrays of strings or enums) instead of rejecting a short list, so arrays of objects, tuples and other forms fail at registration. - Refuse root input keywords other than the projected object constraints and presentation annotations, so a contract rule such as `not` cannot disappear from --schema. * refactor(cli): describe contract commands independently of the CLI framework Split the contract projection into a framework-neutral description and a thin Incur adapter, so a later REA-owned CLI layer (#10583) can render the same description. - contractCliDescription.ts derives each positional and option from the contract and projection: key and short flag, help, argv admission schema, boolean-flag/repeatable/decimal/caller-path facts, object constraints renamed to CLI keys, the optional argv-time cross-field check, and the mapping back to contract input. - contractCommand.ts only renders that description as Incur args and options and runs the handler. Cross-field rules now refuse at argv parsing only when a projection asks (inspect-sqlite-database does, keeping its behavior); otherwise the service's contract parse refuses them as before. Exact-optional fields are projected as optional because argv cannot carry an explicit undefined and Incur's help reads flag and choice types only through optional. The parity guard reads the descriptions, and also checks that boolean fields parse as bare flags and that no projected field stays exact-optional.
This commit is contained in:
1 parent
29fb608559
commit
f3b697da5a
6 files changed
+1145
-731
No files matched your search
@@ -0,0 +1,167 @@
|
||||
import { z } from "incur";
|
||||
import type { Logger } from "pino";
|
||||
|
||||
import { logCliCommand } from "../cliLogging.js";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
import { finishCliEvidenceCommand } from "./cliEvidenceCallerPath.js";
|
||||
import { withCommandCancellation } from "./commandCancellation.js";
|
||||
import {
|
||||
describeContractCommand,
|
||||
type CliContractProjection,
|
||||
type ContractCliDescription,
|
||||
type ContractField,
|
||||
type ProjectedContract,
|
||||
} from "./contractCliDescription.js";
|
||||
import { projectCliAnalysisResult } from "./projectCliAnalysisResult.js";
|
||||
import type { CliInstance } from "./types.js";
|
||||
|
||||
/**
|
||||
* Incur adapter for contract commands. The command itself is described in
|
||||
* `contractCliDescription.ts`; this module only renders that description as
|
||||
* Incur args and options and runs the handler.
|
||||
*/
|
||||
|
||||
/** What a contract command's handler receives besides the contract input. */
|
||||
export interface ContractCommandContext {
|
||||
readonly signal: AbortSignal;
|
||||
/** 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>>;
|
||||
}
|
||||
|
||||
/** A closeable one-shot service that inspects one contract input. */
|
||||
export interface EvidenceInspectionService {
|
||||
inspect(
|
||||
input: unknown,
|
||||
options: { readonly signal: AbortSignal },
|
||||
): Promise<Result<Evidence, AnalysisError>>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
const primaryCallerPath = ({
|
||||
operation,
|
||||
callerInputs,
|
||||
}: ContractCommandContext): string => {
|
||||
const callerPath = callerInputs.path;
|
||||
if (callerPath === undefined)
|
||||
throw new Error(`${operation} has no caller path field named path`);
|
||||
return callerPath;
|
||||
};
|
||||
|
||||
/**
|
||||
* Inspect through a closeable service, finish its cleanup, and record the
|
||||
* caller's spelling of `path` in the Evidence.
|
||||
*/
|
||||
export const inspectWithService =
|
||||
(service: () => EvidenceInspectionService, providerId: string) =>
|
||||
(input: unknown, context: ContractCommandContext) => {
|
||||
const callerPath = primaryCallerPath(context);
|
||||
const owned = service();
|
||||
return finishCliEvidenceCommand(
|
||||
callerPath,
|
||||
() => owned.inspect(input, { signal: context.signal }),
|
||||
owned,
|
||||
providerId,
|
||||
context.operation,
|
||||
context.signal,
|
||||
).then(projectCliAnalysisResult);
|
||||
};
|
||||
|
||||
const descriptions = new WeakMap<CliInstance, ContractCliDescription[]>();
|
||||
|
||||
/** Commands registered on this CLI through `registerContractCommand`. */
|
||||
export const contractCommandDescriptions = (
|
||||
cli: CliInstance,
|
||||
): readonly ContractCliDescription[] => descriptions.get(cli) ?? [];
|
||||
|
||||
const incurOptions = (description: ContractCliDescription): z.ZodType => {
|
||||
const object = z.object(
|
||||
Object.fromEntries(
|
||||
description.parameters
|
||||
.filter(({ positional }) => !positional)
|
||||
.map(({ key, schema }) => [key, schema]),
|
||||
),
|
||||
);
|
||||
const constrained =
|
||||
description.optionConstraints === undefined
|
||||
? object
|
||||
: object.meta(description.optionConstraints);
|
||||
const { checkOptions } = description;
|
||||
return checkOptions === undefined
|
||||
? constrained
|
||||
: constrained.superRefine((parsed, context) => {
|
||||
for (const { path, issue } of checkOptions(parsed))
|
||||
context.addIssue({ ...issue, path: [...path] } as never);
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Register one CLI command described from a tool contract. The handler
|
||||
* receives the contract input, with caller paths made absolute.
|
||||
*/
|
||||
export const registerContractCommand = <
|
||||
Contract extends ProjectedContract,
|
||||
Value,
|
||||
>(
|
||||
cli: CliInstance,
|
||||
logger: Logger,
|
||||
contract: Contract,
|
||||
projection: CliContractProjection<ContractField<Contract>>,
|
||||
run: (
|
||||
input: z.input<Contract["inputSchema"]>,
|
||||
context: ContractCommandContext,
|
||||
) => Promise<Value>,
|
||||
): void => {
|
||||
const description = describeContractCommand(contract, projection);
|
||||
const positionals = description.parameters.filter(
|
||||
({ positional }) => positional,
|
||||
);
|
||||
const alias = Object.fromEntries(
|
||||
description.parameters.flatMap(({ key, alias: short, positional }) =>
|
||||
short === undefined || positional ? [] : [[key, short]],
|
||||
),
|
||||
);
|
||||
cli.command(description.command, {
|
||||
description: description.description,
|
||||
...(positionals.length === 0
|
||||
? {}
|
||||
: {
|
||||
args: z.object(
|
||||
Object.fromEntries(
|
||||
positionals.map(({ key, schema }) => [key, schema]),
|
||||
),
|
||||
),
|
||||
}),
|
||||
options: incurOptions(description),
|
||||
...(Object.keys(alias).length === 0 ? {} : { alias }),
|
||||
run: ({
|
||||
args,
|
||||
options,
|
||||
}: {
|
||||
readonly args?: Readonly<Record<string, unknown>>;
|
||||
readonly options: Readonly<Record<string, unknown>>;
|
||||
}) => {
|
||||
const values = { ...options, ...args };
|
||||
return withCommandCancellation((signal) =>
|
||||
logCliCommand(logger, description.command, () =>
|
||||
run(
|
||||
description.toContractInput(values) as z.input<
|
||||
Contract["inputSchema"]
|
||||
>,
|
||||
{
|
||||
signal,
|
||||
operation: contract.name,
|
||||
callerInputs: description.callerInputs(values),
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
} as never);
|
||||
const registered = descriptions.get(cli) ?? [];
|
||||
registered.push(description);
|
||||
descriptions.set(cli, registered);
|
||||
};
|
||||
Reference in new issue
Block a user