Skip to content

fix(cli): route subcommand --help to the subcommand - #313

Merged
stackbilt-admin merged 2 commits into
mainfrom
auto/bugfix/issue-240
Sep 20, 2026
Merged

stackbilt-admin merged 2 commits into
mainfrom
auto/bugfix/issue-240

Conversation

@stackbilt-admin

@stackbilt-admin stackbilt-admin commented Sep 20, 2026 •

Copy link
Copy Markdown
Member

Root cause

run() in packages/cli/src/index.ts checked for help against the full raw args array, before any routing:

if (args.includes('--help') || args.includes('-h')) {
  console.log(HELP);

Because .includes() scans the whole array, charter adf migrate --help matched on the trailing --help and printed the global HELP constant. Control never reached adfCommand, which has handled --help since packages/cli/src/commands/adf.ts:234 by printing the full ADF subcommand reference. The per-subcommand docs were only reachable by running charter adf bare.

The fix

The obvious narrowing — only fire when --help is args[0] — is not safe here. Only four top-level commands handle --help themselves:

handler location note
adf commands/adf.ts:234 covers adf <subcommand> --help too — see below
hook commands/hook.ts:141
score commands/score.ts:293
telemetry commands/telemetry.ts:30

commands/adf-metrics.ts:31 also has a printHelp(), but it is not on this path: adf.ts:234 checks --help before the subcommand dispatch at adf.ts:239, so charter adf metrics --help prints the ADF reference and the metrics-specific help stays unreachable that way. (It is reachable via charter adf metrics with no args.) Making per-subcommand help reachable would mean restructuring the dispatch inside adf.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 --help and context-refresh --help actually 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:

export const COMMANDS_WITH_OWN_HELP = new Set(['adf', 'hook', 'score', 'telemetry']);
...
const wantsHelp = args.includes('--help') || args.includes('-h');
if (wantsHelp && !COMMANDS_WITH_OWN_HELP.has(args[0])) {

Both failure directions are now handled:

  • Safe direction — a command that grows its own help but isn't added to the set simply keeps today's root-help behavior. It can never be executed by a stray --help.
  • Unsafe direction — a command added to the set whose handler does not short-circuit on --help would 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 adding init to the set made charter init --help scaffold a real .charter/config.json and fail the test, which is exactly the trap this guard is for.

Behavior change, per top-level command

Command <cmd> --help before after
adf, adf <sub> root help ADF subcommand reference
hook, score, telemetry root help that command's own help
bootstrap, context, context-refresh, setup, init, validate, audit, drift, stamp-policies, classify, why, doctor, serve, blast, surface root help root help (unchanged)
bare charter --help / -h root help root help (unchanged)
unknown command + --help root help root help (unchanged)

This satisfies the issue's stated acceptable resolution: "charter adf --help could output the full subcommand reference." It does not deliver the issue's primary expectation of per-subcommand docs, for the adf.ts dispatch reason above.

--version / -v: deliberately left alone

--version on the next lines has the identical .includes() shape, but no subcommand anywhere handles --version (grep -rn -- "--version" packages/cli/src/commands/ returns only an unrelated gh --version invocation). Gating it on the same set would send charter adf --version into adfCommand, where --version is an unknown subcommand — turning working behavior into an error. Consistency of shape isn't worth that regression, so --version keeps its global catch-all. A test pins charter adf --version to the current output so this stays intentional.

Verification

  • pnpm test — 901/901 passed, 63 files (baseline on main is 892; +9 new).
  • pnpm run typecheck — clean.
  • Pre-commit gate ran normally on both commits (no --no-verify); cli_entry_loc 259/297.

New regression test at packages/cli/src/__tests__/help-routing.test.ts follows the telemetry.test.ts pattern (mkdtemp + chdir so run()'s telemetry writes land in a throwaway dir). It asserts:

  1. adf migrate --help does not print the root help signature and does print the ADF reference — this is the assertion that would have caught the bug.
  2. adf --help likewise.
  3. Every member of 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.
  4. Bare --help still prints root help.
  5. bootstrap --help still prints root help and writes nothing — the guard against regressing a --help into a real run.
  6. adf --version still reports the version.

CHANGELOG.md records the fix under ## [Unreleased] → ### Fixed with the issue ref.

Note for the reviewer

packages/cli/dist/ is stale (built Sept 8) and npx tsx packages/cli/src/index.ts currently 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 against run() directly, not the built binary.

Closes #240

🤖 Generated with Claude Code

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 stackbilt-admin left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  • args is process.argv.slice(2) (bin.ts:9), never re-sliced before the guard.
  • At index.ts:145, && short-circuits: for empty args wantsHelp is false ([].includes('--help') is false), so .has(args[0]) is never evaluated. Even if it were, new Set().has(undefined) returns false and does not throw.
  • Bare charter never reaches the help branch at all — it hits args.length === 0 at index.ts:174 and routes to quickstartCommand, byte-identical to pre-fix behavior. It cannot fall through to the switch default.
  • tsc -b packages/cli is clean; noUncheckedIndexedAccess is not set in tsconfig.base.json, so args[0] types as string and 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

  1. [NIT] No CHANGELOG entry. CHANGELOG.md has a maintained ## [Unreleased] → ### Fixed section where comparable user-facing CLI fixes are logged with issue refs (e.g. the two #295 entries). This PR changes observable CLI output for four commands and has no entry. Worth adding one for #240.

  2. [NIT] The PR body slightly overstates adf metrics. The handler table lists adf (incl. adf metrics) | commands/adf.ts:234, commands/adf-metrics.ts:31, implying the metrics help is reachable. It is not: adf.ts:234 checks args.includes('--help') before the subcommand dispatch at adf.ts:239, so charter adf metrics --help prints the ADF reference and adf-metrics.ts:31's printHelp() stays unreachable on the --help path (it's still reachable via bare charter adf metrics). This is not a regression — pre-fix that invocation printed the root help — and the issue's stated acceptable resolution ("charter adf --help could output the full subcommand reference") is satisfied. Fix the table row, and optionally file a follow-up to move adf.ts:234's help check after dispatch for subcommands that document themselves.

  3. [NIT] The set and its test list can drift apart. COMMANDS_WITH_OWN_HELP (index.ts:100) is not exported, and help-routing.test.ts:53 hardcodes it.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, so charter <cmd> --help runs it for real — has no automated guard. Exporting the set and deriving the it.each cases from it would make that mistake fail a test instead of shipping. This is the one structural improvement I'd actually push for.

  4. [NIT] charter adf --help --format markdown changed from exit 0 to exit 2. Pre-fix it printed the root help; now it skips the help branch and hits the markdown guard at index.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.

  5. [NIT] expect(output).toContain(command) (help-routing.test.ts:64) is a weak assertion — 'hook' and 'score' appear in plenty of output. Paired with not.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]>
@stackbilt-admin
stackbilt-admin merged commit 5607fb8 into main Sep 20, 2026
5 checks passed
@stackbilt-admin
stackbilt-admin deleted the auto/bugfix/issue-240 branch September 20, 2026 12:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

adf subcommand --help falls back to root help instead of subcommand docs

1 participant