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

# 31.4 Legacy Configuration Migration

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

***

OpenClaw was not born from scratch—it has undergone multiple renamings and architectural reorganizations: moldbot → moltbot → clawdbot → openclaw, and the configuration structure has evolved accordingly. Early top-level `whatsapp`, `telegram` configuration keys were consolidated into `channels.whatsapp`, `channels.telegram`; early `agent.model` strings were split into `agents.defaults.model.primary` plus a `fallbacks` array; various sub-configurations under `routing` were scattered to more semantically meaningful locations like `agents`, `tools`, `messages`, etc. To enable painless upgrades for legacy users, OpenClaw has built an automatic migration system into the configuration loading pipeline—this section dissects its design and implementation.

***

## 31.4.1 Migration Framework (`src/config/legacy.ts`)

### Two Independent Subsystems

Legacy configuration handling consists of two complementary subsystems:

| Subsystem     | Function                 | Purpose                                                                                      |
| ------------- | ------------------------ | -------------------------------------------------------------------------------------------- |
| **Detection** | `findLegacyConfigIssues` | Scan configuration, discover paths using old formats, return human-readable warning messages |
| **Migration** | `applyLegacyMigrations`  | Automatically convert old format configuration to new format, return change log              |

Both can be used independently: detection is used to display upgrade prompts in Web console or CLI; migration is automatically executed in the configuration loading pipeline.

### Detection: findLegacyConfigIssues

The detection function traverses a set of predefined rules (`LEGACY_CONFIG_RULES`), searching for each rule's path. If the corresponding path exists and (optionally) the match condition is satisfied, a problem is recorded:

```typescript
// src/config/legacy.ts

export function findLegacyConfigIssues(raw: unknown): LegacyConfigIssue[] {
  if (!raw || typeof raw !== "object") return [];

  const root = raw as Record<string, unknown>;
  const issues: LegacyConfigIssue[] = [];

  for (const rule of LEGACY_CONFIG_RULES) {
    // Traverse path layer by layer
    let cursor: unknown = root;
    for (const key of rule.path) {
      if (!cursor || typeof cursor !== "object") {
        cursor = undefined;
        break;
      }
      cursor = (cursor as Record<string, unknown>)[key];
    }

    // Path exists and match condition satisfied → record issue
    if (cursor !== undefined && (!rule.match || rule.match(cursor, root))) {
      issues.push({ path: rule.path.join("."), message: rule.message });
    }
  }
  return issues;
}
```

### Migration: applyLegacyMigrations

The migration function uses `structuredClone` to deep copy the original configuration, then executes all migration rules in sequence:

```typescript
// src/config/legacy.ts

export function applyLegacyMigrations(raw: unknown): {
  next: Record<string, unknown> | null;
  changes: string[];
} {
  if (!raw || typeof raw !== "object") return { next: null, changes: [] };

  const next = structuredClone(raw) as Record<string, unknown>;
  const changes: string[] = [];

  for (const migration of LEGACY_CONFIG_MIGRATIONS) {
    migration.apply(next, changes);
  }

  if (changes.length === 0) return { next: null, changes: [] };
  return { next, changes };
}
```

> **Sidebar**: `structuredClone` is a deep copy API natively provided by browsers and Node.js (v17+), more powerful than `JSON.parse(JSON.stringify(obj))`—it correctly handles types like `Date`, `RegExp`, `Map`, `Set`, circular references, etc. Using deep copy here is critical: the migration function directly modifies object structure (deletes keys, moves values), and without copying it would destroy the original input.

### Core Type Definitions

Type definitions for detection rules and migration rules are in `legacy.shared.ts`:

```typescript
// src/config/legacy.shared.ts

export type LegacyConfigRule = {
  path: string[];                                          // Configuration path to check
  message: string;                                         // Human-readable hint message
  match?: (value: unknown, root: Record<string, unknown>) => boolean;  // Optional match condition
};

export type LegacyConfigMigration = {
  id: string;        // Migration ID (unique identifier for debugging)
  describe: string;  // Migration description
  apply: (raw: Record<string, unknown>, changes: string[]) => void;  // Execute migration
};
```

`match` is an optional predicate function used to distinguish different types of values at the same path. For example, `agent.model` can be either a string (old format) or an object (new format), and only string values need migration:

```typescript
{
  path: ["agent", "model"],
  message: "agent.model string was replaced by agents.defaults.model.primary/fallbacks...",
  match: (value) => typeof value === "string",  // Only match string values
}
```

### Entry Function: migrateLegacyConfig

`legacy-migrate.ts` provides a complete migration entry point—immediately validates configuration after migration:

