Files
reverse-engineering-anything/tests/boundary/cli/routedCommand.test.ts
T
Ysopwnableandgensokyo-dev 62014b566d refactor(cli)!: dispatch commands through REA-owned execution
Run ordinary CLI commands through REA's registry, argv parser and result owner.
Remove Incur, the second admission parse, SDK error middleware, output capture
and redundant command traversal. Preserve explicit redaction, publication
receipts, incremental output, terminal notice eligibility and drain ownership.
Migrate fixtures to real registrations and retain the derived-source notices.

Validation includes unchanged public parity goldens, public and lifecycle
regressions, repaired fixture consumers, real TTY base comparisons, exports
beyond the engine string limit, four schema catalogs and final static/docs
checks. Native provider and optional validator coverage limits are in the PR.

Fixes #11654. Fixes #10583. Refs #11682, #11476 and #10511.

BREAKING CHANGE: Markdown argument diagnostics use REA's literal escaping,
table widths and token counts. Flag-shaped unknown MCP subcommands honor the
selected format. Completion --schema/--version routes use the canonical
REA-owned hook rather than the retired SDK generator. Refresh affected literal
snapshots and regenerate completion hooks with rea completions <shell>.

Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>
2026-11-16 13:56:34 +00:00

177 lines
5.6 KiB
TypeScript

import { cliCommand } from "../../../src/cli/commandRegistry.js";
import { createCommandCli } from "../../support/cli/commandCli.js";
import { z } from "zod";
import pino from "pino";
import { expect, it } from "vitest";
import {
registerRoutedCommand,
commandRoute,
} from "../../../src/cli/contractCommand.js";
import type { CliInstance } from "../../../src/cli/types.js";
import { absoluteLocalPathStringSchema } from "../../../src/domain/localPath.js";
/** Two synthetic contracts routed by whether the target names an archive. */
const harness = () => {
const calls: { route: string; cliOptions: unknown; input: unknown }[] = [];
const cli = createCommandCli();
const command = { command: "probe", description: "Probe" };
registerRoutedCommand(
cli as unknown as CliInstance,
pino({ enabled: false }),
command,
[
commandRoute(
{
name: "archive_probe",
inputSchema: z.object({
input_path: absoluteLocalPathStringSchema,
mode: z.enum(["fast", "full"]).default("fast"),
policy: z
.object({ rules: z.array(z.string()) })
.default({ rules: [] }),
}),
},
{
...command,
positionals: ["input_path"],
callerPaths: ["input_path"],
jsonInputs: { policy: "policy must be JSON" },
fields: { input_path: { name: "path", description: "Target" } },
cliOptions: {
report: z.enum(["text", "json"]).default("text"),
},
},
async (input, { cliOptions }) => {
calls.push({ route: "archive", cliOptions, input });
return {};
},
{
takes: async ({ path }) => String(path).endsWith(".asar"),
requirement: "an archive target",
},
),
commandRoute(
{ name: "program_probe", inputSchema: z.object({}) },
{ ...command, sessionTarget: { description: "Target" } },
async (input, { cliOptions }) => {
calls.push({ route: "program", cliOptions, input });
return {};
},
{ requirement: "a program target" },
),
],
);
const registered = cliCommand(cli, "probe")?.definition;
if (registered === undefined) throw new Error("probe was not registered");
const execute = Reflect.get(registered, "run") as (
value: unknown,
) => Promise<unknown>;
const parse = (key: "args" | "options", value: unknown) =>
(Reflect.get(registered, key) as { parse(v: unknown): unknown }).parse(
value,
);
// A refused command sets the shared worker's exit status; restore it.
const invoke = async (
path: string,
options: Record<string, unknown> = {},
) => {
const exitCode = process.exitCode;
try {
return await execute({
args: parse("args", { path }),
options: parse("options", options),
});
} finally {
process.exitCode = exitCode;
}
};
const options = Reflect.get(registered, "options") as z.ZodType;
return { calls, invoke, options };
};
it("gives the chosen route its CLI-only defaults after routing without them", async () => {
const { calls, invoke } = harness();
await invoke("/x/app.asar");
await invoke("/x/program");
expect(calls).toEqual([
{
route: "archive",
cliOptions: { report: "text" },
input: { input_path: "/x/app.asar" },
},
{ route: "program", cliOptions: {}, input: {} },
]);
});
it("refuses an option the chosen route does not own by its CLI key", async () => {
const { calls, invoke } = harness();
const refused = await invoke("/x/program", { report: "json" });
expect(calls).toEqual([]);
expect(refused).toMatchObject({
code: "invalid_request",
details: {
operation: "program_probe",
issues: [
{
path: ["report"],
message:
"--report requires an archive target; the given input selects a program target, which does not take it.",
},
],
},
});
});
it("advertises each option's default without supplying it to routing", async () => {
const { calls, invoke, options } = harness();
const schema = z.toJSONSchema(options) as {
readonly properties: Readonly<Record<string, unknown>>;
};
expect(schema.properties).toMatchObject({
mode: {
default: "fast",
description: "Default: fast",
},
policy: { default: JSON.stringify({ rules: [] }) },
report: { default: "text" },
});
// A given option routes the input even when it spells the default.
const refused = await invoke("/x/program", { report: "text" });
expect(calls).toEqual([]);
expect(refused).toMatchObject({
code: "invalid_request",
details: { issues: [{ path: ["report"] }] },
});
});
it("refuses routes that check a shared JSON input differently", () => {
const cli = createCommandCli();
const command = { command: "probe", description: "Probe" };
const route = (name: string, check: () => { ok: true; value: string }) =>
commandRoute(
{
name,
inputSchema: z.object({ policy: z.object({}).optional() }),
},
{
...command,
jsonInputs: { policy: "policy must be JSON" },
jsonInputChecks: { policy: check },
},
async () => ({}),
{ takes: async () => true, requirement: name },
);
expect(() =>
registerRoutedCommand(
cli as unknown as CliInstance,
pino({ enabled: false }),
command,
[
route("first_probe", () => ({ ok: true, value: "first" })),
route("second_probe", () => ({ ok: true, value: "second" })),
],
),
).toThrow("probe routes check --policy differently");
});