Skip to content

Commit cd3b5ee

Browse files
committed
fix(cli): preserve explicit option intent
1 parent 7a9d2c3 commit cd3b5ee

25 files changed

Lines changed: 470 additions & 50 deletions

‎src/cli/argv.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
isHelpOrVersionInvocation,
1313
isRootHelpInvocation,
1414
isRootVersionInvocation,
15+
isSimpleCommandHelpInvocation,
1516
normalizeGeneratedHelpCommandArgv,
1617
normalizeRootHelpTargetArgv,
1718
normalizeRootLogLevelArgv,
@@ -480,6 +481,31 @@ describe("argv helpers", () => {
480481
).toEqual(["config", "validate"]);
481482
});
482483

484+
it("limits simple help fast paths to root options, a command, and help", () => {
485+
const commands = new Set(["setup"]);
486+
expect(
487+
isSimpleCommandHelpInvocation(
488+
["node", "openclaw", "--profile", "work", "setup", "--help"],
489+
commands,
490+
),
491+
).toBe(true);
492+
expect(
493+
isSimpleCommandHelpInvocation(
494+
["node", "openclaw", "setup", "--workspace", "--help"],
495+
commands,
496+
),
497+
).toBe(false);
498+
expect(
499+
isSimpleCommandHelpInvocation(
500+
["node", "openclaw", "setup", "--profile", "work", "--help"],
501+
commands,
502+
),
503+
).toBe(false);
504+
expect(isSimpleCommandHelpInvocation(["node", "openclaw", "--help", "setup"], commands)).toBe(
505+
false,
506+
);
507+
});
508+
483509
it("extracts routed config get positionals with interleaved root options", () => {
484510
expect(
485511
getCommandPositionalsWithRootOptions(

‎src/cli/argv.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,42 @@ export function isRootHelpInvocation(argv: string[]): boolean {
164164
return isRootInvocationForFlags(argv, HELP_FLAGS);
165165
}
166166

167+
/** Match fast-path command help only when no command option can own the help token as a value. */
168+
export function isSimpleCommandHelpInvocation(
169+
argv: string[],
170+
commandNames: ReadonlySet<string>,
171+
): boolean {
172+
const args = argv.slice(2);
173+
let commandSeen = false;
174+
let helpSeen = false;
175+
for (let index = 0; index < args.length; index += 1) {
176+
const arg = args[index];
177+
if (!arg || arg === FLAG_TERMINATOR) {
178+
return false;
179+
}
180+
const rootConsumed = commandSeen ? 0 : consumeRootOptionToken(args, index);
181+
if (rootConsumed > 0) {
182+
index += rootConsumed - 1;
183+
continue;
184+
}
185+
if (HELP_FLAGS.has(arg)) {
186+
if (!commandSeen) {
187+
return false;
188+
}
189+
helpSeen = true;
190+
continue;
191+
}
192+
if (arg.startsWith("-") || commandSeen) {
193+
return false;
194+
}
195+
if (!commandNames.has(arg)) {
196+
return false;
197+
}
198+
commandSeen = true;
199+
}
200+
return commandSeen && helpSeen;
201+
}
202+
167203
type HelpNormalizationPositional = { value: string; index: number };
168204

169205
type HelpNormalizationScanResult =

‎src/cli/help-exit.process.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,19 @@ describe("CLI help process exit", () => {
249249
);
250250
});
251251

252+
it("treats --help as a required option value when Commander does", async () => {
253+
let failure: CliProcessFailure | undefined;
254+
try {
255+
await runCliProcess({ args: ["secrets", "apply", "--from", "--help"], config: {} });
256+
} catch (error) {
257+
failure = error as CliProcessFailure;
258+
}
259+
260+
expect(failure?.code).toBe(1);
261+
expect(failure?.stdout ?? "").not.toContain("Usage:");
262+
expect(failure?.stderr).toContain("plan file not found: --help");
263+
});
264+
252265
it.each(LAZY_GROUP_HELP_CASES)(
253266
"renders in-process help for $group",
254267
async ({ group, usageCommand, registry }) => {
@@ -358,6 +371,19 @@ describe("JSON console style process output", () => {
358371
expect(JSON.parse(result.stdout)).toEqual([]);
359372
});
360373

374+
it("emits one JSON object for baseline setup", async () => {
375+
const result = await runCliProcess({ args: ["setup", "--baseline", "--json"], config: {} });
376+
377+
expect(result.stderr).toBe("");
378+
expect(JSON.parse(result.stdout)).toMatchObject({
379+
ok: true,
380+
configPath: expect.any(String),
381+
configStatus: "updated",
382+
workspaceDir: expect.any(String),
383+
sessionsDir: expect.any(String),
384+
});
385+
});
386+
361387
it("structures invalid log-level environment warnings", async () => {
362388
const result = await runCliProcess({
363389
args: ["status", "--timeout", "1000"],

‎src/cli/precomputed-help.test.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// Precomputed help tests cover the strict argv shape required by help fast paths.
2+
import { describe, expect, it, vi } from "vitest";
3+
import { tryOutputPrecomputedCommandHelp } from "./precomputed-help.js";
4+
5+
describe("tryOutputPrecomputedCommandHelp", () => {
6+
it("renders only an unambiguous command help request", async () => {
7+
const outputBrowserHelp = vi.fn(() => true);
8+
9+
await expect(
10+
tryOutputPrecomputedCommandHelp(["node", "openclaw", "browser", "--help"], {
11+
outputPrecomputedBrowserHelpText: outputBrowserHelp,
12+
env: {},
13+
}),
14+
).resolves.toBe(true);
15+
expect(outputBrowserHelp).toHaveBeenCalledOnce();
16+
});
17+
18+
it("falls back when a command option may own --help as its value", async () => {
19+
const outputBrowserHelp = vi.fn(() => true);
20+
21+
await expect(
22+
tryOutputPrecomputedCommandHelp(["node", "openclaw", "browser", "--target", "--help"], {
23+
outputPrecomputedBrowserHelpText: outputBrowserHelp,
24+
env: {},
25+
}),
26+
).resolves.toBe(false);
27+
expect(outputBrowserHelp).not.toHaveBeenCalled();
28+
});
29+
});

‎src/cli/precomputed-help.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { consumeRootOptionToken } from "../infra/cli-root-options.js";
2-
import { getCommandPathWithRootOptions, hasFlag } from "./argv.js";
2+
import { getCommandPathWithRootOptions, isSimpleCommandHelpInvocation } from "./argv.js";
33
import type { RootHelpRenderOptions } from "./program/root-help.js";
44

55
type PrecomputedSubcommandHelpName =
@@ -13,6 +13,8 @@ type PrecomputedSubcommandHelpName =
1313
type PrecomputedCommandHelpName = "browser" | "secrets" | "nodes";
1414
type OutputPrecomputedHelpText = () => boolean;
1515

16+
const PRECOMPUTED_COMMAND_HELP_NAMES = new Set<string>(["browser", "secrets", "nodes"]);
17+
1618
export type PrecomputedCommandHelpDeps = {
1719
outputPrecomputedBrowserHelpText?: OutputPrecomputedHelpText;
1820
outputPrecomputedSecretsHelpText?: OutputPrecomputedHelpText;
@@ -80,7 +82,7 @@ function resolvePrecomputedSubcommandHelpCommand(
8082
}
8183

8284
function resolvePrecomputedCommandHelpName(argv: string[]): PrecomputedCommandHelpName | null {
83-
if (!hasFlag(argv, "--help") && !hasFlag(argv, "-h")) {
85+
if (!isSimpleCommandHelpInvocation(argv, PRECOMPUTED_COMMAND_HELP_NAMES)) {
8486
return null;
8587
}
8688
const commandPath = getCommandPathWithRootOptions(argv, 2);

‎src/cli/program/build-program.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,4 +138,28 @@ describe("buildProgram", () => {
138138
expect(error.code).toBe("commander.help");
139139
expect(process.exitCode).toBe(1);
140140
});
141+
142+
it("preserves caller-configured Commander error output", async () => {
143+
let stderr = "";
144+
const outputError = vi.fn((value: string, write: (value: string) => void) => {
145+
write(`custom: ${value}`);
146+
});
147+
const originalArgv = process.argv;
148+
const program = buildProgram().configureOutput({
149+
writeErr: (value) => {
150+
stderr += value;
151+
},
152+
outputError,
153+
});
154+
program.command("probe").action(() => {});
155+
process.argv = ["node", "openclaw", "probe", "--wat"];
156+
try {
157+
await expectCommanderExit(program.parseAsync(process.argv), 1);
158+
} finally {
159+
process.argv = originalArgv;
160+
}
161+
162+
expect(outputError).toHaveBeenCalledOnce();
163+
expect(stderr).toContain("custom: error: unknown option '--wat'");
164+
});
141165
});

‎src/cli/program/build-program.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
// Builds the root Commander program, context, help, hooks, and command registry.
22
import process from "node:process";
3-
import { Command } from "commander";
43
import { registerProgramCommands } from "./command-registry.js";
54
import { createProgramContext } from "./context.js";
65
import { configureProgramHelp } from "./help.js";
6+
import { OpenClawCommand } from "./openclaw-command.js";
77
import { registerPreActionHooks } from "./preaction.js";
88
import { setProgramContext } from "./program-context.js";
99

1010
export function buildProgram() {
11-
const program = new Command();
11+
const program = new OpenClawCommand();
1212
program.enablePositionalOptions();
1313
// Preserve Commander-computed exit codes while still aborting parse flow.
1414
// Without this, unknown nested commands can print an error
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
// Facts Commander owns after parsing: the active path and which tokens became option values.
2+
import type { Command, Option } from "commander";
3+
4+
const activeErrorCommandByRoot = new WeakMap<Command, Command>();
5+
6+
function getCommandHierarchy(command: Command): Command[] {
7+
const hierarchy: Command[] = [];
8+
for (let current: Command | null = command; current; current = current.parent ?? null) {
9+
hierarchy.unshift(current);
10+
}
11+
return hierarchy;
12+
}
13+
14+
function requiresFollowingValue(token: string, options: readonly Option[]): boolean {
15+
if (token.includes("=")) {
16+
return false;
17+
}
18+
const exact = options.find((option) => option.short === token || option.long === token);
19+
if (exact) {
20+
return exact.required;
21+
}
22+
if (!token.startsWith("-") || token.startsWith("--")) {
23+
return false;
24+
}
25+
const shortGroup = token.slice(1);
26+
for (let index = 0; index < shortGroup.length; index += 1) {
27+
const option = options.find((candidate) => candidate.short === `-${shortGroup[index]}`);
28+
if (!option) {
29+
return false;
30+
}
31+
if (option.required || option.optional) {
32+
return option.required && index === shortGroup.length - 1;
33+
}
34+
}
35+
return false;
36+
}
37+
38+
/** Return whether Commander consumed one of the supplied argv tokens as a required option value. */
39+
export function hasCommanderOptionValue(
40+
command: Command,
41+
argv: readonly string[],
42+
tokens: ReadonlySet<string>,
43+
): boolean {
44+
const hierarchy = getCommandHierarchy(command);
45+
const args = argv.slice(2);
46+
let commandIndex = 0;
47+
for (let index = 0; index < args.length; index += 1) {
48+
const arg = args[index];
49+
if (arg === undefined || arg === "--") {
50+
break;
51+
}
52+
const nextCommand = hierarchy[commandIndex + 1];
53+
if (nextCommand && (arg === nextCommand.name() || nextCommand.aliases().includes(arg))) {
54+
commandIndex += 1;
55+
continue;
56+
}
57+
// The root program enables positional options, so after dispatch Commander
58+
// parses only the active command's options; ancestor flags there never reach pre-action.
59+
if (requiresFollowingValue(arg, hierarchy[commandIndex]?.options ?? [])) {
60+
const value = args[index + 1];
61+
if (value && tokens.has(value)) {
62+
return true;
63+
}
64+
index += 1;
65+
}
66+
}
67+
return false;
68+
}
69+
70+
/** Return the registered command path for the exact Commander node handling an error or action. */
71+
export function getCommanderCommandPath(command: Command): string[] {
72+
const commandPath: string[] = [];
73+
for (let current: Command | null = command; current?.parent; current = current.parent) {
74+
commandPath.unshift(current.name());
75+
}
76+
return commandPath;
77+
}
78+
79+
function getRootCommand(command: Command): Command {
80+
let root = command;
81+
while (root.parent) {
82+
root = root.parent;
83+
}
84+
return root;
85+
}
86+
87+
/** Scope the exact Commander node synchronously emitting an error. */
88+
export function setCommanderErrorCommand(command: Command): () => void {
89+
const root = getRootCommand(command);
90+
const previous = activeErrorCommandByRoot.get(root);
91+
activeErrorCommandByRoot.set(root, command);
92+
return () => {
93+
if (previous) {
94+
activeErrorCommandByRoot.set(root, previous);
95+
} else {
96+
activeErrorCommandByRoot.delete(root);
97+
}
98+
};
99+
}
100+
101+
/** Return the active parse-error path without replacing Commander's configured output handler. */
102+
export function getCommanderErrorCommandPath(program: Command): string[] | undefined {
103+
const command = activeErrorCommandByRoot.get(getRootCommand(program));
104+
return command ? getCommanderCommandPath(command) : undefined;
105+
}

‎src/cli/program/error-output.test.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,4 +68,15 @@ describe("formatCliParseErrorOutput", () => {
6868
'Missing required argument "name".\nTry: openclaw plugins install --help\n',
6969
);
7070
});
71+
72+
it("prefers the parsed Commander path over option-like argv values", () => {
73+
const output = formatCliParseErrorOutput("error: unknown option '--wat'\n", {
74+
argv: ["node", "openclaw", "plugins", "--source", "install", "list", "--wat"],
75+
commandPath: ["plugins", "list"],
76+
});
77+
78+
expect(output).toBe(
79+
'OpenClaw does not recognize option "--wat".\nTry: openclaw plugins list --help\n',
80+
);
81+
});
7182
});

0 commit comments

Comments
 (0)