```typescript
// src/config/legacy-migrate.ts

export function migrateLegacyConfig(raw: unknown): {
  config: OpenClawConfig | null;
  changes: string[];
} {
  const { next, changes } = applyLegacyMigrations(raw);
  if (!next) return { config: null, changes: [] };

  // Re-validate after migration
  const validated = validateConfigObjectWithPlugins(next);
  if (!validated.ok) {
    changes.push("Migration applied, but config still invalid; fix remaining issues manually.");
    return { config: null, changes };
  }
  return { config: validated.config, changes };
}
```

This "migration + validation" combination ensures the correctness of migration results—if automatic migration cannot completely fix the configuration (e.g., cases requiring manual decision), the function returns `null` with a hint message.

### Helper Utilities

`legacy.shared.ts` also provides a set of utility functions for migration rules to use:

```typescript
// src/config/legacy.shared.ts (simplified)

// Type guard: is it a plain object
export const isRecord = (value: unknown): value is Record<string, unknown> =>
  Boolean(value && typeof value === "object" && !Array.isArray(value));

// Safely get object value
export const getRecord = (value: unknown): Record<string, unknown> | null =>
  isRecord(value) ? value : null;

// Ensure a key corresponds to an object (create empty object if not exists)
export const ensureRecord = (root: Record<string, unknown>, key: string) => {
  const existing = root[key];
  if (isRecord(existing)) return existing;
  const next: Record<string, unknown> = {};
  root[key] = next;
  return next;
};

// Merge keys from source into target (don't overwrite existing values)
export const mergeMissing = (target: Record<string, unknown>, source: Record<string, unknown>) => {
  for (const [key, value] of Object.entries(source)) {
    if (value === undefined) continue;
    const existing = target[key];
    if (existing === undefined) {
      target[key] = value;
    } else if (isRecord(existing) && isRecord(value)) {
      mergeMissing(existing, value);  // Recursive merge
    }
    // Existing value and non-object → keep target value (don't overwrite)
  }
};
```

The semantics of `mergeMissing` is "only fill gaps"—it won't overwrite existing values in the target. This is important in migration: users might have both old and new format configurations (e.g., both `whatsapp` and `channels.whatsapp`), and `mergeMissing` ensures new format values won't be overwritten by old format.

***

## 31.4.2 Migration Rules (`src/config/legacy.rules.ts`)

### Detection Rules Overview

The `LEGACY_CONFIG_RULES` array defines 25+ detection rules covering all major configuration structure changes in OpenClaw's history. Grouped by category as follows:

**Channel Migration (7 rules)**:

| Old Path   | New Path            | Description                                    |
| ---------- | ------------------- | ---------------------------------------------- |
| `whatsapp` | `channels.whatsapp` | Top-level channel key → unified under channels |
| `telegram` | `channels.telegram` | Same as above                                  |
| `discord`  | `channels.discord`  | Same as above                                  |
| `slack`    | `channels.slack`    | Same as above                                  |
| `signal`   | `channels.signal`   | Same as above                                  |
| `imessage` | `channels.imessage` | Same as above                                  |
| `msteams`  | `channels.msteams`  | Same as above                                  |

**Routing Decomposition (8 rules)**:

| Old Path                            | New Path                               | Description                                   |
| ----------------------------------- | -------------------------------------- | --------------------------------------------- |
| `routing.allowFrom`                 | `channels.whatsapp.allowFrom`          | Whitelist belongs to specific channel         |
| `routing.bindings`                  | `bindings` (top-level)                 | Bindings elevated to top-level config         |
| `routing.agents`                    | `agents.list`                          | Agent list managed independently              |
| `routing.defaultAgentId`            | `agents.list[].default`                | Default Agent marked in list item             |
| `routing.agentToAgent`              | `tools.agentToAgent`                   | Agent-to-Agent communication belongs to tools |
| `routing.groupChat.requireMention`  | `channels.*.groups."*".requireMention` | Group chat config sinks to channel level      |
| `routing.groupChat.mentionPatterns` | `messages.groupChat.mentionPatterns`   | Mention patterns move to message config       |
| `routing.queue`                     | `messages.queue`                       | Message queue moves to message config         |

**Agent Configuration Reorganization (7 rules)**:

| Old Path                    | New Path                                       | Description                               |
| --------------------------- | ---------------------------------------------- | ----------------------------------------- |
| `agent.*`                   | `agents.defaults.*`                            | Singular form → plural + defaults         |
| `agent.model` (string)      | `agents.defaults.model.primary/fallbacks`      | Single model → primary + fallbacks        |
| `agent.imageModel` (string) | `agents.defaults.imageModel.primary/fallbacks` | Same as above                             |
| `agent.allowedModels`       | `agents.defaults.models`                       | Allowed models list → models mapping      |
| `agent.modelAliases`        | `agents.defaults.models.*.alias`               | Aliases embedded in model definition      |
| `agent.modelFallbacks`      | `agents.defaults.model.fallbacks`              | Fallback models list                      |
| `identity`                  | `agents.list[].identity`                       | Identity config belongs to specific Agent |

