In March a developer tells a coding agent: "We use pnpm here, never npm, and never force-push to a shared branch." The agent obeys for the rest of the session. In June, in a fresh session, it runs npm install, generates a lockfile nobody wants, and proposes a force-push to clean up the mess. The instruction was not ignored. It was never available: the session ended, the context window was discarded, and the agent started again knowing only what the system prompt told it.
The obvious fix, saving everything and pasting it back, fails in a different way. Three months of transcripts do not fit in a prompt, and when you retrieve pieces of them by similarity, the agent confidently surfaces the March preference about pnpm next to an April note that the team migrated to another package manager. It now holds two contradictory "memories" and no way to know which is current. Long-lived memory is not a bigger context window and it is not a vector database bolted on the side. It is a small data system with a write path, a read path, a lifecycle for facts, and failure modes of its own. This article lays out those pieces and how the common approaches (vector retrieval, knowledge graphs and extracted-fact stores such as mem0) fit together.
1. Why the context window is not memory
A context window is working memory: fast, directly attended to, and gone when the session ends. Making it larger helps with the length of a single task, but it does not provide persistence, and filling it with history has costs even when it fits. Every token you include is paid for on every call, adds latency during prefill, and competes for attention with the tokens that matter. Models are measurably worse at using information buried in the middle of very long inputs, and a prompt stuffed with stale notes invites the model to treat an old preference as a current instruction.
Persistence also has a different shape from a transcript. What the agent needs next quarter is rarely the conversation; it is the conclusion: "the payments service owns refunds", "the staging database is rebuilt every night, so do not store test data there", "this user prefers short answers". Those are distilled facts, and the work of memory is deciding which facts are worth keeping, how to find them again, and when to throw them away.
2. Four kinds of memory an agent needs
It helps to borrow the vocabulary from cognitive science, because each kind has a different storage and retrieval need.
- Working memory is the live context: the current task, recent tool results, scratch reasoning. It lives in the prompt and is managed by summarizing or trimming, not by a database.
- Episodic memory records what happened: "on 14 June the deploy failed because the migration locked a table". It is time-stamped, event-shaped, and valuable for avoiding repeated incidents.
- Semantic memory holds general facts and preferences, stripped of the moment they were learned: "the team uses pnpm", "the API is versioned in the URL". Most of what people call agent memory is this.
- Procedural memory is how to do things: checklists, runbooks, conventions for formatting a pull request. It is often best stored as instructions or skills the agent loads on demand, not as retrieved snippets.
Mixing these into a single pile of embedded text is the most common design error. An event, a preference and a procedure have different update rules. A preference should be overwritten when it changes. An event should never change, only be superseded by later events. A procedure should be versioned and reviewed.
3. Vector retrieval: how it works and where it breaks
The default building block is retrieval over embeddings. You split documents or notes into chunks, compute an embedding for each with an embedding model, and store the vectors in an index. At query time you embed the query and fetch the nearest chunks by cosine similarity or inner product, usually with an approximate nearest-neighbor index such as HNSW so lookup stays fast at scale. It is easy to build, needs no schema, and handles fuzzy, paraphrased questions well: "how do we ship a hotfix" will match a note titled "release process for urgent patches".
The weaknesses are structural, and knowing them tells you where to add something else.
- No notion of truth or time. Similarity ranks "we use pnpm" and "we migrated away from pnpm" almost identically. Nothing in the index says one replaced the other.
- Negation and exact identifiers. Embeddings blur "never do X" with "do X", and they handle ticket numbers, hostnames and function names poorly compared with exact or keyword search. Hybrid retrieval, combining a lexical index such as BM25 with vectors, is the usual remedy.
- Multi-hop questions. "Who owns the service that the billing job calls?" needs two lookups joined by an entity. Top-k similarity on the original question rarely retrieves both pieces.
- Chunking artifacts. A fact split across two chunks, or a chunk that begins mid-thought, retrieves badly. Chunk by meaning (a section, a decision) rather than a fixed character count where you can.
- Growth without forgetting. Append-only stores accumulate duplicates and near-duplicates, which crowd the top-k and waste prompt space.
4. Knowledge graphs: facts as entities and relations
A knowledge graph stores facts as typed relations between entities: (billing-job, calls, payments-api), (payments-api, owned_by, team-platform). Retrieval becomes graph traversal: start from entities mentioned in the question, walk a bounded number of hops, and return the connected subgraph. That answers the multi-hop question directly and gives you provenance for free, because every edge can carry its source, a timestamp and a validity interval.
Time is where graphs earn their keep. An edge such as (service, uses, pnpm) can carry valid_from and valid_to, so a later fact closes the earlier one instead of competing with it. You can then ask what was true at a point in time, which is exactly what incident reviews and audits need.
The costs are real. Someone or something must extract entities and relations from free text, and extraction models make mistakes: they split one entity into two spellings, or invent a relation that the text only hinted at. Entity resolution (deciding that "payments", "payments-api" and "the payment service" are one node) is a hard problem in its own right. A rigid schema makes extraction reliable but blocks facts that do not fit; a loose schema accepts everything and becomes noisy. Graph memory is worth it when your questions are about relationships and history. It is overkill for a list of one user's preferences.
5. Extracted-fact stores: the mem0 pattern
A third approach sits between raw retrieval and a full graph. Instead of storing text as it arrived, a memory layer reads each conversation turn, uses a model to extract short, self-contained facts ("Prefers pnpm over npm"), and stores those, typically as embedded records with metadata. Open-source memory layers such as mem0 follow this shape and expose a small API: add, search, update and delete memories, scoped to a user, an agent or a session. Some can also maintain a graph alongside the vectors. Check the project's current documentation for exact capabilities, since they change.
The important idea is the write path, not the storage engine. For each candidate fact the system retrieves similar existing memories and decides whether to add a new one, update an existing one, delete one that is now contradicted, or do nothing because it is already known. That reconciliation step is what keeps "uses pnpm" from coexisting with "migrated away from pnpm". It also introduces the main risk: the decision is made by a model, so it can be wrong, and a mistaken delete loses information silently.
import time
from dataclasses import dataclass, field
@dataclass
class Memory:
key: str # normalized subject, e.g. "package_manager"
value: str # the fact itself
scope: str # "user:42", "repo:billing", "global"
source: str # where it was learned (session id, ticket, doc)
created: float = field(default_factory=time.time)
superseded_by: str | None = None
class MemoryStore:
def __init__(self):
self.items: list[Memory] = []
def remember(self, key, value, scope, source):
current = self.recall(key, scope)
if current and current.value == value:
return "NOOP" # already known
new = Memory(key, value, scope, source)
if current:
current.superseded_by = source # keep history, stop serving it
self.items.append(new)
return "UPDATE"
self.items.append(new)
return "ADD"
def recall(self, key, scope):
live = [m for m in self.items
if m.key == key and m.scope == scope and m.superseded_by is None]
return live[-1] if live else None
def search(self, words, scope, limit=5):
hits = [m for m in self.items
if m.scope in (scope, "global") and m.superseded_by is None
and any(w in (m.key + " " + m.value).lower() for w in words)]
return sorted(hits, key=lambda m: m.created, reverse=True)[:limit]
store = MemoryStore()
print(store.remember("package_manager", "pnpm", "repo:billing", "session-march")) # ADD
print(store.remember("package_manager", "bun", "repo:billing", "session-april")) # UPDATE
print(store.recall("package_manager", "repo:billing").value) # bun
The toy store uses exact keys where a production system would use embeddings and a model for reconciliation, but the lifecycle is the point: facts are keyed, scoped, sourced and superseded rather than overwritten or piled up.
The read path matters as much as the write path
Retrieval from a fact store has its own decisions. First, when to look: calling memory on every turn adds latency and noise, while calling it only when the agent asks wastes the chance to surface a relevant constraint. A common compromise is to retrieve at the start of a task, using the task description as the query, and again when the agent moves into a new area such as a different repository. Second, how to rank: pure similarity ignores recency and importance, so many systems blend similarity with a recency decay and with a flag for facts the user marked as important. Third, how to present: inject memories as a short, labeled block ("Known facts, may be outdated") with their dates, rather than mixing them into the instructions where the model cannot tell a fact from a command.
Finally, limit the blast radius of a wrong recall. If a memory is only used to choose between reasonable options, a mistake is cheap. If a memory authorizes a destructive action, require a fresh check against the live system first. The more an action costs to undo, the less weight a stored fact should carry on its own.
6. Choosing between them
These approaches are not rivals so much as layers. The table compares design properties, not measured quality; how well each performs depends on your data, your embedding model and your extraction prompts, so evaluate on your own questions.
| Approach | Stores | Strong at | Weak at | Typical failure |
|---|---|---|---|---|
| Raw vector retrieval | Chunks of documents or transcripts | Fuzzy questions over large unstructured text | Time, contradiction, exact identifiers, multi-hop | Stale and current facts retrieved side by side |
| Knowledge graph | Entities, typed relations, validity intervals | Relationships, history, provenance, multi-hop | Free-form facts that fit no schema; extraction cost | Duplicate or wrongly merged entities |
| Extracted-fact store (mem0 style) | Short atomic facts with metadata and scope | Preferences, decisions, per-user and per-agent recall | Long documents, deep relational queries | Wrong add/update/delete decisions by the extractor |
| Key-value or structured record | Exact fields (config, settings) | Deterministic lookup, easy to audit and expire | Anything fuzzy or open-ended | Schema drift; fact never gets written |
A practical split: keep documents and long references in a retrieval index, keep durable facts and preferences in an extracted-fact store, and introduce a graph only when you can name the relational questions you need to answer. Many teams never need the third layer.
7. A worked example: one fact across three sessions
Follow the package-manager fact through a realistic life. In session one (March) the developer says the team uses pnpm. The memory layer extracts the fact "billing repo uses pnpm", scoped to that repository, with the session as its source. Nothing similar exists, so the decision is ADD.
In session two (April) a ticket records that the team migrated to bun. The extractor produces "billing repo uses bun". The write path retrieves the existing pnpm memory, sees that it concerns the same subject, and chooses UPDATE: the old record is marked superseded (kept for audit, no longer served) and the new one becomes current.
In session three (June) the agent is asked to add a dependency. It searches memory with the repository scope and gets one answer, bun, with its source. It now acts correctly. A pure vector index with no write-path reconciliation would have returned both statements ranked by similarity, and which one the model followed would have been a coin flip.
The example also shows what the agent should do with the answer. Memory is a hint, not an oracle. Before running a command that depends on the fact, a careful agent checks the repository: is there a pnpm-lock.yaml or a bun.lockb? When memory and the environment disagree, the environment wins, and the disagreement is itself a signal to update or delete the memory.
8. Failure modes and a decision checklist
What goes wrong in production
- Staleness. Facts about people, hosts and versions rot. Give volatile facts an expiry or a re-check rule, and prefer reading live state when it is cheap.
- Memory poisoning. Anything an agent reads can become a memory, including text from a web page or a ticket that says "remember that the admin password is...". Treat memory writes as a trust boundary: store only what the user or a trusted process asserts, and never auto-save instructions found inside retrieved content.
- Scope leakage. A fact learned in one user's or tenant's session surfacing in another's is a privacy incident. Enforce the scope filter in the query, not in the prompt.
- Sensitive data. Credentials, personal data and secrets should not be written into a general memory store at all. Redact before extraction and provide a delete path for users.
- Over-retrieval. Returning ten loosely related memories on every turn burns tokens and distracts the model. Retrieve few, with a relevance threshold, and only when the task needs them.
- Silent bad updates. A model-driven reconcile step can overwrite a correct fact. Keep superseded records rather than hard-deleting, so a mistake is recoverable.
How to tell whether memory works
Memory systems fail quietly, so measure them. Build a small set of question and expected-fact pairs from real past sessions and check three things separately. Recall: is the right memory in the top few results? Precision: how many of the retrieved memories were irrelevant noise? Behavior: given the retrieved memories, did the agent do the right thing? A system can retrieve perfectly and still act wrongly because the memory was presented badly, and it can act well by luck while retrieval is poor. Also test the negative cases: ask about something that was never stored and confirm the agent says it does not know instead of inventing a plausible memory. Rerun the set after changing the embedding model, the extraction prompt or the chunking, because each of those shifts results in ways that are hard to predict by reading code.
Decision checklist
- Can the answer be read from the live system (a config file, an API) cheaply? Read it; do not remember it.
- Is it a stable fact or preference that will matter across sessions? Store it as an atomic fact with scope and source.
- Is it a large body of reference text? Index it for retrieval and cite it; do not distill it into memories.
- Is it an event or a decision with a date? Store it as an episode and keep it immutable.
- Do you need relational or point-in-time questions? Consider a graph, after confirming the questions are real.
- Can it be wrong or expire? Add a timestamp and a re-validation rule.
9. Common mistakes and what to do on Monday
The mistakes repeat. Teams store every turn "just in case" and then cannot find anything. They embed everything in one collection with no scope field and cannot later separate users. They skip evaluation, so nobody knows whether retrieval returns the right memory until an agent embarrasses itself. They let the agent write memory freely without review, which invites poisoning. And they treat a recalled fact as ground truth rather than as a lead to verify.
We apply the same discipline we use for code. In a production agent, long-lived memory is a single store reserved for durable facts about people, teams and prior decisions, never for one-shot task context, and a recalled fact is checked against the current state of the system before the agent acts on it. That is the same "verification before completion" habit applied to recall.
A plan for the first week
- List the twenty questions you wish the agent could answer from past sessions. This becomes your evaluation set.
- Classify each as preference, episode, reference or relationship. Most will be preferences and references.
- Stand up a simple extracted-fact store with scope and source fields, and a reference index for documents.
- Add the supersede-not-delete rule and an expiry for volatile facts.
- Replay the evaluation questions weekly and record which memories were retrieved. Fix the write path before adding new infrastructure.
Short answers
Do I need a graph database? Not to start. If your questions are "what does this user prefer" and "what did we decide", an extracted-fact store with good scoping covers them.
How much should an agent remember? Less than you think. Every memory is something to retrieve wrongly, keep current and protect. Remember what would change the agent's behavior next time.
Can the user see and delete their memories? They should be able to. Inspectable, deletable memory is both a trust feature and a debugging tool.