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

# 28.4 Advanced Memory Features

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

***

The first three sections covered the memory system's foundational infrastructure: Markdown file chunking, vector embedding, hybrid search. This section analyzes five advanced features: batch embedding APIs, embedding caching, session memory, QMD backend, and search manager—features that push the infrastructure from "working" to "polished".

***

## 28.4.1 Batch Indexing

### Why Batch APIs?

For users with many memory files, rebuilding the index might produce hundreds or even thousands of text chunks. If calling the embedding API one by one, each chunk one HTTP request, it's not only slow but also prone to rate limiting. Cloud providers (OpenAI, Gemini, Voyage) all offer **asynchronous batch APIs**—submit many requests at once, the server processes them in the background, returning all results at once when complete.

### Unified Batch Flow

Although the three providers' batch APIs differ in details, OpenClaw encapsulates them into the same process pattern:

```
1. Prepare requests → Build JSONL file (one embedding request per line)
2. Upload file → Upload JSONL via Files API
3. Create batch job → Call Batches API to submit task
4. Poll for completion → Periodically check task status until done
5. Download results → Get output file, parse embeddings from each line
6. Map results → Associate vectors with original text chunks via custom_id
```

Using OpenAI as an example:

```typescript
// src/memory/batch-openai.ts (simplified)

export type OpenAiBatchRequest = {
  custom_id: string;          // Unique identifier for result association
  method: "POST";
  url: "/v1/embeddings";
  body: { model: string; input: string };
};

export async function runOpenAiEmbeddingBatches(params: {
  openAi: OpenAiEmbeddingClient;
  requests: OpenAiBatchRequest[];
  wait: boolean;              // Whether to wait for completion
  pollIntervalMs: number;     // Poll interval (default 2s)
  timeoutMs: number;          // Timeout (default 60min)
  concurrency: number;        // Parallel batch count
}): Promise<Map<string, number[]>> {
  // 1. Split into groups by 50,000 (OpenAI single batch limit)
  const groups = splitOpenAiBatchRequests(params.requests);
  const byCustomId = new Map<string, number[]>();

  const tasks = groups.map(group => async () => {
    // 2. Upload JSONL → 3. Create batch job
    const batchInfo = await submitOpenAiBatch({ openAi, requests: group });

    // 4. Poll for completion
    const completed = await waitForOpenAiBatch({
      batchId: batchInfo.id,
      pollIntervalMs, timeoutMs,
    });

    // 5. Download and parse results
    const content = await fetchOpenAiFileContent({ fileId: completed.outputFileId });
    const outputLines = parseOpenAiBatchOutput(content);

    // 6. Map results
    for (const line of outputLines) {
      const embedding = line.response?.body?.data?.[0]?.embedding ?? [];
      byCustomId.set(line.custom_id, embedding);
    }
  });

  // Execute groups in parallel
  await runWithConcurrency(tasks, params.concurrency);
  return byCustomId;
}
```

### Provider Differences

| Feature            | OpenAI                  | Gemini                   | Voyage                  |
| ------------------ | ----------------------- | ------------------------ | ----------------------- |
| Single batch limit | 50,000                  | 50,000                   | 50,000                  |
| Completion window  | 24 hours                | Unlimited                | 12 hours                |
| API key header     | `Authorization: Bearer` | `x-goog-api-key`         | `Authorization: Bearer` |
| Upload format      | FormData + JSONL        | multipart/related        | FormData + JSONL        |
| Status field       | `status` (completed)    | `state` (SUCCEEDED)      | `status` (completed)    |
| Result ID          | `custom_id`             | `key` / `custom_id`      | `custom_id`             |
| Batch endpoint     | `/v1/batches`           | `asyncBatchEmbedContent` | `/v1/batches`           |

Gemini's implementation is most unique—it uses `multipart/related` format for upload (not FormData), batch endpoint is under the model path (`models/gemini-embedding-001:asyncBatchEmbedContent`), and status values are uppercase (`SUCCEEDED`/`FAILED`).

### Batch Failure Fault Tolerance

