AI agent memory: short-term, long-term and what works in practice

AI agent memory: short-term, long-term and what works in practice

AI agent memory is whatever the software around an agent saves outside the model and puts back into its context window later, because the model itself remembers nothing between calls. This guide covers short-term and long-term memory, context files, summaries and vector stores, and the patterns that hold up in real coding and support agents.

In shortTL;DR
  • Models are stateless: every bit of memory is text your agent code stores and loads back into the context window.
  • Short-term memory is the current conversation, kept within budget by trimming, clearing old tool results and compaction.
  • Long-term memory works best as small, plain files the agent reads at the start and updates at the end, such as CLAUDE.md, a progress log and a feature list.
  • Vector stores help when an agent must search a large pile of past material, not for a handful of facts that should always be loaded.
  • Treat stored memories as untrusted input: they go stale, contradict each other, and can carry injected instructions.

What is AI agent memory?

AI agent memory is information an agent stores outside the language model and loads back into the model's context when it needs it. The model is stateless: each API call sees only the tokens you send, so anything an agent "remembers" from earlier in a task, or from last week, is text the agent's code kept and re-sent.

That makes memory a design problem rather than a model feature. You decide what to save, where to keep it, when to load it and when to throw it away. Researchers and framework authors split it into a few layers:

LayerLives inLifetimeExample
Working memoryThe context windowOne model callThe prompt, recent messages, tool results
Short-term memorySession or thread historyOne conversation or taskThe last 40 turns of a support chat
Long-term memoryFiles, databases, vector storesAcross sessions"User prefers TypeScript", a progress log

The LangChain memory docs borrow three further categories from psychology for long-term memory, and they are useful for deciding what to store:

  • Semantic memory: facts. "This customer is on the Business plan." "The repo uses pnpm."
  • Episodic memory: past experiences. "Last time we migrated this table, the backfill timed out." Often stored as examples of earlier runs.
  • Procedural memory: how to do things. System prompts, instruction files and skills. CLAUDE.md is procedural memory.

The 2023 MemGPT paper framed the same problem as an operating system: a small, fast main context and larger, slower external storage, with the model moving information between the tiers. Most practical systems today are simpler versions of that idea.

Why isn't a bigger context window enough?

A large context window holds more, but models use long contexts unevenly, and every token costs money and attention. Memory design is about putting the right few thousand tokens in front of the model, not all of them.

Three findings explain why:

  • Position matters. The "Lost in the Middle" study found that "performance is often highest when relevant information occurs at the beginning or end of the input context," and drops when the key passage sits in the middle, even for long-context models.
  • Context rot. Anthropic's context engineering guide describes how, as the window fills, "the model's ability to accurately recall information from that context decreases," and treats context as an attention budget that every token depletes.
  • Cost and latency. Each turn re-sends the history. A long agent session with large tool outputs pays for those tokens again on every call, even with caching.

So even with a window of hundreds of thousands of tokens, you still need to decide what stays in it. See what a context window is for the basics of limits and pricing.

100Kinput tokens before Claude's tool-result clearing starts by default
200 linesof the MEMORY.md index Claude Code loads each session (or 25KB)
4 hopsmaximum depth of @ imports in CLAUDE.md files
Sources: Claude docs, Context editing; Claude Code docs, How Claude remembers your project (November 2026)

How does short-term memory work in an agent?

Short-term memory is the running history of the current task: messages, tool calls and tool results. The agent loop appends to it every turn and must shrink it before it overflows or degrades the model's focus.

The common strategies, from simplest to most capable:

StrategyWhat it doesGood forRisk
Full historySend everything every turnShort tasksOverflows, cost grows each turn
Sliding windowKeep the last N messagesChatbotsForgets early instructions and decisions
Tool result clearingReplace old tool outputs with placeholdersAgents that read many files or pagesThe agent may re-read things it needs
Summarization (compaction)Replace old history with a summaryLong sessionsDetails the summary left out are gone
Sub-agentsDo exploration in a separate context, return a short reportResearch, codebase searchesExtra cost, the parent sees only the summary

