Repository navigation
fix(cli): route subcommand --help to the subcommand - #313
Conversation
The top-level dispatcher matched --help/-h anywhere in the raw args before routing, so `charter adf migrate --help` printed the global HELP constant and never reached adfCommand. Narrow the check to commands that have no --help handler of their own, so the four that do (adf, hook, score, telemetry) now render their own docs. Commands without a handler still fall back to the root help rather than executing. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
stackbilt-admin
left a comment
There was a problem hiding this comment.
APPROVED
Adversarial review of the four load-bearing claims, each checked against source rather than the description. All four hold. Nothing blocking; five nits below.
Claims verified
1. The set is exactly right — no serious bug. grep -rn -- "'--help'" packages/cli/src/commands/ returns five hits and only five: adf.ts:234, hook.ts:141, score.ts:293, telemetry.ts:30, and adf-metrics.ts:31 (a nested adf subcommand, not a top-level switch case). Cross-referenced against all 19 case labels in the index.ts switch (lines 186–242): no top-level command handles --help and is missing from the set, and every member of the set checks --help as the first statement of its handler and returns EXIT_CODE.SUCCESS (adf.ts:234-237, hook.ts:141-144, score.ts:293-296, telemetry.ts:30-33). So the dangerous direction — in-set but no handler, causing charter <cmd> --help to execute for real — does not exist here.
2. args[0] is safe; bare charter is not broken. This was flagged as the most likely defect. It isn't one, concretely:
argsisprocess.argv.slice(2)(bin.ts:9), never re-sliced before the guard.- At
index.ts:145,&&short-circuits: for empty argswantsHelpisfalse([].includes('--help')is false), so.has(args[0])is never evaluated. Even if it were,new Set().has(undefined)returnsfalseand does not throw. - Bare
charternever reaches the help branch at all — it hitsargs.length === 0atindex.ts:174and routes toquickstartCommand, byte-identical to pre-fix behavior. It cannot fall through to the switch default. tsc -b packages/cliis clean;noUncheckedIndexedAccessis not set intsconfig.base.json, soargs[0]types asstringand no cast or non-null assertion was needed or smuggled in.
3. --version correctly untouched. The version check at index.ts:151 runs after the help branch and is unconditional, so charter adf --version never enters adfCommand (where it would hit the default: throw at adf.ts:272). Pinned by a test.
4. Flag-value spoofing is noise, and not a regression. Ran charter adf create --name --help against the built CLI: exit 0, prints the ADF reference. The --help is consumed by adf.ts:234's own .includes() check, which predates this PR. Pre-fix the same invocation printed the root help. Both are "help instead of the command"; neither executes anything. No command is reachable for real via a --help-valued option.
Test correctness — empirically confirmed
I verified the regression test actually fails without the fix rather than reasoning about it. Temporarily collapsed index.ts:145 to if (wantsHelp) {, ran the file, then restored via git checkout --: 5 of 8 tests fail on the reverted code (each on expect(output).not.toContain(ROOT_HELP_SIGNATURE)), 8/8 pass with the fix. The working tree is back to clean — git status --porcelain shows only the two pre-existing untracked .ai/context.* files, which are not part of this PR.
cwd cleanup is correct and cannot poison other files. afterEach (help-routing.test.ts:11-19) chdirs back to originalCwd before the rmSync loop — right order; reversing it would rm the cwd out from under the process. Vitest runs afterEach even when a test throws, so a failure cannot leave the process parked in the temp dir. Independently: recordTelemetryEvent is fully synchronous (telemetry.ts:150 mkdirSync, telemetry.ts:167 appendFileSync), so there is no fire-and-forget write that could land against the relative .charter path after the chdir back. And the current config spawns one isolated worker per file (63 workers, no pool/isolate override in vitest.config.mts), so cross-file leakage isn't possible today regardless.
Verification claims in the PR body reproduce exactly. Full suite: 63 files, 900/900 passed. packages/cli alone: 290/290. tsc -b packages/cli: clean. No scope creep — the diff is two files, and the index.ts change is the 6-line comment, the Set, and the one-line guard. Nothing unrelated rode along.
Non-blocking
-
[NIT] No CHANGELOG entry.
CHANGELOG.mdhas a maintained## [Unreleased]→### Fixedsection where comparable user-facing CLI fixes are logged with issue refs (e.g. the two#295entries). This PR changes observable CLI output for four commands and has no entry. Worth adding one for#240. -
[NIT] The PR body slightly overstates
adf metrics. The handler table listsadf (incl. adf metrics) | commands/adf.ts:234, commands/adf-metrics.ts:31, implying the metrics help is reachable. It is not:adf.ts:234checksargs.includes('--help')before the subcommand dispatch atadf.ts:239, socharter adf metrics --helpprints the ADF reference andadf-metrics.ts:31'sprintHelp()stays unreachable on the--helppath (it's still reachable via barecharter adf metrics). This is not a regression — pre-fix that invocation printed the root help — and the issue's stated acceptable resolution ("charter adf --helpcould output the full subcommand reference") is satisfied. Fix the table row, and optionally file a follow-up to moveadf.ts:234's help check after dispatch for subcommands that document themselves. -
[NIT] The set and its test list can drift apart.
COMMANDS_WITH_OWN_HELP(index.ts:100) is not exported, andhelp-routing.test.ts:53hardcodesit.each(['hook', 'score', 'telemetry']). The in-code comment correctly reasons about the safe failure direction, but the unsafe one — someone adds a command to the set whose handler doesn't check--help, socharter <cmd> --helpruns it for real — has no automated guard. Exporting the set and deriving theit.eachcases from it would make that mistake fail a test instead of shipping. This is the one structural improvement I'd actually push for. -
[NIT]
charter adf --help --format markdownchanged from exit 0 to exit 2. Pre-fix it printed the root help; now it skips the help branch and hits the markdown guard atindex.ts:161, throwing--format markdown is only supported by 'charter surface'. Confirmed against the built CLI. Obscure combination, arguably more correct than before — noting it only for completeness. -
[NIT]
expect(output).toContain(command)(help-routing.test.ts:64) is a weak assertion —'hook'and'score'appear in plenty of output. Paired withnot.toContain(ROOT_HELP_SIGNATURE)it's adequate; a signature line per command would be tighter.
Export COMMANDS_WITH_OWN_HELP and derive the help-routing cases from it, so a command added to the set is automatically held to the contract that earns it a place there. Each member must print help and leave no work behind; verified by temporarily adding `init`, which scaffolded a real config and failed the test. Also log the fix in the CHANGELOG's Unreleased section. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Root cause
run()inpackages/cli/src/index.tschecked for help against the full raw args array, before any routing:Because
.includes()scans the whole array,charter adf migrate --helpmatched on the trailing--helpand printed the globalHELPconstant. Control never reachedadfCommand, which has handled--helpsincepackages/cli/src/commands/adf.ts:234by printing the full ADF subcommand reference. The per-subcommand docs were only reachable by runningcharter adfbare.The fix
The obvious narrowing — only fire when
--helpisargs[0]— is not safe here. Only four top-level commands handle--helpthemselves:adfcommands/adf.ts:234adf <subcommand> --helptoo — see belowhookcommands/hook.ts:141scorecommands/score.ts:293telemetrycommands/telemetry.ts:30commands/adf-metrics.ts:31also has aprintHelp(), but it is not on this path:adf.ts:234checks--helpbefore the subcommand dispatch atadf.ts:239, socharter adf metrics --helpprints the ADF reference and the metrics-specific help stays unreachable that way. (It is reachable viacharter adf metricswith no args.) Making per-subcommand help reachable would mean restructuring the dispatch insideadf.ts— out of scope here, and not required by the issue.Every other command has no help handler, so unconditionally falling through would make
charter bootstrap --help,setup --help,init --help,stamp-policies --helpandcontext-refresh --helpactually run — all of which write to the repo. That is a worse bug than the one being fixed.So the top-level check now steps aside only for the commands that can document themselves:
Both failure directions are now handled:
--help.--helpwould be executed for real. The set is exported and the tests derive their cases from it, so any member must print help and leave no work behind. Verified by mutation: temporarily addinginitto the set madecharter init --helpscaffold a real.charter/config.jsonand fail the test, which is exactly the trap this guard is for.Behavior change, per top-level command
<cmd> --helpbeforeadf,adf <sub>hook,score,telemetrybootstrap,context,context-refresh,setup,init,validate,audit,drift,stamp-policies,classify,why,doctor,serve,blast,surfacecharter --help/-h--helpThis satisfies the issue's stated acceptable resolution: "
charter adf --helpcould output the full subcommand reference." It does not deliver the issue's primary expectation of per-subcommand docs, for theadf.tsdispatch reason above.--version/-v: deliberately left alone--versionon the next lines has the identical.includes()shape, but no subcommand anywhere handles--version(grep -rn -- "--version" packages/cli/src/commands/returns only an unrelatedgh --versioninvocation). Gating it on the same set would sendcharter adf --versionintoadfCommand, where--versionis an unknown subcommand — turning working behavior into an error. Consistency of shape isn't worth that regression, so--versionkeeps its global catch-all. A test pinscharter adf --versionto the current output so this stays intentional.Verification
pnpm test— 901/901 passed, 63 files (baseline onmainis 892; +9 new).pnpm run typecheck— clean.--no-verify);cli_entry_loc259/297.New regression test at
packages/cli/src/__tests__/help-routing.test.tsfollows thetelemetry.test.tspattern (mkdtemp+chdirsorun()'s telemetry writes land in a throwaway dir). It asserts:adf migrate --helpdoes not print the root help signature and does print the ADF reference — this is the assertion that would have caught the bug.adf --helplikewise.COMMANDS_WITH_OWN_HELP, derived from the export, prints help-shaped output and creates no files beyond.charter/telemetry— the guard against the unsafe direction.--helpstill prints root help.bootstrap --helpstill prints root help and writes nothing — the guard against regressing a--helpinto a real run.adf --versionstill reports the version.CHANGELOG.mdrecords the fix under## [Unreleased]→### Fixedwith the issue ref.Note for the reviewer
packages/cli/dist/is stale (built Sept 8) andnpx tsx packages/cli/src/index.tscurrently crashes with a circular-import TDZ error (Cannot access 'POINTER_CLAUDE_MD' before initialization). Both are pre-existing and out of scope here; verification was done through vitest againstrun()directly, not the built binary.Closes #240
🤖 Generated with Claude Code