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

# 31.1 Configuration Loading and Parsing

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

***

The configuration system is the "nervous center" of OpenClaw—from Agent behavior to Channel connections, from model selection to security policies, nearly all runtime behavior is controlled by a single JSON5 configuration file. This section deeply analyzes the configuration loading pipeline: from reading raw files from disk to producing the final validated, substituted, and default-value-filled `OpenClawConfig` object, examining what steps occur in between.

***

## 31.1.1 Configuration File Location: `~/.openclaw/openclaw.json` (JSON5 Format)

### Default Path

OpenClaw's configuration file is stored by default in the `.openclaw` directory under the user's home directory:

```
~/.openclaw/openclaw.json
```

> **Sidebar**: JSON5 is a superset of JSON that allows comments (`//` and `/* */`), trailing commas, single-quoted strings, hexadecimal numbers, and more. For configuration files that require manual editing, JSON5 is much more user-friendly than strict JSON—you can write comments to explain the meaning of configuration items. OpenClaw uses the `json5` npm package to parse configuration files.

### Path Resolution Strategy

Configuration path resolution is not straightforward—OpenClaw needs to maintain backward compatibility with multiple product name generations, support environment variable overrides, and handle multiple candidate locations:

```typescript
// src/config/paths.ts (simplified)

const LEGACY_STATE_DIRNAMES = [".clawdbot", ".moltbot", ".moldbot"];
const NEW_STATE_DIRNAME = ".openclaw";
const CONFIG_FILENAME = "openclaw.json";
const LEGACY_CONFIG_FILENAMES = ["clawdbot.json", "moltbot.json", "moldbot.json"];

// State directory resolution (priority from high to low)
export function resolveStateDir(env, homedir): string {
  // 1. Explicitly specified via environment variable
  if (env.OPENCLAW_STATE_DIR) return resolveUserPath(env.OPENCLAW_STATE_DIR);

  // 2. New directory exists → use new directory
  if (fs.existsSync(newStateDir(homedir))) return newStateDir(homedir);

  // 3. Old directory exists → use old directory (backward compatibility)
  const legacy = legacyDirs.find(dir => fs.existsSync(dir));
  if (legacy) return legacy;

  // 4. Neither exists → use new directory
  return newStateDir(homedir);
}
```

The search order for configuration files is even more complex—`resolveDefaultConfigCandidates` generates a candidate list:

| Priority | Candidate Path                           | Source                                        |
| -------- | ---------------------------------------- | --------------------------------------------- |
| 1        | `$OPENCLAW_CONFIG_PATH`                  | Explicitly specified via environment variable |
| 2        | `$OPENCLAW_STATE_DIR/openclaw.json`      | Custom state directory                        |
| 3        | `$OPENCLAW_STATE_DIR/clawdbot.json` etc. | Old filenames in custom directory             |
| 4        | `~/.openclaw/openclaw.json`              | New default location                          |
| 5        | `~/.openclaw/clawdbot.json` etc.         | Old filenames in new directory                |
| 6        | `~/.clawdbot/clawdbot.json` etc.         | Old default locations                         |

The system selects the first candidate file that actually exists. This design ensures that regardless of which version users upgrade from, they don't need to manually migrate configuration file paths.

### Key Environment Variables

| Environment Variable    | Purpose                                           | Default       |
| ----------------------- | ------------------------------------------------- | ------------- |
| `OPENCLAW_CONFIG_PATH`  | Specify complete configuration file path          | None          |
| `OPENCLAW_STATE_DIR`    | Specify state directory (config file is under it) | `~/.openclaw` |
| `OPENCLAW_NIX_MODE`     | Nix mode (read-only config, disable auto-install) | None          |
| `OPENCLAW_GATEWAY_PORT` | Override Gateway listening port                   | 18789         |

***

## 31.1.2 Configuration Schema (`src/config/schema.ts`)

### JSON Schema Generation

OpenClaw's configuration Schema is automatically generated from Zod patterns for use by the Web UI's configuration editor and external tools:

