> 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/ch31-configuration-system/31.3-configuration-hot-reload.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 31.3 Configuration Hot Reload

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~200k tokens, Output \~8k tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

In production environments, having to restart the entire service after modifying configuration is costly—ongoing conversations are interrupted, WebSocket connections are dropped, and all state is wiped. OpenClaw's configuration hot reload system enables most configuration changes to take effect immediately without interrupting service through four stages: "file monitoring → diff comparison → rule routing → tiered execution". This section dissects the complete implementation of this mechanism.

***

## 31.3.1 Configuration Reload Mechanism (`src/gateway/config-reload.ts`)

### Overall Architecture

The core process of configuration hot reload can be summarized as a pipeline:

```
File change → chokidar monitoring → debounce(300ms) → read snapshot → diffConfigPaths
→ buildGatewayReloadPlan → mode determination(off/restart/hot/hybrid) → execute reload
```

Let's break down each stage step by step.

### File Monitoring: chokidar

OpenClaw uses the `chokidar` library to monitor configuration file changes. `startGatewayConfigReloader` creates a watcher at startup:

```typescript
// src/gateway/config-reload.ts (simplified)

const watcher = chokidar.watch(opts.watchPath, {
  ignoreInitial: true,                      // Don't trigger initial scan events
  awaitWriteFinish: {
    stabilityThreshold: 200,                 // Wait 200ms after file write stabilizes
    pollInterval: 50,                        // Poll interval 50ms
  },
  usePolling: Boolean(process.env.VITEST),   // Use polling mode in test environment
});

watcher.on("add", schedule);     // New file
watcher.on("change", schedule);  // File modification
watcher.on("unlink", schedule);  // File deletion
```

