OpenClaw Optimization Guide
Make your OpenClaw AI agent faster, smarter, cheaper, and actually safe to run in production.

July 2026 sweep. Stable baseline: OpenClaw 2026.6.11 (released 2026-06-30). This refresh covers the 2026.6.8–2026.6.11 trains — automatic fast mode, working failover, per-agent cost visibility, prompt-cache retention, cron fallback controls, and channel-delivery self-recovery — and corrects the previous revision, which referenced a “2026.6.4” release and several config keys that were never shipped. See the correction note in Part 33.
By Terp — Terp AI Labs
Start With The July 2026 Reality Check
The June trains (2026.6.8 → 2026.6.11) were about making OpenClaw dependable. If you last read this guide in mid-June, these are the new rules:
- Claude subscription-era advice is dead. Anthropic’s April 4 policy change broke the old “Claude Pro/Max covers OpenClaw” path. Treat Claude as paid API / Bedrock / provider-routed usage unless your own install proves otherwise.
- Cost visibility is per-agent now.
openclaw gateway usage-cost --agent <id> (or --all) shows spend per configured agent; cron it daily and treat spend jumps as context regressions. (There is no per-agent budget-cap config key — an earlier revision of this guide claimed one in error.)
- Failover actually fires. Provider overloads are classified correctly, usage-limit responses route to fallbacks, and individual cron jobs can carry their own
--fallbacks list (or run strict with --fallbacks ""). None of it helps without at least two configured lanes.
- Fast mode is automatic.
/fast auto (2026.6.10) runs short conversational turns in the provider’s fast lane and returns to normal mode for longer work, with correct status through retries and fallback switches.
- Long sessions got cheaper. Tool-heavy sessions now retain prompt-cache savings as results accumulate (2026.6.11) — one more reason to keep sessions long-lived and compaction healthy instead of resetting constantly.
- Stuck channels self-recover. Telegram/WhatsApp queues that wedge after a crash or long-running task resume automatically in 2026.6.11. “Restart the gateway” should leave your runbooks.
Read Part 33 — June 2026 Field Guide first if you want the latest tricks before the deep dives.
The Harness Thesis
Most agent capability comes from the harness, not the weights.
The exact percentage is rhetoric. The operator lesson is concrete: model swaps help, but the big wins come from context budgets, memory discipline, tool permissions, flow control, provider routing, hooks, and verification loops.
flowchart LR
subgraph Model["The Model (weights)"]
M[Claude Opus 4.7<br/>or your choice]
end
subgraph Harness["The Harness (operator-controlled) — this guide"]
direction TB
Inst[Instructions<br/>SOUL/AGENTS/MEMORY/skills]
Ctx[Context engineering<br/>budgets + progressive disclosure]
Tools[Tools + approvals<br/>semantic categories]
Guard[Guardrails<br/>hooks, Task Brain, redaction]
Mem[Memory layer<br/>memory-core + LightRAG + dreaming]
Orch[Orchestration<br/>5 coordination patterns]
end
Model -.-> Harness
Harness -.-> Results[Production results]
You usually cannot change the weights. You can change everything else: context, memory, tools, approvals, verification, cost controls, and orchestration. The rest of this guide is that operator-controlled layer.
Jump straight to the payoff
File Hierarchy At A Glance
OpenClaw’s file layout maps 1:1 to Karpathy’s three-tier LLM Wiki pattern published April 10, 2026. If you only remember one diagram from this guide, make it this one:
flowchart TB
subgraph Raw["Raw sources — immutable, agent read-only"]
Vault["vault/*"]
Daily["memory/YYYY-MM-DD.md"]
end
subgraph Curated["Curated summaries — injected on every message"]
Soul["SOUL.md<br/>identity"]
Agents["AGENTS.md<br/>operational rules"]
Mem["MEMORY.md<br/>durable facts"]
Dreams["DREAMS.md<br/>reflection diary"]
Skills["skills/*<br/>on-demand playbooks"]
end
subgraph Artifacts["Generated artifacts — one-shot output"]
PRs["PRs / commits"]
Reports["Reports / transcripts"]
end
Raw -. memory_search .-> Agent((Agent))
Curated --> Agent
Agent --> Artifacts
Agent -. Deep-phase promote .-> Mem
Artifacts -. auto-capture .-> Daily
| File |
Purpose |
Size cap |
Written by |
Read when |
| SOUL.md |
Identity, invariants, non-negotiables |
< 1 KB |
Human |
Every message |
| AGENTS.md |
Operational rules, decision trees, tool routing |
< 2 KB |
Human + agent (auditable) |
Every message |
| MEMORY.md |
Durable facts promoted from short-term (pointer index) |
< 3 KB |
Agent via memory promote |
Every message |
| DREAMS.md |
Human-readable reflection diary |
latest N entries |
Built-in Dreaming |
Every message |
| skills/ |
Named playbooks |
per-skill small |
Human + SkillClaw |
On activation |
| vault/ |
Raw source notes, transcripts, links |
unbounded |
Auto-capture + humans |
On memory_search |
| memory/YYYY-MM-DD.md |
Daily short-term rollup |
rolling |
Auto-capture |
On memory_search |
Full reasoning and update rules in Part 31 — The LLM Wiki Pattern In OpenClaw.
Who This Is For
Start Here (In This Order)
- Part 25 — Architecture Overview — 15-minute primer on what OpenClaw actually is under the hood (gateway, Task Brain, memory layer, skills, surfaces).
- Part 14 — Quick Checklist — 30-minute setup checklist covering the 80/20.
- Part 17 — The One-Shot Prompt — copy-paste prompt that automates the whole setup.
- Part 27 — Gotchas & FAQ — keep this open while you work. Half your questions are here.
What You Get (Numbers From Our Production Deployment)
| Metric |
Before |
After |
Source |
| Context file size (SOUL + AGENTS + MEMORY) |
~15 KB |
~5 KB |
Part 1 |
| Memory search latency |
2–5s (cloud) |
<100ms (local) |
Part 4, Part 10 |
| Compaction crash rate |
loops on 16K models |
fixed in 4.15+ |
Part 15 |
| Coding-agent token usage |
baseline |
–60% |
Part 19 — Repowise |
| Sessions before audit trail |
0 surfaces |
all surfaces |
Part 24 — Task Brain |
Full numbers in benchmarks/.
Companion resources shipped with the guide
Alongside the 33 parts themselves, this repo now includes the tooling that turns “I read the guide” into “I can audit and reproduce the results”:
- SCORECARD.md — The OpenClaw Production Readiness Scorecard. 50 items across Speed / Memory / Orchestration / Security / Observability, 2 points each, max 100. Designed to be copy-pasted into your own repo and shared publicly.
- AWESOME.md — A curated, opinionated list of OpenClaw resources: skills worth installing, memory and orchestration tools, observability stacks, research papers, talks, communities, adjacent ecosystems.
- templates/ — A starter kit: tiny SOUL.md / AGENTS.md / MEMORY.md / TOOLS.md templates, a
vault/ skeleton, and an example config that documents both legacy JSON blocks and the newer provider-catalog direction.
- benchmarks/METHODOLOGY.md + benchmarks/harness/ + benchmarks/runs/TEMPLATE.md — A reproducible benchmark methodology (4 pillars, 3 reference environments) plus a contract for submitting your own numbers via PR.
- CODE_OF_CONDUCT.md · SECURITY.md · SUPPORT.md — Community standards so you know how to file issues, report problems, and get help.
- GitHub Pages site — rendered from this repo via MkDocs-material: https://onlyterp.github.io/openclaw-optimization-guide/.
What Changed In This Release (July 2026 Refresh)
- Correction. The June refresh referenced a “2026.6.4 stable” release and config keys (
agents.list[].budget, models.providers.<id>.health, policy check --export, memory promote --dry-run, memory.recall.maxParallel, sandbox.network.allow, /context map --diff, secrets.rotation.maxAgeDays, meetingNotes.retentionDays) that do not exist in any published OpenClaw release. Those sections have been rewritten around shipped features, and the templates have been fixed. Details in the correction note at the top of Part 33.
- Rebaselined on 2026.6.11 stable — the version map now tracks the real June trains: 2026.6.8, 2026.6.9, 2026.6.10, 2026.6.11.
- New Part 33 tips — per-agent cost visibility (
openclaw gateway usage-cost), scheduled policy check --json attestations, working failover + per-cron-job --fallbacks, safe-by-default memory promote / --apply workflow, and automatic fast mode (/fast auto).
- Security guidance updated — secrets redacted from debug output, admin-only HTTP session/model overrides, package-source redirect/lookalike-path hardening, actionable
plugins.allow trust warnings, @owner/<slug> skill verification, and key-free web-search providers staying opt-in.
- Ops quality-of-life — official
openclaw/openclaw Docker Hub mirror, Slack router relay mode for multi-gateway deployments, openclaw agent --message-file, and cron deleteAfterRun transcript cleanup.
Previous Late-May 2026 refresh
- Updated Part 33 field guide — upgrade map from 2026.4.15 through 2026.5.22 stable / 2026.5.24-beta.1: Gateway performance caching, Meeting Notes, the bundled Policy plugin, Codex/MCP scoping, Discord voice, image-quality controls, iMessage approvals, and security hardening.
- Codex guidance — native Codex means canonical
openai/gpt-* model refs; the operational work is MCP projection scoping, codex.defaultToolsApprovalMode, named OAuth profiles, and deny-all tool policy verification.
- Security guidance tightened — skill-file read/executable allowlist compatibility removed, symlinked credential files fail closed, doctor warns on plaintext secret-bearing config, and channel conformance belongs in the Policy plugin.
Earlier refreshes (Task Brain, ClawHub, the v4.0 architecture/migration/glossary primers, and the 2026.4.15 line) are captured in the version tables in Part 25 — Architecture Overview and Part 26 — Migration Guide.
How The Pieces Fit Together
flowchart LR
You[You]
subgraph Surfaces
Canvas[Canvas UI]
CLI[CLI / IDE]
Cron[Cron / ACP]
end
subgraph Gateway["Gateway daemon (Task Brain)"]
Ledger[Task ledger]
Approvals[Semantic approvals]
Auth[Auth / secrets]
end
subgraph Agents
Main[Main agent]
Workers[Sub-agents]
end
subgraph Memory["Memory layer"]
MemCore[memory-core<br/>MEMORY.md + DREAMS.md]
Lance[memory-lancedb<br/>vector search]
Light[LightRAG<br/>graph RAG]
end
subgraph Capabilities
Hub[ClawHub skills]
Hooks[Hooks]
Tools[Tools]
end
You --> Surfaces
Surfaces --> Gateway
Gateway --> Agents
Agents --> Memory
Agents --> Capabilities
Capabilities -. register with .-> Gateway
Memory -. feed .-> Agents
Full breakdown of each block in Part 25 — Architecture Overview.
Navigate By Goal
Not every part applies to every reader. Jump directly to the pillar that matches what you’re trying to do:
Full Table of Contents
🎯 Primers & references
⚡ Speed & context
- Speed — Stop Being Slow — trim context, add fallbacks, reasoning mode,
localModelLean
- Context Engineering — The Discipline — quadratic scaling, pruning, compaction, 5-min cache TTL trap
- Cron Session Bloat — The Hidden Killer — session file accumulation, cleanup
🧠 Memory
4. Memory — Stop Forgetting Everything — 3-tier memory, Ollama, lancedb cloud storage, Copilot embeddings
9. Vault Memory System — folders, MOCs, claim-named notes, wiki-links
10. State-of-the-Art Embeddings — qwen3-embedding, GPU tier, Windows path, Copilot provider
11. Auto-Capture Hook — automatic knowledge extraction after every session
12. Self-Improving System — micro-learning loop, HOT/WARM/COLD tiers
13. Memory Bridge — give Codex / Claude Code access to your vault
22. Built-In Dreaming (memory-core) — official 3-phase consolidation, DREAMS.md, memory-you-can-afford (LightMem + vbfs)
31. The LLM Wiki Pattern In OpenClaw — Karpathy’s three-tier pattern mapped onto SOUL/AGENTS/MEMORY/skills
33. June 2026 Field Guide — per-agent cost visibility, scheduled Policy attestations, working failover + cron fallbacks, memory promotion review, automatic fast mode
🤝 Orchestration & models
5. Orchestration — sub-agents-as-GC, Anthropic’s 5 coordination patterns, CEO/COO/Worker, verification
6. Models — What To Actually Use — provider comparison, pricing, local, localModelLean
7. Web Search — Tavily, Brave, Serper, Gemini grounding
8. One-Shotting Big Tasks — research-first methodology
30. The Ralph Loop In OpenClaw — autonomous while true wrappers, PRD.json, overnight runs
32. Self-Evolving Skills With SkillClaw — skill population evolution, Mem²Evolve
🧩 Knowledge graph & codebase
18. LightRAG — Graph RAG — entities + relationships, Web UI, REST, LangFuse tracing
19. Repowise — Codebase Intelligence — 60% fewer tokens, 4x faster coding agents
21. Real-Time Knowledge Sync — event-driven file watcher, <6s vault → LightRAG sync
🔒 Hardening & security
15. Infrastructure Hardening — compaction crash loops, GPU contention, secrets, gateway crash-loop fix, reserve-token cap, auth hot-reload, approval redaction, parallel OpenClaw with git worktrees
23. ClawHub Skills Marketplace — marketplace, malware, install policy
24. Task Brain Control Plane — unified task ledger, semantic approvals, trust boundaries
29. The Hook Catalog — 8 copy-paste hooks, exit-code semantics, deterministic enforcement
🔭 Observability
20. Agent Observability — LangFuse, reranker, n8n, workflow automation
📖 Reference
25. Architecture Overview (v4.0+) — gateway / agents / memory / skills / surfaces primer
26. Migration Guide — opinionated upgrade paths with rollback
27. Common Gotchas & FAQ — symptom-indexed troubleshooting
28. Glossary & Terminology — every term this guide assumes, on one page
📊 Benchmarks — real numbers from a production system (context savings, search latency, reindex results, SWE-bench rankings)
📁 Example Vault — populated mini-vault showing MOCs, wiki-links, Agent Notes, and .learnings/ after 2 weeks of use
🤝 Contributing — how to propose corrections, new parts, and version-bump PRs
The Problem
If you’re running a stock OpenClaw setup, you’re probably dealing with:
- Freezing and hitting context limits. Bloated workspace files exhaust the context window mid-response.
- Slow responses. 15-20KB+ of context injected every message = hundreds of milliseconds of latency per reply.
- Forgetting everything. New session = blank slate. No memory of yesterday’s work or decisions.
- Inconsistent behavior. Without clear rules, personality drifts between sessions.
- Doing everything the expensive way. Main model writes code, does research, AND orchestrates - all at top-tier pricing.
- Flying blind. No web search means guessing at anything after training cutoff.
- Wrong model choice. Using whatever was default without considering the tradeoffs.
What This Fixes
After this setup:
| Metric |
Before |
After |
| Context per msg |
15-20 KB |
4-5 KB |
| Time to respond |
4-8 sec |
1-2 sec |
| Memory recall |
Forgets daily |
Remembers weeks |
| Token cost/msg |
~5,000 tokens |
~1,500 tokens |
| Long sessions |
Degrades |
Stable |
| Concurrent tasks |
One at a time |
Multiple parallel |
How It Works
You ask a question
↓
Orchestrator (main model, lean context ~5KB)
↓
┌─────────────────────────────────────────┐
│ memory_search() - 45ms, local, $0 │
│ ┌─────────┐ ┌──────────┐ ┌────────┐ │
│ │MEMORY.md│→ │memory/*.md│→ │vault/* │ │
│ │(index) │ │(quick) │ │(deep) │ │
│ └─────────┘ └──────────┘ └────────┘ │
└─────────────────────────────────────────┘
↓
Only relevant context loaded (~200 tokens)
↓
Fast, accurate response + sub-agents for heavy work
The key insight: Workspace files become lightweight routers, not storage. All knowledge lives in a local vector database. The bot loads only what it needs - not everything it’s ever learned.
What The Optimized Files Look Like
Full versions in /templates:
SOUL.md (772 bytes - injected every message):
## Who You Are
- Direct, concise, no fluff. Say the useful thing, then stop.
- Have opinions. Disagree when warranted. No sycophancy.
## Memory Rule
Before answering about past work, projects, people, or decisions:
run memory_search FIRST. It costs 45ms. Not searching = wrong answers.
## Orchestrator Rule
You coordinate; sub-agents execute. Never write 50+ lines of code yourself.
MEMORY.md (581 bytes - slim pointer index):
## Active Projects
- Project A → vault/projects/project-a.md
- Project B → vault/projects/project-b.md
## Key People
- Person A - role, relationship → vault/people/person-a.md
Details live in vault/. The bot finds them via local vector search instead of paying the hot-path context tax every turn.
This isn’t a settings tweak - it’s a complete architecture change: memory routing, context engineering, and orchestration working together. The one-shot prompt at the bottom does the entire setup automatically.
Note: The examples assume a frontier orchestrator that can follow multi-step instructions. Opus 4.7 is still a strong default if you have a paid route and budget caps; Gemini/DeepSeek/Kimi/local workers handle most execution.
Templates included: Check /templates for ready-to-use versions of SOUL.md, AGENTS.md, MEMORY.md, TOOLS.md, and a sample vault/ structure.
Part 1: Speed (Stop Being Slow)
Read this if your agent feels laggy, you’re on a Gemini/GPT default, or you just want to know which levers matter most. Start here if you only read one part.
Skip if you’ve already tuned context, fallbacks, reasoning mode, and model selection.
Every message you send, OpenClaw injects selected hot-path context: system prompt, workspace bootstrap files, current conversation state, tool schemas, and sometimes skill/plugin context. Bloated files = slower, more expensive replies. This is the #1 speed issue people don’t realize they have.
Why Trimming Works
You don’t need big hot-path files once you have vector search.
Old approach: Stuff everything into MEMORY.md so the bot “sees” it every message → 15KB+ context, slow responses, wasted tokens on irrelevant info.
New approach: MEMORY.md is a slim index of pointers. Full details live in vault/. memory_search() retrieves them via local Ollama embeddings ($0). Your hot-path files stay tiny without losing any knowledge.
Trim Your Context Files
| File |
Target Size |
What Goes In It |
Why This Size |
| SOUL.md |
< 1 KB |
Personality, tone, core rules |
Injected EVERY message - every byte costs latency |
| AGENTS.md |
2-10 KB |
Decision tree, tool routing, operational protocols (dreaming, coordinator) |
Operational protocols are worth the context cost — they replace manual prompting |
| MEMORY.md |
< 3 KB |
Pointers only - NOT full docs |
Vector search replaces big files |
| TOOLS.md |
< 1 KB |
Tool names + one-liner usage |
Just reminders, not documentation |
| Total |
8-15 KB |
Everything injected per message |
With operational protocols (built-in dreaming, coordinator), 8-15KB is acceptable — these replace manual prompting that would cost more |
Rule: If it’s longer than a tweet thread, it’s too long for a workspace file. Move the details to vault/.
Add a Fallback Model
"agents": {
"defaults": {
"model": {
"primary": "anthropic/opus",
"fallbacks": [
"deepseek/deepseek-v4-flash",
"openrouter/moonshotai/kimi-k2.6"
]
}
}
}
OpenClaw’s late-April and May releases moved hard toward provider-owned catalogs and fallback policy. Use provider/model refs where your install supports them. Explicit user /model selections are strict; configured defaults can fall through primary → fallback. The operator rule is stable: every production agent needs a primary, at least two fallbacks, and budget caps per expensive provider.
Current gotcha: /models add briefly shipped in 2026.4.22, then was deprecated in 2026.4.24. Use /models for browsing and copy-friendly examples, but treat durable model registration as config/catalog work, not chat-time mutation.
Reasoning Mode - Know the Tradeoff
Run /status to see your current reasoning mode.
- Off - fastest, no thinking phase
- Low - slight thinking, faster responses
- High - deep reasoning, adds 2-5 seconds but catches things low/off misses
I run high and keep it there. The context trimming from other steps more than compensates for the reasoning overhead.
Disable Unused Plugins
Every enabled plugin adds overhead. If you’re not using memory-lancedb, memory-core, etc., set "enabled": false.
Lean Mode for Weak Local Models
New in 2026.4.15 and refined in 2026.5.20: if you’re running a small local model (≤14B params, 16K-32K context) and the default tool set is eating the prompt, prefer per-agent lean mode for the small worker. Use the global default only when every agent on that profile is local/small:
{
"agents": {
"list": [
{
"id": "local-worker",
"experimental": { "localModelLean": true }
}
]
}
}
This drops heavyweight default tools (browser, cron, message) from that worker’s system prompt. You keep memory_search, exec, sessions_spawn, and the essentials — which is everything most local setups actually use. 2026.4.29 also relaxed fixed preflight cutoffs so small local models use guard thresholds derived from their effective context window instead of hard-coded 16K/32K floors.
Ollama Housekeeping
ollama ps # Check what's loaded
ollama stop modelname # Unload idle big models
The default model for memory search should be qwen3-embedding:0.6b (500 MB, 1024 dims) — same Qwen3 family that holds #1 on MTEB, runs on anything, and blows away nomic on quality. Pull it: ollama pull qwen3-embedding:0.6b. If you have a GPU with 8GB+ VRAM, upgrade to Qwen3-Embedding-8B for dramatically better search quality — see Part 10. If you have 500+ vault files, also add LightRAG (Part 18) for knowledge graph retrieval that blows away basic vector search.
New in 2026.4.15 — memory-lancedb cloud storage. memory-lancedb can now persist its index to S3-compatible object storage instead of local disk (storage.type: "s3" + bucket + prefix + endpoint). Useful for multi-machine setups where you want every box to see the same index, or for backing up a single-machine index without rsync. The hot path is still in-memory — cloud is just durable storage. Don’t confuse this with cloud embeddings (still a bad idea for the hot path).
New in 2026.4.15 — GitHub Copilot embedding provider. If your team already pays for Copilot Business/Enterprise, agents.defaults.memorySearch.provider: "copilot" reuses that seat for embeddings. It’s still cloud (2-5s round trips, same caveats as OpenAI/Voyage) so local Ollama is still the right default for personal setups — but for a corporate deployment that’s already standardized on Copilot, this removes another vendor from the procurement list.
Part 2: Context Engineering — The Discipline
Renamed in the April 2026 refresh. “Context Bloat” was the problem; context engineering is the discipline. The Part 2 material is the practical version of that discipline for OpenClaw.
Read this if you notice each message getting slower, you’re hitting compaction often, or your SOUL.md / MEMORY.md / AGENTS.md are over a few KB combined.
Skip if your total injected context is already under 15 KB and compaction rarely fires.
The Quadratic Problem
LLM attention scales quadratically with context length:
- 2x the tokens = 4x the compute cost
- 3x the tokens = 9x the compute cost
When context goes from 50K to 100K tokens, the model does four times the work. That means slower responses and higher bills.
What Happens As Context Fills
Just because a model advertises 1M context doesn’t mean it performs well at 1M:
- Long-context evals repeatedly show accuracy falling well before the advertised maximum.
- Latency can spike non-linearly once prompts move from “large” to “huge.”
- Models exhibit “lost-in-the-middle” bias - they track the beginning and end but lose the middle
- Effective context is usually a fraction of the max
Where Bloat Comes From
| Source |
Typical Size |
Injected When |
| System prompt |
2-5 KB |
Every message |
| Workspace files |
5-20 KB |
Every message |
| Conversation history |
Grows per turn |
Every message |
| Tool results |
1-50 KB each |
After tool calls |
| Skill files |
1-5 KB each |
When skill activates |
Tool spam is the worst offender. A single exec returning a large file = 20K+ tokens permanently in your session. Five tool calls = 100K tokens of context the model re-reads every message.
The Numbers That Matter
Production agents often consume far more context than they generate. Your context window IS your performance budget.
Compression targets (from Maxim AI production data):
- Historical context: 3:1 to 5:1 compression ratio
- Tool outputs: 10:1 to 20:1 compression ratio
- If your agent is at >60% context utilization before the user speaks, you’re in trouble
The 60% Rule: If system prompt + workspace files + memory search results exceed 60% of your context window before the user even sends a message, apply these in order:
- Summarize conversation history
- Filter retrieval results (fewer, more relevant chunks)
- Route tools dynamically (only load tool definitions the agent needs this turn)
- Compress step results from previous tool calls
The Cost Math
Lean (5K tokens/msg) → Claude Opus: $0.025/msg
Bloated (50K tokens/msg) → Claude Opus: $0.25/msg ← 10x more
Over 100 msgs/day: $2.25/day vs $22.50/day
Built-In Defenses
Session Pruning - Trims old tool results from context:
{
"agents": {
"defaults": {
"contextPruning": { "mode": "cache-ttl", "ttl": "5m" }
}
}
}
Auto-Compaction - Summarizes older conversation when nearing context limits. Trigger manually with /compact.
2026.4.15 fix: The compaction reserve-token floor is now capped at the model’s actual context window. Before this, compaction on a 16K-token local model could request a larger reserve than the window itself, creating an infinite “try to free N tokens, fail, retry” loop. If you run small local models as compaction workers, upgrade — this is the fix you want. See Part 15.
Context inspection (2026.5+): use the built-in commands before guessing:
/status — quick context and session settings view.
/context list — injected files and rough prompt sizes.
/context detail — top skills, tool schemas, and system-prompt contributors.
/context map — WinDirStat-style treemap image of tracked context contributors after the session has produced a real run report.
If /context map says no cached run report exists yet, send one normal message first; current builds refuse to draw estimates as if they were measured context.
Appendix — The 5-Minute Prompt Cache TTL Trap (March 2026)
Silent production killer that caught most teams in April 2026: Anthropic’s prompt-cache default TTL dropped from 1 hour to 5 minutes sometime in early March 2026, without a release note most operators noticed. See the writeup Claude API Prompt Caching: Cut Costs 80% on Every Repeated Request (Apr 14, 2026).
If you built your SOUL/AGENTS/MEMORY context assuming a 1-hour cache, you’re now paying full token price on every sub-5-minute gap between messages. For an orchestrator running one session at a time with users stopping to think between turns, the cache is essentially never hit. Bills silently tripled.
Symptom: Your Anthropic bill is up 2–4× month-over-month; token counts haven’t changed.
Fix (OpenClaw). Set the cache TTL explicitly on any prompt segment that should live longer than 5 minutes:
{
"agents": {
"defaults": {
"prompts": {
"cacheControl": {
"soul": { "type": "ephemeral", "ttl": "1h" },
"agents": { "type": "ephemeral", "ttl": "1h" },
"memory": { "type": "ephemeral", "ttl": "1h" },
"skills": { "type": "ephemeral", "ttl": "5m" }
}
}
}
}
}
The hot-path files (SOUL, AGENTS, MEMORY) are stable within a session, so pin their TTL to 1h. Skills and dynamic context stay at 5m — they change too often to be worth extending.
Anthropic considers 1h-cached blocks billable, just at ~1/10 the rate of uncached tokens. Worth the trade for anything that’s reused more than twice an hour.
Use both. Pruning handles tool result bloat. Compaction handles conversation history bloat.
Context Bloat Checklist
Part 3: Cron Session Bloat (The Hidden Killer)
Read this if you run cron jobs, the sessions/ folder is huge, or you’ve ever wondered why a background agent gets slower week over week.
Skip if you don’t use cron / scheduled agents.
Every cron job creates a session transcript file (.jsonl). Over time:
- 30 cron jobs × 48 runs/day × 30 days = 43,200 session files
- The
sessions.json index balloons, slowing session management
How to Spot It
# Linux/Mac
ls ~/.openclaw/agents/*/sessions/*.jsonl | wc -l
# Windows (PowerShell)
(Get-ChildItem ~\.openclaw\agents\*\sessions\*.jsonl).Count
Thousands of files = cron session bloat.
The Fix
1. Configure session rotation:
{ "session": { "maintenance": { "rotateBytes": "100mb" } } }
2. Clean up old sessions:
openclaw sessions cleanup
3. Use isolated sessions for cron:
{ "sessionTarget": "isolated", "payload": { "kind": "agentTurn", "message": "Do the thing" } }
Isolated sessions don’t pile up in your main agent’s session history.
Prevention > Cleanup
- Use
delivery: { "mode": "none" } on crons where you don’t need output announced
- Keep cron tasks focused - 1 tool call generates 15x less session data than 15
Part 4: Memory (Stop Forgetting Everything)
Read this if you want the 3-tier memory model (MEMORY.md + session files + vector search) from scratch. This is the foundation for Parts 9, 10, 11, 12, 13, 22.
Skip if you’re already running memory-core with a local embedding provider and a vault — skim for the 2026.4.15 memory_get / lancedb-cloud changes and move on.
Out of the box, OpenClaw forgets everything between sessions. The fix is a 3-tier memory system.
The Architecture
MEMORY.md ← Slim index (< 3 KB), pointers only
memory/ ← Auto-searched by memory_search()
projects.md
people.md
decisions.md
vault/ ← Deep storage, searched via memory
projects/
people/
decisions/
lessons/
reference/
research/
How It Works
- MEMORY.md - table of contents with one-liner pointers. Never put full documents here.
- memory/*.md - automatically searched when the bot calls
memory_search("query").
- vault/ - deep storage for detailed project docs, research notes, full profiles.
Setting It Up
Step 1: Install Ollama + embedding model
# Windows: winget install Ollama.Ollama
# Mac/Linux: curl -fsSL https://ollama.com/install.sh | sh
ollama pull qwen3-embedding:0.6b
OpenClaw detects Ollama on localhost:11434 automatically. No config needed.
Low-RAM fallback: nomic-embed-text still works, but it is now the fallback, not the recommendation. For a major quality upgrade (768-dim → 4096-dim vectors), see Part 10: State-of-the-Art Embeddings.
Step 2: Create the directory structure
workspace/
MEMORY.md
memory/
vault/
projects/ people/ decisions/ lessons/ reference/ research/
Step 3: Slim down MEMORY.md
# MEMORY.md - Core Index
_Pointers only. Search before answering._
## Active Projects
- Project A → vault/projects/project-a.md
## Key Tools
- Tool X: `command here`
## Key Rules
- Rule 1
Step 4: Move everything else to vault/
Every detailed document → vault/. Leave a one-liner pointer in MEMORY.md or memory/.
Step 5: Set up memory consolidation
Session memory files pile up fast — 200+ files in a month. OpenClaw 2026.4+ has built-in dreaming (Part 22) — enable it in memory-core config and it auto-consolidates on a daily schedule. (Pre-2026.4 installs used to need the custom “autoDream” AGENTS.md pattern described in the retired Part 16; that file is gone — upgrade to 2026.4+ and use built-in dreaming instead.)
Security note (2026.4.15): memory_get is now restricted to canonical memory files — MEMORY.md and DREAMS.md. It no longer reads arbitrary files from the workspace by path. If you were doing memory_get("vault/projects/x.md") directly, switch to memory_search or a plain file read — the dedicated memory tool is strictly for the canonical agent indexes now. This closes a path-traversal vector that the memory-qmd backend allowed before.
Context budget change (2026.4.15 stable): memory_get now caps excerpt length by default and returns explicit continuation metadata instead of dumping entire files into context. If an excerpt was truncated, the tool response includes a follow-up cursor the agent can use to fetch the next chunk deterministically. On top of that, default startup and skills prompt budgets were trimmed — long sessions pull less context by default without losing deterministic follow-up reads. Practical effect: your MEMORY.md and DREAMS.md can grow without silently blowing up every reply. If you had custom skills that assumed memory_get returns the whole file, update them to respect the continuation cursor (it’s noisy but one-line).
May 2026 upgrade: Active Memory supports per-conversation allowedChatIds / deniedChatIds, partial recall summaries on timeout, and people-aware wiki provenance reports. Do not enable broad automatic recall in every group chat. Scope it to the conversations where durable memory is actually appropriate, then audit provenance when the agent makes claims about people.
The Golden Rule
Add this to your SOUL.md:
## Memory
Before answering about past work, projects, or decisions:
run memory_search FIRST. It costs 45ms. Not searching = wrong answers.
Part 5: Orchestration (Stop Doing Everything Yourself)
Read this if you do anything non-trivial — research, coding, long tasks — in a single interactive agent and haven’t set up sub-agent workers, verification, or the Ralph loop yet.
Skip if you’re already running CEO/COO/Worker with PreCompletionChecklist verification.
Sub-Agents Are Context Garbage Collection (Not A Speed Hack)
The mistake most teams make with sub-agents: treating them as a performance trick (“run two things in parallel = 2x speed”). That misses the point. The week of April 10–17, 2026 had five independent writeups (heyuan110 Apr 13, Builder.io Apr 16, and three more on DEV) all converging on the same reframe: sub-agents are context garbage collection.
The real unlock: a sub-agent is a disposable context window. You spawn one, it burns 40K tokens searching the codebase, it returns a 500-token summary, the sub-agent’s context is thrown away. Your main agent’s context stays lean. Without sub-agents, that 40K of search noise would permanently live in your main context, degrading every subsequent turn.
The 3-trigger decision table — spawn a sub-agent if any of these are true:
| Trigger |
What it looks like |
Why you spawn |
| Wide search scope |
“find every usage of X”, “how does auth work across the codebase”, “read all related files” |
The search is most of the tokens. Don’t bring them home. |
| 10+ edit targets |
Renaming across many files, systematic refactors, bulk migrations |
Each edit call is noise once it’s done. Worker commits, reports hash, done. |
| Independent verification |
“does the code actually compile”, “do the tests pass”, “is this PR complete” |
You want a fresh pair of eyes with no bias from the implementation conversation. |
If none of those are true, don’t spawn. Sub-agent invocation has real overhead — cold-start prompts, tool-registration roundtrips, summarization cost. Use them surgically, not reflexively.
Your main model should NEVER do heavy work directly. It should plan and delegate to cheaper, faster sub-agents — per the triggers above.
Anthropic’s Five Multi-Agent Coordination Patterns (Apr 10, 2026)
On April 10, 2026, Anthropic published Multi-Agent Coordination Patterns — the first canonical naming of the patterns the community had been reinventing. The taxonomy is now the lingua franca for how agents work together. Use it. Old internal names (“CEO/COO/Worker”, “critic loop”) still map to these.
| Pattern |
When you pick it |
OpenClaw realization |
| Generator-Verifier |
Output correctness matters more than latency (code, plans, architecture decisions) |
Spawn worker to produce, spawn fresh worker to verify. No shared context. |
| Orchestrator-Subagent |
Main agent holds strategy, workers execute narrow tasks |
The classic. What Part 5 started as. |
| Agent Teams |
Bounded problem with clearly separate roles (researcher + writer + editor) |
Each team member is its own persistent thread via ACP. |
| Hierarchical |
Truly large task trees, multiple layers of delegation |
Rare. When you need it, Task Brain’s parent-child ledger is how you keep it sane. |
| Network |
Peer agents passing tasks to each other without a central orchestrator |
Spicy. Only use with strong approval gates. Most failures live here. |
flowchart LR
Q{Task shape?}
Q -->|"Output correctness critical"| GV[Generator-Verifier]
Q -->|"Clear strategy + narrow execute"| OS[Orchestrator-Subagent]
Q -->|"Distinct roles, bounded"| AT[Agent Teams]
Q -->|"Deep task tree"| HI[Hierarchical]
Q -->|"Peer-to-peer flow"| NET[Network — careful]
Default picks for an OpenClaw operator: Orchestrator-Subagent for 80% of work, Generator-Verifier for code and decisions, Agent Teams for long research loops, Hierarchical when Task Brain flows nest 3+ levels deep, Network almost never.
The Ralph Loop (Part 30) is a specific flavor of Orchestrator-Subagent where the orchestrator is an outer bash wrapper and every iteration is a fresh agent session.
Your main model should NEVER do heavy work directly. It should plan and delegate to cheaper, faster sub-agents.
The Mental Model
- You = CEO (gives direction)
- Your Bot (main model) = COO (plans, coordinates, makes decisions)
- Sub-agents (cheaper/faster model) = Workers (execute tasks fast and cheap)
## Core Rule
You are the ORCHESTRATOR. You coordinate; sub-agents execute.
- Code task (3+ files)? → Spawn coding agent
- Research task? → Spawn research agent
- 2+ independent tasks? → Spawn ALL in parallel
## Model Strategy
- YOU (orchestrator): Best model - planning, judgment, synthesis
- Sub-agents (workers): Cheaper/faster model - execution, code, research
2026.3.31-beta.1+ — every spawn is a Task Brain task/flow. Sub-agents, ACP runs, and cron jobs all flow through the same unified task ledger now (openclaw tasks list, with openclaw tasks flow ... for flow views). Semantic approval categories (execution.*, read-only.*, control-plane.*) replace the old name-based allowlist. If you’re seeing unexpected “approval required” prompts on sub-agent spawns, check Part 24 — Task Brain Control Plane for how to configure categories and trust boundaries.
Your expensive model decides WHAT to build. The cheap model builds it. Right model, right job.
A Complete Multi-Agent Example: Chief of Staff + Workers
The patterns above are abstract until you see the whole thing wired together. Here is a minimal-but-complete three-agent setup — a chief-of-staff orchestrator plus two scoped workers — using the config shapes from templates/openclaw.example.json. It’s the Orchestrator-Subagent pattern with real files and real config.
Verify key names against your installed build. Config keys move between betas. Treat this as the shape of a multi-agent setup; confirm the exact keys with openclaw doctor and openclaw exec-policy show, and see the Part 24 version-accuracy note on approvals.
File layout. Each agent gets its own identity (SOUL.md), operating rules (AGENTS.md), and tool docs (TOOLS.md) — the three files that survive the 2026.5.22 worker-bootstrap narrowing (see Part 24). The orchestrator’s files are the only ones loaded into your interactive session; worker files load only when that worker is spawned.
~/.openclaw/
openclaw.json # the agents.list config below
agents/
chief-of-staff/ # orchestrator: plans, delegates, never executes
SOUL.md AGENTS.md TOOLS.md
coding-worker/ # executes code in a sandboxed repo
SOUL.md AGENTS.md TOOLS.md
research-worker/ # read-only research, returns summaries
SOUL.md AGENTS.md TOOLS.md
The config (openclaw.json). agents.defaults sets shared model/memory/compaction (see the template for the full block); agents.list[] adds per-agent overrides. The orchestrator runs a frontier model; workers run cheaper/local models, and the local one opts into lean mode:
{
"agents": {
"defaults": {
"model": { "primary": "anthropic/opus", "fallbacks": ["google/gemini-3-flash", "deepseek/deepseek-v4-flash"] },
"contextPruning": { "mode": "cache-ttl", "ttl": "5m" },
"compaction": { "model": "cerebras/gpt-oss-120b", "reserveTokens": 8000 }
},
"list": [
{
"id": "chief-of-staff",
"model": { "primary": "anthropic/opus" },
"_comment": "Orchestrator. Best model — planning and judgment only. Never does heavy tool work itself."
},
{
"id": "coding-worker",
"model": { "primary": "deepseek/deepseek-v4-flash" },
"_comment": "Spawned for code tasks. Runs tests; commits; reports the hash + a short summary."
},
{
"id": "research-worker",
"model": { "primary": "google/gemini-3-flash" },
"experimental": { "localModelLean": true },
"_comment": "Read-only research. Lean mode drops heavyweight default tools from its prompt."
}
]
}
}
Tool + approval scoping (defense in depth). Don’t rely on the prompt to keep a worker in its lane — enforce it. Use Task Brain semantic approvals for what each agent may do and tools.toolsBySender for who may reach the agent at all (both detailed in Part 24):
{
"taskBrain": {
"approvals": {
"defaults": { "read-only.*": "allow", "execution.sandbox.*": "allow", "execution.*": "ask", "write.fs.workspace": "allow", "write.fs.outside-workspace": "deny", "write.network": "ask", "control-plane.*": "deny" }
}
}
}
- chief-of-staff keeps
execution.* and write.network on ask — it should be pausing for you, not running shells.
- coding-worker can be granted
execution.shell/execution.code/write.fs.workspace = allow (it needs to run tests) but write.network = deny — a worker should never post.
- research-worker gets
read-only.* = allow and everything else deny.
(Per-agent overrides live next to each agents.list[] entry; confirm the exact nesting against your version per the note above.)
The two files that do the orchestration. The orchestrator’s SOUL.md is its identity; its AGENTS.md is the delegation rulebook:
# chief-of-staff/SOUL.md
You are the Chief of Staff. You hold strategy and context; you do not execute.
Your value is judgment, not throughput. Delegate execution; verify results.
# chief-of-staff/AGENTS.md
## Core Rule
You coordinate; workers execute. Never write 50+ lines of code or do wide searches yourself.
- Code task (3+ files / 10+ edits)? → spawn `coding-worker`
- Research / wide search? → spawn `research-worker`
- 2+ independent tasks? → spawn workers in PARALLEL
## Delegation Protocol
- Each spawn is a self-contained work order: goal, constraints, and the bounded
context the worker needs (it no longer inherits your persona/memory by default).
- Workers return a short summary, not their transcript. Their context is thrown away.
## Verification
- For code: require the worker to run tests and report the result, not "looks good".
- Spawn a FRESH worker to verify anything correctness-critical (Generator-Verifier).
The flow at runtime. You ask the chief of staff for something; it plans and delegates:
You → chief-of-staff: "Add rate limiting to the API and document it."
chief-of-staff:
├─ spawn coding-worker: "Add a token-bucket limiter to src/api/*. Run tests. Report hash."
└─ spawn research-worker: "Summarize our past rate-limit decisions from the vault."
(both run as Task Brain tasks — visible in `openclaw tasks list`)
coding-worker → "Done. 3 files, tests green, commit a1b2c3d. Summary: …"
research-worker → "We previously chose token-bucket over leaky-bucket because …"
chief-of-staff → synthesizes both, verifies against your request, replies.
Every spawn is a Task Brain task, so the whole tree is auditable: openclaw tasks list shows what ran, openclaw tasks flow show <id> traces sub-tasks back to the originating request.
Optimizing the setup (tokens + latency). A multi-agent system multiplies token spend if you’re careless. The levers, all in the config above:
| Lever |
Config |
Why it helps |
| Keep the orchestrator’s context lean |
spawn workers for search/edits (their context is discarded) |
The orchestrator’s window stays small, so every turn is cheaper and sharper. |
| Stop re-injecting SOUL+AGENTS+MEMORY every turn |
contextPruning.mode: cache-ttl |
Single biggest latency win on frontier models. |
| Cheap workers, expensive orchestrator |
per-agent model.primary |
Frontier judgment where it matters; volume execution where it doesn’t. |
| Lean mode for small/local workers |
experimental.localModelLean: true |
Drops heavyweight default tools (browser, cron, message) from a small model’s prompt. |
| Cheap, fast compaction |
compaction.model on a non-reasoning model |
Compaction is frequent and shouldn’t burn frontier tokens. |
The result is the CEO/COO/Worker model with enforcement instead of an honor system: scoped tools, audited spawns, and a token bill that scales with the worker tier, not the orchestrator.
PreCompletion Verification (from LangChain’s +13.7 point harness improvement)
LangChain’s coding agent went from outside the Top 30 to Top 5 on Terminal Bench 2.0 by only changing the harness — not the model. Their #1 improvement: force verification before exit.
Add this to your AGENTS.md:
## PreCompletion Verification
Before finishing ANY task, STOP and verify:
1. Re-read the user's original request
2. Compare your output against what was actually asked
3. If there's a gap, fix it before responding
4. For code: run tests — don't just re-read your own code and say "looks good"
Why this works: Agents are biased toward their first plausible solution. They write code, re-read it, say “looks good”, and stop. Forcing a verification pass against the original request (not their own output) catches the gap.
Also add loop detection:
## Loop Detection
If you edit the same file 5+ times without progress, STOP.
Step back, reconsider your approach entirely.
Don't make small variations to the same broken approach — that's a doom loop.
LangChain uses a LoopDetectionMiddleware that tracks per-file edit counts and injects “consider reconsidering your approach” after N edits. Simple but effective.
Long-Running Projects (Multi-Session Work)
From Anthropic’s own engineering blog: for projects spanning multiple sessions, use the initializer + progress file pattern:
## Multi-Session Protocol
- Work on ONE feature at a time — don't one-shot everything
- Create/update a `progress.txt` in the project dir:
- What's DONE (with dates)
- What's IN PROGRESS (with blockers)
- What's NEXT (prioritized)
- Start each session: read progress.txt → git log → run basic test → THEN start work
- End each session: commit with descriptive message, update progress.txt
Use JSON for feature tracking when you need structured state (model is less likely to accidentally modify JSON vs markdown). Anthropic found this solved two critical failure modes: agents trying to one-shot everything, and agents declaring victory too early.
The Ralph Wiggum Loop (Autonomous Tasks)
Named after the Simpsons character, this is one of the most powerful patterns for overnight/autonomous agent work. Core idea: when an agent tries to stop, force it to keep working until tests actually pass.
# The original 5-line Ralph loop
while true; do
cat prompt.md | claude --print | tee output.txt
if ./run_tests.sh; then break; fi
done
The insight: agents love to declare “done” before work is actually done. External verification (tests, linters, type checkers) can’t lie — the agent can. The loop forces build→test→fix cycles until reality matches expectations.
Add to your AGENTS.md for autonomous tasks:
## Ralph Loop (Autonomous Tasks)
For overnight/unattended work:
- Don't trust "looks good" — run REAL tests
- Loop: implement → test → if fail → fix → test again
- Only done when tests ACTUALLY PASS
- 10+ iterations without progress → stop and report failure
Common traps: Loop never ends (criteria too strict), loop ends too early (agent fakes the completion promise), quality degrades over iterations (random changes hoping something sticks). Fix: strengthen verification to run BEFORE accepting the promise.
Source: ghuntley.com/loop, Letta Code /ralph command, LangChain PreCompletionChecklistMiddleware
The 4-Phase Coordinator Protocol (Advanced)
For complex multi-step tasks, use the coordinator pattern — originally reverse-engineered from the Claude Code / autoDream leak, now absorbed into built-in dreaming and sub-agent spawning:
| Phase |
Who |
Purpose |
| Research |
Workers (parallel) |
Investigate codebase, find files, understand problem |
| Synthesis |
Coordinator (you) |
Read ALL findings, craft specific implementation specs |
| Implementation |
Workers (parallel) |
Execute specs, commit changes |
| Verification |
Workers (parallel) |
Test changes, prove they work |
Key rules:
- “Parallelism is your superpower” — launch independent workers concurrently
- Never say “based on your findings” — read the actual findings and write specific specs
- Workers can’t see your conversation — every prompt must be self-contained
- Include a purpose statement: “This research will inform a PR — focus on user-facing changes”
- Exclusive file ownership (from Zerg): each worker’s spec lists which files it owns. No two workers edit the same file. Eliminates merge conflicts entirely.
- Workers self-verify before reporting done: “Run tests and typecheck, then commit and report the hash”
Continue vs Spawn fresh?
| Situation |
Action |
| Worker researched the exact files to edit |
Continue (has context) |
| Research was broad, implementation narrow |
Spawn fresh (avoid noise) |
| Correcting a failure |
Continue (has error context) |
| Verifying another worker’s code |
Spawn fresh (no bias) |
Give Coding Agents Your Brain
Codebase Intelligence (NEW — Part 19): Before spawning coding agents, use Repowise to give them full codebase context — dependency graphs, git ownership, architectural decisions, dead code detection. 60% fewer tokens, 4x faster task completion. pip install repowise && repowise init --path /project --index-only
Memory Bridge: Before spawning any coding sub-agent, run the Memory Bridge preflight to inject relevant vault knowledge into the project directory:
node scripts/memory-bridge/preflight-context.js --task "Build auth middleware" --workdir ./my-project
This writes a CONTEXT.md that the coding agent reads automatically — giving it access to your past decisions, error patterns, and architecture choices. See Part 13 for the full setup.
Part 6: Models (What to Actually Use)
Read this if you’re picking providers/models, debating local vs. cloud, or you want an opinionated cost/latency matrix for 2026-era models.
Skip if you have a provider mix you’re happy with and your bills are sane.
The Model Strategy
| Role |
What It Does |
Best Model(s) |
Why |
| Orchestrator |
Plans, judges, coordinates |
Claude Opus 4.7 |
Best complex reasoning + tool use (new default in 2026.4.15) |
| Sub-agents |
Execute delegated tasks |
Kimi K2.6, DeepSeek V4 Flash, MiMo V2 Pro, Gemini Flash |
Fast, cheap, capable enough |
| Infrastructure |
Compaction, fallbacks, bulk work |
Cerebras gpt-oss-120b |
$0.60/M, 3000 tok/s, reliable |
| Knowledge Graph RAG |
Entity extraction, graph queries |
Cerebras qwen-3-235b |
1400 tok/s, high accuracy for entity extraction |
| Coding (hard) |
Architecture, complex bugs |
Claude Opus 4.7 |
Top SWE-bench — the new Anthropic default as of 2026.4.15 |
| Coding (batch) |
Scaffolding, CRUD, refactors |
openai/gpt-* through Codex app-server |
Fast for code when your Codex route is healthy; pair with Memory Bridge |
| Research |
Web search, analysis |
Kimi K2.6 + Tavily |
Cheap, fast, good at research synthesis |
| Local inference |
$0 forever, private, no rate limits |
QwOpus (27B), TerpBot (Nemotron 30B), Nemotron Nano 4B |
Ollama on any GPU |
| Free tier |
Zero-cost operations |
Gemini (all variants), Cerebras free tier, OpenRouter fre |
|
README 内容过长,已截取前 64 KB。完整内容请前往 GitHub 仓库查看。
评论