```typescript
// src/config/schema.ts (simplified)

export type ConfigSchema = ReturnType<typeof OpenClawSchema.toJSONSchema>;

export type ConfigSchemaResponse = {
  schema: ConfigSchema;        // Complete JSON Schema
  uiHints: ConfigUiHints;      // UI hints (grouping, ordering, sensitive marking, etc.)
  version: string;             // OpenClaw version
  generatedAt: string;         // Generation time
};
```

### UI Grouping and Ordering

The Schema not only defines the configuration structure but also provides rich display hints for the Web UI:

```typescript
const GROUP_LABELS: Record<string, string> = {
  gateway: "Gateway",
  agents: "Agents",
  tools: "Tools",
  models: "Models",
  channels: "Messaging Channels",
  hooks: "Hooks",
  skills: "Skills",
  plugins: "Plugins",
  // ...
};

export type ConfigUiHint = {
  label?: string;         // Display label
  help?: string;          // Help text
  group?: string;         // Belonging group
  order?: number;         // Sort weight
  advanced?: boolean;     // Whether advanced option
  sensitive?: boolean;    // Whether sensitive field (e.g., API Key)
  placeholder?: string;   // Placeholder text
};
```

Fields marked with `sensitive: true` (such as Tokens and API Keys) are masked in the UI and automatically desensitized in logs.

***

## 31.1.3 Zod Schema Validation (`src/config/zod-schema.ts`)

### Zod Runtime Type Validation

OpenClaw uses the Zod library to define and validate configuration runtime types. This is not simple JSON Schema—Zod can provide type inference at TypeScript compile time while executing precise data validation at runtime.

> **Sidebar**: Zod is a TypeScript-first data validation library. The traditional approach is to write TypeScript types first, then write separate validation logic, and the two can easily get out of sync. Zod lets you write a Schema once and get both compile-time types and runtime validation. A Schema like `z.object({ name: z.string(), port: z.number().int().positive() })` is both a TypeScript type definition and a runtime validator.

Zod Schema definitions are scattered across multiple files by functional module:

| Schema File                    | Coverage                           |
| ------------------------------ | ---------------------------------- |
| `zod-schema.core.ts`           | Colors, model configuration        |
| `zod-schema.agents.ts`         | Agent list, audio, bindings        |
| `zod-schema.agent-defaults.ts` | Agent default configuration        |
| `zod-schema.agent-runtime.ts`  | Tool configuration                 |
| `zod-schema.channels.ts`       | Channel configuration              |
| `zod-schema.session.ts`        | Session, message, command          |
| `zod-schema.providers.ts`      | Channel providers (WhatsApp, etc.) |
| `zod-schema.approvals.ts`      | Approval configuration             |

Finally, they are combined into the complete `OpenClawSchema` in `zod-schema.ts`:

```typescript
// src/config/zod-schema.ts (simplified)

import { z } from "zod";

export const OpenClawSchema = z.object({
  gateway: GatewaySchema.optional(),
  agents: AgentsSchema.optional(),
  tools: ToolsSchema.optional(),
  models: ModelsConfigSchema.optional(),
  channels: ChannelsSchema.optional(),
  hooks: z.object({
    enabled: z.boolean().optional(),
    token: z.string().optional(),
    internal: InternalHooksSchema.optional(),
    mappings: z.array(HookMappingSchema).optional(),
    // ...
  }).optional(),
  session: SessionSchema.optional(),
  messages: MessagesSchema.optional(),
  // ... dozens of top-level keys
}).strict();  // strict() rejects unknown keys
```

The use of `.strict()` is important—it ensures that the configuration file contains no typos or obsolete keys. If a user writes `gateway.tokne` (misspelling `token`), Zod will immediately report an error rather than silently ignoring it.

### Validation Process

```typescript
// src/config/validation.ts (simplified)

export function validateConfigObject(raw: unknown) {
  // 1. First check for legacy configuration (e.g., `whatsapp` → `channels.whatsapp`)
  const legacyIssues = findLegacyConfigIssues(raw);
  if (legacyIssues.length > 0) return { ok: false, issues: legacyIssues };

  // 2. Zod Schema validation
  const validated = OpenClawSchema.safeParse(raw);
  if (!validated.success) return { ok: false, issues: validated.error.issues };

  // 3. Semantic validation: Agent directories cannot be duplicated
  const duplicates = findDuplicateAgentDirs(validated.data);
  if (duplicates.length > 0) return { ok: false, issues: [...] };

  // 4. Semantic validation: Avatar paths must be within workspace
  const avatarIssues = validateIdentityAvatar(validated.data);
  if (avatarIssues.length > 0) return { ok: false, issues: avatarIssues };

  // 5. Apply defaults after passing
  return { ok: true, config: applyDefaults(validated.data) };
}
```

