Skip to content

Commit b80d55a

Browse files
authored
fix(cli): report unknown subcommands even with --help (#124707)
* fix(cli): report unknown subcommands even with --help * fix(cli): scope Commander hook lint exceptions * fix(cli): document Commander hook assertion * refactor(cli): delegate the Commander help hook through super
1 parent 1bcec21 commit b80d55a

6 files changed

Lines changed: 136 additions & 18 deletions

File tree

‎src/cli/program/commander-parse-facts.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@
22
import type { Command, Option } from "commander";
33

44
const activeErrorCommandByRoot = new WeakMap<Command, Command>();
5+
const lazyCommands = new WeakSet<Command>();
6+
7+
export function markCommanderLazyCommand(command: Command): void {
8+
lazyCommands.add(command);
9+
}
510

611
function getCommandHierarchy(command: Command): Command[] {
712
const hierarchy: Command[] = [];
@@ -84,6 +89,30 @@ function getRootCommand(command: Command): Command {
8489
return root;
8590
}
8691

92+
/** Classify a possible child token only after Commander owns its active command node. */
93+
export function getCommanderSubcommandFact(
94+
command: Command,
95+
args: readonly string[],
96+
): { kind: "defer" } | { kind: "unknown"; name: string } | undefined {
97+
const firstArgument = command.args[0];
98+
const matchesChild = command.commands.some(
99+
(child) => child.name() === firstArgument || child.aliases().includes(firstArgument ?? ""),
100+
);
101+
if (
102+
command.registeredArguments.length > 0 ||
103+
firstArgument === undefined ||
104+
firstArgument.startsWith("-") ||
105+
matchesChild
106+
) {
107+
return undefined;
108+
}
109+
const helpRequested = args.includes("-h") || args.includes("--help");
110+
if (helpRequested && lazyCommands.has(command)) {
111+
return { kind: "defer" };
112+
}
113+
return command.commands.length > 0 ? { kind: "unknown", name: firstArgument } : undefined;
114+
}
115+
87116
/** Scope the exact Commander node synchronously emitting an error. */
88117
export function setCommanderErrorCommand(command: Command): () => void {
89118
const root = getRootCommand(command);

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

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,17 @@ async function parseLazyGroupError(params: {
1313
argv: string[];
1414
group: string;
1515
subcommands: Array<{ name: string; aliases?: string[] }>;
16-
}): Promise<{ error: CommanderError; output: string }> {
16+
}): Promise<{ error: CommanderError; output: string; stdout: string }> {
1717
const originalArgv = process.argv;
1818
process.argv = ["node", "openclaw", ...params.argv];
1919
let output = "";
20+
let stdout = "";
2021
try {
2122
const program = new OpenClawCommand().name("openclaw").exitOverride();
2223
program.configureOutput({
24+
writeOut: (value) => {
25+
stdout += value;
26+
},
2327
writeErr: (value) => {
2428
output += value;
2529
},
@@ -50,7 +54,7 @@ async function parseLazyGroupError(params: {
5054

5155
const error = await program.parseAsync(process.argv).catch((cause: unknown) => cause);
5256
expect(error).toBeInstanceOf(CommanderError);
53-
return { error: error as CommanderError, output };
57+
return { error: error as CommanderError, output, stdout };
5458
} finally {
5559
process.argv = originalArgv;
5660
}
@@ -103,6 +107,34 @@ describe("formatCliParseErrorOutput", () => {
103107
);
104108
});
105109

110+
it("reports an unmatched lazy subcommand before --help can hide it", async () => {
111+
const { error, output, stdout } = await parseLazyGroupError({
112+
argv: ["sessions", "lst", "--help"],
113+
group: "sessions",
114+
subcommands: [{ name: "list" }, { name: "cleanup" }],
115+
});
116+
117+
expect(error.code).toBe("commander.unknownCommand");
118+
expect(error.exitCode).toBe(1);
119+
expect(stdout).toBe("");
120+
expect(output).toBe(
121+
'OpenClaw sessions has no command "lst".\nDid you mean this?\n openclaw sessions list\nTry: openclaw sessions --help\nDocs: https://docs.openclaw.ai/cli\n',
122+
);
123+
});
124+
125+
it("loads a real lazy subcommand before showing its help", async () => {
126+
const { error, output, stdout } = await parseLazyGroupError({
127+
argv: ["sessions", "list", "--help"],
128+
group: "sessions",
129+
subcommands: [{ name: "list" }, { name: "cleanup" }],
130+
});
131+
132+
expect(error.code).toBe("commander.helpDisplayed");
133+
expect(error.exitCode).toBe(0);
134+
expect(output).toBe("");
135+
expect(stdout).toContain("Usage: openclaw sessions list [options]");
136+
});
137+
106138
it("suggests aliases from the live child command tree", async () => {
107139
const { error, output } = await parseLazyGroupError({
108140
argv: ["cron", "remov"],

‎src/cli/program/help.test.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,31 @@ describe("configureProgramHelp", () => {
118118
}
119119
}
120120

121+
async function parseHelp(argv: string[]) {
122+
process.argv = ["node", "openclaw", ...argv];
123+
let stdout = "";
124+
let stderr = "";
125+
const program = new OpenClawCommand().enablePositionalOptions().exitOverride();
126+
configureProgramHelp(program, testProgramContext);
127+
program.configureOutput({
128+
writeOut: (value) => {
129+
stdout += value;
130+
},
131+
writeErr: (value) => {
132+
stderr += value;
133+
},
134+
});
135+
const plugins = program.command("plugins").description("Manage plugins");
136+
plugins
137+
.command("list")
138+
.description("List plugins")
139+
.action(() => {});
140+
141+
const error = await program.parseAsync(process.argv).catch((cause: unknown) => cause);
142+
expect(error).toBeInstanceOf(CommanderError);
143+
return { error: error as CommanderError, stderr, stdout };
144+
}
145+
121146
it("adds root help hint and marks commands with subcommands", () => {
122147
process.argv = ["node", "openclaw", "--help"];
123148
const program = makeProgramWithCommands();
@@ -146,6 +171,24 @@ describe("configureProgramHelp", () => {
146171
expect(help).toContain("https://docs.openclaw.ai/cli");
147172
});
148173

174+
it("keeps valid root, group, subcommand, short, and help-command output successful", async () => {
175+
const rootHelp = await parseHelp(["--help"]);
176+
const shortHelp = await parseHelp(["-h"]);
177+
const groupHelp = await parseHelp(["plugins", "--help"]);
178+
const subcommandHelp = await parseHelp(["plugins", "list", "--help"]);
179+
const helpCommand = await parseHelp(["help", "plugins"]);
180+
181+
for (const result of [rootHelp, shortHelp, groupHelp, subcommandHelp, helpCommand]) {
182+
expect(result.error.exitCode).toBe(0);
183+
expect(result.stderr).toBe("");
184+
}
185+
expect(rootHelp.error.code).toBe("commander.helpDisplayed");
186+
expect(shortHelp.stdout).toBe(rootHelp.stdout);
187+
expect(groupHelp.stdout).toContain("Usage: openclaw plugins [options] [command]");
188+
expect(subcommandHelp.stdout).toContain("Usage: openclaw plugins list [options]");
189+
expect(helpCommand.stdout).toBe(groupHelp.stdout);
190+
});
191+
149192
it("formats parse errors from the exact Commander command path", async () => {
150193
let stderr = "";
151194
process.argv = ["node", "openclaw", "plugins", "--source", "list", "list", "--wat"];
Lines changed: 27 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,43 @@
11
// Commander subclass that preserves the exact failing command for parse-error guidance.
22
import { Command, type ErrorOptions } from "commander";
3-
import { setCommanderErrorCommand } from "./commander-parse-facts.js";
3+
import { getCommanderSubcommandFact, setCommanderErrorCommand } from "./commander-parse-facts.js";
4+
5+
// Commander 15 declares this help hook only in its runtime class, not its types.
6+
// Declaring it here lets the subclass override and delegate through `super`
7+
// instead of re-binding a captured prototype method.
8+
declare module "commander" {
9+
interface Command {
10+
_outputHelpIfRequested(args: string[]): void;
11+
}
12+
}
413

514
export class OpenClawCommand extends Command {
615
override createCommand(name?: string): Command {
716
return new OpenClawCommand(name);
817
}
918

1019
override error(message: string, errorOptions?: ErrorOptions): never {
11-
const firstArgument = this.args[0];
12-
// Commander checks a parent action before its unknown-command branch.
13-
// Reclassify only zero-argument parents so genuine leaf excess stays intact.
14-
const isUnknownSubcommand =
15-
errorOptions?.code === "commander.excessArguments" &&
16-
this.registeredArguments.length === 0 &&
17-
this.commands.length > 0 &&
18-
firstArgument !== undefined &&
19-
!this.commands.some(
20-
(command) => command.name() === firstArgument || command.aliases().includes(firstArgument),
21-
);
2220
const restoreErrorCommand = setCommanderErrorCommand(this);
2321
try {
24-
return super.error(
25-
isUnknownSubcommand ? `error: unknown command '${firstArgument}'` : message,
26-
isUnknownSubcommand ? { ...errorOptions, code: "commander.unknownCommand" } : errorOptions,
27-
);
22+
return super.error(message, errorOptions);
2823
} finally {
2924
restoreErrorCommand();
3025
}
3126
}
27+
28+
// Commander 15 checks this internal hook before dispatching actions.
29+
// Defer only marked lazy placeholders so their real command tree can decide.
30+
override _outputHelpIfRequested(args: string[]): void {
31+
const subcommandFact = getCommanderSubcommandFact(this, args);
32+
if (subcommandFact?.kind === "defer") {
33+
return;
34+
}
35+
if (subcommandFact?.kind === "unknown") {
36+
this.error(`error: unknown command '${subcommandFact.name}'`, {
37+
code: "commander.unknownCommand",
38+
});
39+
}
40+
// oxlint-disable-next-line eslint/no-underscore-dangle -- Commander 15.0.0 owns this hook name; package.json pins that exact version.
41+
super._outputHelpIfRequested(args);
42+
}
3243
}

‎src/cli/program/register-lazy-command.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import type { Command } from "commander";
33
import { reparseProgramFromActionCommand } from "./action-reparse.js";
44
import { removeCommandByName } from "./command-tree.js";
5+
import { markCommanderLazyCommand } from "./commander-parse-facts.js";
56

67
type RegisterLazyCommandParams = {
78
program: Command;
@@ -25,6 +26,7 @@ export function registerLazyCommand({
2526
register,
2627
}: RegisterLazyCommandParams): void {
2728
const placeholder = program.command(name).description(description);
29+
markCommanderLazyCommand(placeholder);
2830
for (const option of options ?? []) {
2931
placeholder.option(option.flags, option.description);
3032
}

‎test/scripts/lint-suppressions.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,7 @@ describe("production lint suppressions", () => {
208208
"src/cli/cli-utils.ts|typescript/no-unnecessary-type-parameters|1",
209209
"src/cli/command-options.ts|typescript/no-unnecessary-type-parameters|1",
210210
"src/cli/plugins-cli-test-helpers.ts|typescript/no-unnecessary-type-parameters|1",
211+
"src/cli/program/openclaw-command.ts|eslint/no-underscore-dangle|1",
211212
"src/cli/test-runtime-capture.ts|typescript/no-unnecessary-type-parameters|1",
212213
"src/gateway/test-helpers.server.ts|typescript/no-unnecessary-type-parameters|1",
213214
"src/hooks/module-loader.ts|typescript/no-unnecessary-type-parameters|1",

0 commit comments

Comments
 (0)