Batch APIs can fail for various reasons (network timeout, API unavailable, quota exhausted). OpenClaw implements a **progressive disabling** mechanism:

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

const BATCH_FAILURE_LIMIT = 2;

private async recordBatchFailure(params: {
  provider: string;
  message: string;
  forceDisable?: boolean;
}): Promise<{ disabled: boolean; count: number }> {
  this.batchFailureCount += 1;
  const disabled = params.forceDisable
    || this.batchFailureCount >= BATCH_FAILURE_LIMIT;
  if (disabled) {
    this.batch.enabled = false;  // Disable batch, fall back to per-item embedding
  }
  return { disabled, count: this.batchFailureCount };
}
```

The rule is simple: **after 2 cumulative failures, automatically disable batch API** and fall back to per-item `embedBatch` calls. Special cases like Gemini's `asyncBatchEmbedContent not available` error (model doesn't support batching) **disable immediately**. Successful batch operations reset the failure count.

The entire batch execution is also wrapped in `runBatchWithFallback`—even if batch API is completely unavailable, the system transparently falls back to per-item embedding:

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

private async runBatchWithFallback(params) {
  if (!this.batch.enabled) {
    return await params.fallback();        // Use per-item embedding directly
  }
  try {
    const result = await this.runBatchWithTimeoutRetry(params);
    await this.resetBatchFailureCount();   // Success, reset count
    return result;
  } catch (err) {
    await this.recordBatchFailure({ ... });
    return await params.fallback();        // Failure, fall back to per-item
  }
}
```

***

## 28.4.2 Embedding Cache Mechanism

### Cache Necessity

Each time memory files are synced, unchanged text chunks don't need re-computed embeddings. The `embedding_cache` table caches computed vectors based on **text hash**:

```typescript
// embedding_cache table composite primary key
PRIMARY KEY (provider, model, provider_key, hash)
```

Four fields together determine a cache entry:

* `provider`: Embedding provider (openai/gemini/voyage/local)
* `model`: Specific model name (text-embedding-3-small, etc.)
* `provider_key`: Fingerprint of provider configuration (e.g., hash of API baseUrl), ensuring same-named models with different configs don't mix
* `hash`: SHA-256 hash of text content

### Cache Hit Flow

When indexing files, `embedChunksInBatches` checks cache before calling API:

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

private async embedChunksInBatches(chunks: MemoryChunk[]): Promise<number[][]> {
  // 1. Load existing embeddings from cache
  const cached = this.loadEmbeddingCache(chunks.map(c => c.hash));
  const embeddings: number[][] = Array(chunks.length).fill([]);
  const missing: Array<{ index: number; chunk: MemoryChunk }> = [];

  // 2. Use cache hits directly, collect misses
  for (let i = 0; i < chunks.length; i++) {
    const hit = cached.get(chunks[i].hash);
    if (hit && hit.length > 0) {
      embeddings[i] = hit;           // Cache hit
    } else {
      missing.push({ index: i, chunk: chunks[i] }); // Cache miss
    }
  }

  if (missing.length === 0) return embeddings; // All hits, no API calls needed

  // 3. Call embedding API only for misses
  const batches = this.buildEmbeddingBatches(missing.map(m => m.chunk));
  const toCache = [];
  for (const batch of batches) {
    const batchEmbeddings = await this.embedBatchWithRetry(batch.map(c => c.text));
    // Fill results back to correct positions, collect entries to cache
    for (let i = 0; i < batch.length; i++) {
      embeddings[missing[cursor + i].index] = batchEmbeddings[i];
      toCache.push({ hash: batch[i].hash, embedding: batchEmbeddings[i] });
    }
  }

  // 4. Write newly computed embeddings to cache
  this.upsertEmbeddingCache(toCache);
  return embeddings;
}
```

### Cache Pruning

The cache table doesn't grow indefinitely. `pruneEmbeddingCacheIfNeeded` uses LRU strategy to clean expired entries:

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

private pruneEmbeddingCacheIfNeeded(): void {
  const count = this.db.prepare(
    `SELECT COUNT(*) as c FROM embedding_cache`
  ).get().c;

  if (count <= this.cache.maxEntries) return;

  const excess = count - this.cache.maxEntries;
  this.db.prepare(
    `DELETE FROM embedding_cache
     WHERE rowid IN (
       SELECT rowid FROM embedding_cache
       ORDER BY updated_at ASC      -- Delete least recently used first
       LIMIT ?
     )`
  ).run(excess);
}
```

