Fix OpenClaw Memory Loss in 12 Minutes

Solve 'agent forgets' issues in OpenClaw with proper memory configuration, compaction settings, and hybrid search setup.

Problem: Your OpenClaw Agent Forgets Everything

You configured OpenClaw, had a productive session, restarted it, and now the agent acts like you're strangers. Worse, mid-conversation it suddenly forgets what you were just discussing.

You'll learn:

  • Why OpenClaw memory fails (compaction vs. session resets)
  • How to configure automatic memory flush
  • When to use Mem0/Cognee plugins vs. built-in memory

Time: 12 min | Level: Intermediate


Why This Happens

OpenClaw uses Markdown files as the source of truth for memory. The agent only remembers what gets written to MEMORY.md or daily logs in memory/YYYY-MM-DD.md. Three failure modes cause "forgetting":

Common symptoms:

  • Agent doesn't recall facts from previous sessions (files never written)
  • Mid-conversation memory loss (context compaction without memory flush)
  • Manual /reset or /new commands wipe working context
  • Session transcripts aren't indexed (experimental feature disabled)

Root causes:

  1. Default behavior: Files must be explicitly loaded and written
  2. Context compaction: Older context gets summarized to save tokens, destroying anything only in RAM
  3. Stateless sessions: Each restart begins from scratch unless memory files are read
  4. Manual resets: /new and /reset discard sessions without saving context

Solution

Step 1: Verify Memory Files Exist

# Check your OpenClaw workspace
ls -la ~/.openclaw/workspace/

# Expected directory structure:
# MEMORY.md
# memory/
#   └── 2026-02-08.md

If files are missing:

  • OpenClaw creates memory/ directory but not MEMORY.md by default
  • Create manually: touch ~/.openclaw/workspace/MEMORY.md

Expected: You should see today's date file in memory/ and optionally MEMORY.md


Step 2: Enable Automatic Memory Flush

This is critical - it saves context before compaction destroys it.

Edit your OpenClaw config (~/.openclaw/openclaw.json or openclaw.config.ts):

{
  "agents": {
    "defaults": {
      "compaction": {
        "reserveTokensFloor": 20000,
        "memoryFlush": {
          "enabled": true,  // Must be true
          "softThresholdTokens": 4000,
          "systemPrompt": "Session nearing compaction. Store durable memories now.",
          "prompt": "Write any lasting notes to memory/YYYY-MM-DD.md; reply with NO_REPLY if nothing to store."
        }
      }
    }
  }
}

Why this works: When context approaches the window limit, OpenClaw triggers a silent turn reminding the agent to write important facts to disk before compaction summarizes everything.

If it fails:

  • Error: "workspace not writable": Check permissions on ~/.openclaw/workspace/
  • No flush happening: Calculate your threshold - flush triggers at contextWindow - reserveTokensFloor - softThresholdTokens. Default models use ~200k context, so flush happens around 176k tokens.

Step 3: Configure Memory Search (Hybrid Mode)

Enable semantic search so the agent can recall relevant context even when wording differs.

{
  "agents": {
    "defaults": {
      "memorySearch": {
        "provider": "openai",  // or "local" or "gemini"
        "model": "text-embedding-3-small",
        "remote": {
          "apiKey": "your-openai-api-key"  // or use env var OPENAI_API_KEY
        },
        "query": {
          "hybrid": {
            "enabled": true,
            "vectorWeight": 0.7,  // Semantic similarity
            "textWeight": 0.3,    // Exact keyword matching (BM25)
            "candidateMultiplier": 4
          }
        }
      }
    }
  }
}

Provider options:

  • openai: Fast, requires API key, batch mode available
  • local: No API costs, downloads ~600MB GGUF model, requires pnpm approve-builds
  • gemini: Alternative cloud option, needs GEMINI_API_KEY

Expected: Memory searches now find related content using both semantic meaning and exact keywords.


Step 4: Handle Manual Resets (Optional)

Currently, /new and /reset discard sessions without saving. Workaround until this feature request lands:

Train yourself to save first:

# Before resetting
You: "Save important context to memory"
Agent: [writes to memory files]
You: "/new"

Alternative: Install a pre-reset hook (advanced):

{
  "session": {
    "resetFlush": {
      "enabled": true,  // Not in main yet - check releases
      "prompt": "Session is being reset. Save any important context to memory files now. Reply with NO_REPLY.",
      "systemPrompt": "User triggered /new or /reset. Write durable notes before the session is cleared."
    }
  }
}

Step 5: Test Memory Persistence

Write something memorable:

You: "Remember that my project uses Rust with Actix-web framework"
Agent: [Should acknowledge and write to MEMORY.md or daily log]

Restart OpenClaw:

# Stop your OpenClaw process
# Start it again
openclaw start

Verify recall:

You: "What framework am I using for my backend?"
Agent: "You're using Actix-web with Rust" [retrieved from memory search]

You should see: Agent correctly recalls the fact across sessions.


Verification

Check memory files were written:

cat ~/.openclaw/workspace/MEMORY.md
cat ~/.openclaw/workspace/memory/$(date +%Y-%m-%d).md

Confirm memory search is working:

# Check SQLite index was created
ls -lh ~/.openclaw/memory/main.sqlite

# Should show file size >0 if indexing worked

You should see: Markdown files contain your facts, SQLite index exists and has size.