> **Sidebar**: `chokidar` is the most popular file monitoring library in the Node.js ecosystem. It encapsulates native file system events from various operating systems (Linux's `inotify`, macOS's `FSEvents`, Windows's `ReadDirectoryChangesW`), providing a unified cross-platform API. The `awaitWriteFinish` option solves a common problem: when editors save files, they may write in multiple passes (clear first, then write content). If we don't wait for the write to stabilize, we might read an incomplete file.

### Debouncing

After receiving a file change event, the reload is not executed immediately. Instead, it's delayed by 300ms through debouncing:

```typescript
// src/gateway/config-reload.ts (simplified)

const DEFAULT_RELOAD_SETTINGS = {
  mode: "hybrid",
  debounceMs: 300,
};

const schedule = () => {
  if (stopped) return;
  if (debounceTimer) clearTimeout(debounceTimer);
  debounceTimer = setTimeout(() => {
    void runReload();
  }, settings.debounceMs);
};
```

> **Sidebar**: **Debouncing** is a technique for controlling the frequency of function calls. When events are triggered continuously, the callback is only executed after a period of time (300ms in this case) following the last trigger. This differs from **throttling**—throttling ensures at least one execution within a fixed time interval, while debouncing ensures execution only after a period of "silence". In the configuration hot reload scenario, users might save files multiple times in succession, and debouncing ensures only the last save triggers the reload logic.

### Diff Comparison: diffConfigPaths

The core of the reload process is comparing which paths have changed between the "previous configuration" and the "new configuration". `diffConfigPaths` recursively traverses both configuration objects and returns all paths where values differ:

```typescript
// src/gateway/config-reload.ts

export function diffConfigPaths(prev: unknown, next: unknown, prefix = ""): string[] {
  // Strict equality → no change
  if (prev === next) return [];

  // Both sides are objects → recursively compare each key
  if (isPlainObject(prev) && isPlainObject(next)) {
    const keys = new Set([...Object.keys(prev), ...Object.keys(next)]);
    const paths: string[] = [];
    for (const key of keys) {
      const childPrefix = prefix ? `${prefix}.${key}` : key;
      const childPaths = diffConfigPaths(prev[key], next[key], childPrefix);
      paths.push(...childPaths);
    }
    return paths;
  }

  // Both sides are arrays → compare element by element
  if (Array.isArray(prev) && Array.isArray(next)) {
    if (prev.length === next.length && prev.every((val, idx) => val === next[idx])) {
      return [];
    }
  }

  // Other cases → this path has changed
  return [prefix || "<root>"];
}
```

For example, if a user changes `cron.schedule` from `"*/5 * * * *"` to `"*/10 * * * *"`, `diffConfigPaths` will return `["cron.schedule"]`.

### Rule Routing: buildGatewayReloadPlan

After obtaining the configuration change paths, the next step is to decide "how to reload". OpenClaw maintains a prioritized rule table—each configuration path prefix corresponds to one of three handling methods:

| Category    | Meaning                         | Execution Method                               |
| ----------- | ------------------------------- | ---------------------------------------------- |
| `"restart"` | Must completely restart Gateway | Send SIGUSR1 signal to trigger process restart |
| `"hot"`     | Can hot reload                  | Only restart affected subsystems               |
| `"none"`    | No reload needed                | Ignore (takes effect naturally on next read)   |

The rule table is split into three layers: base rules (head), channel plugin rules (dynamic), base rules (tail):

```typescript
// src/gateway/config-reload.ts

// Head rules — highest priority
const BASE_RELOAD_RULES: ReloadRule[] = [
  { prefix: "gateway.remote",             kind: "none" },
  { prefix: "gateway.reload",             kind: "none" },
  { prefix: "hooks.gmail",                kind: "hot", actions: ["restart-gmail-watcher"] },
  { prefix: "hooks",                      kind: "hot", actions: ["reload-hooks"] },
  { prefix: "agents.defaults.heartbeat",  kind: "hot", actions: ["restart-heartbeat"] },
  { prefix: "cron",                       kind: "hot", actions: ["restart-cron"] },
  { prefix: "browser",                    kind: "hot", actions: ["restart-browser-control"] },
];

// Tail rules — fallback
const BASE_RELOAD_RULES_TAIL: ReloadRule[] = [
  { prefix: "identity",   kind: "none" },
  { prefix: "models",     kind: "none" },
  { prefix: "agents",     kind: "none" },
  { prefix: "tools",      kind: "none" },
  { prefix: "skills",     kind: "none" },
  // ... other "none" categories
  { prefix: "plugins",    kind: "restart" },
  { prefix: "gateway",    kind: "restart" },
  { prefix: "discovery",  kind: "restart" },
  { prefix: "canvasHost", kind: "restart" },
];
```

**Plugin Rule Injection**: Channel plugins can declare their own reload rules through `plugin.reload.configPrefixes` and `plugin.reload.noopPrefixes`. These rules are inserted between the head and tail:

```typescript
function listReloadRules(): ReloadRule[] {
  const channelReloadRules = listChannelPlugins().flatMap((plugin) => [
    // configPrefixes → hot reload, restart corresponding channel
    ...(plugin.reload?.configPrefixes ?? []).map((prefix) => ({
      prefix,
      kind: "hot" as const,
      actions: [`restart-channel:${plugin.id}` as ReloadAction],
    })),
    // noopPrefixes → no reload needed
    ...(plugin.reload?.noopPrefixes ?? []).map((prefix) => ({
      prefix,
      kind: "none" as const,
    })),
  ]);

  return [...BASE_RELOAD_RULES, ...channelReloadRules, ...BASE_RELOAD_RULES_TAIL];
}
```

> **Design Point**: Rule matching uses a **first match** strategy—`matchRule` linearly traverses the rule table and returns the first rule with a matching prefix. This means head rules have higher priority than tail rules. For example, the rule for `hooks.gmail` comes before `hooks`, so changes to Gmail hooks trigger `restart-gmail-watcher` rather than the generic `reload-hooks`.

### Building the Reload Plan

`buildGatewayReloadPlan` traverses all changed paths and builds a detailed reload plan based on matched rules:

```typescript
// src/gateway/config-reload.ts (simplified)

export function buildGatewayReloadPlan(changedPaths: string[]): GatewayReloadPlan {
  const plan: GatewayReloadPlan = {
    changedPaths,
    restartGateway: false,
    restartReasons: [],
    hotReasons: [],
    reloadHooks: false,
    restartGmailWatcher: false,
    restartBrowserControl: false,
    restartCron: false,
    restartHeartbeat: false,
    restartChannels: new Set(),
    noopPaths: [],
  };

  for (const path of changedPaths) {
    const rule = matchRule(path);
    if (!rule) {
      // No rule matched → for safety, mark as requiring restart
      plan.restartGateway = true;
      plan.restartReasons.push(path);
      continue;
    }
    if (rule.kind === "restart") {
      plan.restartGateway = true;
      plan.restartReasons.push(path);
    } else if (rule.kind === "none") {
      plan.noopPaths.push(path);
    } else {
      // hot — execute corresponding actions
      plan.hotReasons.push(path);
      for (const action of rule.actions ?? []) {
        applyAction(action);  // Set corresponding boolean flag
      }
    }
  }

  // Gmail watcher depends on hooks; if restarting Gmail, also reload hooks
  if (plan.restartGmailWatcher) {
    plan.reloadHooks = true;
  }

  return plan;
}
```

Note a safety design: if a changed path doesn't match any rule (`rule === null`), the system defaults to treating it as `"restart"`—it's better to restart more than to miss critical configuration changes.

### Four Reload Modes

After the reload plan is built, how to execute it is determined by the `gateway.reload.mode` configuration:

| Mode                 | Behavior                                                                             |
| -------------------- | ------------------------------------------------------------------------------------ |
| `"off"`              | Completely disable hot reload, ignore all file changes                               |
| `"restart"`          | Regardless of change content, always restart Gateway                                 |
| `"hot"`              | Only execute hot reload portion; changes requiring restart are ignored (log warning) |
| `"hybrid"` (default) | Prioritize hot reload; if there are changes requiring restart, trigger full restart  |

```typescript
// Mode determination logic in runReload (simplified)

if (settings.mode === "off") {
  // Completely disabled
  return;
}
if (settings.mode === "restart") {
  // Direct restart
  opts.onRestart(plan, nextConfig);
  return;
}
if (plan.restartGateway) {
  if (settings.mode === "hot") {
    // In hot mode, ignore changes requiring restart
    log.warn("config reload requires gateway restart; hot mode ignoring");
    return;
  }
  // hybrid mode → trigger restart
  opts.onRestart(plan, nextConfig);
  return;
}
// No restart needed → execute hot reload
await opts.onHotReload(plan, nextConfig);
```

### Concurrency Protection and Reentrancy Guard

During the hot reload process, we need to prevent concurrent execution (e.g., user saves file while reload is in progress):

```typescript
let pending = false;
let running = false;
let restartQueued = false;

const runReload = async () => {
  if (running) {
    pending = true;  // Mark that there's a pending reload
    return;
  }
  running = true;
  try {
    // ... execute reload logic ...
  } finally {
    running = false;
    if (pending) {
      pending = false;
      schedule();  // Reschedule
    }
  }
};
```

This is a classic **mutex + queue** pattern: the `running` flag ensures only one reload executes at a time; the `pending` flag ensures new changes arriving during reload aren't lost but are rescheduled after the current reload completes.

***

## 31.3.2 Runtime Overrides (`src/config/runtime-overrides.ts`)

In addition to file-level configuration modifications, OpenClaw also supports temporarily overriding configuration values at runtime via API—these overrides are stored in memory, not written to disk, and expire when the process restarts.

### Override Tree

Runtime overrides use a module-level variable `overrides` to store, with a structure identical to `OpenClawConfig` but containing only overridden paths:

```typescript
// src/config/runtime-overrides.ts

type OverrideTree = Record<string, unknown>;

let overrides: OverrideTree = {};
```

### Setting and Unsetting Overrides

`setConfigOverride` and `unsetConfigOverride` manipulate the override tree through configuration path syntax:

```typescript
// src/config/runtime-overrides.ts

export function setConfigOverride(
  pathRaw: string,
  value: unknown,
): { ok: boolean; error?: string } {
  const parsed = parseConfigPath(pathRaw);
  if (!parsed.ok || !parsed.path) {
    return { ok: false, error: parsed.error ?? "Invalid path." };
  }
  setConfigValueAtPath(overrides, parsed.path, value);
  return { ok: true };
}

export function unsetConfigOverride(pathRaw: string): {
  ok: boolean; removed: boolean; error?: string;
} {
  const parsed = parseConfigPath(pathRaw);
  if (!parsed.ok || !parsed.path) {
    return { ok: false, removed: false, error: parsed.error ?? "Invalid path." };
  }
  const removed = unsetConfigValueAtPath(overrides, parsed.path);
  return { ok: true, removed };
}
```

Path parsing uses `parseConfigPath` (see section 23.1), supporting dot and bracket syntax (e.g., `agents.list[0].model.primary`), with built-in prototype pollution protection.

### Deep Merge: How Overrides Take Effect

`applyConfigOverrides` is called in the final step of the configuration loading pipeline, deeply merging the override tree onto the configuration object:

```typescript
// src/config/runtime-overrides.ts

function mergeOverrides(base: unknown, override: unknown): unknown {
  // If neither side is an object → override value directly replaces
  if (!isPlainObject(base) || !isPlainObject(override)) {
    return override;
  }
  // Both sides are objects → recursively merge
  const next = { ...base };
  for (const [key, value] of Object.entries(override)) {
    if (value === undefined) continue;
    next[key] = mergeOverrides(base[key], value);
  }
  return next;
}

export function applyConfigOverrides(cfg: OpenClawConfig): OpenClawConfig {
  if (!overrides || Object.keys(overrides).length === 0) {
    return cfg;  // No overrides → return directly
  }
  return mergeOverrides(cfg, overrides) as OpenClawConfig;
}
```

Merge semantics are as follows:

| Base Value | Override Value | Result                                                 |
| ---------- | -------------- | ------------------------------------------------------ |
| Object     | Object         | Recursive merge (preserve unoverridden keys from base) |
| Object     | Non-object     | Override value replaces                                |
| Non-object | Any            | Override value replaces                                |
| Any        | `undefined`    | Keep base value                                        |

**Use Case**: Runtime overrides are typically triggered by the Web console's "temporary debug" feature, such as temporarily switching models or temporarily raising log levels, without modifying the configuration file.

***

## 31.3.3 Server Reload Handlers (`src/gateway/server-reload-handlers.ts`)

After the hot reload plan is built, the actual execution of the reload is done by two handlers created by the `createGatewayReloadHandlers` factory function: `applyHotReload` (hot reload) and `requestGatewayRestart` (full restart).

### Factory Pattern and State Injection

`createGatewayReloadHandlers` receives a set of dependencies and state accessors, returning two handler functions. This design decouples reload logic from Gateway's concrete state:

```typescript
// src/gateway/server-reload-handlers.ts (simplified)

type GatewayHotReloadState = {
  hooksConfig: ReturnType<typeof resolveHooksConfig>;
  heartbeatRunner: HeartbeatRunner;
  cronState: GatewayCronState;
  browserControl: BrowserControlServer | null;
};

export function createGatewayReloadHandlers(params: {
  deps: CliDeps;
  broadcast: (event: string, payload: unknown) => void;
  getState: () => GatewayHotReloadState;
  setState: (state: GatewayHotReloadState) => void;
  startChannel: (name: ChannelKind) => Promise<void>;
  stopChannel: (name: ChannelKind) => Promise<void>;
  // ... loggers for various subsystems
}) {
  return { applyHotReload, requestGatewayRestart };
}
```

### applyHotReload: Per-Subsystem Reload

`applyHotReload` restarts affected subsystems one by one based on flags in the reload plan:

```typescript
// src/gateway/server-reload-handlers.ts (simplified)

const applyHotReload = async (plan: GatewayReloadPlan, nextConfig: OpenClawConfig) => {
  const state = params.getState();
  const nextState = { ...state };

  // 1. Hook reload
  if (plan.reloadHooks) {
    nextState.hooksConfig = resolveHooksConfig(nextConfig);
  }

  // 2. Heartbeat reload
  if (plan.restartHeartbeat) {
    nextState.heartbeatRunner.updateConfig(nextConfig);
  }

  // 3. Cron task reload (stop-then-start)
  if (plan.restartCron) {
    state.cronState.cron.stop();
    nextState.cronState = buildGatewayCronService({
      cfg: nextConfig, deps: params.deps, broadcast: params.broadcast
    });
    void nextState.cronState.cron.start().catch(/* ... */);
  }

  // 4. Browser control service reload
  if (plan.restartBrowserControl) {
    if (state.browserControl) await state.browserControl.stop();
    nextState.browserControl = await startBrowserControlServerIfEnabled();
  }

  // 5. Gmail watcher reload
  if (plan.restartGmailWatcher) {
    await stopGmailWatcher();
    if (!isTruthyEnvValue(process.env.OPENCLAW_SKIP_GMAIL_WATCHER)) {
      const result = await startGmailWatcher(nextConfig);
      if (result.started) log.info("gmail watcher started");
    }
  }

  // 6. Channel reload
  if (plan.restartChannels.size > 0) {
    for (const channel of plan.restartChannels) {
      await params.stopChannel(channel);
      await params.startChannel(channel);
    }
  }

  // 7. Update concurrency
  setCommandLaneConcurrency(CommandLane.Cron,     nextConfig.cron?.maxConcurrentRuns ?? 1);
  setCommandLaneConcurrency(CommandLane.Main,     resolveAgentMaxConcurrent(nextConfig));
  setCommandLaneConcurrency(CommandLane.Subagent, resolveSubagentMaxConcurrent(nextConfig));

  // 8. Clear directory cache
  resetDirectoryCache();

  // 9. Commit new state
  params.setState(nextState);
};
```

Note several design points:

1. **Stop-then-start Pattern**: Cron tasks, browser control, and Gmail watcher all use the "stop old instance first, then start new instance" approach to avoid resource leaks.
2. **Environment Variable Skip**: `OPENCLAW_SKIP_GMAIL_WATCHER` and `OPENCLAW_SKIP_CHANNELS` environment variables allow skipping certain subsystem restarts during development/debugging.
3. **Immediate Concurrency Update**: Command queue concurrency (separate limits for main Agent, sub-Agent, and Cron tasks) is synchronized on each hot reload.
4. **Directory Cache Clearing**: `resetDirectoryCache()` ensures Agent directory resolution doesn't use stale cache.

### requestGatewayRestart: Full Restart

When changes cannot be hot reloaded, the system triggers Gateway process restart via Unix signal:

```typescript
// src/gateway/server-reload-handlers.ts (simplified)

const requestGatewayRestart = (plan: GatewayReloadPlan, nextConfig: OpenClawConfig) => {
  setGatewaySigusr1RestartPolicy({
    allowExternal: nextConfig.commands?.restart === true
  });

  const reasons = plan.restartReasons.length
    ? plan.restartReasons.join(", ")
    : plan.changedPaths.join(", ");
  log.warn(`config change requires gateway restart (${reasons})`);

  // Check if SIGUSR1 listener exists
  if (process.listenerCount("SIGUSR1") === 0) {
    log.warn("no SIGUSR1 listener found; restart skipped");
    return;
  }

  authorizeGatewaySigusr1Restart();
  process.emit("SIGUSR1");
};
```

> **Sidebar**: `SIGUSR1` is a user-defined signal (User-defined Signal 1) defined by the POSIX standard. In Node.js, `process.emit("SIGUSR1")` doesn't terminate the process but triggers registered listeners. OpenClaw Gateway registers a SIGUSR1 listener at startup to perform graceful restart—stop accepting new requests, wait for in-flight requests to complete, then reinitialize all subsystems. `authorizeGatewaySigusr1Restart()` sets an authorization flag to prevent SIGUSR1 signals from external processes from accidentally triggering restart.

### Complete Data Flow of Hot Reload

Combining the content of the three subsections, the complete data flow of configuration hot reload is as follows:

```
User edits openclaw.json
         │
    chokidar detects file change
         │
    debounce 300ms
         │
    readSnapshot() ─── read and validate new config
         │                  │
         │         Invalid config? → skip (log warning)
         │
    diffConfigPaths(oldConfig, newConfig)
         │                  │
         │         No change? → skip
         │
    buildGatewayReloadPlan(changedPaths)
         │
    ┌────┴────────────────────────────┐
    │ Mode determination               │
    ├──────────────────────────────────┤
    │ off     → skip                   │
    │ restart → requestGatewayRestart  │
    │ hot     → applyHotReload         │
    │         (changes requiring      │
    │          restart are ignored)    │
    │ hybrid  → needs restart?         │
    │           ├ yes → requestRestart │
    │           └ no → applyHotReload  │
    └──────────────────────────────────┘
         │
    applyHotReload
         │
    ┌────┴────────────────────────────────┐
    │ Reload by subsystem:                 │
    │  • reloadHooks → resolveHooksConfig  │
    │  • restartHeartbeat → updateConfig   │
    │  • restartCron → stop + rebuild      │
    │  • restartBrowser → stop + restart   │
    │  • restartGmail → stop + restart     │
    │  • restartChannels → stop + start    │
    │  • update concurrency                │
    │  • clear directory cache             │
    └─────────────────────────────────────┘
```

***

## Summary of This Section

1. **File monitoring** uses chokidar with `awaitWriteFinish` to wait for file write stabilization, avoiding reading incomplete configurations.
2. **Debounce mechanism** (default 300ms) prevents continuous saves from triggering multiple reloads, while mutex + queue ensures reload doesn't execute concurrently.
3. **Diff comparison** (`diffConfigPaths`) recursively compares old and new configurations, returning a list of all changed paths.
4. **Rule routing** maps each changed path to one of three handling methods: `restart`/`hot`/`none`, with the rule table supporting dynamic injection by channel plugins.
5. **Four reload modes**—`off` (disabled), `restart` (always restart), `hot` (hot reload only), `hybrid` (mixed, default)—provide flexible strategy choices.
6. **Runtime overrides** provide a pure in-memory configuration override mechanism, layered on top of disk configuration through deep merge, suitable for temporary debugging.
7. **Hot reload handlers** execute stop-then-start per subsystem, ensuring each subsystem reloads independently without resource leaks.
8. **Full restart** is triggered via SIGUSR1 signal for graceful restart, with authorization mechanism to prevent accidental triggering.