> **Sidebar**: LRU (Least Recently Used) is a cache eviction strategy—when cache is full, delete the least recently accessed entries first. Here it's implemented via the `updated_at` field: every cache hit or write updates the timestamp, cleanup deletes oldest entries by timestamp ascending.

### Cache Optimization in Batch Queries

`loadEmbeddingCache` queries in batches (400 per batch) to avoid overly long SQL `IN` clauses:

```typescript
const batchSize = 400;
for (let start = 0; start < unique.length; start += batchSize) {
  const batch = unique.slice(start, start + batchSize);
  const placeholders = batch.map(() => "?").join(", ");
  const rows = this.db.prepare(
    `SELECT hash, embedding FROM embedding_cache
     WHERE provider = ? AND model = ? AND provider_key = ?
       AND hash IN (${placeholders})`
  ).all(...baseParams, ...batch);
}
```

***

## 28.4.3 Session Memory Search (Experimental)

### Why Index Session Records?

Memory files record information users actively save. But vast valuable context exists in **historical conversations**—technical solutions users discussed, bugs they fixed, decisions they made. Session memory search allows the Agent to retrieve these historical conversation snippets.

### Session File Format

OpenClaw's session records are stored as JSONL files (one JSON object per line), located in the Agent's transcripts directory:

```
~/.openclaw/state/agents/{agentId}/transcripts/
├── session-abc123.jsonl
├── session-def456.jsonl
└── ...
```

`buildSessionEntry` parses JSONL files, extracting text content from `user` and `assistant` roles, and redacting sensitive information:

```typescript
// src/memory/session-files.ts (simplified)

export async function buildSessionEntry(absPath: string): Promise<SessionFileEntry | null> {
  const raw = await fs.readFile(absPath, "utf-8");
  const lines = raw.split("\n");
  const collected: string[] = [];

  for (const line of lines) {
    const record = JSON.parse(line);
    if (record.type !== "message") continue;

    const { role, content } = record.message;
    if (role !== "user" && role !== "assistant") continue;

    const text = extractSessionText(content);
    if (!text) continue;

    const safe = redactSensitiveText(text, { mode: "tools" }); // Redact
    const label = role === "user" ? "User" : "Assistant";
    collected.push(`${label}: ${safe}`);
  }

  return {
    path: `sessions/${path.basename(absPath)}`,
    absPath,
    hash: hashText(collected.join("\n")),
    content: collected.join("\n"),
  };
}
```

Note the `redactSensitiveText` call—session records may contain API Keys, passwords, and other sensitive information, which are redacted before writing to the index.

### Incremental Sync

Session file syncing uses a delta mechanism: only reindex when file size or message count exceeds a threshold, avoiding frequent conversation updates triggering full rebuilds. Session chunks are marked with `source: "sessions"`, coexisting with memory chunks (`source: "memory"`) in the same SQLite database but can be filtered independently.

***

## 28.4.4 QMD Backend (BM25 + Vector + Reranking)

### What is QMD?

QMD is an **external CLI tool** providing more powerful search capabilities than the built-in engine—BM25 full-text search + vector search + reranking. OpenClaw integrates it through the `QmdMemoryManager` class, as an advanced alternative to the built-in memory engine.

> **Sidebar**: Reranking is a two-stage strategy in information retrieval. The first stage (recall) uses BM25 or vector search to quickly get many candidates; the second stage (reranking) uses a more precise but slower model (like Cross-Encoder) to re-rank candidates. This is similar to search engines using inverted indexes for coarse filtering, then machine learning models for fine ranking.

### Architecture Design

