The model forgets everything when a turn ends. So the agent writes notes to files and searches them later. On three questions, vector search alone gets 2 right, keyword search gets 1, and the hybrid with time decay gets all 3.
Pick a question, then pick a search. Watch which notes reach the prompt and what the agent answers. Then we build the memory piece by piece, from one file to a nightly job that decides what to keep.
You need a rough idea of a prompt (Lesson 5) and what a list and a set are in Python. We build the rest from zero.
Lesson 8 of 11 in Anatomy of an Agent Gateway. The running example is OpenClaw memory. We checked every OpenClaw detail here against its documentation.
Illustrative toy: six notes, dated up to 21 November. We set the vector scores by hand. The keyword score is the share of question words a note holds, and the merge weight is 0.5. Decay halves a dated note every 30 days, as in OpenClaw.
Chapter 0
See why nothing survives a turn, and move memory out of the model into files
On Monday you tell your agent: "I'm Sam, and I use metric units." On Wednesday you open a new chat and ask for the weather. It answers in Fahrenheit and asks your name.
The model is stateless: it keeps nothing between calls. You send it a prompt, it sends back text, and that is the whole exchange. A long chat only feels like memory because the gateway sends the recent conversation again with every turn. A new session starts empty.
Press Replay the week with the file off. Read what the agent says on Wednesday and next Monday. Then turn on Write to MEMORY.md and replay.
Illustrative toy: two facts said on Monday, three sessions, no shared transcript between sessions.
So memory must live outside the model. OpenClaw's answer is plain: durable memory is Markdown files on disk. To remember, the agent writes a line to a file. To recall, the gateway puts part of a file into the next prompt. You can open the file, read what the agent believes, and fix a wrong line by hand.
Three verbs carry the rest of the lesson: write the note, find it again, inject it into the prompt. A fourth job runs at night and decides which notes to keep for good.
Chapter 1
Sort notes into four files by how long they stay true, and see when each file reaches the prompt
One big file does not work. It grows too large to send every turn. It also mixes "allergic to peanuts", true for years, with "waiting on the API key", true for an afternoon. So OpenClaw splits memory by lifespan.
| File | Holds | Reaches the prompt |
|---|---|---|
USER.md | stable preferences and style, written as directives (optional) | at session start, under its own small budget |
MEMORY.md | durable facts and decisions | at session start, within the bootstrap budget |
memory/YYYY-MM-DD.md | daily notes: today's working context | when a search finds them; today's and yesterday's also load on a bare /new or /reset |
DREAMS.md | the dream diary: what the nightly job saw and promoted (optional) | never; it is for a person to review |
Pick a note. The page files it by how long it stays true, then draws the path from that file to the prompt.
The four files and their load rules follow OpenClaw's memory docs. We made up the notes.
The split copies human memory. Daily notes are working memory: most of it fades. MEMORY.md is long-term memory: small, curated, always present. A nightly job, dreaming (Chapter 7), moves the few notes that keep proving useful from one to the other.
Why not load every daily note? A week of notes is thousands of words, most of it stale: the build is fixed, the meeting is over. Sent every turn, they crowd out the conversation. So OpenClaw indexes all memory files for search. A daily note reaches the prompt only when a question touches it.
/context list shows how big each injected file is.MEMORY.md.Chapter 2
Score each note by meaning and by exact words, then blend the two scores into one ranking
You ask "which machine is the gateway host?" The answer is somewhere in a month of notes. The agent's tool memory_search runs two searches and merges them: hybrid search.
The first leg is vector search. An embedding model turns text into a list of numbers, a vector. Texts with the same meaning get vectors that point the same way. So the angle between two vectors measures how alike two texts are.
Call the question's vector q and the note's vector d. The score is the cosine similarity.
The cosine of q and d equals q dot d, divided by the length of q times the length of d.
Multiply q and d number by number and add. Divide by both lengths, so a long note does not win for being long. What is left is the angle as a score.
With made-up vectors q = (0.85, 0.25, 0.15) and d = (0.9, 0.3, 0.1): q · d = 0.765 + 0.075 + 0.015 = 0.855. ‖q‖ = 0.899 and ‖d‖ = 0.954. cos = 0.855 / 0.857 = 0.997: nearly the same meaning.
The second leg is keyword search. OpenClaw's built-in store uses BM25, a classic score that rewards notes holding the question's exact words, rare words most. It finds what vectors miss: error codes, file names, config keys. To an embedding model, E_AUTH_4031 has no meaning.
Vectors miss exact strings. Keywords miss new words for the same idea, and any typo. So blend them. Call the vector score v, the keyword score k, and the weight on meaning w.
h equals w times v, plus one minus w, times k.
Take w of the vector score v and the rest, one minus w, of the keyword score k. Add them. Rank the notes by h.
Toy notes, w = 0.5, question "E_AUTH_4031 again?". The error note has v = 0.31 and k = 1, so h = 0.155 + 0.5 = 0.655. The lunch note has v = 0.34 and k = 0, so h = 0.17. Vectors alone put lunch first; the merge puts the error note first.
Each note has three bars: vector, keyword, merged. Pick a question and drag w. Find the w where every question puts a relevant note first.
Illustrative toy, the hero's notes. No decay yet, so the stale Linux-box note can win the "new words" question; Chapter 3 fixes that.
OpenClaw adds two details. It scales keyword scores per question, so the best keyword match never scores above the best vector match. And if the embedding service fails while the provider is unset, auto or local, search falls back to keywords only. The docs do not list the default weights.
Chapter 3
Shrink a dated note's score by half every 30 days, and leave durable facts alone
In August you wrote "gateway host: old Linux box". In November you moved the gateway to a Mac mini. Ask "which machine is the gateway host?" and the August note wins: it holds both words, "gateway" and "host". It matches best and it is wrong.
Relevance and recency are two different things. Temporal decay adds recency: it multiplies a dated note's score by a factor that shrinks with the note's age. The factor halves once per half-life.
Call the hybrid score h, the note's age in days a, and the half-life in days T. The score after decay is s.
s equals h times one half to the power a over T.
Count how many half-lives T fit into the age a. Halve the score h that many times. A note of age 0 keeps all of h; a note of age T keeps half.
The toy August note has h = 0.733 and a = 111 days. 111 / 30 = 3.7 half-lives, and (1/2)3.7 = 0.077. So s = 0.733 × 0.077 = 0.056. The Mac-mini note in MEMORY.md keeps s = h = 0.597 and wins.
Left: the decay curve. Right: the three notes about the gateway host, ranked. Drag the age of the August note and find the day it stops winning.
Illustrative toy scores from Chapter 2, question "new words". OpenClaw fixes T at 30 days; the T slider is here so you can feel the trade.
Some notes must never fade. "Your timezone is Pacific" is as true in year two as on day one. OpenClaw treats MEMORY.md, USER.md and undated files under memory/ as evergreen: no decay. Dated notes decay at any folder depth.
One more rule from the docs: decay changes only the order. A note must first clear the search's minimum score, 0.35 by default, before decay. Decay then sorts the notes that passed.
MEMORY.md.Chapter 4
Pick results one at a time, and charge each pick for how much it repeats the picks before it
Ask "what do we know about the gateway host?" The top three notes all say "the gateway runs on the Mac mini", in three wordings. The note with the port number ranks fifth and never reaches the prompt. Three slots, one fact.
Maximal Marginal Relevance (MMR) fixes this. It picks one note at a time. Each candidate gets its relevance, minus a charge for how much it looks like a note already picked. The first pick has nothing to repeat, so it is the most relevant note.
First, how alike are two notes? OpenClaw uses the Jaccard overlap of their words. Call the word sets of two notes A and B.
J of A and B equals the size of A intersect B, divided by the size of A union B.
Count the words the two notes share. Divide by the count of all their different words. That share is J.
A = {gateway, runs, mac, mini} and B = {gateway, runs, mac, mini, now}. They share 4 words out of 5 different ones. J = 4 / 5 = 0.8.
Now the pick. Call the set of notes picked so far S, a candidate i, its relevance ri, and the trade-off knob λ (lambda).
Next equals the argmax over i not in S of: lambda r-i, minus one minus lambda, times the max over j in S of J of i, j.
For each candidate i, take lambda of its relevance r-i. Subtract one minus lambda times its overlap with the most similar note in S. Pick the best, add it to S, and repeat.
Toy step 2, λ = 0.7, S = {"gateway runs on the Mac mini"}. "Gateway runs on Mac mini now": 0.7 × 0.84 − 0.3 × 0.8 = 0.348. "Gateway port is 18789": 0.7 × 0.58 − 0.3 × 0.167 = 0.356. The port note wins the slot by 0.008.
Warm bars are relevance; red marks are the repeat charge against the picks so far. Press Pick next three times. Then move λ to 1 and pick again.
Illustrative toy relevances. The overlap is the real Jaccard of each note's words, computed live. OpenClaw runs MMR by default with λ = 0.7 and no setting to change it.
MMR in OpenClaw reorders the candidates. It does not change their scores or which ones pass the minimum, and it needs no extra model call. It does not run when search falls back to keywords only or vectors only.
Chapter 5
Cut the copy that goes into the prompt, keep the file whole, and fetch the rest with a tool
The model reads a limited number of tokens per turn. Memory shares that room with the instructions, the conversation and the tool list. So memory reaches the prompt by two paths.
| Path | What | Cost |
|---|---|---|
| always on | USER.md and MEMORY.md, injected at session start | prompt room on every turn |
| on demand | memory_search finds notes; memory_get reads a file or a line range | one tool call, only when needed |
What if MEMORY.md grows past the bootstrap budget? The injected copy is cut to fit. The file on disk stays whole. The cut part is still one memory_get away. Lesson 5 covers the caps: 20,000 characters per file by default.
Left: the file on disk. Right: the prompt copy. Drag the cap down and watch the copy shrink while the file stays whole. Then press memory_get the rest.
Illustrative 45,000-character MEMORY.md. The 20,000 default cap is OpenClaw's per-file bootstrap cap (Lesson 5).
The search path has its own sizes. The index splits each file into chunks, overlapping pieces that the search scores one by one. Call the file length in tokens L, the chunk size c and the overlap o. The number of chunks is n.
n equals the ceiling of L minus o, over c minus o.
Each chunk holds o tokens it shares with its neighbour and c minus o new ones. Take the overlap o off the length L once. Divide by the new tokens per chunk, c minus o, and round up.
A daily note of L = 2,000 tokens, c = 400, o = 80. (2,000 − 80) / 320 = 6. Six chunks. A search returns at most 6 hits by default, so a full answer is at most 6 × 400 = 2,400 tokens of notes.
MEMORY.md./context detail.Chapter 6
Record who wrote each memory and when, and check both before the agent acts on it
Three weeks ago you said "go ahead and deploy", meaning that afternoon. Today a search finds the line. If the agent reads it as a live permission, it deploys on its own. The memory is true as a record. It is false as an order.
Most memories answer "what is true?" A memory that grants a permission must also answer "who said it?" and "until when?" Recall must carry both answers to the moment the agent acts.
The memory says "you may deploy to production". Choose who wrote it, then drag its age past the 24-hour window.
Illustrative rule, not OpenClaw code: act only on an owner's permission inside its window. The origin classes and the untrusted rule come from OpenClaw's provenance docs.
OpenClaw records provenance, where a memory came from, in database columns the model cannot write through prose. Each piece of indexed text gets an origin class: owner, agent, untrusted or system.
| Rule | What OpenClaw does |
|---|---|
| untrusted write | a non-owner turn, a turn tainted by web results, or a changed file hash marks MEMORY.md untrusted. It then leaves automatic context; tools can still read it, wrapped as untrusted |
| supersession | entries carry a supersession key and an observed time, so a newer fact replaces an older one |
| expiry | standing intents, which fire on an event, expire after 90 days, with a 24-hour cooldown and at most 3 firings |
| background sessions | cron, heartbeat and sub-agent sessions cannot produce memories eligible for promotion |
Chapter 7
Score each candidate note at night, and promote it to long-term memory only if it clears three gates
How does a fact climb from a daily note into MEMORY.md? Doing it during a chat would be slow and distracting. OpenClaw does it offline, the way sleep does for people. It calls this dreaming. It is on by default and runs as one scheduled job, at 3:00 every morning unless you change dreaming.frequency.
MEMORY.md.One writer makes the job safe to run unattended. Light and REM can stop halfway with no harm. All the lasting change sits behind Deep's thresholds.
Deep scores a candidate from six signals, each a strength from 0 to 1. Call signal k's strength xk and its weight wk. The score is S.
S equals the sum over k of w-k times x-k.
Multiply each signal's strength x-k by its weight w-k. Add the six products. Relevance and frequency count most.
With made-up strengths for "prefers metric": 0.30 × 0.90 + 0.24 × 0.80 + 0.15 × 0.70 + 0.15 × 0.85 + 0.10 × 0.60 + 0.06 × 0.50 = 0.270 + 0.192 + 0.105 + 0.128 + 0.060 + 0.030 = 0.785.
A high score is not enough. The candidate must clear all three gates:
minScore: S is at least this value.minRecallCount: searches found it at least this many times.minUniqueQueries: at least this many different queries found it.Each column is a candidate: its score bar, then its recall count and unique queries. Drag the three gates. A candidate rises into MEMORY.md only with three ticks.
The six weights are OpenClaw's. We made up the strengths, counts and gate values. The docs name the gates but call their thresholds internal.
The gates stop gaming. A note found 12 times by one repeated query looks frequent but is narrow; the unique-queries gate blocks it. A note with a great score found once is not proven yet; the recall gate holds it back. The signals propose. The gates decide.
MEMORY.md fills with trivia from one noisy chat.DREAMS.md: what Deep promoted, with which counts.openclaw memory forget.Chapter 8
Swap where the index lives without changing the ranking, or swap the whole memory plugin
The files are the memory. The index, the chunks with their vectors and keyword entries, is a separate thing that lives in a store. Where it lives is a choice, at two levels.
Pick a store. Boxes that change light up. Then turn on the wiki to see what sits beside the memory plugin.
Store facts from OpenClaw's memory docs. The diagram is a simplification.
| Store | What it is | What changes |
|---|---|---|
| built-in SQLite | the default: one SQLite file per agent, FTS5 with BM25 for keywords, vectors in the same file | nothing; this is the baseline |
| PostgreSQL | supported by memory-core for some runtimes | the keyword score uses Postgres's own rank, calibrated as r / (r + 0.0027); the weights stay |
| Honcho | a plugin for cross-session memory with user modelling | the whole memory plugin |
| LanceDB | a plugin with automatic recall and capture, local Ollama support | the whole memory plugin |
Inside memory-core, the store is an adapter, like the channels in Lesson 1. Hybrid merge, decay, MMR and dreaming run the same on SQLite or PostgreSQL. A different memory plugin is another matter: it owns its storage and its recall, so this lesson's ranking rules belong to memory-core, not to it.
The Memory Wiki plugin does not replace either. It sits beside the active memory plugin and compiles durable knowledge into wiki pages. Each page holds claims linked to evidence, and provenance labels carry into search results. With vault.renderMode set to obsidian, it writes Obsidian-friendly pages. You can check a claim with evidence, and retire it when the evidence fails.
openclaw memory index --force for that agent.Chapter 9
Run days of recall, let the notes age, then dream and watch which notes become long-term
Six daily notes sit in short-term memory. Each day, searches find some of them. A note's score grows when many different queries find it and fades when nobody does. At night, dreaming promotes the notes that clear all three gates.
Bottom: short-term notes, bar height is the Deep score. Top: MEMORY.md. Press Run a day a few times, then Dream. Tighten a gate and dream again.
Illustrative toy: fixed-seed random recalls; frequency = recalls / 10, query diversity = unique queries / 5, recency halves every 7 days without a recall. The six weights are OpenClaw's. We made up the gate values and signal formulas.
Watch two notes. Many different questions find "prefers metric", so it climbs. One repeated query finds "build log spam", so it never clears the unique-queries gate. The rest fade. That is the whole memory: write, find, fade, and keep only what keeps proving useful.
Chapter 10
Keep the terms, the numbers, a checklist and the core code in one place
The model forgets, so the agent writes Markdown files. Search runs vectors and keywords and merges them. Dated notes fade with a 30-day half-life, and MMR keeps the results varied. The prompt gets a capped copy; tools fetch the rest. Provenance and time decide what the agent may act on. Each night, dreaming promotes the notes that clear three gates.
| Term | Meaning | OpenClaw value |
|---|---|---|
| USER.md | stable preferences, as directives | session start, own small budget, evergreen |
| MEMORY.md | durable facts and decisions | session start, per-file cap 20,000 characters, evergreen |
| daily note | working memory for one day | memory/YYYY-MM-DD.md, found by search, decays |
| DREAMS.md | the dream diary | for people only, never injected |
| hybrid search | vector plus keyword, merged | BM25 via SQLite FTS5; keyword scaled to the best vector score |
| query limits | how many hits, how good | maxResults 6, minScore 0.35 |
| chunks | the pieces the index scores | 400 tokens, 80 overlap |
| temporal decay | old dated notes rank lower | half-life 30 days, fixed |
| MMR | relevance minus repetition | λ = 0.7, Jaccard on snippet words |
| dreaming | nightly consolidation | on by default, 0 3 * * *; Light, REM, Deep |
| Deep weights | the six signals | 0.30, 0.24, 0.15, 0.15, 0.10, 0.06 |
| gates | all three must pass | minScore, minRecallCount, minUniqueQueries |
| stores | where the index lives | SQLite (default), PostgreSQL; Honcho and LanceDB plugins; memory-wiki beside |
A toy memory_search and a toy Deep gate. It is a sketch for reading, not OpenClaw's code.
pythondef jaccard(a, b): return len(a & b) / len(a | b) def memory_search(q_vec, q_words, chunks, w=0.5, T=30, lam=0.7, k=6, min_score=0.35): hits = [] for ch in chunks: # ch: vec, words, age_days or None v = cosine(q_vec, ch.vec) kw = len(q_words & ch.words) / len(q_words) # a BM25 stand-in h = w * v + (1 - w) * kw # hybrid score if h < min_score: continue # eligibility comes before decay decay = 1.0 if ch.age_days is None else 0.5 ** (ch.age_days / T) hits.append((h * decay, ch)) picked = [] while hits and len(picked) < k: # MMR: relevance minus repetition best = max(hits, key=lambda sc: lam * sc[0] - (1 - lam) * max((jaccard(sc[1].words, p.words) for p in picked), default=0)) hits.remove(best); picked.append(best[1]) return picked WEIGHTS = {"relevance": .30, "frequency": .24, "query_diversity": .15, "recency": .15, "consolidation": .10, "conceptual_richness": .06} def deep_promote(c, min_score, min_recall, min_unique): s = sum(WEIGHTS[n] * c.signals[n] for n in WEIGHTS) return s >= min_score and c.recalls >= min_recall and c.unique_queries >= min_unique
Now press Present or Teach and explain the memory from memory, chapter by chapter. Then go back to the hero and ask the three questions with each search again.