> 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/ch28-memory-system/28.1-memory-model-design.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 28.1 Memory Model Design

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

***

LLMs have no persistent memory—each conversation starts from scratch. The preferences the user told the Agent yesterday, the project decisions discussed last week, the to-do items recorded last month—all disappear in a new conversation. OpenClaw's memory system solves this problem: it enables the Agent to **remember and retrieve important information across sessions**.

This section analyzes the design philosophy, file layout, and core manager of the memory system.

***

## 28.1.1 "Pure Markdown as Memory" Design Philosophy

### Why Not Use a Database?

Many AI Agent frameworks store memory in vector databases (like Pinecone, Weaviate) or relational databases. OpenClaw chose a different path: **the "source" of memory is pure Markdown files**.

```
~/.openclaw/
├── MEMORY.md              ← Long-term memory (manually maintained or Agent-written)
├── memory/
│   ├── 2026-01-15.md      ← Log-style memory (auto-generated by date)
│   ├── 2026-01-16.md
│   └── project-notes.md   ← Custom memory files
```

This design has several deep considerations:

| Feature             | Markdown Approach                      | Database Approach                 |
| ------------------- | -------------------------------------- | --------------------------------- |
| **Readability**     | Users can read and edit directly       | Requires specialized query tools  |
| **Version Control** | Can be managed with Git                | Requires export/migration tools   |
| **Agent Writing**   | Agent writes directly using file tools | Requires specialized API          |
| **Portability**     | Copy files to migrate                  | Requires database driver/protocol |
| **Debugging**       | `cat MEMORY.md`                        | Requires database client          |

In other words, OpenClaw treats Markdown files as the **source of truth**, and vector indexes are merely **derived indexes** built for search acceleration. Lost indexes can be rebuilt, but Markdown files contain all original information.

### Path Determination

The `isMemoryPath` function defines which files belong to "memory":

```typescript
// src/memory/internal.ts

export function isMemoryPath(relPath: string): boolean {
  const normalized = normalizeRelPath(relPath);
  if (normalized === "MEMORY.md" || normalized === "memory.md") {
    return true;
  }
  return normalized.startsWith("memory/");
}
```

The rule is simple: `MEMORY.md` (or `memory.md`) in the root directory, and all `.md` files under the `memory/` directory.

***

## 28.1.2 Memory File Layout

### Long-term Memory: MEMORY.md

`MEMORY.md` is the user's **long-term memory file**, typically containing persistent preferences, rules, and knowledge. It can be manually edited by the user or written by the Agent during conversations. Typical content:

```markdown
# User Preferences
- Programming language preferences: TypeScript, Python
- Editor: VS Code
- Communication style: Concise and direct

# Project Conventions
- Code style: Use ESLint + Prettier
- Test framework: Vitest
- Deployment environment: AWS ECS

# Important Decisions
- 2026-01-10: Decided to migrate from REST to GraphQL
- 2026-01-15: Chose PostgreSQL to replace MongoDB
```

### Log Memory: memory/YYYY-MM-DD.md

Date-named files under the `memory/` directory are **snapshots of session memory**. When the user starts a new session with the `/new` command, the `session-memory` hook automatically saves key conversation content from the current session here:

```typescript
// src/hooks/bundled/session-memory/handler.ts (simplified)

const memoryDir = path.join(workspaceDir, "memory");
await fs.mkdir(memoryDir, { recursive: true });

// Generate filename with date and description
const filename = `${date}-${slug}.md`;  // e.g., "2026-01-15-graphql-migration.md"

// Extract user and assistant messages from session (filter out tool calls)
const entry = messages
  .filter(msg => msg.role === "user" || msg.role === "assistant")
  .filter(msg => typeof msg.content === "string")
  .map(msg => `${msg.role}: ${msg.content}`)
  .join("\n\n");

await fs.writeFile(memoryFilePath, entry, "utf-8");
```

### Additional Memory Paths

Beyond standard paths, users can add additional memory directories through configuration:

```typescript
// src/memory/internal.ts

export function normalizeExtraMemoryPaths(
  workspaceDir: string,
  extraPaths?: string[],
): string[] {
  return extraPaths
    ?.map(value => value.trim())
    .filter(Boolean)
    .map(value => path.isAbsolute(value)
      ? path.resolve(value)
      : path.resolve(workspaceDir, value))
    ?? [];
}
```