`QmdMemoryManager` calls the external `qmd` command via `child_process.spawn`, implementing the same `MemorySearchManager` interface as the built-in engine:

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

export class QmdMemoryManager implements MemorySearchManager {
  private readonly env: NodeJS.ProcessEnv;  // XDG environment variables

  async search(query: string, opts?) {
    const args = ["query", query, "--json", "-n", String(limit)];
    const { stdout } = await this.runQmd(args, { timeoutMs });
    const parsed = JSON.parse(stdout) as QmdQueryResult[];
    // Parse results, path mapping, score filtering...
    return results;
  }

  async sync(params?) {
    await this.runQmd(["update"], { timeoutMs: 120_000 });
    // Execute embed command per configuration interval
    if (shouldEmbed) {
      await this.runQmd(["embed"], { timeoutMs: 120_000 });
    }
  }

  private async runQmd(args: string[], opts?) {
    return new Promise((resolve, reject) => {
      const child = spawn(this.qmd.command, args, {
        env: this.env,      // XDG_CONFIG_HOME, XDG_CACHE_HOME
        cwd: this.workspaceDir,
      });
      // Collect stdout/stderr, timeout SIGKILL...
    });
  }
}
```

### Collection Management

QMD uses the **collection** concept to organize index sources. Each collection corresponds to a directory and file matching pattern:

```typescript
// Default collection layout
collections = [
  { name: "memory-root", path: workspaceDir, pattern: "MEMORY.md" },
  { name: "memory-alt",  path: workspaceDir, pattern: "memory.md" },
  { name: "memory-dir",  path: workspaceDir + "/memory", pattern: "**/*.md" },
  // If session indexing enabled:
  { name: "sessions",    path: sessionsExportDir, pattern: "**/*.md" },
];
```

Collections are created via `qmd collection add` command, OpenClaw checks and ensures all configured collections exist during initialization.

### Session Export

QMD doesn't directly read JSONL session files—it needs Markdown. The `exportSessions` method converts session records to Markdown files, stored in the export directory for QMD to index:

```typescript
private async exportSessions(): Promise<void> {
  const files = await listSessionFilesForAgent(this.agentId);
  for (const sessionFile of files) {
    const entry = await buildSessionEntry(sessionFile);
    if (cutoff && entry.mtimeMs < cutoff) continue;     // Skip expired
    const target = path.join(exportDir, `${basename}.md`);
    await fs.writeFile(target, this.renderSessionMarkdown(entry)); // JSONL → Markdown
  }
  // Clean up old files no longer needed in export directory
}
```

### Scheduled Updates

QMD's index updates are completed via two commands: `qmd update` (scan file changes) and `qmd embed` (generate embedding vectors). Update strategy:

| Parameter                | Default    | Description                                                 |
| ------------------------ | ---------- | ----------------------------------------------------------- |
| `update.onBoot`          | `true`     | Execute update immediately on startup                       |
| `update.intervalMs`      | 5 minutes  | Execute update periodically                                 |
| `update.debounceMs`      | 15 seconds | Debounce: skip if less than this interval since last update |
| `update.embedIntervalMs` | 60 minutes | Minimum execution interval for embed command                |

Embed interval is much larger than update interval—file scanning is fast, but embedding computation is slow.

### Scope Control

QMD supports **scope control** based on session keys, limiting which chat contexts can use QMD search:

```typescript
// Default scope: allow direct messages only, deny groups
const DEFAULT_QMD_SCOPE = {
  default: "deny",
  rules: [
    { action: "allow", match: { chatType: "direct" } },
  ],
};
```

***

## 28.4.5 Search Manager (search-manager.ts)

### Two-Level Management Architecture

`getMemorySearchManager` is the final entry point for memory search. It decides whether to use QMD or the built-in engine, and provides transparent failover between them:

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

export async function getMemorySearchManager(params: {
  cfg: OpenClawConfig;
  agentId: string;
}): Promise<MemorySearchManagerResult> {
  const resolved = resolveMemoryBackendConfig(params);

  if (resolved.backend === "qmd" && resolved.qmd) {
    // Prefer QMD
    const primary = await QmdMemoryManager.create({ cfg, agentId, resolved });
    if (primary) {
      // Wrap with FallbackMemoryManager
      return { manager: new FallbackMemoryManager({
        primary,
        fallbackFactory: async () => {
          const { MemoryIndexManager } = await import("./manager.js");
          return await MemoryIndexManager.get(params);
        },
      }) };
    }
  }

  // QMD unavailable or unconfigured, use built-in engine
  const { MemoryIndexManager } = await import("./manager.js");
  return { manager: await MemoryIndexManager.get(params) };
}
```

