> 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/ch45-risks-and-lessons/45.2-risk-and-improvement-list.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 45.2 Risk and Improvement List

> **Generated by**: Claude Opus 5 (claude-opus-5\[1m]) **Token usage**: Input \~198,000 tokens, Output \~11,000 tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

The previous section covered what's worth copying. This one covers **what not to copy blindly**.

A book that only lists strengths is marketing. Any 500,000-line system has debts and pays costs for its trade-offs, and seeing them clearly is more valuable than memorizing ten best practices — because **every risk here is the invoice for some "advantage."**

Three tiers by severity. All line numbers refer to `v2026.3.8-170-g665f67726`.

## 45.2.1 Verified Defect

### systemd service installation ignores the unit-name override

**Location**: `src/daemon/systemd.ts:484` (install), `:528` (uninstall)

**Symptom**: on Linux, `openclaw node install` writes the unit file **correctly** to `~/.config/systemd/user/openclaw-node.service` — but then enables and restarts `openclaw-gateway.service`. The node service is never actually enabled.

Uninstall is worse: `openclaw node uninstall` runs `disable --now openclaw-gateway.service`, so **uninstalling the node stops the gateway**, and only then removes the node's unit file.

**Root cause**: `resolveSystemdServiceName(env)` correctly handles the `OPENCLAW_SYSTEMD_UNIT` override environment variable, and `resolveSystemdUnitPath` uses it (so the file path is right). But install and uninstall both call `resolveGatewaySystemdServiceName(env.OPENCLAW_PROFILE)` directly, **bypassing the override**:

```ts
// systemd.ts:484 (one copy each in install and uninstall)
const serviceName = resolveGatewaySystemdServiceName(env.OPENCLAW_PROFILE);
const unitName = `${serviceName}.service`;
```

**Confirmed as an oversight, not intent**: three other sites in the same file — `:549` (service action), `:593` (isEnabled), `:617` (readRuntime) — all correctly use `resolveSystemdServiceName(env)`. macOS (`launchd.ts:405` uses `resolveLaunchAgentLabel` throughout) and Windows (`schtasks.ts:242` uses `resolveTaskName`) don't have the problem.

**Why tests missed it**: the existing test (`systemd.test.ts:384-404`) covers the override only for unit **path** resolution, not for the **unitName** used inside install/uninstall.

**The lesson matters more than the bug.** It's the flip side of a pattern §45.1 didn't list: `node-service.ts` is only 66 lines total, reusing all three platform installers by injecting six override environment variables — extreme DRY. The cost is that **the override contract has no type-system enforcement**; it depends on every call site voluntarily honoring it. One omission produces a "uninstalling A stops B" class of behavioral error.

> **Transferable judgment**: whenever you see *parameterize with environment variables or string keys to reuse a large block of code*, that's the shape to focus on in review. The type system can't help here — only enumerating call sites and writing targeted tests can.

> See Appendix F.

## 45.2.2 Architecture-Level Risks

Nothing in this tier is a bug. They're **inherent costs of architectural choices** — they won't be "fixed," only managed.

### 1. The global side effect of `process.chdir()`

**Location**: `src/agents/pi-embedded-runner/run/attempt.ts:774`, `compact.ts:377` (restored at `:2094` and `:900`)

An agent run calls `process.chdir(effectiveWorkspace)` to switch into the workspace, then switches back. The problem: **`process.chdir()` changes the current directory of the entire Gateway process.**

And that process also runs channel connections, timers, the HTTP server, and other agents. During that window, **any code depending on relative paths may read the wrong directory.**

**Why write it this way?** Because the pi engine and its tools (file I/O, shell execution) all use the process cwd as their base. Fixing it properly means making every tool accept an explicit working directory — which means changing upstream, violating the *embed, don't fork* principle from §44.1.

This is Theme Two's invoice: **external adaptation cannot cover an upstream's process-level assumptions.**

### 2. Monolithic single failure domain

The Gateway is one process, and it owns everything. If it dies, everything stops.

Worse, **all in-memory state is lost**:

* `pendingInvokes` (in-flight reverse calls to nodes)
* the followup queue (queued user messages)
* debounce buffers (fragment messages mid-merge)

After a restart these are gone, and the user experiences "the message I just sent vanished."

**The official answer is a profile-isolated rescue instance** — run a second independent Gateway via `--profile` as a rescue channel. That's mitigation, not a fix: it lets you connect and inspect when the main instance dies, but the lost state is still lost.

> See Chapter 11, Chapter 13.

### 3. One plugin means total compromise

§44.4 established that plugins are defined as part of the TCB. Concretely:

* A plugin can write **arbitrary config**, including `plugins.allow` itself — **one plugin can add other plugins to the allowlist**;
* A plugin can fetch **arbitrary provider credentials**;
* `plugins.allow` defaults to empty (i.e. unrestricted), backed only by a startup warning.

This isn't a vulnerability (SECURITY.md is explicit), but it's a fact deployers must know: **installing a plugin hands over the whole machine.**

> See Chapter 21, Chapter 32.

## 45.2.3 Correctness and Maintainability Risks

