Long-Term Context Retention Patterns
PLLong-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.
| Layer | Location | Shared how | Loads |
|---|---|---|---|
| Managed policy | macOS /Library/Application Support/ClaudeCode/CLAUDE.md, Linux and WSL /etc/claude-code/CLAUDE.md | IT deploys it; users cannot exclude it | Every session |
| Project instructions | ./CLAUDE.md or ./.claude/CLAUDE.md | Git | Every session |
| Project rules | .claude/rules/*.md | Git | Every session, or only for matching files when the rule has paths: frontmatter |
| User instructions | ~/.claude/CLAUDE.md, ~/.claude/rules/ | Your machine only | Every session, every project |
| Local instructions | ./CLAUDE.local.md (add it to .gitignore) | Your machine only | Every session in this project |
| Auto memory | ~/.claude/projects/<project>/memory/ | Your machine only | First 200 lines or 25 KB of MEMORY.md, whichever comes first; topic files on demand |
| Subagent memory | .claude/agent-memory/<agent>/ (memory: project) | Git | When 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.
| Layer | Location | Shared how | Loads |
|---|---|---|---|
| Global instructions | ~/.codex/AGENTS.md (or ~/.codex/AGENTS.override.md, which wins when present) | Your machine only | Every session |
| Project instructions | AGENTS.md at the repository root | Git | Every session in a trusted project (untrusted projects skip it since 0.150.0) |
| Nested instructions | services/payments/AGENTS.md | Git | When you start Codex in or below that directory |
| Local override | AGENTS.override.md in any directory | Usually gitignored | Replaces the AGENTS.md beside it |
| Memories | the memories feature | Your machine only | Only when you turn it on |
Codex walks from the project root (the first .git above you) down to your working directory and concatenates one file per directory, up to project_doc_max_bytes, 32 KiB by default. Content past the cap is not loaded. Source: codex-rs/core/src/agents_md.rs at rust-v0.157.1.
The memories feature is stable but off by default in codex-cli 0.157.1 (codex features list). Enable it with codex features enable memories and configure it with /memories. Until you do, AGENTS.md and your own files are the only memory Codex has.
| Layer | Location | Shared how | Loads |
|---|---|---|---|
| Project rules | .cursor/rules/*.mdc | Git | Always (alwaysApply: true), for matching files (globs), or when Agent judges the description relevant |
The agent runtime in @cursor/sdk 1.0.32 loads .cursor/rules/**/*.mdc and reads the alwaysApply, globs and description frontmatter; a plain .md file there is not a rule. cursor.com was unreachable when this page was checked (2026-09-26), so this page treats project rules as Cursor’s durable memory and makes no claim about a built-in memory feature. Set rules up with project rules in Cursor.
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.
Where should a new fact go?
Section titled “Where should a new fact go?”Most memory problems are placement problems. Ask two questions about the fact: who needs it, and what happens if the agent ignores it.
| The fact | Put it in | Why |
|---|---|---|
| Matters only for the task in front of you | The conversation | It dies with the session, which is correct |
| Matters until this feature ships | A handoff file in the repository, such as docs/tasks/search-warmup.md | Survives /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.md | Nobody else should inherit it |
| Every teammate’s agent needs it | CLAUDE.md, AGENTS.md, or an always-applied Cursor rule | Reviewed in a pull request, loaded for everyone |
| Only one part of the codebase needs it | A path-scoped rule (.claude/rules/ with paths:, a Cursor rule with globs) or a nested AGENTS.md | Loads only where it applies |
| Breaking it ships a bug | A test, lint rule or hook, plus one line in the instruction file that names the check | Memory 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.
Teach the agent a fact once
Section titled “Teach the agent a fact once”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 beforeasserting 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.
Codex writes nothing between sessions unless memories is on, so ask it to edit the file itself:
Add to the AGENTS.md in services/search/: integration tests must callPOST /search/warm-up before asserting on results, because a cold indexreturns partial matches. Keep it to two lines under the Testing heading.Show the diff before you accept it. The nested file applies only when Codex starts in services/search/ or below; put facts every session needs in the root AGENTS.md.
Ask Agent to write a project rule with a glob, so it loads only for search code:
Create .cursor/rules/search-tests.mdc with frontmatterglobs: tests/search/**/*.ts and alwaysApply: false. Body: integration testsfor the search service must call POST /search/warm-up before asserting,because a cold index returns partial matches.Commit the rule so every teammate’s Agent gets it.
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.
- Check loading. In Claude Code, run
/contextand look under Memory files; theInstructionsLoadedhook can log every file and rule as it loads (it does not fire for anAGENTS.mdread directly without aCLAUDE.md; check/contextfor 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. - 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.
- 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.
- 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.
- Session 1: plan. Write the plan to
docs/tasks/<feature>.mdwith a checklist, the acceptance criteria, and a “Decisions” section. Name the session so you can find it:claude -n search-warmupin Claude Code; in Codex, run/rename search-warmupinside the session. - 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”).
- End of session: hand off. Run the handoff prompt below so the file, not your memory, holds the state.
- 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.
- 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:
claude -c # continue the most recent conversation in this directoryclaude -r search-warmup # open the resume picker filtered by that search termA 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.
codex resume --last # continue the most recent sessioncodex resume search-warmup # resume by session name or UUIDcodex fork starts a new session from an old one without changing it.
Open a new Agent chat and reference the file with @docs/tasks/search-warmup.md. The file carries the state, so the new chat does not depend on the old 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.
Share memory across the team
Section titled “Share memory across the team”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 inCODEOWNERS. 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: projectkeeps 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.mdcarries 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.
When memory patterns break down
Section titled “When memory patterns break down”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.