# Long-Term Context Retention Patterns

URL: https://developertoolkit.ai/en/workflows/context/memory-patterns/
Description: Decide what Claude Code, Codex and Cursor should remember across sessions, store each fact in the right layer, and prove the memory loaded and still holds.

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

- 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?

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.

**Claude Code**

    | 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](https://code.claude.com/docs/en/memory), checked 2026-09-26 on v2.1.283.

**Codex**

    | 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.

**Cursor**

    | 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](/en/cursor-ide/quick-start/project-rules/).

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](/en/workflows/context/context-windows/) covers that cost.

## 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](/en/developer-scorecard-guide/agent-hooks/) 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](/en/workflows/context/pruning-context-files/) shows how to test which lines earn their place.

## 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.

**Claude Code**

    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:

    ```text
    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.

**Codex**

    Codex writes nothing between sessions unless `memories` is on, so ask it to edit the file itself:

    ```text
    Add to the AGENTS.md in services/search/: integration tests must call
    POST /search/warm-up before asserting on results, because a cold index
    returns 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`.

**Cursor**

    Ask Agent to write a project rule with a glob, so it loads only for search code:

    ```text
    Create .cursor/rules/search-tests.mdc with frontmatter
    globs: tests/search/**/*.ts and alwaysApply: false. Body: integration tests
    for 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.

**Copy-paste prompt: store a lesson in the right layer**

```text
We just learned something the next session must not rediscover:

<one sentence: the fact, and the evidence that proved it>

Before you write anything:
1. Check whether our instruction files (CLAUDE.md / AGENTS.md / .cursor/rules, .claude/rules)
   already say this or something that contradicts it. Quote any match.
2. Propose ONE location: team file, path-scoped rule, or personal memory. Justify it in one line
   (who needs it, where in the codebase it applies).
3. Draft the entry in at most three lines: the rule, the reason, and the command or test that
   proves it.
4. Say whether this should also become a test, lint rule or hook, and name the file.
Wait for my approval, then make the edit and show the diff.
```

## 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.

**Copy-paste prompt: memory canary and probe**

```text
Without opening any files or running any tools, answer from what is already in your context:
1. List every instruction you have about the search service and about integration tests.
   Quote each one and name the file it came from. If you have none, say "none".
2. Now, still without reading files, describe the steps you would take to add an
   integration test for "search by tag". Do not write code.
I will compare your answer with our instruction files.
```

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

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:

**Claude Code**

    ```bash
    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.

**Codex**

    ```bash
    codex resume --last          # continue the most recent session
    codex resume search-warmup   # resume by session name or UUID
    ```
    `codex fork` starts a new session from an old one without changing it.

**Cursor**

    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.

**Copy-paste prompt: end-of-session handoff**

```text
I'm ending this session. Update docs/tasks/search-warmup.md so a fresh session can continue
without this conversation:
1. Tick every checklist item that has passed its check, and name the command that proved it.
2. Under "Next", list the remaining items in order, each with its acceptance check.
3. Under "Decisions", add each decision we made today with its reason and any rejected option.
4. Under "Open questions", list anything you are unsure about. Do not invent answers.
5. Tell me which, if any, of today's lessons belong in a permanent instruction file,
   and which layer. Do not edit those files yet.
Show me the diff of the task file.
```

For multi-week recall beyond one task file, [persistent memory plugins](/en/ecosystem/plugins/memory-plugins/) compares planning-with-files, claude-mem and MCP memory servers. [The artifact chain](/en/method/lifecycle/artifact-chain/) covers the planning file itself.

## 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 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](/en/org/managed-policy/). Technical enforcement, such as denied commands, belongs in managed settings, not in prose.

**Copy-paste prompt: audit memory before it rots**

```text
Audit what you remember about this project. Read every instruction file you load
(CLAUDE.md, CLAUDE.local.md, AGENTS.md, .claude/rules, .cursor/rules) and, if you have one,
your auto memory folder. Produce a table with one row per entry:
file | entry (quoted) | status | evidence | proposed action
Status is one of: CURRENT, STALE (the code or config now says otherwise), DUPLICATE,
CONTRADICTS <other entry>, DERIVABLE (the agent can read it from the code), PERSONAL
(belongs in personal memory), PROMOTE (personal note the whole team needs).
Evidence must be a file path and line, or a command and its output. No evidence, no STALE.
Do not edit anything. I will approve the actions row by row.
```

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

**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](/en/org/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.

## Where to go next with memory patterns

- [Documentation as context](/en/workflows/context/documentation-as-context/) — What belongs in CLAUDE.md, AGENTS.md and Cursor rules, and how to write it.
- [AGENTS.md and CLAUDE.md — concise repository context](/en/developer-scorecard-guide/claude-md-context/) — Keep the root instruction file short, specific and worth loading every session.
- [Pruning context files](/en/workflows/context/pruning-context-files/) — Test which instruction lines earn their place and delete the rest.
- [Claude Code memory system](/en/claude-code/build/memory-system/) — CLAUDE.md, rules, imports and auto memory in depth.
- [AGENTS.md for Codex](/en/codex/quick-start/agents-md/) — Set up root and nested AGENTS.md files for Codex.
- [Persistent memory plugins](/en/ecosystem/plugins/memory-plugins/) — planning-with-files, claude-mem and MCP memory servers for multi-week recall.
- [Error-driven development](/en/method/principles/error-driven-development/) — Turn each failure into a check, so the lesson cannot be forgotten.