Two of these are built into the Claude API. Context editing clears old tool results with the clear_tool_uses_20250919 strategy; by default it starts once the prompt passes 100,000 input tokens and keeps the 3 most recent tool uses. Compaction summarizes the whole conversation on the server when it nears the window limit. Claude Code runs compaction automatically in long sessions, and you can trigger it with /compact.

The weak point of every strategy is the same: something that mattered gets dropped. Claude Code's memory docs put it plainly for one case: if an instruction disappeared after compaction, it was probably "given only in conversation." The fix is to move anything that must survive into long-term memory before the history is trimmed. Claude's context editing does this by warning the model as it nears the clearing threshold, so it can write important results to memory first.

What are the options for long-term memory?

Long-term memory is anything that persists between sessions and gets loaded or retrieved into a new one. The storage choices are files, structured records, vector stores and graphs, and they differ mainly in how the agent finds the right item later.

StoreHow the agent retrievesBest forTypical failure
Plain files (Markdown, JSON)Loaded at start, or read by pathRules, preferences, progress logs, small projectsFiles grow and go stale
Key-value or JSON profileLookup by user or entity IDUser settings, account factsOverwrites lose history
Collection of memory recordsFilter or search a list of small itemsMany independent factsDuplicates and contradictions pile up
Vector storeSemantic similarity search over embeddingsLarge archives of conversations or documentsReturns similar but wrong items, ignores recency
Knowledge graph or SQLStructured queries over entities and relationsFacts with relationships and timeHeavy to build and keep consistent

LangChain's docs describe the profile-versus-collection tradeoff well: a single profile document is easy to load but error-prone to update as it grows, while a collection of narrow memories gives higher recall but forces the model to update or delete old items and makes search harder.

Retrieval is the real design decision. Always-loaded memory (a short file read at session start) is reliable but must stay small. Just-in-time memory keeps "lightweight identifiers (file paths, stored queries, web links, etc.)" in context, in Anthropic's words, and fetches content with tools when needed. Most good agents combine both: a short index that is always loaded, pointing to details that load on demand.

How do coding agents handle memory in practice?

Coding agents use the simplest memory that works: Markdown files in the repository plus git history. The model reads them at session start and updates them as it learns, and you can review every change in a diff.

Claude Code is a clear example of the layered approach:

  • CLAUDE.md files are instructions you write. They load from the working directory and every directory above it, and files in subdirectories load when Claude touches files there. The docs recommend keeping each under 200 lines, because longer files "consume more context and reduce adherence." Claude Code can also read an AGENTS.md shared with other tools.
  • Auto memory is notes Claude writes for itself in ~/.claude/projects/<project>/memory/: a MEMORY.md index with one line per memory, plus one file per topic. Notes are typed as user, feedback, project or reference, and Claude skips anything it can derive from the code.
  • Imports with @path/to/file pull other files into CLAUDE.md, up to four hops deep.

Our guide to CLAUDE.md best practices covers what to put in the procedural layer.

For tasks that span many sessions, Anthropic's write-up on long-running agents adds three artifacts: a claude-progress.txt log of what each session did, a JSON feature list where every feature starts as failing and agents only flip a passes field, and an init.sh that starts the dev server. They chose JSON for the list because the model "is less likely to inappropriately change or overwrite JSON files compared to Markdown files." Git commits with descriptive messages let a later session see what changed and revert bad work.

Handwritten notes in a notebook beside a laptop
A progress log works for agents for the same reason it works for people: the next session starts from notes, not from memory.

A progress file you can adapt:

