> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch33-cli-tools/33.4-source-deep-dive-two-command-trees.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 33.4 Source Deep Dive: Two Command Trees and an Obsession With Startup Speed

> **Generated by**: Claude Opus 5 (claude-opus-5\[1m]) **Token usage**: Input \~232,000 tokens, Output \~14,000 tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`); line numbers refer to this commit

***

§33.1–33.3 covered CLI architecture, core commands, and chat commands. This section answers two source-level questions:

1. **Are CLI commands and chat commands the same system?**
2. **Why are there three parallel dispatch mechanisms on the startup path?**

## 33.4.1 The Answer: Two Independent Trees

**Not one registry — two independent command trees. But chat commands are themselves "one registry, N frontends."**

| Command tree              | Defined in                                                                                                                       | Audience        | Scope                                                |
| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | --------------- | ---------------------------------------------------- |
| **CLI command tree**      | `src/cli/program/command-registry.ts` (core) + `register.subclis.ts` (\~30 sub-CLIs)                                             | Operators       | Installation, configuration, diagnostics, operations |
| **Chat command registry** | `src/auto-reply/commands-registry.data.ts` (777 lines of declarative data) + `commands-registry.ts` (530 lines of parsing logic) | Chat interfaces | `/help`, `/status`, `/model`, `/think`               |

Why not unify them? Their **parameter models** (Commander options vs. positional arguments plus selection menus) and **permission models** differ too much; forcing one registry would produce a more complex abstraction, not a simpler one.

The cost is that semantically overlapping commands like `/config` and `openclaw config` each need their own help text and behavioral consistency.

**The two trees meet not at the registry but lower down**: chat's `/config` and CLI's `openclaw config set` both land on the same `src/config/` read-write layer.

## 33.4.2 The Chat Command Registry: One Source, Five Frontends

This is the genuine "single source of truth" practice (§44.3's theme five).

One `ChatCommandDefinition[]` is consumed by **at least five frontends**:

```
              commands-registry.data.ts (the single source)
                        │
    ┌──────────┬────────┼────────┬──────────┐
    ↓          ↓        ↓        ↓          ↓
 Discord    Telegram  Slack    plain-text   TUI
 native     command   slash    /command     completion
 slash cmds menu      manifest parsing