**Other Migrations**:

| Old Path                  | New Path                                      | Description                              |
| ------------------------- | --------------------------------------------- | ---------------------------------------- |
| `tools.bash`              | `tools.exec`                                  | Command-line tool renamed                |
| `messages.tts.enabled`    | `messages.tts.auto`                           | Boolean → enum value                     |
| `gateway.token`           | `gateway.auth.token`                          | Auth config reorganized                  |
| `routing.transcribeAudio` | `tools.media.audio.models`                    | Audio transcription moves to media tools |
| `telegram.requireMention` | `channels.telegram.groups."*".requireMention` | Same as group chat migration             |

***

## 31.4.3 Phased Migration (`legacy.migrations.part-1/2/3.ts`)

### Migration Architecture

Migration rules are split into three phases by complexity and dependencies, summarized through `legacy.migrations.ts`:

```typescript
// src/config/legacy.migrations.ts

export const LEGACY_CONFIG_MIGRATIONS = [
  ...LEGACY_CONFIG_MIGRATIONS_PART_1,   // Basic migrations (channels, routing)
  ...LEGACY_CONFIG_MIGRATIONS_PART_2,   // Models and Agent list
  ...LEGACY_CONFIG_MIGRATIONS_PART_3,   // Agent defaults and tools
];
```

Order is critical—Part 1 first relocates channel configurations, Part 2 can then correctly handle Agent routing (because routing migration might reference channels), Part 3 finally cleans up `agent.*` remnants to `agents.defaults`.

### Part 1: Basic Migration

Part 1 contains 9 migration rules, mainly handling field renaming and location moves:

**Rule 1: `bindings.match.provider` → `bindings.match.channel`**

Early versions used `provider` to identify message sources (WhatsApp, Telegram, etc.), later unified as `channel`. Migration traverses each entry in the `bindings` array:

```typescript
{
  id: "bindings.match.provider->bindings.match.channel",
  apply: (raw, changes) => {
    const bindings = Array.isArray(raw.bindings) ? raw.bindings : null;
    if (!bindings) return;

    let touched = false;
    for (const entry of bindings) {
      const match = getRecord(entry?.match);
      if (!match) continue;
      if (typeof match.channel === "string") continue;  // Already has channel → skip
      const provider = typeof match.provider === "string" ? match.provider.trim() : "";
      if (!provider) continue;

      match.channel = provider;
      delete match.provider;
      touched = true;
    }
    if (touched) changes.push("Moved bindings[].match.provider → bindings[].match.channel.");
  },
}
```

**Rule 5: Top-level channels → `channels.*`**

This is the most common migration—moving `whatsapp`, `telegram`, etc. top-level keys into the `channels` namespace:

```typescript
{
  id: "providers->channels",
  apply: (raw, changes) => {
    const legacyKeys = ["whatsapp", "telegram", "discord", "slack", "signal", "imessage", "msteams"];
    const legacyEntries = legacyKeys.filter((key) => isRecord(raw[key]));
    if (legacyEntries.length === 0) return;

    const channels = ensureRecord(raw, "channels");
    for (const key of legacyEntries) {
      const legacy = getRecord(raw[key]);
      if (!legacy) continue;

      const channelEntry = ensureRecord(channels, key);
      const hadEntries = Object.keys(channelEntry).length > 0;
      mergeMissing(channelEntry, legacy);   // Only fill gaps
      delete raw[key];                       // Delete old key

      changes.push(
        hadEntries
          ? `Merged ${key} → channels.${key}.`
          : `Moved ${key} → channels.${key}.`
      );
    }
  },
}
```

**Rule 7: `routing.groupChat.requireMention` Fan-out**

This migration is special—a single configuration value needs to "fan out" to multiple channels' group chat configurations:

```typescript
// Simplified logic
const applyTo = (key: "whatsapp" | "telegram" | "imessage") => {
  const section = ensureRecord(channels, key);
  const groups = ensureRecord(section, "groups");
  const entry = ensureRecord(groups, "*");           // "*" = default rule

  if (entry.requireMention === undefined) {
    entry.requireMention = requireMention;            // Fill gap
    changes.push(`Moved → channels.${key}.groups."*".requireMention.`);
  }
};

applyTo("whatsapp", { requireExisting: true });  // WhatsApp requires existing config
applyTo("telegram");                              // Telegram always applies
applyTo("imessage");                               // iMessage always applies
```

Note the `requireExisting` option—for WhatsApp, only migrate `requireMention` if the user has already configured WhatsApp, avoiding creating empty configurations for unused channels.

### Part 2: Model and Routing Migration

Part 2 contains 3 migration rules handling the most complex model configuration and Agent routing migration.

**Model Configuration Migration (`agent.model-config-v2`)**