Validation is multi-layered: Zod handles structural validation (types, ranges, required fields), while custom logic handles semantic validation (business rules, cross-field consistency).

***

## 31.1.4 Configuration IO (`src/config/io.ts`)

### Loading Pipeline

`loadConfig` is the entry point for the entire configuration system—it orchestrates the complete pipeline from disk reading to final output:

```typescript
// src/config/io.ts (simplified)

function loadConfig(): OpenClawConfig {
  // ① Read raw JSON5 file
  const raw = fs.readFileSync(configPath, "utf-8");
  const parsed = JSON5.parse(raw);

  // ② Parse $include directives (configuration file splitting and combining)
  const resolved = resolveConfigIncludes(parsed, configPath);

  // ③ Apply config.env to process.env
  applyConfigEnv(resolved, process.env);

  // ④ Replace ${VAR} environment variable references
  const substituted = resolveConfigEnvVars(resolved, process.env);

  // ⑤ Check for common typos
  warnOnConfigMiskeys(substituted);

  // ⑥ Check for duplicate Agent directories
  findDuplicateAgentDirs(substituted);

  // ⑦ Zod Schema validation + plugin validation
  const validated = validateConfigObjectWithPlugins(substituted);

  // ⑧ Version warning (configuration from newer version)
  warnIfConfigFromFuture(validated.config);

  // ⑨ Apply multi-layer defaults
  const cfg = applyModelDefaults(
    applyCompactionDefaults(
      applyContextPruningDefaults(
        applyAgentDefaults(
          applySessionDefaults(
            applyLoggingDefaults(
              applyMessageDefaults(validated.config)))))));

  // ⑩ Path normalization
  normalizeConfigPaths(cfg);

  // ⑪ Shell environment variable fallback
  loadShellEnvFallback({ enabled, env, expectedKeys });

  // ⑫ Apply runtime overrides
  return applyConfigOverrides(cfg);
}
```

This 12-step pipeline reflects the complexity of configuration loading—each step solves a specific problem. Let's understand the key steps one by one.

### $include Directive

OpenClaw supports configuration file splitting. A large configuration can be split into multiple files:

```json5
// ~/.openclaw/openclaw.json
{
  "$include": ["./channels.json", "./agents.json"],
  "gateway": { "port": 18789 }
}
```

`resolveConfigIncludes` executes after JSON5 parsing but before environment variable substitution, recursively merging all files referenced by `$include`.

### Configuration Caching

Frequently reading configuration files (especially in high-concurrency scenarios) can become a performance bottleneck. OpenClaw has a built-in configuration caching mechanism:

```typescript
// src/config/io.ts

const DEFAULT_CONFIG_CACHE_MS = 200;  // 200ms cache window

export function loadConfig(): OpenClawConfig {
  const now = Date.now();
  if (shouldUseConfigCache(process.env)) {
    if (cached && cached.configPath === configPath && cached.expiresAt > now) {
      return cached.config;  // Cache hit
    }
  }
  const config = io.loadConfig();
  configCache = { configPath, expiresAt: now + cacheMs, config };
  return config;
}
```

The default cache window is 200ms—within this time window, multiple `loadConfig()` calls only read the disk once. The cache duration can be adjusted via the `OPENCLAW_CONFIG_CACHE_MS` environment variable, and setting it to `0` disables caching.

### Atomic Write

Configuration file writes use the classic "write temporary file → atomic rename" strategy:

```typescript
// src/config/io.ts (simplified)

async function writeConfigFile(cfg: OpenClawConfig) {
  // 1. Validate
  validateConfigObjectWithPlugins(cfg);

  // 2. Create directory (permissions 700: owner read/write/execute only)
  await fs.mkdir(dir, { recursive: true, mode: 0o700 });

  // 3. Write temporary file (permissions 600: owner read/write only)
  const tmp = path.join(dir, `${basename}.${process.pid}.${randomUUID()}.tmp`);
  await fs.writeFile(tmp, json, { encoding: "utf-8", mode: 0o600 });

  // 4. Rotate backups (keep at most 5 copies)
  await rotateConfigBackups(configPath);

  // 5. Atomic rename (POSIX) or copy+unlink (Windows)
  await fs.rename(tmp, configPath);
}
```

Three security measures in the write process are worth noting:

1. **File Permissions**: Directory `0o700`, file `0o600`—only the owner can access, preventing other users from reading configurations containing API Keys.
2. **Backup Rotation**: Before each write, save up to 5 historical backups (`openclaw.json.bak`, `openclaw.json.bak.1` ... `openclaw.json.bak.4`), making it easy to recover from accidental overwrites.
3. **Atomic Rename**: Write to a temporary file first, then rename, avoiding configuration file corruption if the process crashes during writing. On Windows, if `rename` fails (permission issues), it falls back to `copyFile` + `chmod`.

***

## 31.1.5 Configuration Path Resolution (`src/config/config-paths.ts`)

### Dot-Notation Path System

OpenClaw's configuration paths use dot-separated path expressions to locate nested values—similar to JavaScript property access chains:

```typescript
// src/config/config-paths.ts

export function parseConfigPath(raw: string): { ok: boolean; path?: string[] } {
  const parts = raw.trim().split(".").map(p => p.trim());
  // Safety check: block __proto__, prototype, constructor
  if (parts.some(part => BLOCKED_KEYS.has(part))) {
    return { ok: false, error: "Invalid path segment." };
  }
  return { ok: true, path: parts };
}
```

Path resolution supports three operations:

```typescript
// Read
getConfigValueAtPath(config, ["agents", "defaults", "model", "primary"]);
// → config.agents.defaults.model.primary

// Set (automatically create intermediate nodes)
setConfigValueAtPath(config, ["hooks", "internal", "enabled"], true);
// → config.hooks.internal.enabled = true

// Delete (automatically clean up empty parent nodes)
unsetConfigValueAtPath(config, ["hooks", "internal", "entries", "command-logger"]);
// → After deletion, if entries is an empty object, delete it too
```

> **Sidebar**: `__proto__`, `prototype`, and `constructor` are JavaScript prototype chain properties. If these paths are not blocked, attackers can conduct **Prototype Pollution attacks** by constructing malicious configuration paths (e.g., `__proto__.polluted`)—injecting malicious properties into all JavaScript objects. OpenClaw defends against such attacks by explicitly blocking these keywords.

### Version Stamping

Each time the configuration is written, a version stamp is automatically added:

```typescript
function stampConfigVersion(cfg: OpenClawConfig): OpenClawConfig {
  return {
    ...cfg,
    meta: {
      ...cfg.meta,
      lastTouchedVersion: VERSION,   // Current OpenClaw version
      lastTouchedAt: new Date().toISOString(),  // Write time
    },
  };
}
```

When loading, this stamp is checked—if the configuration was written by a newer version of OpenClaw, a warning is issued. This is useful in downgrade scenarios: users might accidentally modify the configuration with a newer version and then switch back to an older version to run, and the stamp warning can help diagnose potential compatibility issues.

***

## Summary of This Section

1. **Configuration files** use JSON5 format, located by default at `~/.openclaw/openclaw.json`, supporting environment variable overrides and backward compatibility with multiple historical paths.
2. **Schema system** is driven by Zod, providing compile-time type inference and runtime data validation, while generating JSON Schema for Web UI use.
3. **Loading pipeline** includes 12 steps: JSON5 parsing → $include merging → environment variable injection → ${VAR} substitution → validation → default value filling → path normalization → runtime overrides.
4. **Security measures** permeate the entire system: file permissions (600/700), atomic writes, backup rotation, prototype pollution protection, path traversal detection.
5. **Configuration caching** defaults to a 200ms window, avoiding disk IO overhead from high-frequency reads.