PROGRESS.md
# Progress log (read first, update before you stop)## Current goalMigrate billing from Stripe Charges to PaymentIntents.## Done- 2026-11-01: PaymentIntent creation behind flag `billing.v2` (PR #412, merged)- 2026-11-02: Webhook handler for payment_intent.succeeded (tests pass)## Next1. Refund flow on PaymentIntents (see docs/billing.md#refunds)2. Remove Charges code after 7 days at 100% traffic## Decisions and gotchas- Amounts are integers in cents everywhere. Never floats.- Test webhooks with `stripe listen`; the staging secret differs from prod.

Pair it with one instruction in CLAUDE.md, such as "Read PROGRESS.md at the start of every task and update it before you finish," and each session resumes from a known state instead of re-exploring the repository. This is what makes overnight agent runs reviewable in the morning.

How do you add memory to your own agent?

Start with file-based memory the agent controls through a tool, and add search only when files stop scaling. On the Claude API, the memory tool gives you this pattern with almost no setup.

The memory tool is client-side: Claude asks for file operations (view, create, str_replace, insert, delete, rename) under a /memories path, and your code runs them against storage you choose. When the tool is enabled, the API adds an instruction telling Claude to check its memory directory before starting and to record progress because its "context window might be reset at any moment." The Python SDK ships a local-filesystem implementation:

agent_with_memory.py
import anthropicfrom anthropic.tools import BetaLocalFilesystemMemoryToolclient = anthropic.Anthropic()memory = BetaLocalFilesystemMemoryTool(base_path="./memory")runner = client.beta.messages.tool_runner(    model="claude-opus-5-5",    max_tokens=1024,    messages=[{"role": "user", "content": "Remember that Acme Corp prefers email follow-ups."}],    tools=[memory],)print(runner.until_done().content)

If you write your own handler, for example to store memories per user in a database, validate every path. The docs warn that a path like /memories/../../secrets.env can escape the directory:

safe_path.py
from pathlib import PathROOT = Path("/srv/agent-memory/user-123").resolve()def safe_path(virtual: str) -> Path:    if virtual != "/memories" and not virtual.startswith("/memories/"):        raise ValueError("path outside /memories")    rel = virtual.removeprefix("/memories").lstrip("/")    real = (ROOT / rel).resolve()    real.relative_to(ROOT)  # raises ValueError if the path escaped ROOT    return real

A build order that avoids most rework:

  1. Write down what the agent must remember and why: user preferences, task progress, lessons from failures. Leave out what it can look up.
  2. Give each memory type a home: procedural rules in the system prompt or an instruction file, facts in a profile or small files, progress in a log.
  3. Decide when memories are written. LangChain's docs separate writing "in the hot path" (immediately available, adds latency) from writing in the background (no latency, but timing gets harder).
  4. Load a short index every session and fetch details on demand.
  5. Cap sizes and expire old entries. The memory tool docs suggest tracking file sizes and deleting files not accessed in a long time.
  6. Add vector search later, over archives too large to load, and keep the always-loaded layer.

Put this inside the agent loop you already have; memory is one more tool in it.

When should you use a vector store for agent memory?

Use a vector store when the agent must recall relevant pieces from a large, growing archive, such as thousands of past tickets or conversations, and exact lookup by ID or path is not possible. For a few dozen facts that should always apply, a vector store adds failure modes without benefit.

Similarity search answers "what text looks like this query," which is not the same as "what is true now." Common problems:

  • Stale facts win. "User is on the Free plan" from March can rank above "upgraded to Business" from October. Store timestamps and prefer recent entries.
  • Near misses. A memory about a different customer with a similar problem scores high. Filter by user, project or tenant before ranking.
  • Silent gaps. If the right memory isn't retrieved, the agent doesn't know it exists. Keep critical facts in the always-loaded layer.

The mechanics are the same as retrieval-augmented generation; our explainers on vector databases and what RAG is cover chunking, embeddings and evaluation.

What goes wrong with agent memory?

