From 884b683a94be222538aad84eb7993f62fda9aca7 Mon Sep 17 00:00:00 2001 From: gensokyo-dev Date: Fri, 13 Nov 2026 18:16:22 +0000 Subject: [PATCH] fix(cli): advertise the decimal token grammar on integer arguments `cliIntegerArgument` piped a regex-guarded string into a number but never published Zod's input view, so `--schema` advertised a bare integer for 15 fields while the parser accepted only decimal argv text. `environment-serve --port` had the same gap through the transforming MCP_PORT owner. Remove `cliIntegerArgument` and route every call site through `cliDecimalField`, binding each field to its domain or contract owner where one exists so bounds, defaults and optionality come from that owner. Export the input-view publisher as `publishArgvInput` and apply it to `--port`, which keeps the MCP_PORT grammar shared with `rea mcp --http`. The decimal catalog test now requires every numeric field's advertisement to admit its decimal argv token, covers repeated options and string-advertised token grammars, and checks `--schema` output directly. The string branch's missing numeric range (#9348) is unchanged. Fixes #9344 Co-Authored-By: gensokyo-dev Co-Authored-By: Claude Opus 5.5 --- src/cli/androidCommands.ts | 14 +-- src/cli/cutterCommands.ts | 9 +- src/cli/environmentCommands.ts | 14 ++- src/cli/options.ts | 17 +-- src/cli/utilityCommands.ts | 42 ++++--- src/cli/webModuleCommands.ts | 8 +- src/cli/webNetworkCaptureCommands.ts | 7 +- src/cli/webSourceLocationCommands.ts | 19 ++- .../boundary/cli/cliDecimalArguments.test.ts | 113 +++++++++++++++--- .../cli/cliInputSchemaRequired.test.ts | 10 +- 10 files changed, 182 insertions(+), 71 deletions(-) diff --git a/src/cli/androidCommands.ts b/src/cli/androidCommands.ts index f495804a70..03bf927e82 100644 --- a/src/cli/androidCommands.ts +++ b/src/cli/androidCommands.ts @@ -22,7 +22,7 @@ import { parseAnalysisInput } from "../application/AnalysisInput.js"; import { androidJniSelectionSchema } from "../domain/android/androidJniBindings.js"; import { androidJniDeliverySchema } from "../domain/android/androidJniQuery.js"; import { androidInputSchemas } from "../domain/android/androidAnalysis.js"; -import { cliIntegerArgument } from "./options.js"; +import { cliDecimalField } from "./options.js"; /** Expose the same explicit APK requests through one-shot CLI commands. */ export const registerAndroidCommands = ( @@ -223,11 +223,11 @@ export const registerAndroidCommands = ( ), }), options: z.object({ - overloadIndex: cliIntegerArgument(0) - .optional() - .describe( + overloadIndex: cliDecimalField( + androidInputSchemas.inspect_android_method.shape.overload_index.describe( "Explicit zero-based index among same-name methods; required when ambiguous", ), + ), mappingPath, ...analysisEvidenceDeliveryOptions, }), @@ -255,11 +255,11 @@ export const registerAndroidCommands = ( options: z.object({ methodName: androidInputSchemas.trace_android_references.shape.method_name, - overloadIndex: cliIntegerArgument(0) - .optional() - .describe( + overloadIndex: cliDecimalField( + androidInputSchemas.trace_android_references.shape.overload_index.describe( "Index among defined methods or observed external prototypes listed by an ambiguous query", ), + ), }), run: ({ args, options }) => execute( diff --git a/src/cli/cutterCommands.ts b/src/cli/cutterCommands.ts index 258175c4dd..d2eac140bc 100644 --- a/src/cli/cutterCommands.ts +++ b/src/cli/cutterCommands.ts @@ -8,7 +8,8 @@ import { logCliCommand } from "../cliLogging.js"; import { finishAnalysisCommand } from "./finishAnalysisCommand.js"; import { withCommandCancellation } from "./commandCancellation.js"; import type { CliInstance } from "./types.js"; -import { cliIntegerArgument } from "./options.js"; +import { cliDecimalField } from "./options.js"; +import { cutterCommandInputSchema } from "../contracts/cutterToolContracts.js"; /** Register commands that control an already-running Cutter instance. */ export const registerCutterCommands = ( @@ -43,8 +44,10 @@ export const registerCutterCommands = ( .string() .uuid() .describe("Session ID copied from list-cutter-sessions."), - expectedGeneration: cliIntegerArgument(0).describe( - "Session generation returned by list-cutter-sessions.", + expectedGeneration: cliDecimalField( + cutterCommandInputSchema.shape.expected_generation.describe( + "Session generation returned by list-cutter-sessions.", + ), ), command: z .string() diff --git a/src/cli/environmentCommands.ts b/src/cli/environmentCommands.ts index 7594c08684..6a21af1a38 100644 --- a/src/cli/environmentCommands.ts +++ b/src/cli/environmentCommands.ts @@ -38,7 +38,7 @@ import { inspectWebNetworkCaptureInputSchema } from "../domain/webNetworkCapture import { withCommandCancellation } from "./commandCancellation.js"; import { finishAnalysisCommand } from "./finishAnalysisCommand.js"; import type { CliInstance } from "./types.js"; -import { cliDecimalField } from "./options.js"; +import { cliDecimalField, publishArgvInput } from "./options.js"; /** Same envelope label as the other JSON-input commands and `parseCliJsonInput`. */ const cliError = (error: AnalysisError): JsonValue => ({ @@ -689,11 +689,13 @@ export const registerEnvironmentCommands = ( host: mcpHttpHostSchema .optional() .describe("Listener address; default MCP_HOST, else 127.0.0.1"), - port: mcpHttpPortSchema - .optional() - .describe( - "Listener port; default MCP_PORT, else 0 for an ephemeral port", - ), + port: publishArgvInput( + mcpHttpPortSchema + .optional() + .describe( + "Listener port; default MCP_PORT, else 0 for an ephemeral port", + ), + ), }), run: ({ args, options }) => withCommandCancellation((signal) => diff --git a/src/cli/options.ts b/src/cli/options.ts index 5e4d1773c8..2f5645cae9 100644 --- a/src/cli/options.ts +++ b/src/cli/options.ts @@ -24,13 +24,6 @@ type DecimalWrapper = readonly kind: "optional" | "exactOptional" | "nullable" | "readonly"; }; -/** Parse decimal integer tokens before Number coercion can erase their syntax. */ -export const cliIntegerArgument = (min: number) => - z - .string() - .regex(DECIMAL_INTEGER_TOKEN, "Expected a decimal integer") - .pipe(z.coerce.number().safe().min(min)); - const decimalToken = (domain: z.ZodNumber) => z .string() @@ -42,10 +35,12 @@ const unwrapSchema = (field: { unwrap: () => unknown }): z.ZodType => field.unwrap() as z.ZodType; /** - * Incur advertises Zod's output view. Publish the input view so the decimal - * token guard survives `--schema` and other SDK conversions. + * Incur advertises Zod's output view. Publish the input view so an argv token + * grammar that transforms text survives `--schema` and other SDK conversions. */ -const publishDecimalInput = (field: z.ZodType): z.ZodType => { +export const publishArgvInput = ( + field: Field, +): Field => { const { $schema: _dialect, ...inputSchema } = z.toJSONSchema(field, { io: "input", }); @@ -149,7 +144,7 @@ export const cliDecimalField = ( numeric.description === undefined ? admitted : admitted.describe(numeric.description); - return publishDecimalInput(described) as z.ZodType>; + return publishArgvInput(described) as z.ZodType>; }; /** Adapt each numeric property of a shared shape; other properties stay unchanged. */ diff --git a/src/cli/utilityCommands.ts b/src/cli/utilityCommands.ts index 866fc03450..c431b3cf4e 100644 --- a/src/cli/utilityCommands.ts +++ b/src/cli/utilityCommands.ts @@ -1,6 +1,6 @@ import { projectCliAnalysisResult } from "./projectCliAnalysisResult.js"; import { z } from "incur"; -import { cliDecimalField, cliIntegerArgument } from "./options.js"; +import { cliDecimalField } from "./options.js"; import type { DirectAnalysis } from "../composition/directAnalysis.js"; import { createHistoricalSourceSummary } from "../domain/referenceSourceSummary.js"; @@ -21,7 +21,10 @@ import { } from "../domain/analysisErrorCore.js"; import { projectInputIssues } from "../domain/inputIssueProjection.js"; import { safeParseJson } from "../domain/safeJson.js"; -import { nativeUiScenarioInputSchema } from "../domain/native/nativeUiObservation.js"; +import { + nativeUiObservationInputSchema, + nativeUiScenarioInputSchema, +} from "../domain/native/nativeUiObservation.js"; import { nativeCommandTimeoutField, nativeUiDeadlineField, @@ -49,11 +52,16 @@ export const registerUtilityCommands = ( registerReferenceSourceCommand(cli, logger, environment); }; -// Decimal tokens only; shared fields own their bounds and help. +// Decimal tokens only; shared fields own their bounds and defaults. +const nativeUiScopeFields = nativeUiObservationInputSchema.shape; const nativeUiScopeOptions = { - pid: cliIntegerArgument(1).describe("Existing application PID"), - windowId: cliIntegerArgument(1).describe( - "Exact selected application window ID", + pid: cliDecimalField( + nativeUiScopeFields.pid.describe("Existing application PID"), + ), + windowId: cliDecimalField( + nativeUiScopeFields.window_id.describe( + "Exact selected application window ID", + ), ), screenshot: z .boolean() @@ -63,9 +71,11 @@ const nativeUiScopeOptions = { .boolean() .default(true) .describe("Read the selected window accessibility tree"), - maxNodes: cliIntegerArgument(1) - .default(500) - .describe("Maximum accessibility nodes per capture"), + maxNodes: cliDecimalField( + nativeUiScopeFields.max_nodes.describe( + "Maximum accessibility nodes per capture", + ), + ), nativeUiDeadlineMs: cliDecimalField(nativeUiDeadlineField), }; @@ -364,11 +374,15 @@ const registerReferenceSourceCommand = ( .describe( "Complete committed graph or compact historical-source summary", ), - outlineDepth: cliIntegerArgument(0) - .optional() - .describe( - "Summary outline path depth (default: 2; 0 omits entries); requires --detail summary", - ), + outlineDepth: cliDecimalField( + z + .int() + .min(0) + .optional() + .describe( + "Summary outline path depth (default: 2; 0 omits entries); requires --detail summary", + ), + ), }) .superRefine((options, context) => { if (options.outlineDepth !== undefined && options.detail !== "summary") diff --git a/src/cli/webModuleCommands.ts b/src/cli/webModuleCommands.ts index cef3f31a3a..2611fd926b 100644 --- a/src/cli/webModuleCommands.ts +++ b/src/cli/webModuleCommands.ts @@ -6,7 +6,7 @@ import { logCliCommand } from "../cliLogging.js"; import { webModuleTraceInputSchema } from "../domain/webModuleTrace.js"; import type { Logger } from "pino"; import type { CliInstance } from "./types.js"; -import { cliIntegerArgument } from "./options.js"; +import { cliDecimalField } from "./options.js"; import { withCommandCancellation } from "./commandCancellation.js"; import { finishAnalysisCommand } from "./finishAnalysisCommand.js"; @@ -25,8 +25,10 @@ export const registerWebModuleCommands = ( "Trace one captured script's native imports to URLs and captured source candidates", args: z.object({ manifestPath: webModuleTraceInputSchema.shape.manifest_path, - scriptIndex: cliIntegerArgument(0).describe( - "Zero-based manifest script index", + scriptIndex: cliDecimalField( + webModuleTraceInputSchema.shape.script_index.describe( + "Zero-based manifest script index", + ), ), }), options: z.object({ diff --git a/src/cli/webNetworkCaptureCommands.ts b/src/cli/webNetworkCaptureCommands.ts index 5a33258feb..b90494eed3 100644 --- a/src/cli/webNetworkCaptureCommands.ts +++ b/src/cli/webNetworkCaptureCommands.ts @@ -8,7 +8,7 @@ import { CLI_COMMANDS } from "../cliCommandNames.js"; import { logCliCommand } from "../cliLogging.js"; import type { Logger } from "pino"; import type { CliInstance } from "./types.js"; -import { cliDecimalField, cliIntegerArgument } from "./options.js"; +import { cliDecimalField } from "./options.js"; import { withCommandCancellation } from "./commandCancellation.js"; import { analysisEvidenceDeliveryOptions, @@ -18,6 +18,9 @@ import { localPathStringSchema } from "../domain/localPath.js"; import { absoluteCallerPath } from "../filesystem/callerPath.js"; import { explicitSensitiveValueOptions } from "./explicitSensitiveArguments.js"; +const recordOrdinal = + inspectWebNetworkCaptureInputSchema.shape.record_ordinals.unwrap().element; + /** Expose offline historical capture inspection with the same selection contract as MCP. */ export const registerWebNetworkCaptureCommands = ( cli: CliInstance, @@ -51,7 +54,7 @@ export const registerWebNetworkCaptureCommands = ( .optional() .describe("Fully qualified message type in the descriptor set"), record: z - .array(cliIntegerArgument(0)) + .array(cliDecimalField(recordOrdinal)) .optional() .describe("Zero-based producer ordinals; repeat to select several"), ...explicitSensitiveValueOptions, diff --git a/src/cli/webSourceLocationCommands.ts b/src/cli/webSourceLocationCommands.ts index 3f894fccf7..a5612c6220 100644 --- a/src/cli/webSourceLocationCommands.ts +++ b/src/cli/webSourceLocationCommands.ts @@ -16,10 +16,11 @@ import { CLI_COMMANDS } from "../cliCommandNames.js"; import { logCliCommand } from "../cliLogging.js"; import type { Logger } from "pino"; import type { CliInstance } from "./types.js"; -import { cliDecimalField, cliIntegerArgument } from "./options.js"; +import { cliDecimalField } from "./options.js"; import { withCommandCancellation } from "./commandCancellation.js"; const sourceMapSelection = webSourceLocationInputSchema.shape.source_map; +const generatedPosition = webSourceLocationInputSchema.shape.generated_position; /** Expose the same explicit selected map/point contract through the CLI. */ export const registerWebSourceLocationCommands = ( @@ -33,14 +34,20 @@ export const registerWebSourceLocationCommands = ( "Trace one retained script position through an explicitly selected local source map", args: z.object({ manifestPath: webSourceLocationInputSchema.shape.manifest_path, - scriptIndex: cliIntegerArgument(0).describe( - "Zero-based manifest script index", + scriptIndex: cliDecimalField( + webSourceLocationInputSchema.shape.script_index.describe( + "Zero-based manifest script index", + ), ), sourceMapPath: sourceMapSelection.shape.path, sourceMapUrl: sourceMapSelection.shape.url, - line: cliIntegerArgument(1).describe("One-based generated line"), - column: cliIntegerArgument(0).describe( - "Zero-based UTF-16 generated column", + line: cliDecimalField( + generatedPosition.shape.line.describe("One-based generated line"), + ), + column: cliDecimalField( + generatedPosition.shape.column.describe( + "Zero-based UTF-16 generated column", + ), ), }), options: z.object({ diff --git a/tests/boundary/cli/cliDecimalArguments.test.ts b/tests/boundary/cli/cliDecimalArguments.test.ts index 29aacd7883..95b0345262 100644 --- a/tests/boundary/cli/cliDecimalArguments.test.ts +++ b/tests/boundary/cli/cliDecimalArguments.test.ts @@ -68,8 +68,16 @@ const REQUIRED_NUMERIC_FIELDS = [ "inspect-web-page options.observationMs", "observe-web-execution options.observationMs", "extract-firmware options.maxDepth", + "trace-web-source-location args.line", + "cutter-command args.expectedGeneration", + "observe-native-ui options.maxNodes", + "inspect-web-network-capture options.record", + "environment-serve options.port", ] as const; +/** Decimal argv tokens the parser admits as numbers, for fields advertised as strings. */ +const PROBE_TOKENS = ["0", "1"] as const; + describe("decimal integer CLI admission", () => { it("rejects 0x10 and 1e3 for every numeric input and keeps an in-range decimal", () => { const cli = createCli({}); @@ -83,7 +91,6 @@ describe("decimal integer CLI admission", () => { const advertised = Schema.toJsonSchema(parser); if (!isRecord(advertised) || !isRecord(advertised.properties)) continue; for (const [name, property] of Object.entries(advertised.properties)) { - if (!numericBranches(property)) continue; const field = parser.shape[name]; if (field === undefined) { failures.push( @@ -92,11 +99,31 @@ describe("decimal integer CLI admission", () => { continue; } const label = `${path} ${group}.${name}`; + // A repeated option parses each argv token as one array item. + const repeated = isRecord(property) && property.type === "array"; + const item = repeated ? property.items : property; + const isolated = z.object({ [name]: field }); + const read = (token: string): unknown => { + const parsed = + group === "options" + ? Parser.parse([flagName(name), token], { options: isolated }) + .options[name] + : Parser.parse([token], { args: isolated }).args[name]; + return repeated && Array.isArray(parsed) ? parsed[0] : parsed; + }; + const readsNumber = (token: string): boolean => { + try { + return typeof read(token) === "number"; + } catch { + return false; + } + }; + // String-advertised token grammars (for example --port) still count. + const probed = PROBE_TOKENS.find(readsNumber); + if (!numericBranches(item) && probed === undefined) continue; let validate: ((value: unknown) => boolean) | undefined; try { - validate = ajv.compile( - property as Parameters[0], - ); + validate = ajv.compile(item as Parameters[0]); } catch (error) { failures.push( `${label}: Ajv could not compile the advertised schema (${error instanceof Error ? error.message : String(error)})`, @@ -107,15 +134,6 @@ describe("decimal integer CLI admission", () => { if (validate(token)) failures.push(`${label}: advertised schema accepts ${token}`); } - const isolated = z.object({ [name]: field }); - const read = (token: string): unknown => { - if (group === "options") { - return Parser.parse([flagName(name), token], { - options: isolated, - }).options[name]; - } - return Parser.parse([token], { args: isolated }).args[name]; - }; for (const token of NON_DECIMAL) { try { read(token); @@ -124,7 +142,9 @@ describe("decimal integer CLI admission", () => { // Decimal tokens are the only numeric spelling. } } - const candidate = bounds(property)[0]?.min; + const candidate = + bounds(item)[0]?.min ?? + (probed === undefined ? undefined : Number(probed)); if (candidate === undefined) { failures.push(`${label}: no in-range decimal candidate`); continue; @@ -138,8 +158,7 @@ describe("decimal integer CLI admission", () => { ); continue; } - const admitsLeadingZeros = - JSON.stringify(property).includes("^[0-9]+$"); + const admitsLeadingZeros = JSON.stringify(item).includes("^[0-9]+$"); try { const parsed = read(`0${decimal}`); if (parsed !== candidate) @@ -152,9 +171,10 @@ describe("decimal integer CLI admission", () => { `${label}: leading-zero decimal was rejected (${error instanceof Error ? error.message : String(error)})`, ); } - if (!(validate(decimal) || validate(candidate))) + // Argv supplies text, so the advertisement must admit the token itself. + if (!validate(decimal)) failures.push( - `${label}: advertised schema rejects in-range ${decimal}`, + `${label}: advertised schema rejects in-range token "${decimal}"`, ); checked.push(label); } @@ -168,3 +188,60 @@ describe("decimal integer CLI admission", () => { expect(failures).toEqual([]); }); }); + +describe("decimal integer CLI advertisement", () => { + const schemaOf = async (command: string): Promise => { + let stdout = ""; + let exitCode = 0; + await createCli({}).serve([command, "--schema", "--json"], { + env: {}, + exit: (code) => { + exitCode = code; + }, + stdout: (text) => { + stdout += text; + }, + }); + expect(exitCode, command).toBe(0); + return JSON.parse(stdout) as unknown; + }; + + it("publishes the token grammar in --schema for arguments and options", async () => { + const location = await schemaOf("trace-web-source-location"); + expect(location).toMatchObject({ + args: { + properties: { + line: { + description: "One-based generated line", + anyOf: [ + { type: "integer", minimum: 1 }, + { type: "string", pattern: "^[0-9]+$" }, + ], + }, + }, + }, + }); + expect(await schemaOf("inspect-web-network-capture")).toMatchObject({ + options: { + properties: { + record: { + type: "array", + items: { + anyOf: [ + { type: "integer", minimum: 0 }, + { type: "string", pattern: "^[0-9]+$" }, + ], + }, + }, + }, + }, + }); + expect(await schemaOf("environment-serve")).toMatchObject({ + options: { + properties: { + port: { type: "string", pattern: "^(?:0|[1-9]\\d*)$" }, + }, + }, + }); + }); +}); diff --git a/tests/boundary/cli/cliInputSchemaRequired.test.ts b/tests/boundary/cli/cliInputSchemaRequired.test.ts index 74f37fd62f..4b09092eb4 100644 --- a/tests/boundary/cli/cliInputSchemaRequired.test.ts +++ b/tests/boundary/cli/cliInputSchemaRequired.test.ts @@ -739,7 +739,12 @@ describe("reference-source outline-depth input schema", () => { const cli = createCli({}); const advertised = await advertisedSchema(cli, "import-reference-source"); const outlineDepth = advertised.options?.properties?.outlineDepth; - expect(outlineDepth).toMatchObject({ type: "integer", minimum: 0 }); + expect(outlineDepth).toMatchObject({ + anyOf: [ + { type: "integer", minimum: 0 }, + { type: "string", pattern: "^[0-9]+$" }, + ], + }); const parser = parserSchema(cli, "import-reference-source", "options"); expect(parser?.safeParse({}).success).toBe(true); @@ -785,7 +790,10 @@ describe("reference-source outline-depth input schema", () => { if (parsed === undefined || !parsed.success) throw new Error(`Expected outline-depth token ${token} to parse`); expect(validate(parsed.data)).toBe(true); + expect(validate({ outlineDepth: token, detail: "summary" })).toBe(true); } + for (const token of ["0x2", "2e0", "-1"]) + expect(validate({ outlineDepth: token, detail: "summary" })).toBe(false); expect(validate({ outlineDepth: -1 })).toBe(false); expect(validate({ outlineDepth: 9007199254740992 })).toBe(false); expect(validate({ outlineDepth: 2 })).toBe(false);