> 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.6-source-deep-dive-read-pipeline-and-write-back.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 31.6 Source Deep Dive: The Five-Stage Read Pipeline and Write-Back Restoration

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

***

§31.1–31.5 covered config loading, the type system, hot reload, migration, and environment variables. This section goes into the source for two things:

1. **What actually happens when config is read once** (five stages);
2. **Why writing is much harder than reading** (the implementation of §45.1's sixth pattern).

## 31.6.1 Prelude: Where Config Lives Is Itself a Migration History

`src/config/paths.ts:20` hard-codes three generations of legacy directory names:

```ts
// Support historical (and occasionally misspelled) legacy state dirs.
const LEGACY_STATE_DIRNAMES = [".clawdbot", ".moldbot", ".moltbot"] as const;
const NEW_STATE_DIRNAME = ".openclaw";
const CONFIG_FILENAME = "openclaw.json";
const LEGACY_CONFIG_FILENAMES = ["clawdbot.json", "moldbot.json", "moltbot.json"] as const;
```

Note `.moldbot` — **a fossil left by a typo**, which still has to be supported because users really do have directories named that.

`resolveStateDir` (`paths.ts:60`) searches in this order:

```
OPENCLAW_STATE_DIR explicit override
   ↓ absent
new directory .openclaw exists → use it
   ↓ absent
a legacy directory exists → keep using it (awaiting doctor migration)
   ↓ none
the new directory
```

Environment variables also retain dual `CLAWDBOT_*` prefix compatibility.

> **A rename isn't just swapping a string** — it's smoothly converging three generations of users' state directories, config filenames, and environment variable prefixes. That's why doctor contains so many legacy migration modules (§43.1.2's point that "code taking care of legacy users is a maturity marker").

There's also an `OPENCLAW_NIX_MODE` check (`paths.ts:14`): **under Nix, config is treated as externally managed and read-only**, and every automatic installation flow yields to it. That switch runs through both doctor and onboarding.

## 31.6.2 The Read Path: Five Stages

`~/.openclaw/openclaw.json` is **named json but is actually JSON5** (allowing comments and trailing commas).

`createConfigIO` (`src/config/io.ts:699`) is the config IO factory, with `fs` / `env` / `homedir` / `json5` / `logger` **all injectable** — the 50-plus test files under `src/config/` essentially all use this factory to construct config environments in memory.

Reading config once passes through five stages (`io.ts:708`'s `loadConfig`):

```
① JSON5 parse
     ↓
② $include expansion
     supports 10 levels of nesting, cycle detection, and a path-escape guard
     (readConfigIncludeFileWithGuards)
     ↓
③ ${ENV} substitution
     writes the config.env section into process.env first, then substitutes
     missing variables are collected as warnings rather than thrown
     ↓
④ Validation (§31.6.3)
     ↓
⑤ Default folding
```

Stage ③'s "missing variables warn rather than throw" has its reason in the comment (`io.ts:681`):

> so non-critical config sections with unset vars don't crash the gateway

A user who hasn't configured a Discord token shouldn't be unable to start the whole gateway because `${DISCORD_TOKEN}` doesn't resolve.

### Stage ⑤: eight levels of nested default folding

```ts
// src/config/io.ts:773
const cfg = applyTalkConfigNormalization(
  applyModelDefaults(
    applyCompactionDefaults(
      applyContextPruningDefaults(
        applyAgentDefaults(
          applySessionDefaults(applyLoggingDefaults(applyMessageDefaults(validated.config))),
        ),
      ),
    ),
  ),
);
```

> **This is a piece of "visible duplication"** (§45.2). Similar but not identical combinations appear at least three times across the read path and the snapshot path, and **order is semantics — yet there's no single pipeline definition.**
>
> The right fix would be extracting a `DEFAULT_APPLIERS` array and reducing over it — but only after confirming whether the ordering differences among the three sites are intentional or historical.

### Fail closed is the security floor

On validation failure it constructs an error with `code = "INVALID_CONFIG"` and **rethrows it directly** from the catch block (`io.ts:850`). The comment states the motive:

> Fail closed so invalid configs cannot silently fall back to permissive defaults.

**A broken config must never quietly fall back to permissive defaults.**

> In a system that can execute shell commands, this is the security floor. Picture it: the user's config has a strict `allowFrom` list, a syntax error somewhere makes parsing fail, and if the system "helpfully" falls back to defaults — the default might be allow-everyone.
>
> The counterpart is §33.4.4's config-guard allowlist, ensuring fail-closed doesn't turn into "even the repair tool won't start."

## 31.6.3 Validation: Zod strict Plus Three Additional Layers

The schema is assembled from 18 `zod-schema.*.ts` files (`zod-schema.ts` at 910 lines is the root), and **nearly every object is `.strict()`** — unknown keys error out rather than being silently swallowed.

**That's the first line of defense against typos.** Write `channels.telegram.dmPolicyy` and you find out immediately, instead of wondering why your config had no effect.

The **ordering** in `validateConfigObjectRaw` (`src/config/validation.ts:229`) is worth noting:

```ts
export function validateConfigObjectRaw(raw: unknown) {
  const legacyIssues = findLegacyConfigIssues(raw);
  if (legacyIssues.length > 0) {
    return { ok: false, issues: legacyIssues.map(...) };
  }
  const validated = OpenClawSchema.safeParse(raw);
  if (!validated.success) {
    return { ok: false, issues: validated.error.issues.map(mapZodIssueToConfigIssue) };
  }
  const duplicates = findDuplicateAgentDirs(validated.data);
  ...
  const avatarIssues = validateIdentityAvatar(validated.data);
  ...
}
```

**Legacy detection comes before Zod.**

Why? A legacy key like `routing.allowFrom` entering Zod directly produces an unhelpful "unrecognized key." Matching it first against the rules table (`legacy.rules.ts`) yields **targeted information: what the key was renamed to, and to run doctor to migrate.**

> **The quality of an error message depends on which layer catches it.** The same input caught one layer earlier gives useful guidance; caught later it gives a generic error.

### Three semantic validations after Zod

Things Zod can't express:

| Validation                                              | Defends against                                                   |
| ------------------------------------------------------- | ----------------------------------------------------------------- |
| Agent directory conflicts (`findDuplicateAgentDirs`)    | Two agents sharing a directory and overwriting each other's state |
| Avatar paths must stay inside the workspace             | **Path escape**                                                   |
| Gateway must bind loopback under Tailscale serve/funnel | **Exposing an unencrypted port to the public internet**           |

The third is a classic cross-field constraint: `gateway.bind` and `tailscale.mode` are each individually legal, and only the combination is dangerous.

### Plugin config sections use JSON Schema, not Zod

One ring further out is `validateConfigObjectWithPlugins` (`validation.ts:308`): plugin config sections are validated with **the plugin's own JSON Schema** — **not Zod, because a plugin manifest is data, not code** (§21.5.2).

It also distinguishes errors from warnings: **leftover config for a removed plugin warns rather than blocking**:

> Keep gateway startup resilient when plugins are removed/renamed across upgrades. (`validation.ts:498`)

A user who uninstalled a plugin but left its config section shouldn't be unable to start the gateway.

### Error messages get their own engineering

`mapZodIssueToConfigIssue` **recursively collects the list of allowed values out of Zod's union errors** and folds it into the message (`validation.ts:43`).

The effect: a typo like `channels.telegram.dmPolicy: "alow"` produces **"allowed values: open, allowlist, pairing, disabled"** instead of a page of expanded union.

## 31.6.4 The Write Path: Much Harder Than Reading

The core problem `writeConfigFile` (`io.ts:1475`) solves:

> **The config in runtime memory is "resolved"** (env substituted, SecretRefs resolved, defaults merged) — **and writing it back must restore it to what the user hand-wrote.**

Without handling that, one `openclaw config set` turns a user's file into:

```json5
// what the user originally wrote
{ "openai": { "apiKey": "${OPENAI_KEY}" } }

// after a naive write-back
{ "openai": { "apiKey": "sk-proj-abc123..." } }   // a plaintext key, now in git
```

Plus hundreds of lines of runtime defaults baked in and every comment gone.

### Technique one: merge-patch projection

The gateway runtime holds **two snapshots** (§32.6.3's dual snapshot):

```
resolved runtime snapshot (env substituted, SecretRefs resolved, defaults merged)
source snapshot (what the user hand-wrote)
```

The write flow:

```
① createMergePatch(runtime snapshot, new config)   ← compute only the paths that actually changed
② apply that patch onto the source snapshot
③ write to file
```

**Only genuinely changed paths are written**, leaving `${VAR}` references and SecretRef originals intact on untouched paths.

### Technique two: env-ref restoration

Reading records each `${VAR}`'s location and substituted value (`collectEnvRefPaths`); writing **restores the plaintext back to `${VAR}` on unchanged paths**.

This complements merge-patch: if some path is judged "changed" but its value is equivalent, restoration still prevents leaking plaintext.

### Technique three: auditing and safety rails

| Mechanism                      | Purpose                                                                                                 |
| ------------------------------ | ------------------------------------------------------------------------------------------------------- |
| `appendConfigWriteAuditRecord` | Records suspicious writes (an entire channels section being cleared, say) to an audit log               |
| `isBlockedObjectKey`           | `config set/unset` path segments reject `__proto__` / `constructor`, **preventing prototype pollution** |

The second matters: input like `openclaw config set __proto__.isAdmin true`, unblocked, can pollute the prototype of every object in JS.

### A detail corrected by an issue

Path addressing for `config set/get` lives in `src/cli/config-cli.ts`: a hand-written `parsePath` supporting dots, `[0]` indices, and `\.` escapes; values are first parsed as JSON5 and fall back to raw strings (`--strict-json` disables the fallback).

```ts
// src/cli/config-cli.ts:440
// Use snapshot.resolved (config after $include and ${ENV} resolution, but BEFORE
// runtime defaults) instead of snapshot.config (runtime-merged with defaults).
// This prevents runtime defaults from leaking into the written config file (issue #6070)
const next = structuredClone(snapshot.resolved) as Record<string, unknown>;
```

**`config set`'s base is the "resolved but pre-defaults" intermediate state.**

Otherwise changing one key bakes hundreds of lines of runtime defaults into the user's file — which is exactly what issue #6070 was.

`config get` **runs `redactConfigObject` before output**, so tokens and apiKeys don't appear bare in the terminal.

## 31.6.5 The Runtime Snapshot: An In-Process "Config Bus"

Short-lived CLI processes can read from disk on every `loadConfig()`. **A resident gateway can't** — it needs a stable in-memory view, refreshed atomically after programmatic modification.

`io.ts` solves it with a module-level singleton:

```ts
// src/config/io.ts:1435
export function loadConfig(): OpenClawConfig {
  if (runtimeConfigSnapshot) {
    return runtimeConfigSnapshot;
  }
  const io = createConfigIO();
  ...
  if (shouldUseConfigCache(process.env)) {
    const cached = configCache;
    if (cached && cached.configPath === configPath && cached.expiresAt > now) {
      return cached.config;
    }
  }
  const config = io.loadConfig();
  ...
}
```

**Three levels of retrieval**:

```
① the gateway has set a runtime snapshot → return it directly (zero IO)
② a TTL'd in-process cache
③ the full disk read pipeline
```

### The write side is coupled to the snapshot

After `writeConfigFile` lands on disk it first tries `runtimeConfigSnapshotRefreshHandler.refresh()` — a **dedicated refresh hook registered by the gateway** guaranteeing SecretRefs are resolved before the snapshot swaps:

> so concurrent readers do not observe unresolved SecretRefs mid-refresh (`io.ts:1493`)

**A failed refresh throws `ConfigRuntimeRefreshError`** — config written but not yet effective, **a state surfaced explicitly to the caller rather than swallowed**.

> Good error design. "Written but not effective" is a real intermediate state, and folding it into either success or failure misleads the caller (compare §20.6.3's `sendMayHaveLanded` — the same instinct).

Ordinary CLI processes without a snapshot **clear the cache instead**, so subsequent reads fall back to disk — ensuring **hand edits to `openclaw.json` are always visible**.

## 31.6.6 Migration Is Table-Driven

| File                                     | Responsibility                                                        |
| ---------------------------------------- | --------------------------------------------------------------------- |
| `legacy.rules.ts`                        | Declares which legacy keys count and what error to report             |
| `legacy.migrations.ts`                   | Declares how to rewrite them                                          |
| `applyLegacyMigrations` (`legacy.ts:42`) | Executes them in order, accumulating a **human-readable change list** |

**The execution entry point isn't on the load path — it's in doctor** (`migrateLegacyConfig`, `legacy-migrate.ts:5`): after migrating it **immediately re-validates in full**, refusing to write and prompting for manual repair if validation fails.

**The load path only detects and reports; it never modifies files.**

> **"Diagnose on read, confirm on write" moves the risk of silent data mutation off the hot path.**
>
> Worth remembering: automatic migration sounds considerate, but if it happens on every read, one bug silently corrupts every user's config file. Confining it to a user-invoked command with a confirmation step and a `.bak` backup keeps the risk manageable.

Version compatibility also has a soft mechanism: config carries a `meta.lastTouchedVersion` stamp, and `warnIfConfigFromFuture` detects "this config came from a newer version than the current CLI" and warns (`io.ts:593`) — preventing a downgraded runtime from silently dropping fields only the newer version understands.

## 31.6.7 A Counterintuitive Hazard: Reading Writes Files

§45.2 didn't detail this one.

`loadConfig` has **more implicit side effects than you'd expect**:

* Reading config **writes `process.env`** (the `config.env` section plus shell env fallback);
* It may even trigger an **asynchronous config write** — auto-generating `ownerDisplaySecret` and persisting it fire-and-forget (`io.ts:821`).

> **"Reading writes files" is counterintuitive.**
>
> There's in-flight deduplication and warning backstops, but a race window remains when several processes read for the first time simultaneously — currently mitigated by atomic writes at the filesystem layer rather than an explicit lock.
>
> This "lazy initialization on the read path" pattern shows up in many projects, usually originating as "convenient to generate it here." The problem isn't that it breaks today — it's that **it makes `loadConfig`, a function that looks pure, no longer safe to call casually.**

***

## Section Summary

1. **The config path is itself a migration history**: three generations of legacy directory names hard-coded (including a typo'd `.moldbot`), searched as "explicit env > new dir exists > legacy dir exists (awaiting doctor) > new dir"; under `OPENCLAW_NIX_MODE` config is treated as externally managed and read-only.
2. **Five read stages**: JSON5 parse → `$include` expansion (10 levels + cycle detection + path-escape guard) → `${ENV}` substitution (**missing variables warn rather than crash**) → validation → default folding (eight nested levels, a piece of visible duplication).
3. **Fail closed is the security floor**: `INVALID_CONFIG` rethrows directly, **never quietly falling back to permissive defaults** — in a shell-capable system that could mean an allowlist becoming allow-everyone.
4. **Validation order puts legacy detection before Zod** — otherwise a legacy key only produces "unrecognized key" instead of "here's what it was renamed to." **The quality of an error message depends on which layer catches it.**
5. **Three semantic validations after Zod**: agent directory conflicts, avatar paths confined to the workspace, and **loopback binding required under Tailscale modes** (a cross-field constraint); plugin sections validate with JSON Schema and **leftover config from removed plugins only warns**.
6. **Three write techniques**: **merge-patch projection** (write only genuinely changed paths) + **env-ref restoration** (restore plaintext back to `${VAR}`) + auditing and safety rails (prototype key blocklist).
7. **`config set`'s base is the resolved-but-pre-defaults intermediate state** (issue #6070) — otherwise changing one key bakes hundreds of default lines into the user's file; `config get` redacts before output.
8. **Three-level runtime snapshot retrieval** (snapshot → TTL cache → disk); a failed refresh throws `ConfigRuntimeRefreshError` — **"written but not effective" is an intermediate state that must be modeled**.
9. **Migration is table-driven and executed only by doctor** — **"diagnose on read, confirm on write" moves silent data mutation off the hot path**.
10. **A counterintuitive hazard**: `loadConfig` writes `process.env` and may even persist fire-and-forget — **"reading writes files" makes this function no longer safe to call casually.**
