"AI agent memory" is one of the most searched agent topics right now, and memory layers are among the most popular open-source AI projects: Mem0 alone has about 68,000 GitHub stars. The interest makes sense. Everyone who has used a coding agent has had this conversation: you explain your project's conventions, the agent does great work, and the next morning it has forgotten all of it.
Here is the thing to understand first: the model remembers nothing. As how LLMs work explains, a model is a function of the tokens in the current request. Agent memory is therefore not a model feature. It is a data problem: what does your code save, and what does it put back into the context next time?
Short-term vs long-term memory#
- Short-term memory is the conversation so far, resent with every call and limited by the context window. It disappears when the session ends (or earlier, when the history is trimmed or summarized).
- Long-term memory is anything you store outside the model and bring back in a later session.
Long-term memory is usually split three ways. The labels come from cognitive science, and the CoALA paper on language agent architectures uses the same split:
| Type | What it holds | Example | Where it usually lives |
|---|---|---|---|
| Semantic (facts) | Things that are true | "The user prefers pnpm." | A memory store, recalled by relevance |
| Episodic (events) | Things that happened | "Last deploy failed: disk full." | A memory store, recent ones favored |
| Procedural (rules) | How to behave | "Always run the tests before committing." | A file loaded every session |
You already use procedural memory if you have a CLAUDE.md or a similar rules file: it is a markdown file that gets loaded into every session. The Claude API's memory tool goes one step further and lets the model itself read and write files in a /memories directory, while your application runs those file operations against storage you control.
How agent memory works: write, then recall#
Start simpler than this diagram. In my opinion, most agents should begin with one markdown file of rules and a few facts, loaded every session. It is readable, reviewable in a pull request, and costs nothing. You need recall (the right half of the diagram) only when memories outgrow what you want in every prompt.
A small memory store in TypeScript#
When you do need recall, it is the embeddings search you may have already built, plus three memory-specific decisions: refresh near-duplicates, favor recent memories, and remember who wrote what.
import { cosine, embed } from "./embeddings.ts";
export type Kind = "fact" | "event" | "rule";
export interface MemoryItem {
id: number;
kind: Kind; // fact = semantic, event = episodic, rule = procedural
text: string;
vector: number[];
at: number; // when it was written (ms)
untrusted: boolean; // written after reading outside content
}
const DAY = 86_400_000;Saving. A memory that says almost exactly the same thing as an existing one (similarity above 0.9) refreshes it instead of piling up a duplicate:
export class Memory {
items: MemoryItem[] = [];
private nextId = 1;
/** Save a memory, or refresh a near-identical one. */
async remember(
kind: Kind,
text: string,
{ untrusted = false, now = Date.now() } = {},
): Promise<MemoryItem> {
const [vector] = await embed([text]);
const twin = this.items.find(
(m) => m.kind === kind && cosine(m.vector, vector) > 0.9,
);
if (twin) {
// an untrusted rewrite must not inherit a trusted label
untrusted ||= twin.untrusted;
const update = { text, vector, at: now, untrusted };
return Object.assign(twin, update);
}
const item = { id: this.nextId++, kind, text, vector,
at: now, untrusted };
this.items.push(item);
return item;
}That comment is there because my first version had a bug: an update copied the new text but kept the old "trusted" label, so text from a compromised session could slip in under a trusted flag. A test caught it. Taint only ever gets added, never removed.
Recalling. Rank by meaning, give recent memories a small bonus (it halves every 30 days), and drop anything below a threshold:
/** Most relevant memories, with a small bonus for recent ones. */
async recall(query: string, k = 3, now = Date.now()) {
const [q] = await embed([query]);
return this.items
.map((m) => {
const recency = 0.5 ** ((now - m.at) / (30 * DAY));
const score = cosine(q, m.vector) * (0.8 + 0.2 * recency);
return { m, score };
})
.filter((r) => r.score > 0.2) // tune per model
.sort((a, b) => b.score - a.score)
.slice(0, k)
.map((r) => r.m);
}
forget(id: number): void {
this.items = this.items.filter((m) => m.id !== id);
}
}The 0.2 threshold is measured, not universal: with this embedding model, "Which package manager should I use?" scored 0.26 against the pnpm memory and an unrelated question about the capital of Peru scored 0.18. Different model, different numbers.
Finally, recalled memories go into the prompt as information, never as orders, and memories from untrusted sessions say so:
/** Render recalled memories for the prompt. Never as orders. */
export function asContext(items: MemoryItem[]): string {
const lines = items.map((m) =>
m.untrusted
? `- (unverified, from outside content) ${m.text}`
: `- [${m.kind}] ${m.text}`,
);
return `<memory>\n${lines.join("\n")}\n</memory>`;
}The open problems#
This is where agent memory is still being figured out, and where the store above is honest about its limits.
1. Stale facts win#
This one surprised me. Save "The user prefers pnpm over npm." and later "The user switched from pnpm to npm." The two are not similar enough to count as duplicates, so both are kept. Then ask "Which package manager should I use?" and recall returns only the old one: the stale preference scores higher for that question than the update does.
Similarity search finds what is related, not what is current. A common fix is to ask a model, at write time, whether a new memory adds to, updates or contradicts what is already stored, and to delete the loser. That costs a model call per write, and it can be wrong too. There is no free answer yet.
2. Deciding what to keep#
Save everything and recall drowns in noise. Save too little and the agent keeps asking the same questions. Most systems ask a model at the end of a session to extract a few durable facts, which works until it confidently saves something you said as a joke. Show users what was saved.
3. Forgetting#
Nothing forgets unless you build it: decay (the recency bonus above), expiry dates, deletion when contradicted, and, not optional when memories are about people, a way for users to see and delete what you stored.
4. Memory poisoning#
A prompt injection in a web page lasts one session. Write it to memory and it attacks every future session. The store above labels memories written after reading untrusted content, keeps that label through updates, and renders them as unverified. On top of that: never let an untrusted session write rules, and review rules files like code.
5. Knowing it helps#
Memory can make an agent worse: outdated facts, irrelevant recalls, a bloated context. Measure it like any feature, with the same tasks run with and without memory. That is an eval.
How I tested this#
The store ran under Node 24 with real embeddings from all-MiniLM-L6-v2 via transformers.js 4.3.1. Eight tests cover recall by meaning, refreshing a near-duplicate, the contradiction case above (both kept, the stale one recalled), an unrelated question recalling nothing, a recent event beating an old one, untrusted memories being labelled in the prompt, untrusted labels surviving an update, and forget never reusing ids. The scores in this post are copied from those runs.
What I would do on Monday#
- One markdown file of rules and stable facts, loaded every session, reviewed in pull requests.
- Recall for facts and events only when that file gets too long to load every time.
- Labels on everything written after reading untrusted content, and no rules from those sessions.
- A page where users can see and delete what the agent remembers about them.
Sources: CoALA: Cognitive Architectures for Language Agents, Claude memory tool, Mem0.
Frequently asked questions
How do AI agents remember things?
The model does not. The application saves selected information (facts, past events, rules) outside the model and puts the relevant parts back into the context of later calls. That retrieval step is what people call agent memory.
What are the types of AI agent memory?
Short-term memory is the current conversation in the context window. Long-term memory is usually split into semantic memory (facts), episodic memory (past events and sessions) and procedural memory (rules and instructions), a split borrowed from cognitive science.
Do I need a vector database for agent memory?
Often not. A markdown file loaded into every session works well for rules and a handful of facts. Use embedding-based recall when memories outgrow what you want in every prompt, and a vector database only when you have many thousands of them.
What is memory poisoning?
When an attacker gets text into an agent's long-term memory, for example through a prompt injection in a web page the agent read, the bad instruction comes back in every later session. Label memories written after reading untrusted content, and never let them become rules.
How does an agent forget?
Only if you build it: delete memories that are contradicted, decay old ones, expire them after a time limit, and let users see and delete what is stored about them.
Prefer plain text? Read this page as Markdown.