Tutorial
Agent memory and compaction in practice
Keep long Claude Code sessions accurate with compaction, CLAUDE.md, auto memory, subagents and a summarise-and-restart routine, and know what survives each.
Bookmark
Bookmarks are kept in your free account, so you can find this page again on any device.
Sign in to bookmarkOn this page
Every coding agent works inside a context window. As a session goes on, it fills with file contents, test output, tool results and your back-and-forth. Two things happen. Costs rise, because the whole conversation is sent with every request. And quality drops: models attend less reliably to details buried in a long context, so instructions from an hour ago get missed and stale facts compete with new ones. Researchers call the second effect context rot.
This tutorial covers the tools Claude Code gives you to manage that, what each one keeps and loses, and a routine for long tasks. Checked against the Claude Code documentation on 20 November 2026.
See what is in the context
Start by looking. In a session, run:
/context
It breaks down what is using the window: system prompt, tools, MCP servers, memory files, skills and the conversation itself. /context all also lists every memory file that loaded. If your CLAUDE.md is not in that list, Claude cannot see it.
Look for surprises. A large MCP server, a long CLAUDE.md or one enormous test log can take a big share before you have asked anything.
The four kinds of memory
Claude Code has several places where knowledge lives, and they last for different lengths of time:
| Where | Written by | Lasts | Loaded |
|---|---|---|---|
| Conversation | You and Claude | This session (until cleared or compacted) | Always, in full |
CLAUDE.md, .claude/rules/ |
You | Permanently, in Git | At session start; project-root CLAUDE.md is re-read after compaction |
| Auto memory | Claude | Permanently, on your machine | First 200 lines or 25 KB of MEMORY.md at session start |
| Files you ask it to write (plans, notes, handoffs) | Claude, at your request | Until you delete them | When something tells Claude to read them |
The rule that follows: anything that must outlive this conversation goes in a file, not in chat.
Compaction
When the conversation gets close to the auto-compact threshold, Claude Code summarises older history and replaces it with the summary. You can also do it yourself at a good moment:
/compact
Compaction is lossy by design. The summary keeps decisions and current state; it drops the exact wording of old tool output and the dead ends. Usually that is what you want. Sometimes it drops a detail you needed.
Tell it what to keep:
/compact keep the list of failing tests and the decision to keep the v1 API; drop the exploration of the logging module
Or set standing instructions in CLAUDE.md, which Claude Code reads when it compacts:
# Compact instructions
When compacting, keep: test output from the latest run, file paths changed so far,
and any decision the user made. Drop: exploration that led nowhere.
Compact at natural boundaries (a sub-task finished, tests green) rather than letting the automatic threshold pick a random moment mid-debugging.
Clear instead of compact
/clear starts a fresh conversation with nothing carried over except your memory files. It costs nothing, where compaction itself is a large request that reads the whole conversation to summarise it.
Use /clear when you switch to an unrelated task. A fresh context with a good CLAUDE.md beats a compacted context full of another task’s leftovers. Before clearing, /rename the session so you can /resume it later if you need to.
Auto memory
Claude Code also keeps notes for itself across sessions. When you correct it (“we use pnpm, not npm”) or tell it to remember something, it saves a short note in ~/.claude/projects/<project>/memory/, with an index file MEMORY.md and one file per topic. The start of MEMORY.md loads in every new session.
Auto memory is on by default. Check what it holds now and then with /memory, which lists your memory files and lets you open them. Delete notes that are wrong or out of date; a stale memory is worse than none. If you want something shared with the team, put it in CLAUDE.md instead, because auto memory stays on your machine.
Subagents keep noise out
Some work generates a lot of text you do not need to keep: searching a large codebase, reading long logs, running a test suite with verbose output. A subagent does that in its own context window and returns only a summary to your main conversation.
use a subagent to run the full test suite and report only the failing tests with their first error line
Your main context grows by a paragraph instead of thousands of lines. Subagents in Claude Code covers defining your own.
Summarise and restart
For a long task that will not fit in one context, do the compaction yourself, into a file you can read and edit. This is the most reliable pattern we know for multi-hour work.
When a phase is done, ask:
Write docs/handoff.md for whoever continues this task. Include:
- the goal, in two sentences
- what is done, with file paths
- what is left, as a checklist
- decisions made and why
- anything that surprised you or is fragile
Do not include exploration that led nowhere.
Read the file. Fix anything wrong; this is your chance to correct the record before it propagates. Then:
/clear
Read docs/handoff.md and continue with the first unchecked item.
Compared with /compact, the handoff is explicit, reviewable and editable, and it survives the session ending, a crash, or handing the work to a colleague or a different agent. Some teams keep a PLAN.md with a checklist throughout and update it after every step, which does the same job continuously.
A routine for long sessions
- Start each task with
/clearand a specific request. - Keep standing rules in
CLAUDE.md(under about 200 lines; move specialist workflows into skills so they load only when needed). - Delegate noisy work to subagents.
- Watch the context indicator. When it is getting full at a natural break,
/compactwith instructions, or write a handoff and/clear. - Before ending the day, write the handoff. Tomorrow starts clean.
How you know it is working
- Claude still follows the instructions from your
CLAUDE.mdlate in a session. - It does not re-read files it has already summarised, or re-propose rejected approaches.
/usageshows most input served from the prompt cache, and per-request token counts are not growing without bound.
If late-session quality drops anyway, the context is probably carrying things it should not. Run /context again and look for what grew.
Pitfalls
Letting auto-compaction choose the moment. It can fire mid-investigation and summarise away the detail you were about to use. Compact deliberately at boundaries.
Huge CLAUDE.md files. Everything in them is sent with every request. Keep them short and specific; move rarely-needed instructions to skills or path-scoped rules.
Trusting the summary blindly. Compaction and handoffs can carry forward a wrong conclusion. Read handoffs before continuing from them.
One session for everything. Unrelated tasks in one conversation poison each other’s context. Clear between them.
Next steps
- Understand why long contexts fail in Context rot: why long contexts fail and what to do.
- Write a better project memory with CLAUDE.md and AGENTS.md.
- Apply the same pattern outside code with the workplace memory skill, which keeps people, projects and team shorthand in a CLAUDE.md and a
memory/folder. - Offload noisy work with Subagents in Claude Code.
- See how context size drives cost in Cut LLM costs with prompt caching.
- Work through the rest of this topic in order with the prompt and context engineering learning path.
Covers
- Tools
Check your understanding
Agent memory and compaction quiz
Reading /context, the four kinds of memory in Claude Code, compaction and what survives it, /clear, auto memory, subagents and the summarise-and-restart handoff.
8 questions · pass mark 70%
Review
Related
- Context rot: why long contexts fail and what to do
Why models get worse as their context fills up, from lost-in-the-middle to distractors and poisoned context, and the practical fixes for agents and RAG.
- CLAUDE.md and AGENTS.md: instruction files for coding agents
CLAUDE.md vs AGENTS.md: what to put in each, where Claude Code, Codex, Cursor and Copilot look for them, and how to keep one source of truth without drift.
- Subagents in Claude Code: delegate without losing control
Define Claude Code subagents with their own tools, model and permissions, keep noisy work out of your main context, and avoid conflicts in parallel runs.
- Compaction
Summarising earlier parts of a long conversation and replacing them with the summary to free context space for the work still to do.
- Context rot
The gradual decline in a model's accuracy and instruction-following as its context fills up with long, stale or irrelevant content.