Skip to content

refactor(cli): registry-driven command dispatch module - #1451

Merged
Wibias merged 2 commits into
devfrom
codex/cli-dispatch
Aug 11, 2026
Merged

refactor(cli): registry-driven command dispatch module#1451
Wibias merged 2 commits into
devfrom
codex/cli-dispatch

Conversation

@Wibias

@Wibias Wibias commented Aug 11, 2026

Copy link
Copy Markdown
Collaborator

Summary

Extract command dispatch out of the entry module into a registry-driven runner table.

  • Adds src/cli/dispatch.ts: dispatchCommand(head, deps) replaces the 61-case switch in src/cli/index.ts. Each command is a runner keyed by name; aliases (setup/eject/remove/model) resolve through the registry alias map.
  • src/cli/index.ts becomes a thin main: it runs the head, then calls dispatchCommand with its local lifecycle helpers (handleStart, handleStop, handleEnsure, handleStatus, handleReady, …) passed as CliDispatchDeps.
  • Source-level tests that read switch cases were migrated to read dispatch.ts (cli-registry, cli-ready, grok-lifecycle, stale-state-purge, update*, uninstall, windows-deploy-*, codex-retained-root-serialization).

Behavior is preserved: the restore, sync, sync-cache, claude, route, integration, health, ready, gui, codex-shim, and update runners match their original case bodies, including exit codes and the --help short-circuit.

Verification

  • bun run typecheck — exit 0.
  • CLI-focused suite — 211 pass; the only 4 failures are the known pre-existing cli-restore-back (2) and POST /api/sync Task Scheduler (2) cases, proven identical on clean upstream/dev and unrelated to this change.
  • ocx --versionopencodex 2.10.2, exit 0.
  • ocx help nosuch — exit 1, Unknown command: nosuch.
  • ocx ready --timeout 5 — exit 64.
  • ocx sync --helpUsage: ocx sync …, exit 0.

No GUI changes; no screenshot required.

Checklist

  • Scope stays focused and avoids unrelated cleanup.
  • Docs or release notes were updated when needed.
  • Security-sensitive changes were reviewed for secrets, auth, and unsafe defaults.

Review notes (stacked PR): this PR stacks on #1446 (codex/cli-registry). It does not target dev. The diff here is only the dispatch extraction (7feb16c42..0bb19e1e): 11 files, +585/−513. Merge only after #1444 and #1446 land; the base will be retargeted then.

Summary by CodeRabbit

  • New Features

    • Expanded CLI command handling across lifecycle, integrations, maintenance, GUI, service, authentication, diagnostics, and background operations.
    • Added command aliases and consistent help and unknown-command handling.
    • Improved command reliability with structured errors, exit codes, health checks, and startup validation.
  • Bug Fixes

    • Improved synchronization, restoration, update notifications, restart behavior, and GUI-related command flows.
  • Tests

    • Updated CLI coverage to validate command registration, alias resolution, dispatch ordering, and regression scenarios.

@coderabbitai

coderabbitai Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The CLI command switch moved from src/cli/index.ts to a dependency-injected, registry-driven src/cli/dispatch.ts. The change adds command runners, alias metadata, centralized error handling, and updated source-level wiring tests.

Changes

CLI dispatch centralization