```

Corresponding files: `src/discord/monitor/native-command.ts`, `src/telegram/bot-native-commands.ts`, `src/slack/monitor/slash.ts`, `src/auto-reply/command-detection.ts`, `src/tui/commands.ts`.

### Differences compressed into three dimensions

```ts
// src/auto-reply/commands-registry.data.ts:26
function defineChatCommand(command: DefineChatCommandInput): ChatCommandDefinition {
  const aliases = (command.textAliases ?? (command.textAlias ? [command.textAlias] : []))
    .map((alias) => alias.trim())
    .filter(Boolean);
  const scope =
    command.scope ?? (command.nativeName ? (aliases.length ? "both" : "native") : "text");
  const acceptsArgs = command.acceptsArgs ?? Boolean(command.args?.length);
  ...
}
```

Three dimensions: `nativeName` (the native command name), `textAliases` (text aliases), and `scope` (`native` / `text` / `both`).

### Platform reserved-word collisions go in an override table

```ts
// src/auto-reply/commands-registry.ts:122
const NATIVE_NAME_OVERRIDES: Record<string, Record<string, string>> = {
  discord: { tts: "voice" },
  slack: {
    // Slack reserves /status — registering it returns "invalid name"
    // and invalidates the entire slash_commands manifest array.
    status: "agentstatus",
  },
};
```

The consequence noted in that Slack comment is severe: **registering a reserved name doesn't just fail for that one command — it invalidates the entire slash\_commands manifest array**, so nothing registers.

If quirks like this were scattered across channel implementations, the second person to hit it wouldn't know the first had already solved it. Centralized in an override table, it becomes searchable knowledge.

### Build-time self-check

`assertCommandRegistry` (`commands-registry.data.ts:81`) checks at build time:

```
no duplicate keys
no duplicate native names
text-only commands may not carry a nativeName
aliases must start with /
```

**Fail-fast at startup, keeping "registry rot" out of the first run after a merge.**

> This is §45.1's fourth pattern: **a declaration table plus a build-time self-check driving multiple frontends.** Compare §19.4.7's dock/plugin double-write kept in sync only by comments — within the same repository, this theme is executed inconsistently.

### Two dynamic sources

Merged into the registry at runtime:

| Source                    | Contents                                                                                               |
| ------------------------- | ------------------------------------------------------------------------------------------------------ |
| **Channel dock commands** | `/dock-telegram` and similar reply-channel switches, generated automatically from channel capabilities |
| **Skill commands**        | `listChatCommands({ skillCommands })` maps installed skills to `/skill-name`                           |

The cache is **keyed on the plugin registry instance**, so it invalidates automatically after a plugin hot reload (`:753`) — object identity as a cache key again (compare §14.5.3's WeakMap).

### Input normalization on the text frontend

Chat users type all sorts of things:

```
/think: high        colon syntax
/status@mybot       Telegram group with bot name
/THINK              mixed case
/t                  alias
```

`normalizeCommandBody` (`commands-registry.ts:378`) handles them all, **then canonicalizes aliases to the "primary alias" rather than `/${key}`** — because some keys are internal identifiers (like `dock:telegram`) whose public canonical form is `/dock-telegram`.

Command detection pre-compiles one large regex plus an exact-match set (`getCommandDetection`, `:434`), **cached by registry instance** so it isn't rebuilt per message.

### The execution side is also a single entry point

`handleCommands` (`src/auto-reply/reply/commands-core.ts:171`) maintains a **chain of 24 handlers**:

```ts
// src/auto-reply/reply/commands-core.ts:172
HANDLERS = [
  // Plugin commands are processed first, before built-in commands
  handlePluginCommand,
  handleBashCommand,
  handleActivationCommand,
  ...
  handleModelsCommand,
  handleStopCommand,
  handleCompactCommand,
  handleAbortTrigger,
];
...
for (const handler of HANDLERS) {
  const result = await handler(params, allowTextCommands);
  if (result) {
    return result;
  }
}
```

Whatever channel the message came from, native slash command or text `/command`, **it all goes through this one chain**.

**Plugin commands take precedence over built-ins** — allowing plugins to override built-in behavior.

Before the chain there's special handling: `/new` and `/reset` are high-risk, so **sender authorization is checked first** (unauthorized requests are silently ignored), then a `before_reset` hook fires so memory plugins can rescue data before the session history is destroyed (§30.3.2's session-memory hook).

### The TUI is a hybrid

The TUI has its own local commands (`/exit`, `/settings`, the `/model` picker) and additionally **merges the gateway-side chat command registry into its completion list** (`src/tui/commands.ts:118`), with **local commands winning on a name collision**.

So what a TUI user sees = local UI commands ∪ the chat command registry.

## 33.4.3 Three Parallel Dispatch Mechanisms: An Obsession With Startup Speed

`openclaw`'s startup path has three segments: `entry.ts` → `cli/run-main.ts` → `cli/program/*`.

### Layer one: `entry.ts`'s head start

Before importing anything heavy, `entry.ts` (195 lines) does three things:

**Main-module guard.** A bundler may import `entry.js` as a dependency; without a guard, top-level code runs `runCli` a second time and **starts a duplicate gateway that collides on locks and ports** (`entry.ts:31`'s comment names the incident directly).

**Self-respawn.** To suppress Node's ExperimentalWarning, the parent process **re-spawns itself** with `--disable-warning=ExperimentalWarning` (the flag isn't permitted in `NODE_OPTIONS` and can only be passed on the command line), using the `OPENCLAW_NODE_OPTIONS_READY` environment variable to prevent recursion (`:94`).

**Version fast path.**

```ts
// src/entry.ts:128
function tryHandleRootVersionFastPath(argv: string[]): boolean {
  if (!isRootVersionInvocation(argv)) {
    return false;
  }
  Promise.all([import("./version.js"), import("./infra/git-commit.js")])
    .then(([{ VERSION }, { resolveCommitHash }]) => {
      const commit = resolveCommitHash({ moduleUrl: import.meta.url });
      console.log(commit ? `OpenClaw ${VERSION} (${commit})` : `OpenClaw ${VERSION}`);
      process.exit(0);
    })
  ...
}
```

`openclaw --version` **doesn't build the Commander program at all** — it dynamically loads two small modules.

> **Why is that worth it?** `--version` / `--help` are called **at high frequency by scripts and installers**. A cold start that fully loads Commander plus 30 sub-CLIs is simply unacceptable there.
>
> Similar moves include `enableCompileCache()` (Node's compile cache) and argv sniffing to force a read-only auth store in `secrets audit` scenarios.

### Layer two: route-first hand-written routing

`tryRouteCli` (`src/cli/route.ts:29`) is more aggressive still:

For high-frequency read-only commands — `status`, `health`, `sessions`, `config get/unset`, `models list/status`, `agents list` — the CLI **doesn't build a Commander program at all**, matching argv by hand and routing straight to the implementation function (all 9 routes are listed at `src/cli/program/routes.ts:251`).

Only when route-first misses does it take the full `buildProgram()` path.

### Layer three: Commander lazy-registration placeholders

Even the full path is lazy:

```ts
// src/cli/program/command-registry.ts:254
function registerLazyCoreCommand(program, ctx, entry, command) {
  const placeholder = program.command(command.name).description(command.description);
  placeholder.allowUnknownOption(true);
  placeholder.allowExcessArguments(true);
  placeholder.action(async (...actionArgs) => {
    removeEntryCommands(program, entry);
    await entry.register({ program, ctx, argv: process.argv });
    await reparseProgramFromActionArgs(program, actionArgs);
  });
}
```

Each core command first registers a **placeholder**; the placeholder's action loads the real implementation module, then **removes the placeholder, re-registers, and re-parses**.

> A dignified hack around Commander's lack of native lazy loading: for `--help` the placeholder supplies the description text; for actual execution it's swapped for the real thing and re-parsed.

`runCli` also **predicts the main command from argv and registers only that one** (`run-main.ts:117`), and **only loads config and registers plugin CLI commands when the main command isn't a built-in** — plugin command registration requires reading config, and this skip (`shouldSkipPluginCommandRegistration`) stops `openclaw status` from paying for plugins it won't use.

### What the three layers cost

> **From §45.2's perspective**: this trades maintenance cost for cold-start milliseconds.
>
> Every new high-frequency command forces a decision about which layer it belongs in, and **route-first's hand-written argv parsing duplicates Commander's option definitions** (`routes.ts` hand-writes `hasFlag(argv, "--probe")`).
>
> For a CLI called constantly by installers and scripts it's a reasonable trade, but the 9-route list will keep growing, and drift between the two parsers won't be caught by any build-time check — **compare the chat command registry in the same repository, which does have one.**

## 33.4.4 config-guard: A Health Check Before Every Command

`ensureConfigReady` (`src/cli/program/config-guard.ts:41`) runs on **both** the route-first path and Commander's preAction: it reads a config snapshot, and if invalid, prints the issue list, suggests `openclaw doctor --fix`, and **exits immediately**.

**Unless the command is on an allowlist**:

```ts
// src/cli/program/config-guard.ts:10
const ALLOWED_INVALID_COMMANDS = new Set(["doctor", "logs", "health", "help", "status"]);
const ALLOWED_INVALID_GATEWAY_SUBCOMMANDS = new Set([
  "status", "probe", "health", "discover", "call",
  "install", "uninstall", "start", "stop", "restart",
]);
```

The allowlist's criteria are clear:

| Category                                | Why it must pass                                                                          |
| --------------------------------------- | ----------------------------------------------------------------------------------------- |
| Diagnostics (doctor/logs/health/status) | Otherwise the user is deadlocked: "config broken → the repair tool also refuses to start" |
| Shutdown (gateway stop/uninstall)       | You must be able to stop a runaway gateway                                                |

> **"Fail closed plus an allowlist" is the key seam between the config system and the CLI**: with a broken config most commands refuse to run, but you can always run doctor to fix it.
>
> Worth copying. Many systems implement startup validation as pure fail-closed, with the result that once config is damaged even the repair tool won't start — leaving the user to hand-edit JSON.

The guard also runs a **silent doctor migration probe** (`loadAndMaybeMigrateDoctorConfig`, non-interactive, detect-only, no writes), so "there's legacy config awaiting migration" gets surfaced on **any** command.

## 33.4.5 `--profile` / `--dev`: Multi-Instance Through Environment Variables

`src/cli/profile.ts:100` translates `--profile foo` into three environment variable **defaults**:

```
OPENCLAW_PROFILE=foo
OPENCLAW_STATE_DIR=~/.openclaw-foo
OPENCLAW_CONFIG_PATH=<stateDir>/openclaw.json
```

`--dev` additionally defaults the gateway port to 19001.

The comment reads:

> Convenience only: fill defaults, never override explicit env values.

**A profile is only syntactic sugar over environment variables; explicit env always wins.**

That's what lets "run production and development OpenClaw side by side on one machine" work **with no support needed at the config-file layer** (paired with the service-name suffixing in Appendix F.1).

## 33.4.6 Dependency Injection: Narrow Interfaces and Default Parameters

The repo's `CLAUDE.md` lists `createDefaultDeps` as an official project pattern. The implementation is **deliberately narrow**:

```ts
// src/cli/deps.ts:10
export type CliDeps = {
  sendMessageWhatsApp: typeof sendMessageWhatsApp;
  sendMessageTelegram: typeof sendMessageTelegram;
  sendMessageDiscord: typeof sendMessageDiscord;
  sendMessageSlack: typeof sendMessageSlack;
  sendMessageSignal: typeof sendMessageSignal;
  sendMessageIMessage: typeof sendMessageIMessage;
};
```

**`CliDeps` isn't a global DI container — it's six channel send functions.**

Each function returned by `createDefaultDeps()` does its own `await import("./deps-send-*.runtime.js")` internally — `*.runtime.ts` being the **dynamic-import boundary file** the repo's coding standards explicitly require (so one module is never both statically and dynamically imported, which would break the bundler's code splitting).

Consumption is by **default parameter injection**:

```ts
// src/commands/agent.ts:681
export async function agentCommand(opts, runtime, deps: CliDeps = createDefaultDeps()) { ... }
```

A test passes an object with six stubs and can assert "this command sent a message to which channel with what content" — **no module-system mocking, and no loading WhatsApp's or Telegram's heavy clients.**

Similarly, `RuntimeEnv` (`log` / `error` / `exit`) is the second injection point running through every command function — **`runtime.exit(1)` is a capturable call in tests rather than process termination.**

> **The entire CLI's testability rests on those two injection points, not on any framework.**
>
> Every interface in the book is narrow: `CliDeps`'s six functions, `RuntimeEnv`'s three methods, `WizardPrompter`'s eight methods, `createConfigIO`'s five injectable dependencies — **every one small enough to hand-write a test double** with no DI framework's cognitive tax.
>
> A useful heuristic: **if your DI interface is big enough that you need a tool to generate mocks, it's too wide.**

## 33.4.7 The Whole Picture

```mermaid
flowchart TB
  subgraph Entry layer
    E[entry.ts<br/>respawn / compile cache] --> FP{--version / --help?}
    FP -- yes --> V[fast path, print and exit]
    FP -- no --> RM[run-main.ts runCli<br/>profile / dotenv]
    RM --> RT{route-first hit?<br/>status·health·config get…}
    RT -- yes --> RUN1[call the implementation directly]
    RT -- no --> BP[buildProgram<br/>Commander + lazy placeholders]
    BP --> GUARD[config-guard<br/>invalid config → suggest doctor and exit]
    GUARD --> CMDS[core commands + 30 sub-CLIs + plugin commands]
  end

  subgraph Chat command registry, src/auto-reply
    REG[commands-registry.data.ts<br/>one ChatCommandDefinition table]
    REG --> DC[Discord native commands]
    REG --> TG[Telegram menu]
    REG --> SL[Slack slash manifest]
    REG --> TX[text /command parsing]
    REG --> TUI[TUI completion]
    DC & TG & SL & TX --> HC[handleCommands chain<br/>24 handlers]
  end
  HC -.->|/config etc. read/write| IO[src/config read-write layer]
  CMDS --> IO
  RUN1 --> IO
```

***

## Section Summary

1. **Two independent command trees** (CLI Commander tree / chat command registry), unified only at the lower `src/config/` layer — their parameter and permission models differ too much to merge.
2. **The chat command registry is a textbook single source of truth**: one declaration drives five frontends, differences compressed into `nativeName` / `textAliases` / `scope`, platform reserved words handled in an override table (**Slack's `/status` invalidates the whole manifest**), with a **build-time self-check against rot**.
3. **The execution side is also a single entry point**: a 24-handler chain with plugin commands first; `/new` and `/reset` get a pre-chain authorization check plus a `before_reset` hook so memory plugins can rescue data.
4. **Three startup optimizations**: `--version` fast path (no Commander build) → route-first hand-written routing (9 high-frequency read-only commands) → Commander lazy placeholders (remove, re-register, re-parse); the cost is **three coexisting dispatch mechanisms with no build-time check**.
5. **config-guard's "fail closed plus allowlist"**: a broken config stops most commands, but diagnostics and shutdown always work — **avoiding the deadlock where even the repair tool won't start**.
6. **`--profile` is only syntactic sugar over environment variables**, with explicit env always winning; running multiple instances needs no config-file support.
7. **DI uses narrow interfaces and default parameters, not a container**: `CliDeps`'s six functions, `RuntimeEnv`'s three methods — **small enough to hand-write test doubles**; `runtime.exit(1)` is a capturable call rather than process termination. **If your DI interface needs tooling to generate mocks, it's too wide.**
