Skip to content

Long-term context retention for coding agents means storing each lesson in the layer that reloads it: instruction files (CLAUDE.md, AGENTS.md, Cursor project rules) for team facts, Claude Code auto memory or Codex memories for personal notes, a handoff file for unfinished work. Anything that must always hold belongs in a test or hook: memory is only advice.

It is Thursday. On Monday you spent 40 minutes teaching the agent that the search service needs a warm-up call before its results are accurate, that integration tests must seed the index first, and that the staging API uses a separate database. Today a fresh session writes a search test without the warm-up, it passes locally against a warm cache, and it fails in CI. This page is for developers who run agents across many sessions, and for tech leads who want one person’s hard-won lesson to reach the whole team.

What you’ll walk away with from memory patterns

Section titled “What you’ll walk away with from memory patterns”
  • A map of what Claude Code, Codex and Cursor load at the start of every session, and what they never load.
  • A decision table for where a new fact goes: conversation, handoff file, personal memory, team file, scoped rule, or a check.
  • Four copy-paste prompts: teach a fact, prove it loaded, hand off a task, and audit memory before it rots.
  • A failure-modes list for stale, contradictory, truncated and poisoned memory, with recovery steps.

Which memory layers do Claude Code, Codex and Cursor load?

Section titled “Which memory layers do Claude Code, Codex and Cursor load?”

Each tool reloads a different set of files. Know the set before you decide where a fact goes, because a fact stored in a layer that does not load is a fact the agent does not have.

