Skip to content

Commit 4c02b6a

Browse files
fix(cli): reject excess positionals (#1433)
* fix(cli): reject excess positionals * fix: preserve get ref labels in arity checks --------- Co-authored-by: Andrew Barnes <[email protected]> Co-authored-by: Michał Pierzchała <[email protected]>
1 parent fcaa6c9 commit 4c02b6a

8 files changed

Lines changed: 92 additions & 25 deletions

File tree

‎scripts/help-conformance-command-validator.ts‎

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import { pathToFileURL } from 'node:url';
22
import { parseArgs } from '../src/cli/parser/args.ts';
3-
import { getCommandSchema } from '../src/cli-schema/command-schema.ts';
43
import { readInputFromCli } from '../src/commands/cli-grammar.ts';
54
import { isCommandName } from '../src/commands/command-metadata.ts';
65

@@ -34,8 +33,6 @@ export function validateAgentDeviceCommand(value: unknown): ValidationResult {
3433
function validateParsedCommand(parsed: ReturnType<typeof parseArgs>): ValidationResult {
3534
if (!parsed.command) return validateGlobalFlags(parsed.flags);
3635

37-
const arityError = validatePositionalArity(parsed.command, parsed.positionals);
38-
if (arityError) return arityError;
3936
const pseudoRef = targetRefCandidate(parsed.command, parsed.positionals);
4037
if (pseudoRef && !CONCRETE_REF.test(pseudoRef)) {
4138
return invalid('pseudo-ref', `Pseudo ref "${pseudoRef}" is not an observed @eN or @cN ref.`);
@@ -53,20 +50,6 @@ function validateGlobalFlags(flags: ReturnType<typeof parseArgs>['flags']): Vali
5350
: invalid('agent-device-grammar', 'Missing command.');
5451
}
5552

56-
function validatePositionalArity(
57-
command: string,
58-
positionals: string[],
59-
): ValidationResult | undefined {
60-
const schema = getCommandSchema(command);
61-
if (!schema || schema.allowsExtraPositionals) return undefined;
62-
const maximum = schema.positionalArgs?.length ?? 0;
63-
if (positionals.length <= maximum) return undefined;
64-
return invalid(
65-
'agent-device-grammar',
66-
`${command} accepts at most ${maximum} positional argument(s), received ${positionals.length}: ${positionals.join(' ')}`,
67-
);
68-
}
69-
7053
function targetRefCandidate(command: string, positionals: string[]): string | undefined {
7154
const targetPosition = TARGET_POSITION_BY_COMMAND.get(command);
7255
if (targetPosition !== undefined) {

‎src/cli-schema/command-overrides.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ const SCHEMA_ONLY_CLI_COMMAND_SCHEMAS = {
5858
listUsageOverride: 'connect',
5959
summary:
6060
'Attach CLI commands to a saved remote daemon/cloud lease; inspect for remote runs, tenants, or service-token CI',
61+
positionalArgs: ['provider?'],
6162
allowedFlags: [
6263
'remoteConfig',
6364
'daemonBaseUrl',

‎src/cli-schema/command-schema.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
type FlagDefinition,
1313
type FlagKey,
1414
} from '../commands/cli-grammar/flag-types.ts';
15+
import { AppError } from '../kernel/errors.ts';
1516

1617
export type { CliFlags, FlagDefinition, FlagKey };
1718
export type { CommandSchema };
@@ -37,6 +38,22 @@ export function getCliCommandSchema(command: CliCommandName): CommandSchema {
3738
return schema;
3839
}
3940

41+
export function assertCommandPositionalArity(
42+
command: string | null,
43+
positionals: readonly string[],
44+
context?: string,
45+
): void {
46+
const schema = getCommandSchema(command);
47+
if (!command || !schema || schema.allowsExtraPositionals) return;
48+
const maximum = schema.positionalArgs?.length ?? 0;
49+
if (positionals.length <= maximum) return;
50+
const subject = context ? `${context} ${command}` : command;
51+
throw new AppError(
52+
'INVALID_ARGS',
53+
`${subject} accepts at most ${maximum} positional argument(s), received ${positionals.length}: ${positionals.join(' ')}`,
54+
);
55+
}
56+
4057
function readCommandSchema(command: string): CommandSchema | undefined {
4158
const schemaOnly = getSchemaOnlyCliCommandSchema(command);
4259
if (schemaOnly) return schemaOnly;

‎src/cli/batch-steps.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { isCommandName, type CommandName } from '../commands/command-metadata.ts
66
import type { CliFlags } from '../contracts/cli-flags.ts';
77
import { AppError } from '../kernel/errors.ts';
88
import { isRecord } from '../utils/parsing.ts';
9+
import { assertCommandPositionalArity } from '../cli-schema/command-schema.ts';
910

1011
type LegacyCliBatchStep = {
1112
command: CommandName;
@@ -79,6 +80,7 @@ function readLegacyCliBatchStep(step: unknown, stepNumber: number): LegacyCliBat
7980
assertLegacyBatchStepKeys(step, stepNumber);
8081
const command = readLegacyCommand(step.command, stepNumber);
8182
const positionals = readLegacyPositionals(step.positionals, stepNumber);
83+
assertCommandPositionalArity(command, positionals ?? [], `Batch step ${stepNumber}`);
8284
const flags = readLegacyFlags(step.flags, stepNumber);
8385
const runtime = parseBatchStepRuntime(step.runtime, stepNumber);
8486
return {

‎src/cli/parser/__tests__/args-validation.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import { test } from 'vitest';
22
import assert from 'node:assert/strict';
33
import { parseArgs } from '../args.ts';
44
import { AppError } from '../../../kernel/errors.ts';
5+
import { listCliCommandNames } from '../../../command-catalog.ts';
6+
import { getCliCommandSchema } from '../../../cli-schema/command-schema.ts';
57

68
test('parseArgs rejects test retries above the supported ceiling', () => {
79
assert.throws(
@@ -130,6 +132,32 @@ test('negative numeric positionals are accepted without -- separator', () => {
130132
assert.deepEqual(pressed.positionals, ['-10', '20']);
131133
});
132134

135+
test('get accepts a snapshot ref with a multiword label', () => {
136+
const parsed = parseArgs(['get', 'text', '@e5~s3', 'World', 'Clock'], { strictFlags: true });
137+
138+
assert.equal(parsed.command, 'get');
139+
assert.deepEqual(parsed.positionals, ['text', '@e5~s3', 'World', 'Clock']);
140+
});
141+
142+
test('bounded commands reject excess positionals from their CLI schema', () => {
143+
for (const command of listCliCommandNames()) {
144+
const schema = getCliCommandSchema(command);
145+
if (schema.allowsExtraPositionals) continue;
146+
const maximum = schema.positionalArgs?.length ?? 0;
147+
const positionals = Array.from({ length: maximum + 1 }, (_, index) => `arg-${index + 1}`);
148+
149+
assert.throws(
150+
() => parseArgs([command, ...positionals], { strictFlags: true }),
151+
(error: unknown) =>
152+
error instanceof AppError &&
153+
error.code === 'INVALID_ARGS' &&
154+
error.message ===
155+
`${command} accepts at most ${maximum} positional argument(s), received ${positionals.length}: ${positionals.join(' ')}`,
156+
`Expected ${command} to reject excess positionals`,
157+
);
158+
}
159+
});
160+
133161
test('command-specific flags without command fail in strict mode', () => {
134162
assert.throws(
135163
() => parseArgs(['--depth', '3'], { strictFlags: true }),

‎src/cli/parser/args.ts‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { AppError } from '../../kernel/errors.ts';
22
import { mergeDefinedFlags } from '../../utils/merge-flags.ts';
33
import {
44
applyCommandDefaults,
5+
assertCommandPositionalArity,
56
getCommandSchema,
67
getFlagDefinition,
78
getFlagDefinitions,
@@ -200,7 +201,14 @@ export function finalizeParsedArgs(
200201
}
201202
assertNoConflictingBackModeFlags(parsed);
202203
applyCommandDefaults(parsed.command, flags);
203-
if (parsed.command === 'batch') {
204+
const normalized = normalizeParsedCommandAliases({
205+
command: parsed.command,
206+
positionals: parsed.positionals,
207+
flags,
208+
warnings,
209+
});
210+
assertCommandPositionalArity(normalized.command, normalized.positionals);
211+
if (normalized.command === 'batch') {
204212
const stepSourceCount = (flags.steps ? 1 : 0) + (flags.stepsFile ? 1 : 0);
205213
if (stepSourceCount !== 1) {
206214
throw new AppError(
@@ -209,12 +217,7 @@ export function finalizeParsedArgs(
209217
);
210218
}
211219
}
212-
return normalizeParsedCommandAliases({
213-
command: parsed.command,
214-
positionals: parsed.positionals,
215-
flags,
216-
warnings,
217-
});
220+
return normalized;
218221
}
219222

220223
function assertNoConflictingBackModeFlags(parsed: RawParsedArgs): void {

‎src/commands/batch/cli.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,38 @@ test('batch accepts legacy positionals/flags steps with deprecation warning', as
153153
});
154154
});
155155

156+
test('batch rejects excess legacy positionals before daemon projection', async () => {
157+
const result = await runCliCapture([
158+
'batch',
159+
'--steps',
160+
'[{"command":"open","positionals":["settings","https://example.com","close"]}]',
161+
]);
162+
163+
assert.equal(result.code, 1);
164+
assert.equal(result.calls.length, 0);
165+
assert.match(
166+
result.stderr,
167+
/Batch step 1 open accepts at most 2 positional argument\(s\), received 3/,
168+
);
169+
});
170+
171+
test('batch accepts a multiword ref label in a legacy get step', async () => {
172+
const result = await runCliCapture([
173+
'batch',
174+
'--steps',
175+
'[{"command":"get","positionals":["text","@e5~s3","World","Clock"]}]',
176+
'--json',
177+
]);
178+
179+
assert.equal(result.code, null);
180+
assert.equal(result.calls.length, 1);
181+
assert.deepEqual((result.calls[0]?.flags?.batchSteps ?? [])[0]?.positionals, [
182+
'text',
183+
'@e5~s3',
184+
'World Clock',
185+
]);
186+
});
187+
156188
test('batch rejects hybrid structured and legacy step shapes', async () => {
157189
const result = await runCliCapture([
158190
'batch',

‎src/commands/interaction/index.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ const interactionCliSchemas = {
5858
get: {
5959
usageOverride: 'get text|attrs <@ref|selector>',
6060
positionalArgs: ['subcommand', 'target'],
61+
allowsExtraPositionals: true,
6162
allowedFlags: [...SELECTOR_SNAPSHOT_FLAGS, 'record'],
6263
},
6364
find: {
@@ -106,7 +107,7 @@ const interactionCliSchemas = {
106107
},
107108
swipe: {
108109
helpDescription: 'Quick coordinate fling with optional repeat pattern.',
109-
positionalArgs: ['x1', 'y1', 'x2', 'y2'],
110+
positionalArgs: ['x1', 'y1', 'x2', 'y2', 'durationMs?'],
110111
allowedFlags: ['count', 'pauseMs', 'pattern'],
111112
},
112113
gesture: {

0 commit comments

Comments
 (0)