---
title: "How to add agent memory to an agent loop with SurrealDB"
description: "Add agent memory to an agent loop in SurrealDB: vector and full-text search merged with search::rrf, then weighted by importance, decay, expiry and replacement."
url: https://surrealdb.com/blog/how-to-add-agent-memory-to-an-agent-loop-with-surrealdb
date: 2026-11-24
authors: "Martin Schaer"
---

# How to add agent memory to an agent loop with SurrealDB

![How to add agent memory to an agent loop with SurrealDB](https://cdn.surrealdb.com/s6yt5gc1854h5sesaq9fpuqq.auto)

Agent memory for a coding agent loop is a table of lessons, decisions and conventions that
the agent reads before it starts a task and writes to when it finishes. In SurrealDB, recall
combines vector search and full-text search with `search::rrf`, then weights each hit by
importance and decay, so stale memories fade and the useful ones stay.

This is part 2. [Part 1](https://surrealdb.com/blog/how-to-build-an-agent-loop-with-surrealdb-a-task-graph-for-agents) built the loop itself: a task graph with a ready queue,
atomic claims and a human review gate. Here we give that loop a memory.

## Why does an agent loop need memory?

Without memory, every task starts from zero. The agent that fixed a flaky test on Monday
meets the same flaky test on Thursday and spends the same tokens working it out again. The
team's conventions live in a document the agent may or may not have been shown.

Memory fixes that, and it brings its own risk. A memory store that only grows becomes a
pile of outdated advice, and an agent that trusts a year-old lesson about Node 18 is worse
than an agent with no memory at all. So the design question is less "how do we store it?"
and more "how do we decide what to trust?". That is what the rest of this post is about, and
it is the part to bring to your team: **importance, decay, expiry and replacement** are
product decisions as much as technical ones.

## What should a coding agent remember?

I split memory into four kinds, because they age differently:

| Kind | Example | Half-life |
| --- | --- | --- |
| `convention` | "Every schema change ships as a migration file." | never decays |
| `decision` | "Saved searches store filters as JSON, so the interface can version them." | 180 days |
| `lesson` | "ECONNRESET from staging means the proxy idle timeout was hit." | 90 days |
| `episode` | "Run on the docs task: regenerate the API docs after a schema change." | 14 days, expires after 30 |

Conventions are rules, so they stay. Decisions last a while. Lessons are most useful soon
after they are learned and get less certain as the code changes. Episodes are a diary: they
are good for a few weeks and then they are noise. These half-lives are starting points I
picked, not measured values, so expect to tune them on your own project.

## How do you model a memory?

One table, linked to the `task` table from part 1. The `source` field records which task
taught the agent the lesson, so you can always trace a memory back to the work that produced it.

![Schema diagram of the memory and task tables, linked by source](schema.full)

The full definition is in the [schema.surql gist](https://gist.github.com/martinschaer/3f4fb6789196db5c9b4b31f9a81821c1). The fields that
turn a document table into memory:

| Field | What it does |
| --- | --- |
| `importance` | How much the memory counts, from 0 to 1 |
| `last_accessed` | Resets the decay clock each time the memory is used |
| `recalls` | How often it has been used |
| `expires_at` | Hard expiry. Episodes get `created_at + 30d` by default |
| `superseded_by` | Points at the memory that replaced this one |
| `scope` | `global`, or a repo, so one project's lessons stay out of another |

Two indexes do the searching. A full-text index with a BM25 ranking, and an HNSW vector index:

```surql
DEFINE INDEX memory_fts ON memory FIELDS content FULLTEXT ANALYZER memory_text BM25;
DEFINE INDEX memory_vec ON memory FIELDS embedding HNSW DIMENSION 4 DIST COSINE TYPE F32;
```

The embeddings in the [seed.surql gist](https://gist.github.com/martinschaer/5c87a809eb1886ee82dd6838a50ec57d) are hand-made 4-dimensional
vectors, with axes for tests, database, deploy and interface, so the numbers stay readable.
With a real embedding model you change `DIMENSION` and nothing else.

## Why use both vector and full-text search?

Each one misses something the other finds. Say the agent is debugging `ECONNRESET` errors
on the staging API. Its embedding points at the deploy and infrastructure axis.

Vector search alone finds the right area, but the memory we want is third:

```surql
SELECT id, vector::distance::knn() AS distance FROM memory
    WHERE embedding <|5, 40|> $vec;
-- memory:conv_branch      0.0077
-- memory:lesson_node      0.0090
-- memory:lesson_econnreset 0.0116
```

Full-text search alone nails the exact error code, but it only works when the words match.
A query for "connection dropped" returns nothing (I ran it):

```surql
SELECT id, search::score(0) AS score FROM memory
    WHERE content @0,OR@ 'ECONNRESET' ORDER BY score DESC LIMIT 5;
-- memory:lesson_econnreset  1.708
```

Code and error messages are full of exact tokens, and agents describe situations in loose
language. You want both.

## How does search::rrf merge them?

Reciprocal rank fusion (RRF) merges ranked lists by position, so you never have to compare a
vector distance with a BM25 score. Each list gives a memory `1 / (k + rank)`, and the scores
add up. SurrealQL has it built in as `search::rrf`, which takes the lists, a limit and `k`
(60 is the usual value):

```surql
LET $v = SELECT id, vector::distance::knn() AS distance FROM memory WHERE embedding <|20, 40|> $vec;
LET $f = SELECT id, search::score(0) AS score FROM memory WHERE content @0,OR@ 'ECONNRESET' ORDER BY score DESC LIMIT 20;
RETURN search::rrf([$v, $f], 5, 60);
```

```surql
[
  { id: memory:lesson_econnreset, rrf_score: 0.0323 },  -- 3rd in vectors, 1st in full-text
  { id: memory:conv_branch,       rrf_score: 0.0164 },
  { id: memory:lesson_node,       rrf_score: 0.0161 },
  ...
]
```

`lesson_econnreset` was third by vector and first by full-text: `1/63 + 1/61 = 0.0323`, and it
now leads by a wide margin, because it is near the top of both lists. The others appear in one list each.

## How do importance and decay change the ranking?

Fusion tells you what is relevant. It doesn't tell you what is still true or worth acting
on. So the recall function multiplies the fused score by the memory's current strength:

```surql
score = rrf_score × strength
strength = importance × 0.5 ^ (days since last used ÷ half-life)
```

I multiply instead of adding because the RRF score is tiny (around 0.03) and a weighted sum
would let importance drown it. Multiplying keeps relevance in charge and lets strength
scale it up or down. Conventions skip the decay term, so their strength is their importance.

```surql
RETURN fn::strength(memory:lesson_node, $now);       -- 0.0406  (importance 0.8, last used over a year ago)
RETURN fn::strength(memory:conv_migrations, $now);   -- 0.9     (conventions never decay)
```

The recall function does the whole job: both searches, fusion, then strength. Memories from
other repos, replaced memories and expired memories never appear. This is what the agent sees before it starts
the flaky-tests task:

```surql
RETURN fn::recall('repo:saved-searches', 'flaky tests CI', [0.95, 0.25, 0.1, 0.1], 4, $now);
```

| id | kind | rrf_score | strength | score |
| --- | --- | --- | --- | --- |
| `lesson_flaky` | lesson | 0.0328 | 0.616 | 0.0202 |
| `conv_migrations` | convention | 0.0152 | 0.900 | 0.0136 |
| `conv_branch` | convention | 0.0149 | 0.600 | 0.0090 |
| `decision_filters` | decision | 0.0154 | 0.509 | 0.0078 |

Only the first row is a strong match. The store has nine memories, so the other three are
filler that every search returns at this size. In a real store, more relevant memories would
take their place. The old "just retry three times" lesson matches the query too, but a newer
lesson replaced it, so it isn't listed (more on that below). `$now` is pinned in these examples so you
get the same numbers. In production, leave it out and the functions use `time::now()`.

## How do memories expire, get replaced and get forgotten?

Four mechanisms, all plain fields and a `WHERE` clause:

- **Expiry.** Episodes get `expires_at` from a field default, and recall skips anything
  past it
- **Replacement.** `fn::remember` takes a `$supersedes` argument. The old memory stays for
  the record, with `superseded_by` set, and recall skips it
- **Reinforcement.** `fn::touch` resets `last_accessed` and adds one to `recalls`. A memory
  the agent keeps using stays strong
- **Forgetting.** `fn::forget` deletes what has expired and what has decayed below a floor
  (5% strength by default), except memories that were superseded

```surql
-- Learn something new that replaces an old lesson
RETURN fn::remember('global', 'lesson',
    'Node 20 is now the minimum on CI. Node 22 is the target for next quarter.',
    [0.2, 0.0, 0.8, 0.0], 0.8, NONE, memory:lesson_node);

-- Clean up
RETURN fn::forget($now, NONE);
-- [ memory:episode_lint ]   (expired). lesson_node is superseded, so it stays as history
```

`fn::forget` leaves superseded memories alone, so `lesson_node` stays as history. Replacing,
rather than overwriting, is deliberate: when an agent acts on a memory and gets it wrong, you
want to see what it believed at the time.

## What happens when the store grows?

Filters decide whether the vector side of recall stays correct. The scope and `superseded_by`
conditions sit in the same `WHERE` as the KNN operator, so SurrealDB pushes them into the
index walk instead of applying them to a list the walk already chose. I checked it on v4.0.1
with 300 memories from another repo, all nearer to the query than anything in this repo's
scope: the vector side still returned every eligible memory for this scope. I wrote about
how this works, and how it fails, in
[Why does my vector search return nothing when I add a filter?](https://surrealdb.com/blog/why-does-my-vector-search-return-nothing-when-i-add-a-filter).

The expiry test is the exception. The `expires_at = NONE OR expires_at > $t` condition did
not push down when I combined it with the scope filter, so recall applies it to the 20
candidates afterwards. That means expired memories hold a candidate slot until `fn::forget`
removes them, so run it on a schedule.

## How does the memory plug into the loop?

Two additions to the loop from part 1: recall after claiming a task, and remember before
handing it to review. I ran this against both sets of seed data, with a script approving
each task in review. It completed all seven tasks and wrote seven new lessons.
The setup is the same as part 1 (`db`, signed in, `use("agents", "loop")`), plus
`SCOPE = "repo:saved-searches"`. `embed` is where your embedding model goes (mine was a toy
that counts four keywords), and `do_work` is where your LLM goes, with the memories in its prompt.

```python
while True:
    claimed = db.query("RETURN fn::claim('agent-1', NONE)").execute()
    task = claimed[0] if claimed else None
    if task:
        memories = db.query(
            "RETURN fn::recall($scope, $text, $vec, 3, NONE)",
            {"scope": SCOPE, "text": task["title"], "vec": embed(task["title"])},
        ).execute()[0]
        db.query("fn::touch($ids, NONE)", {"ids": [m["id"] for m in memories]}).execute()

        result, lesson = do_work(task, memories)

        db.query(
            "fn::remember($scope, 'lesson', $lesson, $vec, 0.6, $source, NONE)",
            {"scope": SCOPE, "lesson": lesson, "vec": embed(lesson), "source": task["id"]},
        ).execute()
        db.query(
            "UPDATE $id SET notes += { at: time::now(), by: 'agent-1', text: $text }, status = 'review'",
            {"id": task["id"], "text": result},
        ).execute()
    elif not db.query("SELECT id FROM task WHERE status IN ['todo', 'in_progress', 'review']").execute():
        break
    else:
        time.sleep(1)
```

The loop still has no ranking logic. Recall is one function call, and swapping the model,
the weights or the half-lives never touches the agent code.

## What should you tune first?

A few things I'd look at before trusting this in production, none of which I have tuned yet:

- **The full-text query.** `@0,OR@` matches any term, so common words add noise. Pass
  keywords rather than a whole sentence, or add a stop-word step in the agent
- **Half-lives.** Start from the table above, then look at which memories the agent
  actually used and which it ignored
- **What counts as a lesson.** Let the agent write memories, and let a person promote the
  good ones to `convention`. That fits the review gate from part 1
- **Embeddings.** Hand-made vectors are for reading. A real model changes the distances, so
  re-check the candidate count (the `20` in `fn::recall`) and consider a distance cutoff, so
  weak vector matches don't fill the tail

All the queries above are in the [queries.surql gist](https://gist.github.com/martinschaer/8550e03e9b99905ec9b34c0b475aff03), in order.
Load part 1's schema and seed first, then these three files, into the same database. The
queries file shares `$now` and `$vec` between statements, so send it as one request (the
header of each file has the command). I ran
everything on SurrealDB v4.0.1 on 23 November 2026.

## Summary

- Give a coding agent four kinds of memory: conventions, decisions, lessons and episodes,
  each with its own half-life
- Search by vector and by full-text, and merge the ranked lists with `search::rrf`
- Multiply the fused score by strength (importance with decay), so stale advice fades
- Expire episodes, replace outdated lessons instead of overwriting them, and forget what
  has decayed
- Reinforce what gets used by resetting `last_accessed` on recall

## Get started

Want to try it? Load the two parts into a free instance and point your agent at `fn::recall`.

- [Create a free cloud instance](https://surrealdb.com/cloud)
- [Start building](https://surrealdb.com/docs)
- [Join our Discord server](https://discord.gg/surrealdb)