This allows users to include team-shared knowledge bases, project documentation, and other resources in the memory search scope.

### File Discovery

The `listMemoryFiles` function scans all memory files:

```typescript
// src/memory/internal.ts (simplified)

export async function listMemoryFiles(
  workspaceDir: string,
  extraPaths?: string[],
): Promise<string[]> {
  const result: string[] = [];

  // 1. MEMORY.md and memory.md in root directory
  await addMarkdownFile(path.join(workspaceDir, "MEMORY.md"));
  await addMarkdownFile(path.join(workspaceDir, "memory.md"));

  // 2. Recursive scan of memory/ directory
  await walkDir(path.join(workspaceDir, "memory"), result);

  // 3. Additional paths
  for (const inputPath of normalizeExtraMemoryPaths(workspaceDir, extraPaths)) {
    const stat = await fs.lstat(inputPath);
    if (stat.isDirectory()) await walkDir(inputPath, result);
    else if (stat.isFile() && inputPath.endsWith(".md")) result.push(inputPath);
  }

  // 4. Deduplication (via realpath)
  return dedupeByRealpath(result);
}
```

Note the security measure: `walkDir` **skips symbolic links** (`entry.isSymbolicLink()`), preventing uncontrolled files from being introduced via symlinks.

***

## 28.1.3 Memory Manager (`src/memory/manager.ts`)

### MemoryIndexManager

`MemoryIndexManager` is the core engine of the memory system. It is responsible for: file indexing, vector embedding, BM25 full-text search, hybrid ranking, and cache management.

```typescript
// src/memory/manager.ts

export class MemoryIndexManager implements MemorySearchManager {
  private readonly cfg: OpenClawConfig;
  private readonly agentId: string;
  private readonly workspaceDir: string;
  private readonly settings: ResolvedMemorySearchConfig;
  private provider: EmbeddingProvider;   // Embedding provider
  private db: DatabaseSync;              // SQLite database
  private watcher: FSWatcher | null;     // File watcher
  private dirty: boolean;               // Whether reindexing is needed
  // ...
}
```

### Singleton Cache

`MemoryIndexManager` obtains instances through the static method `get`, using a global cache to avoid duplicate creation:

```typescript
// src/memory/manager.ts

const INDEX_CACHE = new Map<string, MemoryIndexManager>();

static async get(params: {
  cfg: OpenClawConfig;
  agentId: string;
}): Promise<MemoryIndexManager | null> {
  const settings = resolveMemorySearchConfig(cfg, agentId);
  if (!settings) return null;

  // Cache key = agentId + workspaceDir + serialized config
  const key = `${agentId}:${workspaceDir}:${JSON.stringify(settings)}`;
  const existing = INDEX_CACHE.get(key);
  if (existing) return existing;

  // Create embedding provider
  const providerResult = await createEmbeddingProvider({ ... });

  // Create and cache manager
  const manager = new MemoryIndexManager({ ... });
  INDEX_CACHE.set(key, manager);
  return manager;
}
```

> **Sidebar: Singleton Pattern and Cache Keys**
>
> The Singleton Pattern ensures a class has only one instance. Here, a Map is used as a cache, with the Key composed of agentId + serialized configuration. This means the same Agent with the same configuration shares the same manager instance, but different Agents or different configurations create independent instances. This is more flexible than traditional singletons—it's a **parameterized singleton**.

### Configuration Resolution

Memory search configuration is uniformly resolved by `resolveMemorySearchConfig`, supporting global defaults and per-Agent overrides:

```typescript
// src/agents/memory-search.ts (simplified)

export type ResolvedMemorySearchConfig = {
  enabled: boolean;
  sources: Array<"memory" | "sessions">;     // Data sources
  extraPaths: string[];                       // Additional paths
  provider: "openai" | "local" | "gemini" | "voyage" | "auto";  // Embedding provider
  model: string;                              // Embedding model
  store: {
    driver: "sqlite";
    path: string;                             // Index file path
    vector: { enabled: boolean; extensionPath?: string };
  };
  chunking: { tokens: number; overlap: number };  // Chunking parameters
  query: {
    maxResults: number;                       // Maximum results to return
    minScore: number;                         // Minimum score threshold
    hybrid: {
      enabled: boolean;                       // Whether to enable hybrid search
      vectorWeight: number;                   // Vector weight (default 0.7)
      textWeight: number;                     // Text weight (default 0.3)
      candidateMultiplier: number;            // Candidate multiplier
    };
  };
  cache: { enabled: boolean; maxEntries?: number };
  // ...
};
```

