Agent Memory

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.

Ask the agent

Question
Search

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

The Model Forgets

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.

Live through one week

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.

The road

  1. Where memory lives: four files, and when each reaches the prompt.
  2. Two searches, merged: vector and keyword. The hero's first three searches.
  3. Old notes fade: a 30-day half-life. The hero's last search.
  4. No repeats: MMR picks notes that say different things.
  5. Inside the budget: cut the prompt copy, never the file.
  6. Trust and time: who wrote a memory, and when it stops being true.
  7. Dreaming: three phases and three gates decide what becomes long-term.
  8. Pluggable stores: SQLite, PostgreSQL, plugins and the wiki.
  9. The whole memory, live: days of recall, then a dream.
  10. Field guide: terms, numbers, a checklist and the core code.
Your agent remembers your name in a new session a week later. Where did that memory live?

Chapter 1

Where Memory Lives

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.

FileHoldsReaches the prompt
USER.mdstable preferences and style, written as directives (optional)at session start, under its own small budget
MEMORY.mddurable facts and decisionsat session start, within the bootstrap budget
memory/YYYY-MM-DD.mddaily notes: today's working contextwhen a search finds them; today's and yesterday's also load on a bare /new or /reset
DREAMS.mdthe dream diary: what the nightly job saw and promoted (optional)never; it is for a person to review

File a note

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.

A note says "still waiting on the API key from IT today". Where does it go, and when does the model see it?

Chapter 2

Two Searches, Merged

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.

Say it aloud

The cosine of q and d equals q dot d, divided by the length of q times the length of d.

cos(q, d)
the cosine of q and d the vector score: 1 when the two point the same way, 0 when they share no direction.
q · d
q dot d multiply the two vectors number by number and add the products.
‖q‖
the length of q the square root of the sum of q's squared numbers.
‖d‖
the length of d the same for the note's vector.
In plain words

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 numbers

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.

Say it aloud

h equals w times v, plus one minus w, times k.

h
h the hybrid score that ranks the note, from 0 to 1.
w
w the weight on meaning, from 0 (keywords only) to 1 (vectors only).
v
v the vector score, the cosine from above.
k
k the keyword score, scaled to 0 to 1.
In plain words

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.

With numbers

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.

Blend two scores

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.

0.50

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.

Why does memory_search run a vector search and a keyword search, not one of them?

Chapter 3

Old Notes Fade

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.

Say it aloud

s equals h times one half to the power a over T.

s
s the score used to order the results.
h
h the hybrid score from Chapter 2.
(1/2)
one half to the power halve once for each half-life that has passed.
a
a the note's age in days, from the date in its file name.
T
T the half-life: 30 days in OpenClaw, fixed.
In plain words

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.

With numbers

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.

Age the old note

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.

111
30

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.

Dated notes decay with a 30-day half-life, but MEMORY.md does not. Why?

Chapter 4

No Repeats

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.

Say it aloud

J of A and B equals the size of A intersect B, divided by the size of A union B.

J(A, B)
J of A and B the overlap, from 0 (no shared words) to 1 (the same words).
|A ∩ B|
the size of A intersect B how many words are in both notes.
|A ∪ B|
the size of A union B how many different words are in either note.
In plain words

Count the words the two notes share. Divide by the count of all their different words. That share is J.

With numbers

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).

Say it aloud

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.

argmaxi ∉ S
the argmax over i not in S the candidate, not yet picked, that makes the bracket largest.
λ
lambda the trade-off: 1 means relevance only; lower values buy variety. OpenClaw fixes it at 0.7.
ri
r-i the relevance of candidate i, its score after decay.
maxj ∈ S J(i, j)
the max over j in S of J of i and j how much candidate i repeats its closest pick so far.
In plain words

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.

With numbers

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.

Pick three notes

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.

0.70

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.

With λ = 1, what does MMR return?

Chapter 5

Inside the Budget

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.

PathWhatCost
always onUSER.md and MEMORY.md, injected at session startprompt room on every turn
on demandmemory_search finds notes; memory_get reads a file or a line rangeone 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.

Fit MEMORY.md

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.

20,000

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.

Say it aloud

n equals the ceiling of L minus o, over c minus o.

