From 5257a3d91278387d832aed41c96b8896c2313a46 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:23:51 +0800 Subject: [PATCH] refactor(cli): read global arguments once with one REA owner (#11687) parseCliGlobalArguments replaces normalizeCliArguments, splitIncurBuiltinArguments and splitCliTimingArguments: it normalizes spaced output forms, routes the root --update alias, splits builtin switches and output values, and reads the timing global in one pass. The output-argument reader, the launcher's doctor path, lazy registration, the Amp scope guard, completions, mcp add, strict positionals and sensitive-value redaction read that record instead of scanning argv again. Only the incur hand-off adapter remains until dispatch moves to REA. Output is unchanged; the CLI parity goldens pass as recorded. --- scripts/rea.mjs | 8 +- src/cli/cliLoader.ts | 20 +- src/cli/cliResultOutput.ts | 11 +- src/cli/cliShell.ts | 33 +-- src/cli/completions.ts | 129 +++++----- src/cli/explicitSensitiveArguments.ts | 23 +- src/cli/mcpBuiltinCommands.ts | 24 +- src/cli/mcpRegistration.ts | 32 +-- src/cli/strictPositionals.ts | 12 +- src/cliBuiltinArguments.ts | 234 +++++++++--------- src/cliOneShot.ts | 29 +-- src/cliOutput.ts | 172 ++++++------- .../boundary/cli/cliBuiltinArguments.test.ts | 73 ++---- .../boundary/cli/cliLazyRegistration.test.ts | 19 +- tests/boundary/cli/cliOutput.test.ts | 15 +- tests/boundary/cli/cliTimingArguments.test.ts | 67 ++--- tests/boundary/cli/completions.test.ts | 11 +- .../cli/defaultAmpRegistration.test.ts | 7 +- .../cli/markdownArgumentErrors.test.ts | 31 +-- tests/boundary/cli/strictPositionals.test.ts | 11 +- tests/support/cli/cliFixture.ts | 4 +- 21 files changed, 484 insertions(+), 481 deletions(-) diff --git a/scripts/rea.mjs b/scripts/rea.mjs index 3cfd650612..fc15ea1923 100755 --- a/scripts/rea.mjs +++ b/scripts/rea.mjs @@ -84,10 +84,10 @@ if (!(await compiledRuntimeExists(runtimeFiles))) { await runMcpHttpEntrypoint(args.slice(1)); } else if (isMcpDoctorMode) { guardClosedStdout(); - // Doctor runs outside Incur, so handle its global timing flag here. Keep a - // token consumed by --format as a value, even when it looks like a flag. - const { arguments: doctorCliArguments, enabled: timingRequested } = - builtinArguments.splitCliTimingArguments(doctorArguments); + // Doctor runs outside the command dispatcher, so the launcher measures its + // timing global, which the global argument reader has taken out. + const { arguments: doctorCliArguments, timings: timingRequested } = + doctorArguments; const started = performance.now(); try { const { runProductionMcpDoctorCli } = diff --git a/src/cli/cliLoader.ts b/src/cli/cliLoader.ts index ef11e23651..f4ccc50854 100644 --- a/src/cli/cliLoader.ts +++ b/src/cli/cliLoader.ts @@ -1,7 +1,4 @@ -import { - cliCompletionShell, - splitIncurBuiltinArguments, -} from "../cliBuiltinArguments.js"; +import type { CliGlobalArguments } from "../cliBuiltinArguments.js"; import { RECORDED_CLI_COMMAND_REGISTRATIONS } from "../recordedCliCommandRegistrations.js"; import { CLI_COMMAND_REGISTRATIONS, @@ -24,18 +21,18 @@ const isRegistrationId = (id: string): id is CliCommandRegistrationId => /** * The registrars the command these arguments run needs, or undefined when the - * complete CLI must answer. A standalone `--version` needs none: Incur answers + * complete CLI must answer, as it does for shell completion, which has no + * global arguments. A standalone `--version` needs none: Incur answers * it from the CLI identity alone. Help, schemas, `--llms`, completions, other * Incur builtins, unknown names ("did you mean"), and a missing or unusable * recording all describe or search every command. */ export const selectCliRegistrations = ( - arguments_: readonly string[], - environment: Readonly, + global: CliGlobalArguments | undefined, recorded: Readonly> | undefined, ): readonly CliCommandRegistrationId[] | undefined => { - if (cliCompletionShell(environment) !== undefined) return undefined; - const { command, flags } = splitIncurBuiltinArguments(arguments_); + if (global === undefined) return undefined; + const { command, flags } = global; if (command.length === 0 && flags.size === 1 && flags.has("--version")) return []; if (recorded === undefined) return undefined; @@ -61,12 +58,11 @@ export interface CliRuntime { * none, and anything else loads the complete CLI. */ export const loadCliRuntime = async ( - arguments_: readonly string[], + global: CliGlobalArguments | undefined, environment: NodeJS.ProcessEnv, ): Promise => { const ids = selectCliRegistrations( - arguments_, - environment, + global, RECORDED_CLI_COMMAND_REGISTRATIONS, ); if (ids === undefined) { diff --git a/src/cli/cliResultOutput.ts b/src/cli/cliResultOutput.ts index 619549969e..16dd1f7ef0 100644 --- a/src/cli/cliResultOutput.ts +++ b/src/cli/cliResultOutput.ts @@ -5,10 +5,7 @@ import { estimateTokenCount } from "tokenx"; import { analysisErrorProjectionSchema } from "../domain/analysisErrorProjectionSchema.js"; import type { ParsedCliOutputArguments } from "../cliOutput.js"; -import { - normalizeCliArguments, - splitIncurBuiltinArguments, -} from "../cliBuiltinArguments.js"; +import { parseCliGlobalArguments } from "../cliBuiltinArguments.js"; import { cliOperationFailureIdentity, cliOperationFailurePayload, @@ -308,8 +305,8 @@ export const createCliResultOutput = ( sdkCompletion = undefined; }, sdkArguments(args) { - const normalized = normalizeCliArguments(args); - const split = splitIncurBuiltinArguments(normalized); + const split = parseCliGlobalArguments(args); + const normalized = split.arguments; const values = new Set(split.outputValues.map(({ index }) => index)); const hasFlag = (flag: string) => normalized.some((token, index) => token === flag && !values.has(index)); @@ -328,7 +325,7 @@ export const createCliResultOutput = ( !hasFlag("--version"))); // The caller's parsed controls remain authoritative: the CLI may adapt // CSV/TSV to JSON for Incur without changing the requested presentation. - if (format !== "jsonl" || !options.tokenCount) return normalized; + if (format !== "jsonl" || !options.tokenCount) return [...normalized]; // Incur counts errors before REA can retain their diagnostic payload. // Preserve operands using the shared builtin consumption rules. return normalized.filter( diff --git a/src/cli/cliShell.ts b/src/cli/cliShell.ts index 26a5d67cbc..2be9bb85bd 100644 --- a/src/cli/cliShell.ts +++ b/src/cli/cliShell.ts @@ -6,7 +6,7 @@ import type { FridaInstrumentationPort } from "../ports/frida/FridaInstrumentati import { currentClientRegistrationCommand } from "../application/ClientRegistrationIdentity.js"; import { adaptCliOutputArgumentsForIncur, - normalizeCliArguments, + parseCliGlobalArguments, } from "../cliBuiltinArguments.js"; import type { DirectAnalysis } from "../composition/directAnalysis.js"; import { parseLogLevel } from "../config/processStart.js"; @@ -153,28 +153,31 @@ export const createCliShell = (options: CliShellOptions): CliInstance => { const serveDeclared = excludeDeclaredSensitiveArguments(cli); encodeCliArgumentErrors(cli); const serve = cli.serve.bind(cli); - const complete = createCliCompletions(cli, environment); + const completions = createCliCompletions(cli, environment); cli.serve = (arguments_ = process.argv.slice(2), serveOptions) => { - if (complete(arguments_, serveOptions ?? {})) return Promise.resolve(); - const normalized = normalizeCliArguments(arguments_); + if (completions.complete(arguments_, serveOptions ?? {})) + return Promise.resolve(); + const global = parseCliGlobalArguments(arguments_); + if (completions.writeScript(global, serveOptions ?? {})) + return Promise.resolve(); const registration = serveMcpRegistration( - normalized, + global, environment, defaultRegistration, serveOptions ?? {}, ); if (registration !== undefined) return registration; - const result = serveStrict( - normalized, - serveOptions ?? {}, - (tokens, selected) => - serveDeclared(tokens, selected, (declared, declaredOptions) => - reportUnknownMcpSubcommand(cli.name, declared, declaredOptions) - ? Promise.resolve() - : serve(adaptCliOutputArgumentsForIncur(declared), declaredOptions), - ), + const result = serveStrict(global, serveOptions ?? {}, (selected) => + serveDeclared(global, selected, (declaredOptions) => + reportUnknownMcpSubcommand(cli.name, global, declaredOptions) + ? Promise.resolve() + : serve( + adaptCliOutputArgumentsForIncur(global.arguments), + declaredOptions, + ), + ), ); - const note = completionHelpNote(normalized); + const note = completionHelpNote(global); if (note === undefined) return result; return result.then(() => { const write = diff --git a/src/cli/completions.ts b/src/cli/completions.ts index 33da47afcf..713d292753 100644 --- a/src/cli/completions.ts +++ b/src/cli/completions.ts @@ -1,15 +1,15 @@ import { z } from "zod"; import { + CLI_BUILTIN_FLAGS, CLI_COMPLETION_SHELLS, cliCompletionShell, - INCUR_BUILTIN_FLAGS, OUTPUT_SWITCHES, VALUED_OUTPUT_FLAGS, - normalizeCliArguments, - splitIncurBuiltinArguments, + parseCliGlobalArguments, + type CliGlobalArguments, } from "../cliBuiltinArguments.js"; -import { CLI_OUTPUT_FORMATS, parseCliOutputArguments } from "../cliOutput.js"; +import { CLI_OUTPUT_FORMATS, readCliOutputArguments } from "../cliOutput.js"; import { completeWords, completionScript, @@ -26,11 +26,10 @@ const ROOT_FLAGS = new Set(["--mcp", "--update", "--version"]); /** Supplement Incur's built-in setup instructions without replacing its help. */ export const completionHelpNote = ( - arguments_: readonly string[], + global: CliGlobalArguments, ): string | undefined => { - const split = splitIncurBuiltinArguments(arguments_); const words = - split.command[0] === "rea" ? split.command.slice(1) : split.command; + global.command[0] === "rea" ? global.command.slice(1) : global.command; if (words[0] !== "completions") return undefined; const rest = words.slice(1); if ( @@ -41,8 +40,8 @@ export const completionHelpNote = ( )) ) return undefined; - const values = new Set(split.outputValues.map(({ index }) => index)); - const flags = arguments_.filter((_, index) => !values.has(index)); + const values = new Set(global.outputValues.map(({ index }) => index)); + const flags = global.arguments.filter((_, index) => !values.has(index)); if ( flags.some((word) => [ @@ -73,7 +72,7 @@ const standardGlobals = (root: boolean): z.ZodObject => : z.string().optional(), ] as const, ), - ...[...INCUR_BUILTIN_FLAGS] + ...[...CLI_BUILTIN_FLAGS] .filter( (flag) => flag.startsWith("--") && @@ -113,77 +112,89 @@ const completionCommands = ( return commands; }; -/** One tree owns command scope; completionProtocol owns candidates and shell encoding. */ +/** + * One tree owns command scope; completionProtocol owns candidates and shell + * encoding. `complete` answers the shell's completion protocol, whose words + * are transport data; `writeScript` answers `completions `. + */ export const createCliCompletions = ( cli: CliInstance, environment: Readonly, -) => { +): { + complete(arguments_: readonly string[], options: ServeOptions): boolean; + writeScript(global: CliGlobalArguments, options: ServeOptions): boolean; +} => { const script = (shell: (typeof CLI_COMPLETION_SHELLS)[number]) => completionScript(shell, cli.name); - return (arguments_: readonly string[], options: ServeOptions): boolean => { - const write = - options.stdout ?? ((text: string) => process.stdout.write(text)); + const writer = (options: ServeOptions) => + options.stdout ?? ((text: string) => process.stdout.write(text)); + const complete = ( + arguments_: readonly string[], + options: ServeOptions, + ): boolean => { const shell = cliCompletionShell(environment); - if (shell !== undefined) { - const separator = arguments_.indexOf("--"); - const words = - separator < 0 ? arguments_ : arguments_.slice(separator + 1); - if (words.length === 0) { - write(script(shell)); - return true; - } - const index = Number(environment._COMPLETE_INDEX ?? words.length - 1); - if (!Number.isSafeInteger(index) || index < 0 || index > words.length) - return true; - // Consume global option values before scope resolution. A value named - // 'mcp' is still data; leave an unfinished flag for Incur's enum hints. - const before = splitIncurBuiltinArguments( - normalizeCliArguments(words.slice(1, index)), - ).command; - if (before.includes("--")) return true; - const input = [cli.name, ...before, words[index] ?? ""]; - const doctor = before[0] === "mcp" && before[1] === "doctor"; - const candidates = completeWords( - completionCommands(cli), - input, - input.length - 1, - { - schema: doctor - ? // The launcher consumes this global before doctor parses options. - MCP_DOCTOR_OPTIONS.extend({ timings: z.boolean().optional() }) - : standardGlobals(before.length === 0), - alias: doctor ? MCP_DOCTOR_ALIAS : { help: "h" }, - }, - ); - const result = formatCompletions(shell, candidates); - if (result !== "") write(result); + if (shell === undefined) return false; + const write = writer(options); + const separator = arguments_.indexOf("--"); + const words = separator < 0 ? arguments_ : arguments_.slice(separator + 1); + if (words.length === 0) { + write(script(shell)); return true; } - const normalized = normalizeCliArguments(arguments_); - const split = splitIncurBuiltinArguments(normalized); - const offset = split.command[0] === cli.name ? 1 : 0; + const index = Number(environment._COMPLETE_INDEX ?? words.length - 1); + if (!Number.isSafeInteger(index) || index < 0 || index > words.length) + return true; + // Consume global option values before scope resolution. A value named + // 'mcp' is still data; leave an unfinished flag for Incur's enum hints. + const before = parseCliGlobalArguments(words.slice(1, index)).command; + if (before.includes("--")) return true; + const input = [cli.name, ...before, words[index] ?? ""]; + const doctor = before[0] === "mcp" && before[1] === "doctor"; + const candidates = completeWords( + completionCommands(cli), + input, + input.length - 1, + { + schema: doctor + ? // The launcher consumes this global before doctor parses options. + MCP_DOCTOR_OPTIONS.extend({ timings: z.boolean().optional() }) + : standardGlobals(before.length === 0), + alias: doctor ? MCP_DOCTOR_ALIAS : { help: "h" }, + }, + ); + const result = formatCompletions(shell, candidates); + if (result !== "") write(result); + return true; + }; + const writeScript = ( + global: CliGlobalArguments, + options: ServeOptions, + ): boolean => { + const { command } = global; + const offset = command[0] === cli.name ? 1 : 0; const selected = CLI_COMPLETION_SHELLS.find( - (value) => value === split.command[offset + 1], + (value) => value === command[offset + 1], ); if ( - split.command[offset] !== "completions" || + command[offset] !== "completions" || selected === undefined || - split.command.length !== offset + 2 + command.length !== offset + 2 ) return false; // Help/manifests/schema/version and server controls keep framework precedence. - const values = new Set(split.outputValues.map(({ index }) => index)); + const values = new Set(global.outputValues.map(({ index }) => index)); if ( - normalized.some( + global.arguments.some( (token, index) => !values.has(index) && - ((INCUR_BUILTIN_FLAGS.has(token) && !OUTPUT_SWITCHES.has(token)) || + ((CLI_BUILTIN_FLAGS.has(token) && !OUTPUT_SWITCHES.has(token)) || token === "--version"), ) ) return false; - if (!parseCliOutputArguments(normalized).validation.ok) return false; - write(`${script(selected)}\n`); + if (!readCliOutputArguments(global).validation.ok) return false; + writer(options)(`${script(selected)}\n`); return true; }; + return { complete, writeScript }; }; diff --git a/src/cli/explicitSensitiveArguments.ts b/src/cli/explicitSensitiveArguments.ts index 502a6a478d..573f941518 100644 --- a/src/cli/explicitSensitiveArguments.ts +++ b/src/cli/explicitSensitiveArguments.ts @@ -4,12 +4,12 @@ import { Errors, type MiddlewareHandler } from "incur"; import { z } from "zod"; import { - parseCliOutputArguments, + readCliOutputArguments, renderCliOutputArgumentError, } from "../cliOutput.js"; import { declaredSensitiveValues, - splitIncurBuiltinArguments, + type CliGlobalArguments, } from "../cliBuiltinArguments.js"; import { redactExplicitText } from "../domain/explicitSensitiveValues.js"; import type { CliInstance } from "./types.js"; @@ -31,10 +31,10 @@ type ServeOptions = NonNullable[1]>; /** Share the executable boundary's output admission and structured diagnostics. */ const reportDeclaredOutputRejection = ( - arguments_: readonly string[], + global: CliGlobalArguments, options: ServeOptions, ): boolean => { - const validation = parseCliOutputArguments(arguments_).validation; + const validation = readCliOutputArguments(global).validation; if (validation.ok) return false; (options.stdout ?? ((text: string) => process.stdout.write(text)))( renderCliOutputArgumentError(validation), @@ -98,9 +98,9 @@ const withoutDeclaredText = ( export const excludeDeclaredSensitiveArguments = ( cli: CliInstance, ): (( - arguments_: readonly string[], + global: CliGlobalArguments, options: ServeOptions, - serve: (arguments_: string[], options: ServeOptions) => Promise, + serve: (options: ServeOptions) => Promise, ) => Promise) => { const declarations = new AsyncLocalStorage(); const excludeFromFailures: MiddlewareHandler = async (_context, next) => { @@ -121,11 +121,10 @@ export const excludeDeclaredSensitiveArguments = ( // as the parsing and run that Incur executes inside the chain. command.middleware = [excludeFromFailures, ...(command.middleware ?? [])]; }); - return async (arguments_, options, serve) => { - const split = splitIncurBuiltinArguments(arguments_); - const values = declaredSensitiveValues(split.command); - if (values.length === 0) return serve([...arguments_], options); - if (reportDeclaredOutputRejection(arguments_, options)) return; - return declarations.run(values, () => serve([...arguments_], options)); + return async (global, options, serve) => { + const values = declaredSensitiveValues(global.command); + if (values.length === 0) return serve(options); + if (reportDeclaredOutputRejection(global, options)) return; + return declarations.run(values, () => serve(options)); }; }; diff --git a/src/cli/mcpBuiltinCommands.ts b/src/cli/mcpBuiltinCommands.ts index a73be21507..7557f13100 100644 --- a/src/cli/mcpBuiltinCommands.ts +++ b/src/cli/mcpBuiltinCommands.ts @@ -3,10 +3,11 @@ import { mcpRegistrationOptionsSchema } from "../contracts/mcpRegistration.js"; import { adaptCliOutputArgumentsForIncur, declaredSensitiveValues, - splitIncurBuiltinArguments, + parseCliGlobalArguments, + type CliGlobalArguments, } from "../cliBuiltinArguments.js"; import { - parseCliOutputArguments, + readCliOutputArguments, renderCliDocument, type CliOutputFormat, } from "../cliOutput.js"; @@ -44,22 +45,23 @@ const PLAIN_SHELL_WORD = /^(?!=)[\w./+=:,-]+$/u; * Incur 0.6.1 rejects an unknown `mcp` subcommand in TOON regardless of the * selected format. Report the same envelope in the explicitly selected format; * without one, Incur's TOON or human rendering is already the selected output. - * The arguments are the caller's normalized ones, before REA adapts output - * flags for Incur, so the suggested command keeps the caller's selection. + * The caller's arguments are read before REA adapts output flags for Incur, + * so the suggested command keeps the caller's selection. */ export const reportUnknownMcpSubcommand = ( name: string, - arguments_: readonly string[], + global: CliGlobalArguments, options: ServeOptions, ): boolean => { - const { command, commandIndices } = splitIncurBuiltinArguments(arguments_); + const { arguments: arguments_, command, commandIndices } = global; const [entry, subcommand] = command; // Incur receives JSON for REA's delimited formats and no `--columns`. - const incurArguments = adaptCliOutputArgumentsForIncur(arguments_); + const incur = parseCliGlobalArguments( + adaptCliOutputArgumentsForIncur(arguments_), + ); + const incurArguments = incur.arguments; const incurOutputValues = new Set( - splitIncurBuiltinArguments(incurArguments).outputValues.map( - ({ index }) => index, - ), + incur.outputValues.map(({ index }) => index), ); if ( entry !== "mcp" || @@ -75,7 +77,7 @@ export const reportUnknownMcpSubcommand = ( ) ) return false; - const output = parseCliOutputArguments(incurArguments); + const output = readCliOutputArguments(incur); // Invalid output controls keep Incur's own parse diagnostic. if (!output.formatExplicit || !output.validation.ok) return false; const sensitive = declaredSensitiveValues(command); diff --git a/src/cli/mcpRegistration.ts b/src/cli/mcpRegistration.ts index 8e93024a83..4c2e8a8afe 100644 --- a/src/cli/mcpRegistration.ts +++ b/src/cli/mcpRegistration.ts @@ -21,11 +21,11 @@ import { classifyMcpAddDiscovery, declaredSensitiveValues, readMcpAddArguments, - splitIncurBuiltinArguments, + type CliGlobalArguments, } from "../cliBuiltinArguments.js"; import { CLI_DOCUMENT_OUTPUT_FORMATS, - parseCliOutputArguments, + readCliOutputArguments, renderCliDocument, renderCliOutputArgumentError, type CliOutputArgumentValidation, @@ -98,7 +98,7 @@ const precedingFlags = [ /** Route only the named REA registration operation; other Incur commands remain theirs. */ export const serveMcpRegistration = ( - arguments_: readonly string[], + global: CliGlobalArguments, environment: Readonly, defaultCommand: Result< ClientRegistrationCommand, @@ -106,27 +106,22 @@ export const serveMcpRegistration = ( >, options: ServeOptions, ): Promise | undefined => { - const split = splitIncurBuiltinArguments(arguments_); - const offset = split.command[0] === PRODUCT_IDENTITY.cliBinary ? 1 : 0; + const offset = global.command[0] === PRODUCT_IDENTITY.cliBinary ? 1 : 0; if ( - split.command[offset] !== "mcp" || - split.command[offset + 1] !== "add" || - precedingFlags.some((flag) => split.flags.has(flag)) + global.command[offset] !== "mcp" || + global.command[offset + 1] !== "add" || + precedingFlags.some((flag) => global.flags.has(flag)) ) return undefined; return (async () => { - const presentation = createRegistrationPresentation( - arguments_, - split.command, - options, - ); + const presentation = createRegistrationPresentation(global, options); if ( presentation === undefined || - (await serveRegistrationDiscovery(split.flags, presentation)) + (await serveRegistrationDiscovery(global.flags, presentation)) ) return Promise.resolve(); const request = readRegistrationRequest( - split.command.slice(offset + 2), + global.command.slice(offset + 2), defaultCommand, ); if (!request.ok) { @@ -146,8 +141,7 @@ export const serveMcpRegistration = ( /** Bind one invocation's rendering, explicit redaction and exit behavior. */ const createRegistrationPresentation = ( - arguments_: readonly string[], - command: readonly string[], + global: CliGlobalArguments, options: ServeOptions, ): RegistrationPresentation | undefined => { const write = @@ -156,7 +150,7 @@ const createRegistrationPresentation = ( if (options.exit !== undefined) options.exit(1); else process.exitCode = 1; }; - const output = parseCliOutputArguments(arguments_); + const output = readCliOutputArguments(global); const validation: CliOutputArgumentValidation = output.validation.ok && (output.format === "csv" || output.format === "tsv") ? { @@ -209,7 +203,7 @@ const createRegistrationPresentation = ( async validation(message, field, error, code = "invalid_value") { const retained = redactExplicitText( message, - declaredSensitiveValues(command), + declaredSensitiveValues(global.command), ); await document( { diff --git a/src/cli/strictPositionals.ts b/src/cli/strictPositionals.ts index 72e3077813..09e0d47a96 100644 --- a/src/cli/strictPositionals.ts +++ b/src/cli/strictPositionals.ts @@ -3,7 +3,7 @@ import { AsyncLocalStorage } from "node:async_hooks"; import { Errors } from "incur"; import { z } from "zod"; -import { splitIncurBuiltinArguments } from "../cliBuiltinArguments.js"; +import type { CliGlobalArguments } from "../cliBuiltinArguments.js"; import { parseCliArgv } from "./argvParser.js"; import type { CliInstance } from "./types.js"; import { visitRegisteredCommands } from "./visitRegisteredCommands.js"; @@ -43,9 +43,9 @@ const optionTokenShape = ( export const validateCliArguments = ( cli: CliInstance, ): (( - arguments_: readonly string[], + global: CliGlobalArguments, options: ServeOptions, - serve: (arguments_: string[], options: ServeOptions) => Promise, + serve: (options: ServeOptions) => Promise, ) => Promise) => { const invocation = new AsyncLocalStorage(); visitRegisteredCommands(cli, (command) => { @@ -139,8 +139,6 @@ export const validateCliArguments = ( ...(command.middleware ?? []), ]; }); - return (arguments_, options, serve) => - invocation.run(splitIncurBuiltinArguments(arguments_).command, () => - serve([...arguments_], options), - ); + return (global, options, serve) => + invocation.run(global.command, () => serve(options)); }; diff --git a/src/cliBuiltinArguments.ts b/src/cliBuiltinArguments.ts index ff82fea8d4..ee6c3ee2c6 100644 --- a/src/cliBuiltinArguments.ts +++ b/src/cliBuiltinArguments.ts @@ -16,8 +16,8 @@ export const OUTPUT_SWITCHES: ReadonlySet = new Set([ "--timings", ]); -/** Valueless flags Incur removes from every position before command parsing. */ -export const INCUR_BUILTIN_FLAGS: ReadonlySet = new Set([ +/** Valueless global flags taken out of every position before command parsing. */ +export const CLI_BUILTIN_FLAGS: ReadonlySet = new Set([ "--full-output", "--llms", "--llms-full", @@ -25,7 +25,7 @@ export const INCUR_BUILTIN_FLAGS: ReadonlySet = new Set([ "--help", "-h", "--update", - // Incur's internal update-check flag. + // The detached update check's own flag. "--incur-update-check", "--schema", "--json", @@ -33,7 +33,7 @@ export const INCUR_BUILTIN_FLAGS: ReadonlySet = new Set([ "--timings", ]); -/** Supported boolean spelling under the pinned Incur global parser. */ +/** The timing global's spellings: `--timings`, `--no-timings`, `--timings=`. */ const cliTimingFlagValue = (token: string): boolean | undefined => token === "--timings" ? true @@ -43,112 +43,45 @@ const cliTimingFlagValue = (token: string): boolean | undefined => ? token.slice("--timings=".length) === "true" : undefined; -/** Remove only timing globals, preserving valued output data and the -- boundary. */ -export const splitCliTimingArguments = ( - arguments_: readonly string[], -): { arguments: string[]; enabled: boolean } => { - const values = new Set( - splitIncurBuiltinArguments(arguments_).outputValues.map( - ({ index }) => index, - ), - ); - let enabled = false; - let ended = false; - const remaining = arguments_.filter((token, index) => { - if (values.has(index)) return true; - if (token === "--") ended = true; - const value = ended ? undefined : cliTimingFlagValue(token); - if (value === undefined) return true; - enabled = value; - return false; - }); - return { arguments: remaining, enabled }; -}; - -/** Command tokens and output-flag values as Incur's builtin pass assigns them. */ -export interface IncurBuiltinArgumentSplit { +/** + * One invocation's global arguments, read once from the caller's argv. + * Consumers read these facts instead of scanning argv again. + */ +export interface CliGlobalArguments { + /** + * The caller's arguments with valued output flags in spaced form and a root + * `--update` routed to `update`. The positions below index into this list. + */ + readonly arguments: readonly string[]; /** Tokens left for command resolution and command option parsing. */ readonly command: readonly string[]; /** Argument position of each `command` token. */ readonly commandIndices: readonly number[]; - /** Valueless global flags extracted by Incur before command dispatch. */ + /** Valueless global flags and timing spellings taken out before command parsing. */ readonly flags: ReadonlySet; /** Positions of nonempty values consumed by valued output flags. */ readonly outputValues: readonly { readonly flag: string; readonly index: number; }[]; + /** Positions of the timing spellings in `flags`. */ + readonly timingIndices: readonly number[]; + /** The timing global's value; the last spelling wins. */ + readonly timings: boolean; } /** - * Mirror Incur's builtin pass over normalized arguments without stopping at a - * rejected value, so callers can still see every later token. Then mirror the - * boolean timing global pass over the remaining tokens; no config is registered. + * Route the root update alias and split `--flag=value` output forms. Command + * options accept both forms; the global split below reads the spaced one. */ -export const splitIncurBuiltinArguments = ( - arguments_: readonly string[], -): IncurBuiltinArgumentSplit => { - const command: string[] = []; - const commandIndices: number[] = []; - const flags = new Set(); - const outputValues: { readonly flag: string; readonly index: number }[] = []; - for (let index = 0; index < arguments_.length; index += 1) { - const argument = arguments_[index]!; - const next = arguments_[index + 1]; - if ( - (INCUR_BUILTIN_FLAGS.has(argument) && argument !== "--timings") || - // A following value belongs to a command-local `--version` option. - (argument === "--version" && (next === undefined || next.startsWith("-"))) - ) { - flags.add(argument); - continue; - } - if (VALUED_OUTPUT_FLAGS.has(argument) && next) { - outputValues.push({ flag: argument, index: index + 1 }); - index += 1; - continue; - } - command.push(argument); - commandIndices.push(index); - } - // Incur extracts builtin output values first, then parses globals until `--`. - // A timing-shaped output value is data; a command option's value is still - // subject to this global pass before the registration builtin consumes it. - let globalsEnded = false; - const remaining: string[] = []; - const remainingIndices: number[] = []; - command.forEach((token, position) => { - if (token === "--") globalsEnded = true; - if (!globalsEnded && cliTimingFlagValue(token) !== undefined) { - flags.add(token); - return; - } - remaining.push(token); - remainingIndices.push(commandIndices[position]!); - }); - return { - command: remaining, - commandIndices: remainingIndices, - flags, - outputValues, - }; -}; - -/** - * Route the root update alias and split `--flag=value` output forms. Incur reads these - * flags only in spaced form, so `--format=json` otherwise reaches the command - * parser and fails as an unknown flag. Command options accept both forms. - */ -export const normalizeCliArguments = ( - arguments_: readonly string[], -): string[] => { +const normalizeCliArguments = (arguments_: readonly string[]): string[] => { const normalized: string[] = []; const updates = new Set(); let rootUpdate = true; for (let index = 0; index < arguments_.length; index += 1) { const argument = arguments_[index]!; if (VALUED_OUTPUT_FLAGS.has(argument) && arguments_[index + 1]) { - // Incur consumes a nonempty spaced value before looking for more flags. + // A nonempty spaced value is consumed before looking for more flags. // Its contents belong to that option, even when they look like a flag. normalized.push(argument, arguments_[index + 1]!); index += 1; @@ -169,12 +102,76 @@ export const normalizeCliArguments = ( } } // Output option values were consumed above; flag-shaped data is never an alias. - // Help/check/command/unknown tokens retain Incur's parsing and precedence. + // Help/check/command/unknown tokens keep their own parsing and precedence. return rootUpdate && updates.size > 0 ? ["update", ...normalized.filter((_, index) => !updates.has(index))] : normalized; }; +/** + * Read one invocation's global arguments. Builtin switches are taken from any + * position, including after `--`; a valued output flag consumes the next + * nonempty token as data. The timing global is then read from the remaining + * tokens until `--`. The output argument reader reports malformed output + * values from these same positions. + */ +export const parseCliGlobalArguments = ( + arguments_: readonly string[], +): CliGlobalArguments => { + const normalized = normalizeCliArguments(arguments_); + const command: string[] = []; + const commandIndices: number[] = []; + const flags = new Set(); + const outputValues: { readonly flag: string; readonly index: number }[] = []; + for (let index = 0; index < normalized.length; index += 1) { + const argument = normalized[index]!; + const next = normalized[index + 1]; + if ( + (CLI_BUILTIN_FLAGS.has(argument) && argument !== "--timings") || + // A following value belongs to a command-local `--version` option. + (argument === "--version" && (next === undefined || next.startsWith("-"))) + ) { + flags.add(argument); + continue; + } + if (VALUED_OUTPUT_FLAGS.has(argument) && next) { + outputValues.push({ flag: argument, index: index + 1 }); + index += 1; + continue; + } + command.push(argument); + commandIndices.push(index); + } + // A timing-shaped output value is data; a command option's value is still + // read by this global pass before the command parser sees it. + let globalsEnded = false; + let timings = false; + const remaining: string[] = []; + const remainingIndices: number[] = []; + const timingIndices: number[] = []; + command.forEach((token, position) => { + if (token === "--") globalsEnded = true; + const value = globalsEnded ? undefined : cliTimingFlagValue(token); + if (value === undefined) { + remaining.push(token); + remainingIndices.push(commandIndices[position]!); + return; + } + flags.add(token); + timings = value; + timingIndices.push(commandIndices[position]!); + }); + return { + arguments: normalized, + command: remaining, + commandIndices: remainingIndices, + flags, + outputValues, + timingIndices, + timings, + }; +}; + /** Keep REA-owned delimited formats out of Incur's narrower formatter surface. */ export const adaptCliOutputArgumentsForIncur = ( arguments_: readonly string[], @@ -219,7 +216,7 @@ type McpAddArgumentError = * and dispatch cannot interpret a command value as an agent selector. */ export const readMcpAddArguments = ( - command: IncurBuiltinArgumentSplit["command"], + command: CliGlobalArguments["command"], ): { readonly agents: readonly string[]; readonly commandText: string | undefined; @@ -292,10 +289,10 @@ export const classifyMcpAddDiscovery = ( }; /** The lightweight launcher and full dispatcher share the same parsed scope fact. */ -export const isProjectScopedAmpRegistration = ( - arguments_: readonly string[], -): boolean => { - const { command, flags } = splitIncurBuiltinArguments(arguments_); +export const isProjectScopedAmpRegistration = ({ + command, + flags, +}: CliGlobalArguments): boolean => { if (command[0] !== "mcp" || command[1] !== "add") return false; if (classifyMcpAddDiscovery(flags) !== undefined) return false; const rest = command.slice(2); @@ -303,35 +300,42 @@ export const isProjectScopedAmpRegistration = ( return !global && (agents.length === 0 || agents.includes("amp")); }; -/** Select production doctor using the same normalized builtin argument owner as CLI dispatch. */ +/** + * The arguments production `mcp doctor` parses itself: the caller's, without + * the `mcp doctor` words and the timing global the launcher measures. Returns + * undefined for any other command. + */ export const productionMcpDoctorArguments = ( arguments_: readonly string[], -): readonly string[] | undefined => { - const normalized = normalizeCliArguments(arguments_); - const split = splitIncurBuiltinArguments(normalized); - if (split.command[0] !== "mcp" || split.command[1] !== "doctor") +): + | { readonly arguments: readonly string[]; readonly timings: boolean } + | undefined => { + const global = parseCliGlobalArguments(arguments_); + if (global.command[0] !== "mcp" || global.command[1] !== "doctor") return undefined; - const values = new Set(split.outputValues.map(({ index }) => index)); - const mcp = normalized.findIndex( - (token, index) => token === "mcp" && !values.has(index), - ); - const doctor = normalized.findIndex( - (token, index) => index > mcp && token === "doctor" && !values.has(index), - ); - return normalized.filter((_, index) => index !== mcp && index !== doctor); + const removed = new Set([ + global.commandIndices[0]!, + global.commandIndices[1]!, + ...global.timingIndices, + ]); + return { + arguments: global.arguments.filter((_, index) => !removed.has(index)), + timings: global.timings, + }; }; -/** Incur accepts the schema key and its kebab-case spelling. */ +/** The command parser accepts the schema key and its kebab-case spelling. */ const FLAGS = ["--sensitive-value", "--sensitiveValue"] as const; /** - * Read declarations from the tokens Incur leaves for command parsing. Incur - * rejects a malformed token before it reaches later declarations, so this scan - * is independent of parse success. A token following a declaration flag counts - * as declared even where the command parser would bind it to another option. + * Read declarations from the tokens left for command parsing. The command + * parser rejects a malformed token before it reaches later declarations, so + * this scan is independent of parse success. A token following a declaration + * flag counts as declared even where the command parser would bind it to + * another option. */ export const declaredSensitiveValues = ( - command: IncurBuiltinArgumentSplit["command"], + command: CliGlobalArguments["command"], ): readonly string[] => { const values = new Set(); for (let index = 0; index < command.length; index += 1) { diff --git a/src/cliOneShot.ts b/src/cliOneShot.ts index 41580c7fc9..bae4b455fb 100644 --- a/src/cliOneShot.ts +++ b/src/cliOneShot.ts @@ -3,12 +3,12 @@ import type { Writable } from "node:stream"; import { cliCompletionShell, isProjectScopedAmpRegistration, - normalizeCliArguments, - splitIncurBuiltinArguments, + parseCliGlobalArguments, } from "./cliBuiltinArguments.js"; import { cliConfigurationError, parseCliOutputArguments, + readCliOutputArguments, renderCliOutputArgumentError, renderEmptyFilteredCliOutput, renderVersionReport, @@ -57,14 +57,16 @@ export const runOneShotCli = async ( arguments_: readonly string[], host: OneShotCliHost, ): Promise => { - const isShellCompletion = cliCompletionShell(host.environment) !== undefined; - const cliArguments = isShellCompletion - ? [...arguments_] - : normalizeCliArguments([...arguments_]); // Completion words are transport data, including partial output flags. - const outputOptions = parseCliOutputArguments( - isShellCompletion ? [] : cliArguments, - ); + const global = + cliCompletionShell(host.environment) === undefined + ? parseCliGlobalArguments(arguments_) + : undefined; + const cliArguments = global?.arguments ?? arguments_; + const outputOptions = + global === undefined + ? parseCliOutputArguments([]) + : readCliOutputArguments(global); const outputArguments = outputOptions.validation; // `--version` with an explicit format reports the runtime as a document; // plain `--version` stays Incur's bare version string. @@ -78,8 +80,7 @@ export const runOneShotCli = async ( // here so they do not run with an unusable log level. if ( configurationError !== undefined && - (isShellCompletion || - splitIncurBuiltinArguments(cliArguments).command[0] !== "doctor") + (global === undefined || global.command[0] !== "doctor") ) { host.writeStderr(`${configurationError}\n`); host.setExitCode(1); @@ -94,7 +95,7 @@ export const runOneShotCli = async ( host.writeStdout(versionOutput); return; } - if (!isShellCompletion && isProjectScopedAmpRegistration(cliArguments)) { + if (global !== undefined && isProjectScopedAmpRegistration(global)) { // Amp has global settings only. Share the parsed scope fact with the // registration workflow and refuse before loading the command runtime. // @@ -123,7 +124,7 @@ export const runOneShotCli = async ( // Loaded only now: the documents above answer without the command catalog. const { loadCliRuntime } = await import("./cli/cliLoader.js"); - const runtime = await loadCliRuntime(cliArguments, host.environment); + const runtime = await loadCliRuntime(global, host.environment); host.ownCliResources(runtime.closeCliResources); const { createCliResultOutput } = await import("./cli/cliResultOutput.js"); let wroteOutput = false; @@ -132,7 +133,7 @@ export const runOneShotCli = async ( host.resultDestination, ); try { - await runtime.createCli(resultOutput).serve(cliArguments, { + await runtime.createCli(resultOutput).serve([...cliArguments], { stdout: (output) => { if (resultOutput?.handled) { if (resultOutput.failed && !host.stdoutClosed()) diff --git a/src/cliOutput.ts b/src/cliOutput.ts index 71f4ed47cf..9cd430e938 100644 --- a/src/cliOutput.ts +++ b/src/cliOutput.ts @@ -1,6 +1,8 @@ import { declaredSensitiveValues, - splitIncurBuiltinArguments, + parseCliGlobalArguments, + VALUED_OUTPUT_FLAGS, + type CliGlobalArguments, } from "./cliBuiltinArguments.js"; import { redactExplicitText } from "./domain/explicitSensitiveValues.js"; import { formatCliOutput } from "./cli/cliOutputFormatter.js"; @@ -124,10 +126,22 @@ export interface ParsedCliOutputArguments extends CliOutputControls { readonly versionReportFormat: CliOutputFormat | undefined; } -/** Read effective Incur output controls at the executable boundary. */ +/** Read effective output controls from the caller's argv. */ export const parseCliOutputArguments = ( arguments_: readonly string[], +): ParsedCliOutputArguments => + readCliOutputArguments(parseCliGlobalArguments(arguments_)); + +/** + * Read effective output controls from one invocation's global arguments. The + * global split decides which tokens are flag values; this reader interprets + * them, and a valued flag left among the command tokens is missing its value. + */ +export const readCliOutputArguments = ( + global: CliGlobalArguments, ): ParsedCliOutputArguments => { + const tokens = global.arguments; + const values = new Set(global.outputValues.map(({ index }) => index)); let format: CliOutputFormat = "toon"; let rootVersion = false; let versionEligible = true; @@ -140,56 +154,13 @@ export const parseCliOutputArguments = ( let tokenCount = false; let tokenLimit: number | undefined; let tokenOffset: number | undefined; - const parsed = (): ParsedCliOutputArguments => { - const parseError = invalidValue !== undefined; - const controls: CliOutputControls = { - filterOutput, - filterPaths: - filterOutput === undefined - ? undefined - : parseOutputFilter(filterOutput), - columns, - format, - formatExplicit, - fullOutput, - missingValue, - invalidValue: - invalidValue === undefined - ? undefined - : redactExplicitText( - invalidValue, - declaredSensitiveValues( - splitIncurBuiltinArguments(arguments_).command, - ), - ), - tokenCount, - tokenWindow: - !parseError && (tokenLimit !== undefined || tokenOffset !== undefined), - tokenLimit: parseError ? undefined : tokenLimit, - tokenOffset: parseError ? undefined : tokenOffset, - }; - return { - ...controls, - validation: validateCliOutputControls(controls, rootVersion), - versionReportFormat: - rootVersion && - versionEligible && - formatExplicit && - !parseError && - missingValue === undefined && - format !== "csv" && - format !== "tsv" && - isCliOutputFormat(format) - ? format - : undefined, - }; - }; - for (let index = 0; index < arguments_.length; index += 1) { - const argument = arguments_[index]; + for (let index = 0; index < tokens.length; index += 1) { + const argument = tokens[index]!; + // A value is read with the flag that consumed it. + if (values.has(index)) continue; // Only these flags can accompany a formatted root version request. - // Valued output flags consume their data below before the next iteration. if (argument === "--version") { - const next = arguments_[index + 1]; + const next = tokens[index + 1]; if (next === undefined || next.startsWith("-")) rootVersion = true; else versionEligible = false; } else if ( @@ -198,58 +169,71 @@ export const parseCliOutputArguments = ( argument !== "--timings" ) versionEligible = false; - // Incur scans builtins across `--` and reads spaced value forms, which - // normalizeCliArguments has produced. Mirror those effective values. if (argument === "--json") { format = "json"; formatExplicit = true; continue; } - if (argument === "--format") { - const value = arguments_[index + 1]; - if (value) { - const rejection = cliOutputValueRejection(argument, value); - if (rejection !== undefined) invalidValue ??= rejection; - else if (isCliOutputFormat(value)) { - format = value; - formatExplicit = true; - } - index += 1; - } else missingValue ??= argument; - continue; - } - if (argument === "--filter-output") { - if (arguments_[index + 1]) { - filterOutput = arguments_[index + 1]; - index += 1; - } else missingValue ??= argument; - continue; - } - if (argument === "--columns") { - const value = arguments_[index + 1]; - if (value) { - const rejection = cliOutputValueRejection(argument, value); - if (rejection !== undefined) invalidValue ??= rejection; - else columns = value.split(",").map((column) => column.trim()); - index += 1; - } else missingValue ??= argument; - continue; - } - if (argument === "--token-limit" || argument === "--token-offset") { - const value = arguments_[index + 1]; - if (value) { - const rejection = cliOutputValueRejection(argument, value); - if (rejection !== undefined) invalidValue ??= rejection; - else if (argument === "--token-limit") tokenLimit = Number(value); - else tokenOffset = Number(value); - index += 1; - } else missingValue ??= argument; - continue; - } if (argument === "--full-output") fullOutput = true; if (argument === "--token-count") tokenCount = true; + if (!VALUED_OUTPUT_FLAGS.has(argument)) continue; + const value = values.has(index + 1) ? tokens[index + 1]! : undefined; + if (value === undefined) { + missingValue ??= argument; + continue; + } + const rejection = cliOutputValueRejection(argument, value); + if (rejection !== undefined) { + invalidValue ??= rejection; + continue; + } + if (argument === "--format" && isCliOutputFormat(value)) { + format = value; + formatExplicit = true; + } else if (argument === "--filter-output") filterOutput = value; + else if (argument === "--columns") + columns = value.split(",").map((column) => column.trim()); + else if (argument === "--token-limit") tokenLimit = Number(value); + else if (argument === "--token-offset") tokenOffset = Number(value); } - return parsed(); + const parseError = invalidValue !== undefined; + const controls: CliOutputControls = { + filterOutput, + filterPaths: + filterOutput === undefined ? undefined : parseOutputFilter(filterOutput), + columns, + format, + formatExplicit, + fullOutput, + missingValue, + invalidValue: + invalidValue === undefined + ? undefined + : redactExplicitText( + invalidValue, + declaredSensitiveValues(global.command), + ), + tokenCount, + tokenWindow: + !parseError && (tokenLimit !== undefined || tokenOffset !== undefined), + tokenLimit: parseError ? undefined : tokenLimit, + tokenOffset: parseError ? undefined : tokenOffset, + }; + return { + ...controls, + validation: validateCliOutputControls(controls, rootVersion), + versionReportFormat: + rootVersion && + versionEligible && + formatExplicit && + !parseError && + missingValue === undefined && + format !== "csv" && + format !== "tsv" && + isCliOutputFormat(format) + ? format + : undefined, + }; }; /** Name a valued output flag that was given without a value. */ diff --git a/tests/boundary/cli/cliBuiltinArguments.test.ts b/tests/boundary/cli/cliBuiltinArguments.test.ts index 1562be6d57..c35aaeab29 100644 --- a/tests/boundary/cli/cliBuiltinArguments.test.ts +++ b/tests/boundary/cli/cliBuiltinArguments.test.ts @@ -9,8 +9,13 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { classifyMcpAddDiscovery, isProjectScopedAmpRegistration, + parseCliGlobalArguments, } from "../../../src/cliBuiltinArguments.js"; +/** Whether these caller arguments ask for a project-scoped Amp registration. */ +const projectScoped = (arguments_: readonly string[]): boolean => + isProjectScopedAmpRegistration(parseCliGlobalArguments(arguments_)); + describe("mcp add discovery classification", () => { it("bypasses help and listing flags", () => { for (const flag of [ @@ -49,7 +54,7 @@ describe("mcp add discovery classification", () => { describe("project-scoped Amp registration guard", () => { it("flags explicit Amp targets under --no-global", () => { expect( - isProjectScopedAmpRegistration([ + projectScoped([ "mcp", "add", "--no-global", @@ -62,14 +67,12 @@ describe("project-scoped Amp registration guard", () => { }); it("flags the default Amp registration when no agent is given", () => { - expect(isProjectScopedAmpRegistration(["mcp", "add", "--no-global"])).toBe( - true, - ); + expect(projectScoped(["mcp", "add", "--no-global"])).toBe(true); }); it("ignores output flags Incur strips before dispatch", () => { expect( - isProjectScopedAmpRegistration([ + projectScoped([ "mcp", "add", "--no-global", @@ -84,7 +87,7 @@ describe("project-scoped Amp registration guard", () => { it("passes global Amp registration through", () => { expect( - isProjectScopedAmpRegistration([ + projectScoped([ "mcp", "add", "--agent", @@ -97,13 +100,7 @@ describe("project-scoped Amp registration guard", () => { it("passes project-scoped non-Amp agents through", () => { expect( - isProjectScopedAmpRegistration([ - "mcp", - "add", - "--no-global", - "--agent", - "claude-code", - ]), + projectScoped(["mcp", "add", "--no-global", "--agent", "claude-code"]), ).toBe(false); }); @@ -117,7 +114,7 @@ describe("project-scoped Amp registration guard", () => { "--schema", ]) { expect( - isProjectScopedAmpRegistration([ + projectScoped([ "mcp", "add", "--no-global", @@ -127,32 +124,20 @@ describe("project-scoped Amp registration guard", () => { ]), ).toBe(false); } - expect( - isProjectScopedAmpRegistration(["mcp", "add", "--no-global", "--help"]), - ).toBe(false); + expect(projectScoped(["mcp", "add", "--no-global", "--help"])).toBe(false); }); it("reads equals-form agents the same way dispatch does", () => { // --agent=claude-code is a non-Amp registration, not the default Amp. expect( - isProjectScopedAmpRegistration([ - "mcp", - "add", - "--no-global", - "--agent=claude-code", - ]), + projectScoped(["mcp", "add", "--no-global", "--agent=claude-code"]), ).toBe(false); - expect( - isProjectScopedAmpRegistration([ - "mcp", - "add", - "--no-global", - "--agent=amp", - ]), - ).toBe(true); + expect(projectScoped(["mcp", "add", "--no-global", "--agent=amp"])).toBe( + true, + ); // A later equals-form Amp must not slip past an earlier spaced agent. expect( - isProjectScopedAmpRegistration([ + projectScoped([ "mcp", "add", "--no-global", @@ -163,28 +148,16 @@ describe("project-scoped Amp registration guard", () => { ).toBe(true); // A --command value is never read as an agent, even in equals form. expect( - isProjectScopedAmpRegistration([ - "mcp", - "add", - "--no-global", - "--command=--agent", - "amp", - ]), + projectScoped(["mcp", "add", "--no-global", "--command=--agent", "amp"]), ).toBe(true); }); it("passes other commands through", () => { - expect(isProjectScopedAmpRegistration(["mcp", "doctor"])).toBe(false); - expect(isProjectScopedAmpRegistration(["doctor"])).toBe(false); - expect( - isProjectScopedAmpRegistration([ - "mcp", - "add", - "--no-global", - "--agent", - "Amp", - ]), - ).toBe(false); + expect(projectScoped(["mcp", "doctor"])).toBe(false); + expect(projectScoped(["doctor"])).toBe(false); + expect(projectScoped(["mcp", "add", "--no-global", "--agent", "Amp"])).toBe( + false, + ); }); }); diff --git a/tests/boundary/cli/cliLazyRegistration.test.ts b/tests/boundary/cli/cliLazyRegistration.test.ts index 6d38a95d2b..e88e0e5c90 100644 --- a/tests/boundary/cli/cliLazyRegistration.test.ts +++ b/tests/boundary/cli/cliLazyRegistration.test.ts @@ -10,6 +10,23 @@ import { type CliCommandRegistrationId, } from "../../../src/cli/cliCommandRegistrations.js"; import { selectCliRegistrations } from "../../../src/cli/cliLoader.js"; +import { + cliCompletionShell, + parseCliGlobalArguments, +} from "../../../src/cliBuiltinArguments.js"; + +/** Select registrars as the executable does: completion has no global arguments. */ +const selectFor = ( + arguments_: readonly string[], + environment: NodeJS.ProcessEnv, + recorded: Readonly> | undefined, +) => + selectCliRegistrations( + cliCompletionShell(environment) === undefined + ? parseCliGlobalArguments(arguments_) + : undefined, + recorded, + ); import { createCliShell } from "../../../src/cli/cliShell.js"; import type { CliInstance } from "../../../src/cli/types.js"; import { visitRegisteredCommands } from "../../../src/cli/visitRegisteredCommands.js"; @@ -102,7 +119,7 @@ describe("lazy CLI registration", () => { arguments_: readonly string[], environment: NodeJS.ProcessEnv = {}, record: Readonly> | null = recorded, - ) => selectCliRegistrations(arguments_, environment, record ?? undefined); + ) => selectFor(arguments_, environment, record ?? undefined); expect(select(["inspect-go-binary", "a.out"])).toEqual(["go"]); expect(select(["inspect-go-binary", "a.out", "--json"])).toEqual(["go"]); diff --git a/tests/boundary/cli/cliOutput.test.ts b/tests/boundary/cli/cliOutput.test.ts index 85cc02eb1d..53aae401f5 100644 --- a/tests/boundary/cli/cliOutput.test.ts +++ b/tests/boundary/cli/cliOutput.test.ts @@ -8,8 +8,8 @@ import { describe, expect, it } from "vitest"; import { workspaceCliTest } from "../../support/cli/workspaceCliFixture.js"; import { - normalizeCliArguments, adaptCliOutputArgumentsForIncur, + parseCliGlobalArguments, } from "../../../src/cliBuiltinArguments.js"; import { renderCliOutputArgumentError, @@ -279,7 +279,8 @@ describe("CLI output flag value forms", () => { "preserves a flag-shaped spaced value owned by %s", (flag) => { expect( - normalizeCliArguments([flag, "--format=json", "providers", "--json"]), + parseCliGlobalArguments([flag, "--format=json", "providers", "--json"]) + .arguments, ).toEqual([flag, "--format=json", "providers", "--json"]); }, ); @@ -303,7 +304,7 @@ describe("CLI output flag value forms", () => { it("splits only the equals forms of valued output flags", () => { expect( - normalizeCliArguments([ + parseCliGlobalArguments([ "inspect-sqlite-database", "--table=a=b", "--format=json", @@ -312,7 +313,7 @@ describe("CLI output flag value forms", () => { "--token-offset=", "--json", "--format-hint=x", - ]), + ]).arguments, ).toEqual([ "inspect-sqlite-database", "--table=a=b", @@ -804,8 +805,8 @@ describe("CLI update root alias", () => { ])( "routes only an unambiguous root update while retaining option data: %j", (input, expected) => { - expect(normalizeCliArguments(input)).toEqual(expected); - expect(normalizeCliArguments(expected)).toEqual(expected); + expect(parseCliGlobalArguments(input).arguments).toEqual(expected); + expect(parseCliGlobalArguments(expected).arguments).toEqual(expected); }, ); }); @@ -815,7 +816,7 @@ describe("version report requests", () => { [["--version", "--json"], "json"], [["--json", "--version"], "json"], [["--version", "--format", "yaml"], "yaml"], - [normalizeCliArguments(["--version", "--format=toon"]), "toon"], + [parseCliGlobalArguments(["--version", "--format=toon"]).arguments, "toon"], // Without an explicit format, Incur prints the bare version. [["--version"], undefined], // Help keeps precedence over --version. diff --git a/tests/boundary/cli/cliTimingArguments.test.ts b/tests/boundary/cli/cliTimingArguments.test.ts index 34b5e9bf89..fd41f4813e 100644 --- a/tests/boundary/cli/cliTimingArguments.test.ts +++ b/tests/boundary/cli/cliTimingArguments.test.ts @@ -2,9 +2,8 @@ import { it, expect } from "vitest"; import { Parser } from "incur"; import { z } from "zod"; import { - splitCliTimingArguments, - normalizeCliArguments, - splitIncurBuiltinArguments, + parseCliGlobalArguments, + productionMcpDoctorArguments, } from "../../../src/cliBuiltinArguments.js"; it.each([ @@ -20,12 +19,12 @@ it.each([ ["--timings=false", "--timings"], ["--", "--timings"], ])("matches pinned boolean global parsing for %j", (...input: string[]) => { - const actual = splitCliTimingArguments(input); + const actual = parseCliGlobalArguments(input); const parsed = Parser.parseGlobals( input, z.object({ timings: z.boolean().default(false) }), ); - expect(actual).toEqual({ + expect({ arguments: actual.command, enabled: actual.timings }).toEqual({ arguments: parsed.rest, enabled: parsed.parsed.timings, }); @@ -38,32 +37,44 @@ it.each([ "--timings=other", "--timings=", ])("preserves output values and root alias with %s", (flag) => { - expect(splitCliTimingArguments(["--format", flag])).toEqual({ - arguments: ["--format", flag], - enabled: false, - }); - expect(normalizeCliArguments([flag, "--update", "--json"])).toEqual([ - "update", - flag, - "--json", - ]); - expect(normalizeCliArguments(["--update", flag, "--json"])).toEqual([ - "update", - flag, - "--json", - ]); - expect(splitIncurBuiltinArguments([flag, "mcp", "doctor"]).command).toEqual([ + expect( + productionMcpDoctorArguments(["mcp", "doctor", "--format", flag]), + ).toEqual({ arguments: ["--format", flag], timings: false }); + expect( + parseCliGlobalArguments([flag, "--update", "--json"]).arguments, + ).toEqual(["update", flag, "--json"]); + expect( + parseCliGlobalArguments(["--update", flag, "--json"]).arguments, + ).toEqual(["update", flag, "--json"]); + expect(parseCliGlobalArguments([flag, "mcp", "doctor"]).command).toEqual([ "mcp", "doctor", ]); }); it("retains the separator and its following timing-shaped data", () => { - expect(normalizeCliArguments(["--", "--update", "--timings=false"])).toEqual([ - "--", - "--update", - "--timings=false", - ]); - expect(splitCliTimingArguments(["--format", "--", "--timings=true"])).toEqual( - { arguments: ["--format", "--"], enabled: true }, - ); + expect( + parseCliGlobalArguments(["--", "--update", "--timings=false"]).arguments, + ).toEqual(["--", "--update", "--timings=false"]); + expect( + productionMcpDoctorArguments([ + "mcp", + "doctor", + "--format", + "--", + "--timings=true", + ]), + ).toEqual({ arguments: ["--format", "--"], timings: true }); +}); +it("takes the doctor words and timing global out of the doctor's arguments", () => { + expect( + productionMcpDoctorArguments([ + "--timings", + "mcp", + "--format=json", + "doctor", + "--no-timings", + "--verbose", + ]), + ).toEqual({ arguments: ["--format", "json", "--verbose"], timings: false }); + expect(productionMcpDoctorArguments(["mcp", "add"])).toBeUndefined(); }); diff --git a/tests/boundary/cli/completions.test.ts b/tests/boundary/cli/completions.test.ts index 9db94b9bb6..0b699629a6 100644 --- a/tests/boundary/cli/completions.test.ts +++ b/tests/boundary/cli/completions.test.ts @@ -6,6 +6,9 @@ import { expect, it } from "vitest"; import { registerCliCommand } from "../../../src/cli/commandRegistry.js"; import { createCliCompletions } from "../../../src/cli/completions.js"; import type { CliInstance } from "../../../src/cli/types.js"; +import { parseCliGlobalArguments } from "../../../src/cliBuiltinArguments.js"; + +type ServeOptions = NonNullable[1]>; import { workspaceCliTest } from "../../support/cli/workspaceCliFixture.js"; const registry = () => { @@ -28,7 +31,7 @@ const complete = (words: string[], index = words.length - 1) => { _COMPLETE_INDEX: String(index), }); expect( - callback(["--", ...words], { + callback.complete(["--", ...words], { stdout: (value) => { text += value; }, @@ -109,7 +112,9 @@ it("uses canonical global flag metadata and retains command options and enum hin it("shares Bash registration across ordinary and protocol routes while retaining builtin precedence", () => { const cli = registry(); let direct = ""; - const ordinary = createCliCompletions(cli, {}); + const completions = createCliCompletions(cli, {}); + const ordinary = (arguments_: readonly string[], options: ServeOptions) => + completions.writeScript(parseCliGlobalArguments(arguments_), options); expect( ordinary(["--format", "json", "completions", "bash"], { stdout: (text) => { @@ -119,7 +124,7 @@ it("shares Bash registration across ordinary and protocol routes while retaining ).toBe(true); let protocol = ""; expect( - createCliCompletions(cli, { COMPLETE: "bash" })([], { + createCliCompletions(cli, { COMPLETE: "bash" }).complete([], { stdout: (text) => { protocol += text; }, diff --git a/tests/boundary/cli/defaultAmpRegistration.test.ts b/tests/boundary/cli/defaultAmpRegistration.test.ts index 4264af5be6..f18bb47cdd 100644 --- a/tests/boundary/cli/defaultAmpRegistration.test.ts +++ b/tests/boundary/cli/defaultAmpRegistration.test.ts @@ -6,7 +6,7 @@ import { z } from "zod"; import { decode } from "@toon-format/toon"; import { mcpRegistrationReportSchema } from "../../../src/contracts/mcpRegistration.js"; -import { splitIncurBuiltinArguments } from "../../../src/cliBuiltinArguments.js"; +import { parseCliGlobalArguments } from "../../../src/cliBuiltinArguments.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { cliTest } from "../../support/cli/cliFixture.js"; import { registrationEnvironment } from "../../support/cli/registrationEnvironment.js"; @@ -207,10 +207,9 @@ it("timing splitting matches Incur after output values and before the terminator undefined, { validate: false }, ).rest; - expect(splitIncurBuiltinArguments(command).command).toEqual(expected); + expect(parseCliGlobalArguments(command).command).toEqual(expected); expect( - splitIncurBuiltinArguments(["--filter-output", flag, ...command]) - .command, + parseCliGlobalArguments(["--filter-output", flag, ...command]).command, ).toEqual(expected); } } diff --git a/tests/boundary/cli/markdownArgumentErrors.test.ts b/tests/boundary/cli/markdownArgumentErrors.test.ts index c55cee93b3..647bf16990 100644 --- a/tests/boundary/cli/markdownArgumentErrors.test.ts +++ b/tests/boundary/cli/markdownArgumentErrors.test.ts @@ -14,6 +14,7 @@ import { explicitSensitiveValueOptions, } from "../../../src/cli/explicitSensitiveArguments.js"; +import { parseCliGlobalArguments } from "../../../src/cliBuiltinArguments.js"; import { cliTest } from "../../support/cli/cliFixture.js"; afterAll(() => disposeMdItInstance()); @@ -175,13 +176,14 @@ it("redacts Markdown punctuation in validation fields before presentation", asyn const run = async (format: string, sensitive: boolean) => { let stdout = ""; let exitCode = 0; + const global = parseCliGlobalArguments([ + "inspect", + ...(sensitive ? ["--sensitive-value", secret] : []), + "--format", + format, + ]); await declared( - [ - "inspect", - ...(sensitive ? ["--sensitive-value", secret] : []), - "--format", - format, - ], + global, { env: {}, stdout: (text) => { @@ -191,7 +193,7 @@ it("redacts Markdown punctuation in validation fields before presentation", asyn exitCode = code; }, }, - original, + (options) => original([...global.arguments], options), ); expect(exitCode).toBe(1); return stdout; @@ -241,13 +243,14 @@ it("retains upstream Markdown literal-cell protections after redaction", async ( const run = async (format: string, sensitive: boolean) => { let stdout = ""; let exitCode = 0; + const global = parseCliGlobalArguments([ + "inspect", + ...(sensitive ? ["--sensitive-value", secret] : []), + "--format", + format, + ]); await declared( - [ - "inspect", - ...(sensitive ? ["--sensitive-value", secret] : []), - "--format", - format, - ], + global, { env: {}, stdout: (text) => { @@ -257,7 +260,7 @@ it("retains upstream Markdown literal-cell protections after redaction", async ( exitCode = code; }, }, - original, + (options) => original([...global.arguments], options), ); expect(exitCode).toBe(1); return stdout; diff --git a/tests/boundary/cli/strictPositionals.test.ts b/tests/boundary/cli/strictPositionals.test.ts index 119d323d94..0321e6b96f 100644 --- a/tests/boundary/cli/strictPositionals.test.ts +++ b/tests/boundary/cli/strictPositionals.test.ts @@ -7,6 +7,7 @@ import { expect, it } from "vitest"; import { createCli } from "../../../src/cli.js"; import { validateCliArguments } from "../../../src/cli/strictPositionals.js"; +import { parseCliGlobalArguments } from "../../../src/cliBuiltinArguments.js"; import { excludeDeclaredSensitiveArguments, explicitSensitiveValueOptions, @@ -32,10 +33,14 @@ const installAdmission = (cli: CliInstance) => { const strict = validateCliArguments(cli); const declared = excludeDeclaredSensitiveArguments(cli); const original = cli.serve.bind(cli); - cli.serve = (argv = [], options = {}) => - strict(argv, options, (tokens, selected) => - declared(tokens, selected, original), + cli.serve = (argv = [], options = {}) => { + const global = parseCliGlobalArguments(argv); + return strict(global, options, (selected) => + declared(global, selected, (declaredOptions) => + original([...global.arguments], declaredOptions), + ), ); + }; }; it("rejects surplus public CLI inputs before importing and retains the one-path control", async () => { diff --git a/tests/support/cli/cliFixture.ts b/tests/support/cli/cliFixture.ts index 1d20b83ca6..d79a8d95cc 100644 --- a/tests/support/cli/cliFixture.ts +++ b/tests/support/cli/cliFixture.ts @@ -2,7 +2,7 @@ import { resolve } from "node:path"; import { tmpdir } from "node:os"; import { productionMcpDoctorArguments, - splitIncurBuiltinArguments, + parseCliGlobalArguments, } from "../../../src/cliBuiltinArguments.js"; import { DEFAULT_INFO_LOGGING_COMMANDS } from "../../../src/contracts/cliCommandNames.js"; import { parseLogLevel } from "../../../src/config/processStart.js"; @@ -306,7 +306,7 @@ const logsByDefault = ( ): boolean => level === undefined && DEFAULT_INFO_LOGGING_COMMANDS.has( - splitIncurBuiltinArguments([...arguments_]).command[0] ?? "", + parseCliGlobalArguments(arguments_).command[0] ?? "", ); /** A valid level other than silent; an invalid level is a captured refusal. */