This is the most complex rule in the entire migration system. In early versions, model configuration was a set of flat fields:

```json5
// Old format
{
  "agent": {
    "model": "claude-3-opus",                    // String
    "allowedModels": ["claude-3-opus", "gpt-4"],
    "modelAliases": { "opus": "claude-3-opus" },
    "modelFallbacks": ["gpt-4", "claude-3-sonnet"],
    "imageModel": "dall-e-3",
    "imageModelFallbacks": ["stable-diffusion-xl"]
  }
}
```

Needs to migrate to structured format:

```json5
// New format
{
  "agents": {
    "defaults": {
      "model": {
        "primary": "claude-3-opus",
        "fallbacks": ["gpt-4", "claude-3-sonnet"]
      },
      "imageModel": {
        "primary": "dall-e-3",
        "fallbacks": ["stable-diffusion-xl"]
      },
      "models": {
        "claude-3-opus": { "alias": "opus" },
        "gpt-4": {},
        "claude-3-sonnet": {},
        "dall-e-3": {},
        "stable-diffusion-xl": {}
      }
    }
  }
}
```

The migration process has four steps: (1) Collect all involved model names and create entries in the `models` mapping; (2) Embed alias relationships from `modelAliases` into the corresponding model's `alias` field; (3) Build `model.primary/fallbacks` and `imageModel.primary/fallbacks` structures; (4) Clean up old fields.

**Agent Routing Migration (`routing.agents-v2`)**

Migrate configurations grouped by Agent ID in `routing.agents` to the `agents.list` array, while handling position adjustments for sub-configurations like `mentionPatterns`, `groupChat`, `sandbox.tools`, etc.

### Part 3: Agent Defaults and Tools

Part 3 contains 5 cleanup-oriented migration rules:

**`agent.defaults-v2`: Final Cleanup**

This rule executes the final `agent.*` → `agents.defaults` migration, while diverting tool-related configurations to `tools.*`:

```
agent.tools.allow   → tools.allow
agent.tools.deny    → tools.deny
agent.elevated      → tools.elevated
agent.bash          → tools.exec
agent.sandbox.tools → tools.sandbox.tools
agent.subagents.tools → tools.subagents.tools
agent.* (remaining) → agents.defaults.*
```

**`identity->agents.list`: Identity Config Attribution**

Move top-level `identity` to the default Agent's configuration. Determining the "default Agent" uses `resolveDefaultAgentIdFromRaw`—it searches by priority: (1) Entry with `default: true` in `agents.list`; (2) `routing.defaultAgentId`; (3) First entry in list; (4) Fallback value `"main"`.

**Other Part 3 Rules**:

| Rule ID                                | Migration Content                                                    |
| -------------------------------------- | -------------------------------------------------------------------- |
| `auth.anthropic-claude-cli-mode-oauth` | Auth mode `token` → `oauth`                                          |
| `tools.bash->tools.exec`               | Tool renamed                                                         |
| `messages.tts.enabled->auto`           | `enabled: true` → `auto: "always"`, `enabled: false` → `auto: "off"` |

### Design Principles of Migration Rules

From the source code, the following design principles can be summarized:

1. **Idempotency**: Each rule first checks if the target location already has a value. If it does, skip migration (or only delete old key), ensuring consistent results across multiple executions.
2. **Fill Gaps, Don't Overwrite**: `mergeMissing` semantics ensure values manually set by users in new locations won't be overwritten by old values.
3. **Complete Logging**: After each rule executes, human-readable change descriptions are appended to the `changes` array, helping users understand what automatic migration did.
4. **Gradual Cleanup**: After migration, if an object becomes empty (e.g., all keys under `routing` have been migrated away), delete the empty object to keep configuration clean.
5. **Order Dependency**: The Part 1 → Part 2 → Part 3 order ensures prerequisite migrations complete before executing migrations that depend on them.

***

## Summary of This Section

1. **Dual-track System**: Legacy configuration handling is split into "detection" (`findLegacyConfigIssues`, generates warnings) and "migration" (`applyLegacyMigrations`, auto-fixes) two independent subsystems.
2. **Deep Copy Protection**: Migration operates on a copy produced by `structuredClone`, not affecting the original input.
3. **25+ Detection Rules** cover channel migration, routing decomposition, Agent configuration reorganization, tool renaming, and all historical changes.
4. **Three-phase Migration** (Part 1/2/3) ordered by dependencies: basic migration → models and routing → Agent defaults and tools.
5. **Idempotent Design** ensures migration can safely execute multiple times without corrupting already-migrated configurations.
6. **mergeMissing Semantics** guarantee "manually set new format configurations" won't be overwritten by old format values.
7. **Post-Migration Validation** (`migrateLegacyConfig`) ensures migration results pass Zod validation, prompting manual fixes if invalid.