n
n how many chunks the file becomes.
⌈ ⌉
the ceiling of round up to a whole number, because a part chunk is still a chunk.
L
L the file's length in tokens.
c
c the chunk size: 400 tokens in OpenClaw's built-in store.
o
o the overlap between neighbours: 80 tokens.
In plain words

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.

With numbers

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 is larger than the cap, so only part of it goes into the prompt. What happened to the rest?

Chapter 6

Trust and Time

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.

Check before acting

The memory says "you may deploy to production". Choose who wrote it, then drag its age past the 24-hour window.

6

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.

RuleWhat OpenClaw does
untrusted writea 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
supersessionentries carry a supersession key and an observed time, so a newer fact replaces an older one
expirystanding intents, which fire on an event, expire after 90 days, with a 24-hour cooldown and at most 3 firings
background sessionscron, heartbeat and sub-agent sessions cannot produce memories eligible for promotion
Three weeks ago you wrote "you may deploy now". Today a search finds it. What should the agent do?

Chapter 7

Dreaming

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.

  1. Light. Sort and stage recent material, drop duplicate signals, record which notes searches found.
  2. REM. Build theme and reflection summaries, and record more signals.
  3. Deep. Score the candidates and promote the winners. Only Deep writes 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.

Say it aloud

S equals the sum over k of w-k times x-k.

S
S the candidate's Deep score, from 0 to 1.
Σk
the sum over k add one term for each of the six signals.
wk
w-k the weight of signal k: relevance 0.30, frequency 0.24, query diversity 0.15, recency 0.15, consolidation 0.10, conceptual richness 0.06. They add to 1.
xk
x-k how strong signal k is for this candidate, from 0 to 1.
In plain words

Multiply each signal's strength x-k by its weight w-k. Add the six products. Relevance and frequency count most.

With numbers

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:

  1. minScore: S is at least this value.
  2. minRecallCount: searches found it at least this many times.
  3. minUniqueQueries: at least this many different queries found it.

Run the Deep phase

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.

0.55
3
2

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.

A candidate scores well above minScore, but searches found it only once, below minRecallCount. Is it promoted?

Chapter 8

Pluggable Stores

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.

Swap the store

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.

StoreWhat it isWhat changes
built-in SQLitethe default: one SQLite file per agent, FTS5 with BM25 for keywords, vectors in the same filenothing; this is the baseline
PostgreSQLsupported by memory-core for some runtimesthe keyword score uses Postgres's own rank, calibrated as r / (r + 0.0027); the weights stay
Honchoa plugin for cross-session memory with user modellingthe whole memory plugin
LanceDBa plugin with automatic recall and capture, local Ollama supportthe 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.

You move memory-core from SQLite to PostgreSQL. What happens to decay and MMR?

Chapter 9

The Whole Memory, Live

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.

Run the memory

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.

0.55
3
2

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

Field Guide

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.

TermMeaningOpenClaw value
USER.mdstable preferences, as directivessession start, own small budget, evergreen
MEMORY.mddurable facts and decisionssession start, per-file cap 20,000 characters, evergreen
daily noteworking memory for one daymemory/YYYY-MM-DD.md, found by search, decays
DREAMS.mdthe dream diaryfor people only, never injected
hybrid searchvector plus keyword, mergedBM25 via SQLite FTS5; keyword scaled to the best vector score
query limitshow many hits, how goodmaxResults 6, minScore 0.35
chunksthe pieces the index scores400 tokens, 80 overlap
temporal decayold dated notes rank lowerhalf-life 30 days, fixed
MMRrelevance minus repetitionλ = 0.7, Jaccard on snippet words
dreamingnightly consolidationon by default, 0 3 * * *; Light, REM, Deep
Deep weightsthe six signals0.30, 0.24, 0.15, 0.15, 0.10, 0.06
gatesall three must passminScore, minRecallCount, minUniqueQueries
storeswhere the index livesSQLite (default), PostgreSQL; Honcho and LanceDB plugins; memory-wiki beside

Checklist for any agent memory

The core, in code

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

Where each thread continues

The takeaway. Write it down, find it two ways, let the dated notes fade, do not repeat yourself, cut the copy and not the file, check who said it and when, and keep only what keeps proving useful.
In one sentence, what is OpenClaw's agent memory?

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.

Anatomy of an Agent Gateway, Lesson 8: Agent Memory
OpenClaw memory docs · Next: self-healing · Back to Gleams