Advanced: Third-Party Memory Plugins

If built-in memory still doesn't meet your needs, consider these plugins:

Best for: Cross-session persistence without file management

openclaw plugins install @mem0/openclaw-mem0

Configure in openclaw.json:

{
  "plugins": {
    "mem0": {
      "apiKey": "your-mem0-api-key",
      "userId": "unique-user-id",
      "autoRecall": true,   // Inject relevant memories automatically
      "autoCapture": true   // Extract and store facts after each exchange
    }
  }
}

Advantages:

  • Memory stored externally (survives compaction/resets/reinstalls)
  • Automatic fact extraction (no manual "write to MEMORY.md")
  • Long-term (user-scoped) vs. short-term (session-scoped) separation

Cost: Requires Mem0 API key (free tier available at app.mem0.ai)


Cognee Plugin (Best for Knowledge Graphs)

Best for: Complex projects with entity relationships

openclaw plugins install @cognee/openclaw-cognee

When to use Cognee:

  • Working across multiple projects with cross-references
  • Need to query "Who manages the Auth team?" type relationships
  • Want provenance and auditability for answers

How it works: Builds a knowledge graph on top of Markdown files. Memory files stay editable, but queries traverse entity relationships.


QMD Backend (Local-First Alternative)

Best for: Privacy-focused users, no cloud dependencies

Enable in config:

{
  "memory": {
    "backend": "qmd",  // Replaces built-in SQLite indexer
    "qmd": {
      "includeDefaultMemory": true,
      "update": { 
        "interval": "5m",
        "debounceMs": 15000 
      }
    }
  }
}

Prerequisites:

# Install QMD CLI
bun install -g github.com/tobi/qmd

# macOS users need SQLite with extensions
brew install sqlite

# Verify installation
which qmd

Advantages:

  • Fully local (no API keys)
  • Combines BM25 + vectors + reranking
  • Auto-downloads GGUF models from HuggingFace

Limitations:

  • ~600MB disk space for models
  • First search is slow (downloads models)
  • Windows requires WSL2

What You Learned

  • OpenClaw memory is file-based - agents only remember what's written to disk
  • Enable memoryFlush to prevent compaction from destroying context
  • Hybrid search (vector + BM25) improves recall across semantic and exact queries
  • Third-party plugins (Mem0, Cognee, QMD) solve specific persistence/structure needs

Limitations:

  • Built-in memory requires manual prompting ("remember this")
  • No automatic extraction without plugins
  • Manual resets still lose context (workaround: save before /new)

When NOT to use built-in memory:

  • Need cross-platform sync (OpenClaw on phone + desktop)
  • Want zero-configuration persistence
  • Building commercial agents (enterprise features like audit trails)

Common Memory Issues & Quick Fixes

"Memory search returns 401 errors"

Cause: Built-in memory search defaults to OpenAI embeddings but auth fails.

Fix:

// Option 1: Use local embeddings (no API key)
{
  "memorySearch": {
    "provider": "local",
    "fallback": "none"
  }
}

// Option 2: Set OpenAI key properly
{
  "memorySearch": {
    "provider": "openai",
    "remote": {
      "apiKey": "sk-..."  // or use OPENAI_API_KEY env var
    }
  }
}

"Agent writes to memory but can't find it later"

Cause: Memory files written but not indexed, or search disabled.

Fix:

# Force reindex
rm ~/.openclaw/memory/main.sqlite

# Restart OpenClaw - it will rebuild index
openclaw start

Verify indexing is enabled:

{
  "memorySearch": {
    "enabled": true,  // Must be true
    "sync": {
      "watch": true   // Auto-reindex when files change
    }
  }
}

"Cross-project context pollution"

Symptom: Asking about Project A returns facts from Project B.

Cause: All memory in one MEMORY.md file.

Fix - Use separate workspaces:

# Create per-project configs
~/.openclaw/
  ├── work-agent/
  │   └── workspace/
  │       └── MEMORY.md
  └── personal-agent/
      └── workspace/
          └── MEMORY.md

Run with specific config:

openclaw start --config ~/.openclaw/work-agent/openclaw.json

Better fix - Use Mem0 with session scoping:

{
  "plugins": {
    "mem0": {
      "apiKey": "...",
      "userId": "user-123",
      "sessionScope": "project-alpha"  // Isolates memories per project
    }
  }
}

"First memory search is extremely slow"

Cause: Local embeddings downloading GGUF models on first use.

Fix - Pre-download models:

# Manually warm the cache
export XDG_CONFIG_HOME="$HOME/.openclaw/agents/main/qmd/xdg-config"
export XDG_CACHE_HOME="$HOME/.openclaw/agents/main/qmd/xdg-cache"

# Trigger download (if using QMD)
qmd query "test" -c memory-root --json

# Or switch to OpenAI for instant startup
{
  "memorySearch": {
    "provider": "openai"  // No download, just needs API key
  }
}

"Session transcripts not searchable"

Cause: Session memory is experimental and opt-in.

Fix:

{
  "memorySearch": {
    "experimental": {
      "sessionMemory": true  // Enable experimental flag
    },
    "sources": ["memory", "sessions"]  // Include sessions in search
  }
}

Note: Session indexing is async and may lag by 50 messages or 100KB.


Tested on OpenClaw 2026.2.1, Node.js 22.x, macOS 14.7 & Ubuntu 24.04