LayerLocationShared howLoads
Managed policymacOS /Library/Application Support/ClaudeCode/CLAUDE.md, Linux and WSL /etc/claude-code/CLAUDE.mdIT deploys it; users cannot exclude itEvery session
Project instructions./CLAUDE.md or ./.claude/CLAUDE.mdGitEvery session
Project rules.claude/rules/*.mdGitEvery session, or only for matching files when the rule has paths: frontmatter
User instructions~/.claude/CLAUDE.md, ~/.claude/rules/Your machine onlyEvery session, every project
Local instructions./CLAUDE.local.md (add it to .gitignore)Your machine onlyEvery session in this project
Auto memory~/.claude/projects/<project>/memory/Your machine onlyFirst 200 lines or 25 KB of MEMORY.md, whichever comes first; topic files on demand
Subagent memory.claude/agent-memory/<agent>/ (memory: project)GitWhen that subagent runs

Auto memory is on by default. Claude writes notes of four types (user, feedback, project, reference) and skips anything it can derive from the code or that CLAUDE.md already says. The <project> key comes from the git repository, so all worktrees of one repository share one memory directory; it never leaves your machine. Turn it off per project with "autoMemoryEnabled": false in .claude/settings.json, or everywhere with CLAUDE_CODE_DISABLE_AUTO_MEMORY=1.

With no CLAUDE.md or CLAUDE.local.md on the path, Claude Code reads AGENTS.md instead, from v2.1.277 (v2.1.281 on Bedrock, Google Cloud, Foundry, LLM gateways and telemetry-off sessions), on both release channels since stable reached v2.1.287. Source: Claude Code memory docs, checked 2026-09-26 on v2.1.283.

Two things hold in all three tools. First, nothing from yesterday’s conversation reloads by itself; only files do. Second, every loaded line costs context in every session, so a memory layer that grows without pruning slowly crowds out the task. Context windows covers that cost.

Most memory problems are placement problems. Ask two questions about the fact: who needs it, and what happens if the agent ignores it.

The factPut it inWhy
Matters only for the task in front of youThe conversationIt dies with the session, which is correct
Matters until this feature shipsA handoff file in the repository, such as docs/tasks/search-warmup.mdSurvives /clear, compaction and a switch of tool; deleted when the work merges
Your preference (“I review diffs in small commits”)Auto memory, ~/.claude/CLAUDE.md, or ~/.codex/AGENTS.mdNobody else should inherit it
Every teammate’s agent needs itCLAUDE.md, AGENTS.md, or an always-applied Cursor ruleReviewed in a pull request, loaded for everyone
Only one part of the codebase needs itA path-scoped rule (.claude/rules/ with paths:, a Cursor rule with globs) or a nested AGENTS.mdLoads only where it applies
Breaking it ships a bugA test, lint rule or hook, plus one line in the instruction file that names the checkMemory is advice; a check is enforcement

The last row is the one that makes quality provable. “Search tests must call the warm-up endpoint” in CLAUDE.md makes the agent more likely to comply. A shared test fixture that performs the warm-up, and a lint rule that flags a search test without it, make non-compliance fail CI whatever the agent remembered. Write the memory line anyway: it tells the agent why the check exists, so it fixes the cause instead of working around the failure. Hooks as deterministic guardrails shows the hook side.

Keep out of every layer: facts the agent can read from the code (directory layouts, dependency lists, package.json scripts), temporary workarounds, and anything secret. Claude Code’s own guidance targets under 200 lines per CLAUDE.md; pruning context files shows how to test which lines earn their place.

When a session uncovers something non-obvious, store it before you close the session, while the evidence is still in context. Name the layer explicitly. “Remember this” alone lets the tool choose, and the choice differs per tool.

Asking Claude to “remember” something saves it to auto memory, which only you see. To give it to the team, say “add this to CLAUDE.md” or name a rules file:

Add a path-scoped rule at .claude/rules/search.md with paths: ["src/search/**", "tests/search/**"]:
integration tests for the search service must call POST /search/warm-up before
asserting on results, because a cold index returns partial matches.

Run /memory to browse your memory files and open the auto memory folder; /context shows which ones loaded in this session. Messages such as “Saved 2 memories” show when Claude writes there.

Prove the memory loaded and changes behaviour

Section titled “Prove the memory loaded and changes behaviour”

A memory entry is an untested instruction. Check two things: that the file loaded in this session, and that the agent acts on it when the task does not mention it.

  1. Check loading. In Claude Code, run /context and look under Memory files; the InstructionsLoaded hook can log every file and rule as it loads (it does not fire for an AGENTS.md read directly without a CLAUDE.md; check /context for that case). In Codex and Cursor, ask the agent to quote the entry without opening any file (prompt below). A path-scoped rule loads only after the agent touches a matching file, so test it on a matching task.
  2. Run a probe task. Ask for work where the fact matters but is not mentioned: “Add an integration test for search by tag.” Do not hint at the warm-up.
  3. Let a command decide. Run the test or the lint rule that encodes the fact. You check the result of one command, not the whole diff.
  4. Record the outcome. If the probe failed, the entry is too vague, in the wrong layer, or buried. Fix it and rerun the probe in a fresh session.

If the quote is missing, the file did not load: check its location against the table above. If the quote is present but step 2 skips the warm-up, the entry loaded and did not steer; move it higher, make it concrete, or promote it to a check.

Carry a task across sessions with a handoff file

Section titled “Carry a task across sessions with a handoff file”

Conversation history is the least durable memory there is. Compaction summarises it, /clear removes it, and a new tool never sees it. For work that spans days, keep the state in a file the repository owns.

  1. Session 1: plan. Write the plan to docs/tasks/<feature>.md with a checklist, the acceptance criteria, and a “Decisions” section. Name the session so you can find it: claude -n search-warmup in Claude Code; in Codex, run /rename search-warmup inside the session.
  2. Every session: work from the file. Tick items as they pass their checks, and add each decision with its reason (“rejected retry-on-read: it hides index lag”).
  3. End of session: hand off. Run the handoff prompt below so the file, not your memory, holds the state.
  4. Next session: resume. Start fresh and point the agent at the file. Resuming the old session also works, but a long history costs context; the file gives the agent the same state in a few hundred tokens.
  5. Merge: clean up. Move lasting decisions to an ADR or the instruction file, then delete the handoff file.

Resume commands, checked on Claude Code v2.1.283 and codex-cli 0.157.1:

Terminal window
claude -c # continue the most recent conversation in this directory
claude -r search-warmup # open the resume picker filtered by that search term

A name is treated as a search term, so pick the session in the list; pass a session ID to resume it directly. Inside a session, /rename renames the current one.

For multi-week recall beyond one task file, persistent memory plugins compares planning-with-files, claude-mem and MCP memory servers. The artifact chain covers the planning file itself.

Personal memory helps one person. The lesson that cost you an afternoon should reach everyone’s agent, and it should reach them through review.

  • Treat instruction files as code. Changes to CLAUDE.md, AGENTS.md, .claude/rules/ and .cursor/rules/ go through pull requests with a named owner in CODEOWNERS. The OWASP GenAI LLM Top 10 2026 lists “Treat agent memory writes as privileged operations” among its prompt-injection mitigations (LLM01, checked 2026-09-26); a reviewed pull request is how a team does that.
  • Promote personal memory on a schedule. Auto memory and Codex memories stay on one machine and are never reviewed. Once a fortnight, run the audit prompt below and move anything team-relevant into a shared file through a pull request.
  • Give reviewers a memory. A Claude Code subagent with memory: project keeps its notes in .claude/agent-memory/<agent>/, which you can commit. A review subagent then accumulates the team’s recurring findings where everyone can read and correct them.
  • Keep organisation policy separate. A managed CLAUDE.md carries company-wide behaviour that users cannot exclude; see managed policy. Technical enforcement, such as denied commands, belongs in managed settings, not in prose.

From v2.1.283 (both release channels on 2026-10-12), /doctor prompt-audit runs a similar check across your instruction files, skills and subagents and proposes edits without applying them.

The agent follows a rule that is no longer true. A note from March says “run migrations with db:push”; the team moved to versioned migrations in June. Recovery: run the audit prompt, delete the stale entry, and add the command that proves the current rule. Auto memory files carry a modified timestamp (Claude Code v2.1.214 and later), which helps you spot old notes.

Two entries contradict each other. Claude Code’s docs warn that Claude “may pick one arbitrarily”. Recovery: the audit prompt’s CONTRADICTS status finds them; keep one, and put the rule nearest the code it governs.

MEMORY.md grew past its load limit. Only the first 200 lines or 25 KB load; Claude Code returns an error telling Claude to rewrite the index when a write crosses the limit. Recovery: keep one line per entry in MEMORY.md and move detail into topic files, which load on demand.

Codex silently drops the end of your instructions. The concatenated AGENTS.md chain stops at 32 KiB by default. Recovery: move service-specific sections into nested AGENTS.md files and prune the root; raise project_doc_max_bytes only after pruning.

A local file hides the team file. In Codex, an AGENTS.override.md replaces the AGENTS.md beside it. In Claude Code, adding a CLAUDE.local.md to a project that relies on AGENTS.md stops Claude from reading AGENTS.md. Recovery: delete forgotten overrides; in Claude Code, set Project instructions to claude-md-and-agents-md in /config.

Memory is missing in a worktree, the cloud or CI. A gitignored CLAUDE.local.md exists only in the worktree where you created it, and auto memory never leaves your machine, so a cloud or CI agent has none of it. Recovery: anything a remote agent needs goes in a committed file.

An untrusted repository writes to your agent’s memory. Instruction files and memory are read as guidance, so a malicious AGENTS.md or a poisoned memory note steers the agent. Codex already ignores project AGENTS.md in untrusted projects (since 0.150.0). Recovery: review instruction-file changes like code, never run an agent with secrets in its environment against an unreviewed ref, and see the agent threat model.

A personal preference leaks into every project. Something project-specific landed in ~/.claude/CLAUDE.md or ~/.codex/AGENTS.md. Recovery: keep user-level files to preferences that are true in every repository, and move the rest into that project’s files.