Memory fails in four predictable ways: it goes stale, it contradicts itself, it grows until it hurts more than it helps, and it becomes a channel for attacks. Each has a simple countermeasure.

  • Stale memory. A note that says "tests run with Jest" outlives the move to Vitest, and the agent follows it. Date entries, and make "update or delete outdated notes" part of the agent's instructions.
  • Contradictions. Two memories disagree and the model picks one. Prefer updating a single record over appending new ones, and review memory files like code.
  • Bloat. Every session adds a little, and the always-loaded file becomes noise. Anthropic's progress-file pattern works because each session records only what was done and what comes next.
  • Memory poisoning. If an agent saves text from web pages, emails or issues into memory, injected instructions can persist and fire in later sessions. Keep instructions and observed data separate, and never let untrusted content write to procedural memory. Our guide to prompt injection in coding agents covers the attack in detail.
  • Privacy. Memories about people are personal data. The memory tool docs note that Claude usually refuses to write sensitive information, but recommend your own validation for stronger guarantees, plus expiry for unused files.
Warning

Memory files in a repository are instructions to every agent that opens it. Review changes to CLAUDE.md, AGENTS.md and progress files in pull requests the same way you review code.

A practical memory setup for your next agent

Start with files, measure what the agent forgets, and add machinery only where a real failure shows up. This setup covers most coding and assistant agents:

  1. One instruction file (CLAUDE.md or AGENTS.md) under 200 lines with commands, conventions and hard rules.
  2. One progress log the agent reads first and updates before it stops, committed with the code.
  3. One structured task list in JSON for multi-session work, with a status field the agent may change and nothing else.
  4. Automatic compaction or tool-result clearing for long sessions, with a rule to save anything important to the progress log first.
  5. Sub-agents for exploration so large searches return a summary instead of filling the main context.
  6. Vector search only for large archives, filtered by user or project and sorted by recency.
  7. A monthly review where you delete stale memories and fold repeated lessons into the instruction file.

Memory matters most when agents run for hours without you watching. Orkio runs Claude Code on an always-on cloud box, so a long task keeps going after you close your laptop, and a progress log in the repository tells you what happened when you check in from your phone.

Frequently asked questions

Do AI agents have memory?

The underlying language model has no memory between requests. Agents appear to remember because the software around the model stores conversation history, notes or documents and sends the relevant parts back with each new request.

What is the difference between short-term and long-term memory in AI agents?

Short-term memory is the history of the current session, held in the context window. Long-term memory persists across sessions in files, databases or vector stores and is loaded or retrieved when a new session needs it.

Is RAG the same as agent memory?

No, but they overlap. Retrieval-augmented generation fetches relevant documents into the prompt, and an agent can use the same retrieval machinery over its own past notes. Memory adds writing: the agent decides what to save, update and delete, not only what to read.

How does Claude Code remember things between sessions?

Claude Code loads CLAUDE.md files you write and an auto memory directory where Claude keeps its own notes, at ~/.claude/projects/<project>/memory/ by default. The first 200 lines or 25KB of the MEMORY.md index load at the start of every session.

Do I need a vector database for agent memory?

Usually not at first. A few files or a small key-value store cover user preferences, project rules and progress. Add vector search when the volume of past conversations or documents is too large to load and the agent needs fuzzy recall across it.

SOURCES

  1. Claude docs: Memory tool
  2. Claude docs: Context editing
  3. Claude Code docs: How Claude remembers your project
  4. Anthropic Engineering: Effective context engineering for AI agents
  5. Anthropic Engineering: Long-running agent setups (progress files and feature lists)
  6. LangChain docs: Memory overview
  7. Packer et al.: MemGPT, Towards LLMs as Operating Systems
  8. Liu et al.: Lost in the Middle, How Language Models Use Long Contexts
  • #ai agents
  • #memory
  • #context engineering
  • #llm
Orkio team

The team building Orkio. We write about putting AI to work: coding agents that run overnight, always-on boxes and pull requests ready by morning.

Keep reading

All posts

07:06 · YOU MERGED #128

Go to sleep. Wake up to pull requests.

Start for $19 a month
© 2026 Orkio · Hosted in Europe TürkçeStatus