Layer / File(s) Summary
Dispatch contract and entry routing
src/cli/dispatch.ts, src/cli/index.ts
Adds CliDispatchDeps, command and alias registries, centralized command resolution, help handling, unknown-command errors, and entry-point delegation.
Lifecycle and integration runners
src/cli/dispatch.ts
Adds runners for lifecycle, synchronization, recovery, GUI, service, tray, update, health, and readiness commands.
Command-specific runners
src/cli/dispatch.ts
Adds runners for provider, account, model, routing, access, export, integration, configuration, Claude, and OpenCode commands.
Dispatch wiring validation
tests/cli-ready.test.ts, tests/cli-registry.test.ts, tests/*
Updates source inspections and registry tests to validate dispatch handlers, aliases, command parity, and relocated wiring.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related PRs

  • lidge-jun/opencodex#1444: Refactors CLI routing out of src/cli/index.ts and provides the preceding CliHead/runCli structure.
  • lidge-jun/opencodex#1446: Introduces the CLI_COMMANDS registry used here for alias resolution and dispatch parity.
  • lidge-jun/opencodex#518: Modifies the sync and sync-cache CLI handlers that this change relocates to dispatch.ts.

Suggested reviewers: lidge-jun

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: replacing CLI command dispatch with a registry-driven dispatch module.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/cli-dispatch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions github-actions Bot added the chore Maintenance, CI, tests, refactors, or build changes (not a user-facing bug or feature). label Aug 11, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Deterministic PR hygiene checks passed.

@Ingwannu Ingwannu left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

I am deferring the content review because the stack no longer has reviewable ancestry after the root rewrite.

Current state:

  • #1446 now has head 35628105 on current dev@87e3ff9f.
  • #1451's head cb952c07 is 6 commits ahead and 8 behind that new base; GitHub reports mergeable: false, mergeable_state: dirty, and rebaseable: false.
  • #1455, #1456, and #1457 are stacked on the old #1451 lineage. Their previously green jobs therefore do not validate the stack that would actually land after the #1446 rewrite.
  • The new exact-head #1446 run is currently red in Linux shard 3 and macOS (with shard 4 still running at the time of review). #1457's old run also ended red because the aggregate test job was cancelled after shard 3 hit the 15-minute bound. Those failures should not be “fixed” on stale child heads.

Please rebuild the stack sequentially: rebase #1451 onto the current #1446 head, then #1455 onto the new #1451 head, #1456 onto the new #1455 head, and #1457 onto the new #1456 head. Resolve the root exact-head CI failure first, then rerun CI on every resulting child head. Once ancestry is linear and the exact commits are green, request review again; reviewing the current diverged diff would mostly review code that the rebase will discard or rewrite.

Base automatically changed from codex/cli-registry to dev August 11, 2026 08:43
Wibias added 2 commits August 11, 2026 10:47
Phase 3 of the CLI deepening: extract the command switch out of
src/cli/index.ts into src/cli/dispatch.ts as a registry-driven runner
table. index.ts becomes a thin main that passes its local lifecycle
helpers through CliDispatchDeps; aliases resolve via the registry alias
map.

- dispatchCommand(head, deps) replaces the 61-case switch
- behavior preserved: restore/sync/sync-cache/claude/route/integration/
  health/ready/gui/codex-shim/update runners match the original bodies
- source-level tests migrated to read dispatch.ts
- typecheck green; CLI suite 211 pass (4 known pre-existing failures)
Phase 3 moved the command switch into src/cli/dispatch.ts as runner
keys, but tests/codex-app-server-processes.test.ts still sliced the old
case labels out of src/cli/index.ts. Update it to read the sync,
sync-cache, v2, and gui runner bodies from dispatch.ts (using deps.args),
which restores the #476 sync/sync-cache app-server-wiring assertions.
@Wibias
Wibias force-pushed the codex/cli-dispatch branch from cb952c0 to 46b18f0 Compare August 11, 2026 08:48

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/cli/dispatch.ts`:
- Line 497: Capture the canonical runner key in src/cli/dispatch.ts lines
497-497, update CommandRunner to accept a name argument, and pass that resolved
name to the runner. In src/cli/dispatch.ts lines 391-406, make the logs, usage,
storage, and memory runners use the bound name or new parameter when calling
handleObserveCommand. In src/cli/index.ts lines 915-944, remove the redundant
command property from the deps literal and derive the command from head.command
in dispatch.ts.
- Around line 491-504: Update the runner lookup in dispatchCommand to prevent
prototype-inherited keys from resolving as commands: use a null-prototype
commandRunners table or explicitly require own-property membership before
selecting a runner. Preserve declared command and alias resolution, while
ensuring inputs such as constructor, toString, and __defineGetter__ reach the
existing unknown-command error path.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 473cf018-8063-47e2-b881-b9db0963aae7

📥 Commits

Reviewing files that changed from the base of the PR and between 38c9b35 and 46b18f0.

📒 Files selected for processing (12)
  • src/cli/dispatch.ts
  • src/cli/index.ts
  • tests/cli-ready.test.ts
  • tests/cli-registry.test.ts
  • tests/codex-app-server-processes.test.ts
  • tests/codex-retained-root-serialization.test.ts
  • tests/grok-lifecycle.test.ts
  • tests/stale-state-purge.test.ts
  • tests/uninstall.test.ts
  • tests/update-notify.test.ts
  • tests/update-stop-first.test.ts
  • tests/windows-deploy-close-regressions.test.ts

Comment thread src/cli/dispatch.ts
Comment on lines +491 to +504
export async function dispatchCommand(head: CliHead, deps: CliDispatchDeps): Promise<void> {
const command = head.command;
if (command === undefined || command === "help" || command === "--help" || command === "-h") {
printUsage();
return;
}
const runner = commandRunners[command] ?? commandRunners[aliasTargets.get(command) ?? ""];
if (!runner) {
console.error(`Unknown command: ${command}`);
printUsage();
process.exit(1);
}
await runner(deps);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Guard the runner lookup against Object.prototype keys; unknown commands can silently succeed.

commandRunners is a plain object literal, so commandRunners[command] walks the prototype chain. Line 497 indexes it directly with unvalidated user input.

Failure mode, reproducible today:

ocx constructor

commandRunners["constructor"] resolves to Object, which is truthy. The !runner guard at Line 498 does not fire. Line 503 then evaluates await Object(deps), which returns deps without throwing. The CLI exits 0 and prints nothing, instead of printing Unknown command: constructor and exiting 1. The same holds for toString, valueOf, hasOwnProperty, and __defineGetter__.

DISPATCH_COMMANDS at Line 488 uses Object.keys, so a command-parity test over that set will not detect this.

Use a null-prototype table so only declared runners resolve.

🐛 Proposed fix using a null-prototype runner table
-const commandRunners: Record<string, CommandRunner> = {
+const commandRunners: Record<string, CommandRunner> = Object.assign(Object.create(null) as Record<string, CommandRunner>, {
   init: async () => {

Close the literal accordingly:

   "-h": async () => {
     printUsage();
   },
-};
+});

An Object.hasOwn(commandRunners, command) check at Line 497 is an equivalent fix if you prefer to keep the literal shape.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/cli/dispatch.ts` around lines 491 - 504, Update the runner lookup in
dispatchCommand to prevent prototype-inherited keys from resolving as commands:
use a null-prototype commandRunners table or explicitly require own-property
membership before selecting a runner. Preserve declared command and alias
resolution, while ensuring inputs such as constructor, toString, and
__defineGetter__ reach the existing unknown-command error path.

Comment thread src/cli/dispatch.ts
printUsage();
return;
}
const runner = commandRunners[command] ?? commandRunners[aliasTargets.get(command) ?? ""];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Dispatch treats the user-typed token and the matched runner key as the same value. Line 497 resolves an alias to a canonical runner but discards which key matched, so downstream code that needs the canonical name reads deps.command instead and receives the alias the user typed. Every site below is a consequence of that one modeling gap.

  • src/cli/dispatch.ts#L497-L497: capture the resolved key, then pass it to the runner. Change CommandRunner to (deps: CliDispatchDeps, name: string) => Promise<void>, compute const name = commandRunners[command] ? command : (aliasTargets.get(command) ?? ""), and call await runner(deps, name). This makes the canonical name authoritative at the single point where it is known.
  • src/cli/dispatch.ts#L391-L406: stop reading deps.command! in the logs, usage, storage, and memory runners. Use the bound name from the factory proposed on that comment, or the new name parameter, so handleObserveCommand always receives the canonical subcommand.
  • src/cli/index.ts#L915-L944: drop the redundant command property from the deps literal and derive it from head.command inside dispatch.ts. Passing args, command, and head gives three representations of one parse result, which is what lets the alias and the canonical name drift apart unnoticed.
📍 Affects 2 files
  • src/cli/dispatch.ts#L497-L497 (this comment)
  • src/cli/dispatch.ts#L391-L406
  • src/cli/index.ts#L915-L944
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/cli/dispatch.ts` at line 497, Capture the canonical runner key in
src/cli/dispatch.ts lines 497-497, update CommandRunner to accept a name
argument, and pass that resolved name to the runner. In src/cli/dispatch.ts
lines 391-406, make the logs, usage, storage, and memory runners use the bound
name or new parameter when calling handleObserveCommand. In src/cli/index.ts
lines 915-944, remove the redundant command property from the deps literal and
derive the command from head.command in dispatch.ts.

@Wibias
Wibias merged commit 5d8c4fe into dev Aug 11, 2026
33 checks passed
@Wibias
Wibias deleted the codex/cli-dispatch branch August 11, 2026 09:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

chore Maintenance, CI, tests, refactors, or build changes (not a user-facing bug or feature).

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants