Skip to content

Commit e2c9151

Browse files
jrusso1020claude
andauthored
fix(cli): add help [cmd], suggest the closest command or flag, and quiet the nags (#6621)
* fix(cli): add help [cmd], suggest the closest command or flag, and quiet the nags `hyperframes help` printed "Unknown command help" with raw ANSI codes and no suggestion. It is now an alias: `help [cmd...]` is `[cmd...] --help`. An unknown command (at the root or inside a group like `cloud`) prints "Unknown command: rendr", "Did you mean 'hyperframes render'?" and the group's usage, all on stderr, and exits 2. An unknown flag suggests the flag it most likely means ("Did you mean --output?"). Usage text printed for a usage error now goes to stderr instead of stdout, and citty's colors are stripped from help whenever this CLI's own colors are off. No update, skills or app-history notice is appended to a usage error. The skills notice shows at most once a day per project (timestamps in ~/.hyperframes/skills-notice.json) and, in an unattended run, only when a core skill is missing. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(cli): reject an unknown top-level command without loading every command citty looks for an alias on every registered command before it reports an unknown name, which loads all of them. From a source checkout without the studio packages built, that meant `hyperframes rendr` failed in preview's build check with exit 1 instead of suggesting `render`. The name is now checked against the registry first. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(cli): help with a mistyped subcommand reports it like the command itself `hyperframes help cloud rendr` printed cloud's help and exited 0, while `hyperframes cloud rendr` exits 2 with a suggestion. Both now exit 2 with the suggestion. A group that also takes positional arguments (timeline takes a project directory) still shows its help for a word it does not know. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 3d1c076 commit e2c9151

11 files changed

Lines changed: 310 additions & 41 deletions

‎docs/packages/cli.mdx‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@ This page lists every command and every flag. If you are still deciding which
88
command you need, the [CLI guide](/developers/cli) is the shorter route.
99

1010
The installed version is always the authority. Run
11-
`npx hyperframes <command> --help` to see exactly what your copy accepts.
11+
`npx hyperframes help <command>` (or `npx hyperframes <command> --help`) to see
12+
exactly what your copy accepts. A mistyped command or flag exits 2 and suggests
13+
the closest one: `Did you mean 'hyperframes render'?`.
1214

1315
```bash
1416
# No install needed
@@ -96,6 +98,12 @@ there. While an install is underway, the notice is not shown.
9698
`HYPERFRAMES_NO_UPDATE_CHECK=1` turns off the check, the install, and the
9799
notice; `HYPERFRAMES_NO_AUTO_INSTALL=1` turns off only the install.
98100

101+
**Skills notice.** When installed HyperFrames skills are out of date or missing,
102+
a command ends with one line on stderr naming `npx hyperframes skills update`.
103+
It shows at most once a day per project. In an unattended run it shows only when
104+
a core skill is missing. `HYPERFRAMES_SKIP_SKILLS=1` turns it off. No notice
105+
follows a usage error.
106+
99107
## Create a project
100108

101109
### `init`

‎packages/cli/src/cli.agentMode.test.ts‎

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ interface Run {
7070
stderr: string;
7171
}
7272

73-
function runAsAgent(args: string[]): Promise<Run> {
73+
function runAsAgent(args: string[], { ci = true } = {}): Promise<Run> {
7474
return new Promise((resolve, reject) => {
7575
const child = spawn("bun", ["run", cliEntry, ...args], {
7676
cwd: home,
@@ -80,7 +80,7 @@ function runAsAgent(args: string[]): Promise<Run> {
8080
PATH: process.env.PATH,
8181
HOME: home,
8282
USERPROFILE: home,
83-
CI: "1",
83+
...(ci ? { CI: "1" } : {}),
8484
CLAUDECODE: "1",
8585
},
8686
});
@@ -153,6 +153,46 @@ describe("agent-mode contract", () => {
153153
expect(run.code, run.stderr).toBe(2);
154154
});
155155

156+
it.each([
157+
["help", "Usage:"],
158+
["help render", "USAGE hyperframes render"],
159+
["help cloud render", "USAGE cloud render"],
160+
])("`%s` prints that help on stdout and exits 0", async (args, heading) => {
161+
const run = await runAsAgent(args.split(" "));
162+
expectQuiet(run);
163+
expect(run.code, run.stderr).toBe(0);
164+
expect(run.stdout).toContain(heading);
165+
expect(run.stderr).toBe("");
166+
});
167+
168+
it("help stays plain inside an agent even without CI", async () => {
169+
const run = await runAsAgent(["render", "--help"], { ci: false });
170+
expectQuiet(run);
171+
expect(run.code).toBe(0);
172+
});
173+
174+
it.each([
175+
["rendr", "Did you mean 'hyperframes render'?"],
176+
["cloud rendr", "Did you mean 'hyperframes cloud render'?"],
177+
["help rendr", "Did you mean 'hyperframes render'?"],
178+
["help cloud rendr", "Did you mean 'hyperframes cloud render'?"],
179+
])(
180+
"unknown command `%s` suggests the closest one, usage on stderr, exit 2",
181+
async (args, hint) => {
182+
const run = await runAsAgent(args.split(" "));
183+
expectQuiet(run);
184+
expect(run.code).toBe(2);
185+
expect(run.stdout).toBe("");
186+
expect(run.stderr).toContain(hint);
187+
},
188+
);
189+
190+
it("an unknown flag suggests the flag it most likely means", async () => {
191+
const run = await runAsAgent(["render", "--out", "x.mp4"]);
192+
expect(run.code).toBe(2);
193+
expect(run.stderr).toContain("Did you mean --output?");
194+
});
195+
156196
it.each([["publish"], ["upgrade"]])(
157197
"%s without --yes refuses to prompt, names --yes, and exits 2",
158198
async (name) => {

‎packages/cli/src/cli.ts‎

Lines changed: 72 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,10 @@ import { existsSync } from "node:fs";
5050
import { VERSION } from "./version.js";
5151

5252
let argv = process.argv.slice(2);
53+
if (argv[0] === "help") {
54+
process.argv = [...process.argv.slice(0, 2), ...argv.slice(1), "--help"];
55+
argv = process.argv.slice(2);
56+
}
5357
const commandArg = argv[0];
5458
const rootVersionRequested =
5559
commandArg === "--version" ||
@@ -89,7 +93,8 @@ import type { ArgsDef, CommandDef } from "citty";
8993
import { getRunId } from "./telemetry/runId.js";
9094
import { reportCommandFailure, trackCommandFailures } from "./utils/command-failure-tracking.js";
9195
import { isRenderSucceeded } from "./utils/render-success-state.js";
92-
import { resolveCommandUsage } from "./utils/commandUsageResolution.js";
96+
import { resolveCommandUsage, type ResolvedCommandUsage } from "./utils/commandUsageResolution.js";
97+
import { closestMatch } from "./utils/didYouMean.js";
9398
import { isDevMode } from "./utils/env.js";
9499
import {
95100
CliResultSignal,
@@ -347,13 +352,17 @@ async function finalizeCli(result: CommandResult): Promise<void> {
347352
runId,
348353
});
349354
// No network wait: the exit handler's flushSync() delivers what is still queued.
355+
if (result.kind !== "usage_error") printNotices();
356+
process.exitCode = exitCode;
357+
}
358+
359+
function printNotices(): void {
350360
if (!hasJsonFlag) {
351361
_printUpdateNotice?.();
352362
_printStalePinNotice?.();
353363
}
354364
_printSkillsUpdateNotice?.();
355365
if (_appHistoryNotice) process.stderr.write(`◇ ${_appHistoryNotice}\n`);
356-
process.exitCode = exitCode;
357366
}
358367

359368
registerRootExitRequester((exitCode) => {
@@ -512,28 +521,71 @@ process.on("unhandledRejection", (reason) => {
512521
// Lazy-load help renderer — avoids allocating help data on non-help invocations
513522
async function showUsage<T extends ArgsDef>(
514523
cmd: CommandDef<T>,
515-
parent?: CommandDef<T>,
524+
parent: CommandDef<T> | undefined,
525+
print: (text: string) => void,
516526
): Promise<void> {
517527
const { showUsage: impl } = await import("./help.js");
518-
return impl(cmd as CommandDef, parent as CommandDef | undefined);
528+
return impl(cmd as CommandDef, parent as CommandDef | undefined, print);
529+
}
530+
531+
// Prints the suggestion and the group's usage on stderr; the caller throws the returned error.
532+
async function unknownCommandError(requested: ResolvedCommandUsage): Promise<CliUsageError> {
533+
const word = requested.unknownSubcommand ?? "";
534+
const group = ["hyperframes", ...requested.path].join(" ");
535+
const declared = requested.command.subCommands;
536+
const subCommands = typeof declared === "function" ? await declared() : await declared;
537+
const match = closestMatch(word, Object.keys(subCommands ?? {}));
538+
console.error(`Unknown command: ${word}`);
539+
if (match) console.error(`Did you mean '${group} ${match}'?`);
540+
console.error("");
541+
await showUsage(requested.command, requested.parent, console.error);
542+
return new CliUsageError(`Unknown command: ${word}`, { presented: true });
543+
}
544+
545+
// A group like `timeline` also takes a project directory, so a word it does not know may be one.
546+
function takesPositionals(command: CommandDef): boolean {
547+
const args = command.args;
548+
return (
549+
typeof args === "object" &&
550+
args !== null &&
551+
Object.values(args).some((arg) => arg.type === "positional")
552+
);
519553
}
520554

521-
async function showRequestedUsage(): Promise<void> {
555+
async function showRequestedUsage(print: (text: string) => void): Promise<void> {
522556
const requested = await resolveCommandUsage(main as CommandDef, argv);
523-
return showUsage(requested.command, requested.parent);
557+
if (requested.unknownSubcommand && !takesPositionals(requested.command)) {
558+
throw await unknownCommandError(requested);
559+
}
560+
return showUsage(requested.command, requested.parent, print);
524561
}
525562

526-
// citty's own parse errors (missing argument, bad enum value, unknown or missing subcommand).
527-
const CITTY_USAGE_CODES = new Set(["EARG", "E_UNKNOWN_COMMAND", "E_NO_COMMAND"]);
563+
// citty would load every command looking for an alias before it gives up on an unknown name.
564+
async function rejectUnknownTopLevelCommand(): Promise<void> {
565+
const word = argv[0];
566+
if (!word || word.startsWith("-") || Object.hasOwn(subCommands, word)) return;
567+
throw await unknownCommandError({
568+
command: main as CommandDef,
569+
path: [],
570+
unknownSubcommand: word,
571+
});
572+
}
528573

529-
function isCittyUsageError(error: unknown): boolean {
574+
function isCittyError(error: unknown, code: string): boolean {
530575
return (
531576
error instanceof Error &&
532577
error.name === "CLIError" &&
533-
CITTY_USAGE_CODES.has(String((error as { code?: unknown }).code))
578+
(error as { code?: unknown }).code === code
534579
);
535580
}
536581

582+
// citty's own parse errors (missing argument, bad enum value, unknown or missing subcommand).
583+
const CITTY_USAGE_CODES = new Set(["EARG", "E_UNKNOWN_COMMAND", "E_NO_COMMAND"]);
584+
585+
function isCittyUsageError(error: unknown): boolean {
586+
return [...CITTY_USAGE_CODES].some((code) => isCittyError(error, code));
587+
}
588+
537589
function commandResultForError(error: unknown): CommandResult {
538590
if (error instanceof CliResultSignal) return error.result;
539591
if (error instanceof CliUsageError || error instanceof CliRuntimeError) return error.result;
@@ -547,16 +599,22 @@ function commandResultForError(error: unknown): CommandResult {
547599
async function executeCli(): Promise<void> {
548600
let result: CommandResult = { exitCode: 0, kind: "success" };
549601
try {
550-
if (isHelp) await showRequestedUsage();
551-
else await runCommand(main, { rawArgs: argv });
552-
} catch (error) {
602+
if (isHelp) await showRequestedUsage(console.log);
603+
else {
604+
await rejectUnknownTopLevelCommand();
605+
await runCommand(main, { rawArgs: argv });
606+
}
607+
} catch (caught) {
608+
const error = isCittyError(caught, "E_UNKNOWN_COMMAND")
609+
? await unknownCommandError(await resolveCommandUsage(main as CommandDef, argv))
610+
: caught;
553611
result = commandResultForError(error);
554612
if (!(error instanceof CliResultSignal)) {
555613
commandFailed = true;
556614
await reportCommandFailure(command, error);
557615
const typed = error instanceof CliUsageError || error instanceof CliRuntimeError;
558616
const usage = error instanceof CliUsageError && !error.result.presented;
559-
if (usage && !error.hint) await showRequestedUsage();
617+
if (usage && !error.hint) await showRequestedUsage(console.error);
560618
if (!typed || !error.result.presented) {
561619
console.error(error instanceof Error ? error.message : String(error));
562620
}

‎packages/cli/src/help.ts‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@
66
*/
77
import { renderUsage } from "citty";
88
import type { CommandDef } from "citty";
9-
import { c } from "./ui/colors.js";
9+
import { stripVTControlCharacters } from "node:util";
10+
import { c, isColorSupported } from "./ui/colors.js";
1011
import { VERSION } from "./version.js";
1112

1213
// ── Root-level command groups ──────────────────────────────────────────────
@@ -190,7 +191,9 @@ function renderRootHelp(): string {
190191
}
191192
lines.push("");
192193

193-
lines.push(`Run ${c.cyan("hyperframes <command> --help")} for more information about a command.`);
194+
lines.push(
195+
`Run ${c.cyan("hyperframes help <command>")} (or ${c.cyan("<command> --help")}) for more information about a command.`,
196+
);
194197

195198
return lines.join("\n");
196199
}
@@ -209,23 +212,27 @@ function formatExamples(examples: Example[]): string {
209212

210213
// ── Main showUsage override ────────────────────────────────────────────────
211214
// fallow-ignore-next-line complexity
212-
export async function showUsage(cmd: CommandDef, parent?: CommandDef): Promise<void> {
215+
export async function showUsage(
216+
cmd: CommandDef,
217+
parent?: CommandDef,
218+
print: (text: string) => void = console.log,
219+
): Promise<void> {
213220
if (!parent) {
214-
console.log(renderRootHelp() + "\n");
221+
print(renderRootHelp() + "\n");
215222
return;
216223
}
217224

218225
const meta = await (typeof cmd.meta === "function" ? cmd.meta() : cmd.meta);
219226
const usage = await renderUsage(cmd, parent);
220-
console.log(usage + "\n");
227+
print((isColorSupported ? usage : stripVTControlCharacters(usage)) + "\n");
221228

222229
const name = meta?.name;
223230
if (name) {
224231
const parentMeta = await (typeof parent.meta === "function" ? parent.meta() : parent.meta);
225232
const parentName = parentMeta?.name;
226233
const examples = STATIC_EXAMPLES[name] ?? (await loadExamples(name, parentName));
227234
if (examples) {
228-
console.log(formatExamples(examples) + "\n");
235+
print(formatExamples(examples) + "\n");
229236
}
230237
}
231238
}

‎packages/cli/src/utils/commandUsageResolution.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,3 +36,29 @@ describe("resolveCommandUsage", () => {
3636
expect((await resolveCommandUsage(root, ["--help"])).command).toBe(root);
3737
});
3838
});
39+
40+
describe("resolveCommandUsage path and unknown words", () => {
41+
const render = defineCommand({ meta: { name: "render" } });
42+
const cloud = defineCommand({ meta: { name: "cloud" }, subCommands: { render } });
43+
const root = defineCommand({ meta: { name: "hyperframes" }, subCommands: { cloud } });
44+
45+
it("returns the words that named the command", async () => {
46+
expect((await resolveCommandUsage(root, ["cloud", "render", "x"])).path).toEqual([
47+
"cloud",
48+
"render",
49+
]);
50+
});
51+
52+
it("names the first word that is not a subcommand of a group", async () => {
53+
const resolved = await resolveCommandUsage(root, ["cloud", "rendr"]);
54+
expect(resolved.command).toBe(cloud);
55+
expect(resolved.path).toEqual(["cloud"]);
56+
expect(resolved.unknownSubcommand).toBe("rendr");
57+
});
58+
59+
it("does not treat a leaf command's positional as an unknown command", async () => {
60+
expect(
61+
(await resolveCommandUsage(root, ["cloud", "render", "./dir"])).unknownSubcommand,
62+
).toBeUndefined();
63+
});
64+
});

‎packages/cli/src/utils/commandUsageResolution.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ type LazyCommandDef = CommandDef | (() => CommandDef | Promise<CommandDef>);
55
export interface ResolvedCommandUsage {
66
command: CommandDef;
77
parent?: CommandDef;
8+
path: string[];
9+
unknownSubcommand?: string;
810
}
911

1012
async function loadSubcommand(command: CommandDef, name: string): Promise<CommandDef | undefined> {
@@ -21,12 +23,20 @@ export async function resolveCommandUsage(
2123
): Promise<ResolvedCommandUsage> {
2224
let command = root;
2325
let parent: CommandDef | undefined;
26+
const path: string[] = [];
2427
for (const argument of argv) {
2528
if (argument.startsWith("-")) break;
2629
const child = await loadSubcommand(command, argument);
27-
if (!child) break;
30+
if (!child)
31+
return {
32+
command,
33+
parent,
34+
path,
35+
unknownSubcommand: command.subCommands ? argument : undefined,
36+
};
2837
parent = command;
2938
command = child;
39+
path.push(argument);
3040
}
31-
return { command, parent };
41+
return { command, parent, path };
3242
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { describe, expect, it } from "vitest";
2+
import { closestMatch } from "./didYouMean.js";
3+
4+
describe("closestMatch", () => {
5+
const commands = ["render", "preview", "publish", "lint", "check", "help"];
6+
7+
it.each([
8+
["rendr", "render"],
9+
["previw", "preview"],
10+
["pub", "publish"],
11+
["chekc", "check"],
12+
])("suggests %s -> %s", (input, expected) => {
13+
expect(closestMatch(input, commands)).toBe(expected);
14+
});
15+
16+
it("suggests nothing when no candidate is close", () => {
17+
expect(closestMatch("zzzzzz", commands)).toBeUndefined();
18+
expect(closestMatch("x", commands)).toBeUndefined();
19+
});
20+
21+
it("completes an abbreviated flag", () => {
22+
expect(closestMatch("out", ["output", "fps", "quality"])).toBe("output");
23+
});
24+
});

0 commit comments

Comments
 (0)