> 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.5-source-deep-dive-files-as-truth-and-hybrid-search.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 28.5 Source Deep Dive: Files as the Source of Truth, and Hybrid Retrieval

> **Generated by**: Claude Opus 5 (claude-opus-5\[1m]) **Token usage**: Input \~242,000 tokens, Output \~14,000 tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`); line numbers refer to this commit

***

§44.3 lists "files first, indexes derived" as a design theme running through the codebase. The memory system is its most complete expression.

`docs/concepts/memory.md:10` opens with it:

> OpenClaw memory is **plain Markdown in the agent workspace**. The files are the source of truth; the model only "remembers" what gets written to disk.

## 28.5.1 Four Layers, Clean Boundaries

| Layer              | Medium                                     | Lifetime                                   | How it enters context                                      |
| ------------------ | ------------------------------------------ | ------------------------------------------ | ---------------------------------------------------------- |
| Session transcript | `~/.openclaw/agents/<id>/sessions/*.jsonl` | Per session, compactable                   | Natively in context                                        |
| Daily log          | `memory/YYYY-MM-DD.md` (**append-only**)   | Permanent                                  | Via `memory_search` / written by flush                     |
| Long-term memory   | `MEMORY.md` (human/model curated)          | Permanent                                  | **Injected wholesale at bootstrap** (main DM session only) |
| Vector index       | `~/.openclaw/memory/<agentId>.sqlite`      | **Derived cache, rebuildable at any time** | Serves retrieval only; never enters context directly       |

The relationship between layers three and four is the point: **the SQLite index is merely a derivative of the Markdown.**

The index stores the embedding provider, model, endpoint fingerprint, and chunking parameters, and **any change to one triggers a full rebuild** (`src/memory/manager-sync-ops.ts:878-879` checks conditions like `meta.chunkTokens !== this.settings.chunking.tokens`).

That "the index is disposable" design makes memory migration trivial: **copying the Markdown copies all your memory.**

## 28.5.2 Injection Timing: Bootstrap Wholesale Plus On-Demand Retrieval

### Session-level filtering: subagents and cron don't get memory

`MEMORY.md` is one of the workspace bootstrap files, injected wholesale at session start alongside `AGENTS.md`, `SOUL.md`, and `TOOLS.md`.

But injection is filtered per session:

```ts
// src/agents/workspace.ts:557-573
const MINIMAL_BOOTSTRAP_ALLOWLIST = new Set([
  DEFAULT_AGENTS_FILENAME,
  DEFAULT_TOOLS_FILENAME,
  DEFAULT_SOUL_FILENAME,
  DEFAULT_IDENTITY_FILENAME,
  DEFAULT_USER_FILENAME,
]);

export function filterBootstrapFilesForSession(
  files: WorkspaceBootstrapFile[],
  sessionKey?: string,
): WorkspaceBootstrapFile[] {
  if (!sessionKey || (!isSubagentSessionKey(sessionKey) && !isCronSessionKey(sessionKey))) {
    return files;
  }
  return files.filter((file) => MINIMAL_BOOTSTRAP_ALLOWLIST.has(file.name));
}
```

Note that **`MEMORY.md` is not in the allowlist**.

The motives are direct:

* `MEMORY.md` often contains private material ("the boss's name, where they live"), which **group chats and isolated tasks shouldn't see**;
* Dropping the memory text also **saves tokens** for cron jobs.

### Retrieval injection: left to the model

This is an important design orientation.

OpenClaw **does not do automatic RAG pre-injection**. Instead it uses prompt discipline to push the model into calling the tool when needed.

The system prompt has a mandatory "Memory Recall" section (`src/agents/system-prompt.ts:51`):

> Before answering anything about prior work, decisions, dates, people, preferences, or todos: run `memory_search` on `MEMORY.md` + `memory/*.md`; then use `memory_get` to pull only the needed lines.

Reinforced by the "Mandatory recall step" in `memory_search`'s tool description (`memory-tool.ts:52-53`).

> **The trade-off is explicit**: handing the call decision to the model saves per-turn retrieval overhead (an embedding + a search + injection = latency plus tokens), but **recall becomes hostage to the model's discipline** — weak models forget to check memory.
>
> The LanceDB plugin goes to the opposite extreme (§28.5.5). **The coexistence of both routes suggests the author hasn't settled the question either.**

## 28.5.3 Tools Exposed Through a Plugin Slot

`memory_search` / `memory_get` are **not hard-coded built-in tools** — they're registered by a memory-class plugin:

```ts
// extensions/memory-core/index.ts:10-27
register(api: OpenClawPluginApi) {
  api.registerTool(
    (ctx) => {
      const memorySearchTool = api.runtime.tools.createMemorySearchTool({
        config: ctx.config,
        agentSessionKey: ctx.sessionKey,
      });
      const memoryGetTool = api.runtime.tools.createMemoryGetTool({ ... });
      if (!memorySearchTool || !memoryGetTool) return null;
      return [memorySearchTool, memoryGetTool];
    },
    { names: ["memory_search", "memory_get"] },
  );
```

`plugins.slots.memory = "none"` disables them entirely. **The "slot" design means the memory backend is wholly replaceable** — the LanceDB extension is another way of filling it.

### Two security boundaries

| Boundary         | Implementation                                                                                                                            |
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| Path restriction | `memory_get` may only read paths prefixed `MEMORY.md` or `memory/` (`src/memory/internal.ts:48-57`'s `isMemoryPath`), rejecting traversal |
| Symlinks         | Index scanning **skips all symlinks** (`internal.ts:63-64`), preventing files outside the workspace from being pulled into the index      |

The second matters: without skipping symlinks, a link pointing at `~/.ssh/` would put private keys into a searchable memory index.

## 28.5.4 The Built-in Index: Hybrid Retrieval on SQLite

`MemoryIndexManager` (`src/memory/manager.ts:61`) chunks Markdown into **roughly 400-token chunks with 80-token overlap**, written into three SQLite tables:

| Table        | Purpose                                                            |
| ------------ | ------------------------------------------------------------------ |
| `chunks`     | Raw chunks                                                         |
| `chunks_vec` | sqlite-vec virtual table, **vector distance computed in-database** |
| `chunks_fts` | FTS5 full-text index                                               |

Retrieval recalls along both paths and fuses with weights:

```ts
// src/memory/hybrid.ts:127-137
const merged = Array.from(byId.values()).map((entry) => {
  const score = params.vectorWeight * entry.vectorScore + params.textWeight * entry.textScore;
  return { path: entry.path, startLine: entry.startLine, endLine: entry.endLine,
           score, snippet: entry.snippet, source: entry.source };
});
```

BM25 rank is squashed to 0..1 with `1/(1+rank)` (`hybrid.ts:46-55`), then blended by normalized weights.

**Why hybrid rather than pure vector?**

| Retrieval mode | Good at                                                      |
| -------------- | ------------------------------------------------------------ |
| Vector         | Semantic paraphrase ("that deployment problem we discussed") |
| BM25           | **IDs, error strings, code symbols** — exact tokens          |

Pure vector search for `ERR_MODULE_NOT_FOUND` performs terribly — that string's semantic embedding is meaningless, and only exact matching works.

> The docs candidly acknowledge the fusion formula **isn't IR-optimal** (linear weighting rather than RRF or normalization) but is adequate for personal notes. That kind of "good enough" candor is uncommon in open source.

### Two post-processing stages, both off by default

The complete pipeline:

```
Weighted Merge → Temporal Decay → Sort → MMR → Top-K
```

| Stage                    | Parameters                                                                              | Default |
| ------------------------ | --------------------------------------------------------------------------------------- | ------- |
| Temporal decay           | `score × e^(-λ·age)`, 30-day half-life; **`MEMORY.md` and non-dated files never decay** | Off     |
| MMR diversity re-ranking | λ=0.7, Jaccard similarity to deduplicate near-identical passages                        | Off     |

`MEMORY.md` never decaying is correct — it's curated long-term memory and shouldn't be down-weighted for being old.

> **Risk note** (§45.2): both switches default to off and **most users will never discover they exist.** For someone two years in with hundreds of daily files accumulated, temporal decay is genuinely useful.

### What retrieval failure returns

Most frameworks throw when the vector store is unavailable. OpenClaw constructs a **structured result with an actionable recommendation**:

```ts
// src/agents/tools/memory-tool.ts:195-212
function buildMemorySearchUnavailableResult(error: string | undefined) {
  const reason = (error ?? "memory search unavailable").trim() || "memory search unavailable";
  const isQuotaError = /insufficient_quota|quota|429/.test(reason.toLowerCase());
  const warning = isQuotaError
    ? "Memory search is unavailable because the embedding provider quota is exhausted."
    : "Memory search is unavailable due to an embedding/provider error.";
  const action = isQuotaError
    ? "Top up or switch embedding provider, then retry memory_search."
    : "Check embedding provider configuration and retry memory_search.";
  return { results: [], disabled: true, unavailable: true, error: reason, warning, action };
}
```

The tool description separately instructs that when `disabled=true` the model should tell the user memory is unavailable.

**Even the error path is designed as something the model can understand and relay, rather than a traceback.**

> That's exactly the "errors teach the model" approach from §45.3's contrast — OpenClaw uses the same idea here.

### Two budget and privacy details

* **Injection budget**: QMD-backend results are trimmed item by item against `maxInjectedChars` (`memory-tool.ts:169-193`'s `clampResultsByInjectedChars`), so one search can't blow up the context;
* **Citation format is session-aware**: in `citations: "auto"` mode, **DMs get a `Source: path#L12-L34` footnote while group chats have it suppressed** (`memory-tool.ts:224-227`), with path metadata reserved for `memory_get`'s internal use.

The second is thoughtful — exposing a path like `/Users/yourname/notes/...` in a group is a privacy leak.

### Embedding providers: whatever works

Selection order (`docs/concepts/memory.md:103-109`):

```
a local GGUF model path is configured → node-llama-cpp local inference
      ↓ otherwise
probe OpenAI / Gemini / Voyage / Mistral API keys in order
      ↓ none available
disabled
```

Another degradation chain (§44.2).

Large backfills also support the **asynchronous Batch APIs** of OpenAI / Gemini / Voyage (a whole family of `src/memory/batch-*.ts` files), rebuilding the index at batch-discount pricing.

**Index updates are fully asynchronous**: a chokidar watcher observes memory files (1.5 s debounce to mark dirty), background syncs are triggered at session start, on retrieval, and on a timer, and **`memory_search` never blocks waiting for the index**.

## 28.5.5 Two Replaceable Backends

### QMD: outsourcing to a local sidecar

`memory.backend = "qmd"` outsources retrieval to a local QMD sidecar (BM25 + vector + reranking). OpenClaw invokes it via CLI and confines it to each agent's own directory with XDG environment variables (`qmd-manager.ts:200-210` sets `XDG_CONFIG_HOME` / `XDG_CACHE_HOME`).

**The most engineering-savvy part is the `FallbackMemoryManager` wrapper** (`src/memory/search-manager.ts:104-139`):

```
QMD throws
   ↓
mark primaryFailed → disable QMD → evict itself from the cache
   ↓
forward the request to the built-in SQLite manager
```

**Memory tools never become unavailable because of an experimental backend.** Another instance of §44.2's degradation chains — and the "evict itself from the cache" step is key, since without it the next call would try QMD and fail again, adding latency for nothing.

QMD can also export **redacted session transcripts** as a separate collection so `memory_search` can recall past conversations. Its `scope` setting **defaults to DM-only, invisible in group chats** (preventing cross-session leakage).

### LanceDB: a completely different paradigm

`extensions/memory-lancedb` isn't a file index but an automated "fact store":

```ts
// extensions/memory-lancedb/index.ts:546-567
if (cfg.autoRecall) {
  api.on("before_agent_start", async (event) => {
    const vector = await embeddings.embed(event.prompt);
    const results = await db.search(vector, 3, 0.3);
    if (results.length === 0) return;
    return {
      prependContext: formatRelevantMemoriesContext(
        results.map((r) => ({ category: r.entry.category, text: r.entry.text })),
      ),
    };
  });
}
```

The `before_agent_start` hook **automatically retrieves the top-3 memories and prepends them**, while the `agent_end` hook automatically extracts and stores what's worth remembering.

**One crucial detail** (`index.ts:591-593`): auto-capture **only processes messages with `role === "user"`**.

The comment states the reason: **"avoid self-poisoning from model output"** — preventing model hallucinations from being solidified into "memory" and fed back into subsequent conversations.

That defense is important. If the model fabricates a fact and it gets stored, the next retrieval surfaces it and the model reasons from the fabrication as established truth — **a hallucination laundered into knowledge by its own memory system.**

## 28.5.6 Memory Rescue Before Compaction (memory flush)

§44.3 mentioned this mechanism; here's the source.

As a session approaches automatic compaction, a **silent, user-invisible agent turn** is inserted, prompting the model to write volatile context to disk.

The trigger is pure arithmetic (`src/auto-reply/reply/memory-flush.ts:195-207`):

```ts
const totalTokens = overrideTokens ?? resolveFreshSessionTotalTokens(params.entry);
// ...
const threshold = Math.max(0, contextWindow - reserveTokens - softThreshold);
if (totalTokens < threshold) return false;
if (hasAlreadyFlushedForCurrentCompaction(params.entry)) return false;
```

That is: tokens exceed `contextWindow - reserveTokensFloor (default 20k) - softThreshold (default 4k)`, **and no flush has happened yet this compaction cycle** (the cycle counter lives in `sessions.json`, preventing repeat triggers).

There's also a **2 MB transcript size** forced trigger as a backstop.

### The prompt's safety design

The default flush prompt is entirely defensive (`memory-flush.ts:25-32`):

* Only write `memory/YYYY-MM-DD.md`
* **Append only**
* Treat `MEMORY.md` / `SOUL.md` and other bootstrap files as **read-only**
* Reply `NO_REPLY` if there's nothing worth writing

Harder still is `ensureMemoryFlushSafetyHints` (`:151-159`):

> **Even if the user customizes the flush prompt, these three safety hints are forcibly re-appended.**

**Users can change the tone; they cannot change the safety boundary.**

That's a pattern worth stealing: **allow prompt customization, but make safety constraints a non-overridable suffix.** Many systems abandon control entirely once they "support custom prompts."

If the session mounts the workspace read-only under sandbox, flush is skipped.

### The complete data flow

```mermaid
flowchart LR
  subgraph Write path
    U[user conversation] --> T[session transcript JSONL]
    T -- pre-compaction flush --> D["memory/YYYY-MM-DD.md<br/>daily log (append-only)"]
    U -- "'remember this' / model initiative" --> M[MEMORY.md long-term memory]
  end
  subgraph Index
    D & M -- chokidar watch --> IDX["SQLite index<br/>chunks + FTS5 + sqlite-vec"]
    IDX -. replaceable .-> QMD[QMD sidecar]
    QMD -- failure --> IDX
  end
  subgraph Read path
    M -- "bootstrap wholesale injection<br/>(main DM session only)" --> CTX[model context]
    IDX -- "memory_search hybrid retrieval<br/>→ memory_get exact lines" --> CTX
  end
```

## 28.5.7 Three Known Weaknesses

From §45.2, with detail:

**1. The daily log grows without bound.** `memory/YYYY-MM-DD.md` only ever grows, with **no archival or compaction mechanism**. A few years in, index size and temporal-decay parameters both need manual tuning.

By contrast, cron's run sessions *do* have a reaper (24-hour reclamation) — **the handling of unbounded growth isn't consistent within the same repository.**

**2. flush's last stand can fail.** Memory flush depends on "there being enough tokens left before compaction to complete one file-writing turn." But **a long tool output can cross the soft threshold and land straight in hard compaction** — a `cat` of a large file, for instance. The 2 MB byte backstop only mitigates.

**3. Memory isolation is session-level, not field-level.** `MEMORY.md` is either **injected wholesale** (DMs) or **not at all** (groups / cron); there's no "partial memory visible" middle ground.

QMD's scope rules cover some of this, but the built-in backend has no equivalent. In practice: wanting a group agent to know "the project deadline" but not "the boss's private phone number" isn't currently possible — you'd have to split them across different agents.

***

## Section Summary

1. **Four layers with Markdown as the source of truth**: transcript / daily log (append-only) / `MEMORY.md` (bootstrap wholesale injection) / vector index (**a derived cache; a parameter change rebuilds the whole thing**). Copying the Markdown copies all your memory.
2. **Subagent and cron sessions are excluded from `MEMORY.md`** (`MINIMAL_BOOTSTRAP_ALLOWLIST`) — privacy plus token savings.
3. **Retrieval is the model's behavior, not the framework's**: no automatic RAG by default, pushed instead by the system prompt's "Mandatory recall step"; recall becomes hostage to model discipline, and the LanceDB plugin takes the opposite extreme.
4. **Two security boundaries**: `memory_get`'s path prefix restriction, and **index scanning skipping all symlinks** (keeping private keys out of the index).
5. **Hybrid retrieval = vector (semantic paraphrase) + BM25 (IDs, error strings, code symbols)**, fused linearly (the docs admit it isn't IR-optimal); temporal decay and MMR default to off, and **`MEMORY.md` never decays**.
6. **Retrieval failure returns a structured, actionable result rather than an exception** — the error path is designed as something the model can relay.
7. **QMD failure falls back to the built-in index and evicts itself from the cache**; **LanceDB's auto-capture processes only user messages**, with the stated reason of avoiding self-poisoning from model output — preventing hallucinations from being laundered into knowledge.
8. **flush's safety hints cannot be overridden by users** (`ensureMemoryFlushSafetyHints` forcibly re-appends them) — **allow tone customization, forbid changing the safety boundary**. Worth stealing.
9. Three weaknesses: **no archival for daily logs**, **long tool outputs can skip past the flush window**, and **memory isolation is only session-level, never field-level**.