Default values are carefully tuned:

| Parameter             | Default | Meaning                                     |
| --------------------- | ------- | ------------------------------------------- |
| `chunking.tokens`     | 400     | Each chunk \~400 tokens (\~1600 characters) |
| `chunking.overlap`    | 80      | Adjacent chunks overlap by 80 tokens        |
| `query.maxResults`    | 6       | Return at most 6 results                    |
| `query.minScore`      | 0.35    | Results below 0.35 score are discarded      |
| `hybrid.vectorWeight` | 0.7     | Vector similarity accounts for 70% weight   |
| `hybrid.textWeight`   | 0.3     | Keyword matching accounts for 30% weight    |

### File Chunking

Markdown files are divided into fixed-size **chunks**, each chunk independently embedded as a vector:

```typescript
// src/memory/internal.ts

export function chunkMarkdown(
  content: string,
  chunking: { tokens: number; overlap: number },
): MemoryChunk[] {
  const maxChars = Math.max(32, chunking.tokens * 4); // Rough estimate: 1 token ≈ 4 characters
  const overlapChars = Math.max(0, chunking.overlap * 4);
  const chunks: MemoryChunk[] = [];

  let current: Array<{ line: string; lineNo: number }> = [];
  let currentChars = 0;

  for (let i = 0; i < lines.length; i++) {
    const lineSize = line.length + 1;
    if (currentChars + lineSize > maxChars && current.length > 0) {
      flush();         // Output current chunk
      carryOverlap();  // Retain tail as beginning of next chunk
    }
    current.push({ line, lineNo: i + 1 });
    currentChars += lineSize;
  }
  flush();
  return chunks;
}
```

> **Sidebar: Chunking and Overlap**
>
> Why chunk? Because embedding models have input length limits (e.g., 8192 tokens), and shorter text typically produces more precise semantic vectors. The challenge of chunking is **semantic breakage**—a coherent passage may be cut off at the boundary between two chunks. **Overlap** mitigates this by having adjacent chunks share a portion of text. For example, 80 tokens of overlap means the last 80 tokens of chunk A also appear at the beginning of chunk B.

### File Watching and Dirty Marking

The manager uses `chokidar` to watch for changes in memory files and sets the `dirty` flag:

```typescript
// src/memory/manager.ts (simplified)

private ensureWatcher() {
  const watchPaths = [
    path.join(this.workspaceDir, "MEMORY.md"),
    path.join(this.workspaceDir, "memory.md"),
    path.join(this.workspaceDir, "memory"),
  ];

  this.watcher = chokidar.watch(watchPaths, {
    ignoreInitial: true,
    awaitWriteFinish: { stabilityThreshold: 1500 },
  });

  const markDirty = () => {
    this.dirty = true;
    this.scheduleWatchSync();  // Debounced trigger for reindexing
  };

  this.watcher.on("add", markDirty);
  this.watcher.on("change", markDirty);
  this.watcher.on("unlink", markDirty);
}
```

When the Agent calls `memory_search`, if `dirty` is `true`, it triggers an incremental sync before executing the search—implementing **lazy indexing**.

***

## Summary of This Section

1. **"Markdown as Memory"** is the core design philosophy—pure text files as the source of truth, vector indexes are merely derived data.
2. **Memory has a two-layer structure**—`MEMORY.md` stores long-term knowledge, `memory/YYYY-MM-DD.md` stores session snapshots.
3. **MemoryIndexManager is the core engine**—managing the entire memory lifecycle through parameterized singleton caching, file watching, lazy indexing, and other mechanisms.
4. **Chunking algorithm uses lines as units**—estimates token count by character count, supports overlap to avoid semantic breakage.
5. **File watching enables real-time awareness**—`chokidar` listens for file changes, sets dirty flags, rebuilds indexes on-demand during search.
6. **Configuration supports multi-layer overrides**—global defaults → Agent-level overrides, including embedding providers, chunking strategies, search parameters, etc.