### FallbackMemoryManager

`FallbackMemoryManager` implements the **transparent failover** pattern:

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

class FallbackMemoryManager implements MemorySearchManager {
  private primaryFailed = false;
  private fallback: MemorySearchManager | null = null;

  async search(query, opts?) {
    if (!this.primaryFailed) {
      try {
        return await this.deps.primary.search(query, opts);
      } catch (err) {
        this.primaryFailed = true;         // Mark primary engine failed
        this.lastError = err.message;
        await this.deps.primary.close();   // Close primary engine
      }
    }
    // Lazy-create fallback engine
    const fallback = await this.ensureFallback();
    return await fallback.search(query, opts);
  }

  private async ensureFallback(): Promise<MemorySearchManager | null> {
    if (!this.fallback) {
      this.fallback = await this.deps.fallbackFactory(); // Dynamically import built-in engine
    }
    return this.fallback;
  }
}
```

This design has three elegant aspects:

1. **Lazy fallback**: Only create fallback engine (built-in) after primary (QMD) actually fails, avoiding wasted resources.
2. **Permanent switch**: Once `primaryFailed` is `true`, all subsequent searches use the fallback path, never retrying the failed primary.
3. **Unified interface**: Completely transparent to callers—whether underlying is QMD, built-in, or fallback built-in, `search()` signature and return type are identical.

### Caching Strategy

The search manager uses `QMD_MANAGER_CACHE` to cache created manager instances:

```typescript
const QMD_MANAGER_CACHE = new Map<string, MemorySearchManager>();
```

Cache key is composed of `agentId` and stable serialization of QMD config (sorted JSON), ensuring:

* Same Agent with same config reuses same instance
* Config changes automatically create new instance
* Removed from cache on `close()`

***

## Summary of This Section

1. **Batch embedding APIs** pack hundreds of embedding requests into one async task, supporting three providers: OpenAI, Gemini, Voyage. After 2 cumulative failures, automatically disable and transparently fall back to per-item embedding.
2. **Embedding cache** uses four-dimensional composite key based on text hash (provider + model + provider\_key + hash), checks cache before API calls during indexing, LRU strategy controls cache size.
3. **Session memory search** parses JSONL conversation records into text chunks and indexes them, supports sensitive information redaction and incremental sync, enabling Agent to retrieve historical conversation content.
4. **QMD backend** provides three-stage search (BM25 + vector + reranking) via external CLI, uses collections to manage multi-source data, scheduled index updates, supports scope control.
5. **Search manager** implements two-level architecture: QMD preferred → built-in fallback. `FallbackMemoryManager` provides transparent failover, ensuring search functionality is always available.
6. **Degradation philosophy** runs through the entire memory system—from embedding providers, vector search, batch APIs to backend selection, each level has fallback plans, reflecting the **availability-first** design principle.

***

> ### 🔬 Going Deeper: 28.5 Source Deep Dive
>
> That's the end of the chapter's main text. If you're going to **modify this code**, or reproduce it in your own project, read on: [**28.5 Source Deep Dive: Files as the Source of Truth, and Hybrid Retrieval**](https://www.openclawbook.xyz/en/ch28-memory-system/28.5-source-deep-dive-files-as-truth-and-hybrid-search.md) traces the real implementation line by line along with the issues behind it, at a noticeably higher information density.
>
> **The main text is for understanding structure; the deep dive is for understanding trade-offs.**