This tier is "works today, but leaking continuously."

### Order coupling in the streamFn chain

The *embed, don't fork* approach from §44.1 is implemented by wrapping pi's streaming function in layers. **Order changes behavior** (A-wrapping-B ≠ B-wrapping-A), but **nothing prevents inserting a layer in the wrong place**. When adding a layer, the correct position can only be determined by reading comments and running tests.

The assembly site is `src/agents/pi-embedded-runner/run/attempt.ts` — **2,096 lines**.

### Dual write paths for auth state

Auth-profile health state has two write paths. When multiple Gateway instances share one `agentDir`, there's a **lost-update window** — two processes updating account state, last writer wins.

Single-machine single-instance is the recommended deployment (§44.4's trust model), so this doesn't trigger under recommended usage. But `--profile` multi-instance plus a shared agentDir is a legal configuration.

### Races between pi compaction and timeout interruption

What happens when the user aborts while context compaction is in progress? This boundary has been leaking continuously, with patches accumulating case by case — each newly discovered race gets its own patch, with no unified state machine to fix it at the root.

This is another cost of *embed, don't fork*: compaction logic lives partly inside pi and partly in OpenClaw's external layer, and **the interrupt signal has to cross that boundary** where the two state machines don't line up.

### The command authorization function is a high-risk area for permission bugs

`resolveCommandAuthorization` (`src/auto-reply/command-auth.ts:258`, in a 389-line file) interleaves two `allowFrom` systems and is called from three places: Discord, Telegram, and the generic reply path.

**Places where multiple rule systems converge in one function are a classic breeding ground for permission bugs** — each system is correct in isolation, but some branch of the combination misses a check. Audits should look at functions of this shape first.

### Dock table and plugin written twice, synced only by comment

§44.3 listed "channel dock table vs. plugin runtime light/heavy separation" as a strength. The cost lands here: **the two must stay consistent, but the synchronization mechanism is a comment** — no build-time self-check (contrast case 4 with the command declaration table, which does have one).

The same theme is executed inconsistently within the project, which is itself worth noting.

### Group policy constrains different dimensions on different channels

`dmPolicy` × `groupPolicy` × pairing — three dimensions that constrain somewhat different things on different platforms (because the platform concepts themselves differ: Discord has servers/channels/threads, Telegram has groups/supergroups/topics).

**The result is frequent misconfiguration.** Users assume setting a policy makes them safe, when its semantics differ on another channel.

### Daily memory files grow without bound

`memory/YYYY-MM-DD.md` is one file per day with **no archival or compaction mechanism**. Two years is 700+ files. Retrieval performance and token cost both degrade slowly.

### Combinatorial explosion in authentication branches

`src/gateway/server/ws-connection/message-handler.ts` — **1,242 lines**.

The reason is that every authentication combination converges here: auth mode × surface × device identity × local/remote. This is the direct invoice for §44.1's *converge the network surface* — **entry-point count driven to 1, branches per entry point driven up.**

The real hazard is the growth mode: **each new surface expands the audit surface multiplicatively**, not additively.

***

## How to Use This List

Three suggestions:

**First, look for the advantage–invoice pairing.** Nearly every risk here traces back to a theme in Chapter 44:

* `process.chdir` ← Theme Two (embed, don't fork)
* Monolithic failure domain ← Theme One (everything converges on one Gateway)
* Total plugin compromise ← Theme Six (the honest cost of plugins-as-TCB)
* message-handler's 1,242 lines ← Theme One (entry convergence)

**There are no free architectural decisions.** Copy a pattern and you take on its invoice too.

**Second, note which risks don't trigger under recommended usage.** Auth dual-writes and multi-instance contention only appear when you deviate from the recommended deployment. That's not an excuse — but it tells you **this project's reliability rests on the premise of deploying as documented**, and that premise itself needs to be communicated clearly to users.

**Third, watch the "contract by discipline" reuse points.** The systemd bug, the streamFn ordering, the dock double-write — all three share the shape *correctness depends on developer diligence and the type system can't help*. That's where code review has the highest return on investment.

***

## Section Summary

1. **One verified defect**: `systemd.ts:484/528` ignores the unit-name override, so on Linux `node install` enables the wrong service and **`node uninstall` stops the gateway**; macOS/Windows are unaffected and tests happened to miss it. The lesson is the hidden cost of extreme DRY — **override contracts have no type-system enforcement**.
2. **Three architecture-level risks**: `process.chdir()`'s process-wide side effect, the monolithic failure domain (in-memory state lost on restart), and total compromise from one plugin (which can write `plugins.allow` itself).
3. **Seven correctness/maintainability risks**: streamFn order coupling (2,096-line assembly file), auth-state dual writes, compaction/interruption races, a command-auth function interleaving two rule systems, dock double-write synced only by comment, group-policy semantics differing across channels, unbounded daily memory growth, and combinatorial authentication branches (`message-handler.ts` at 1,242 lines).
4. **Every risk is the invoice for one of Chapter 44's advantages** — copying a pattern means taking on its invoice; "contract by discipline" reuse points offer the highest review ROI.
