◆ AI All-in-One

Level 2 Agentic Coding · Agentic Coding

Project Context and Memory Files

Coding agents forget everything between sessions. Memory files such as CLAUDE.md and AGENTS.md give them a short, permanent briefing on your project. This chapter covers what to put in them, what to leave out, how each tool finds them, and how to manage the context window during long sessions.

Level
●●●●● Easy
Reading
12 min
To learn it well
40 minutes to read, an hour to write your first good one
↗ Plan a path here

Read first

Planning and Specs: Telling an Agent What to BuildContext Engineering and Memory

This leads to

Extending Your Agent: Skills, Hooks, MCP and Subagents
The full path from zero — 15 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Python for AI
  4. How Machines Learn
  5. Dot Product, Norms and Similarity
  6. Large Language Models, Explained Simply
  7. AI Fluency: Working Well with AI
  8. Prompt Engineering
  9. Using LLM APIs
  10. Asking Well: Everyday Prompting
  11. Embeddings and Semantic Search
  12. What Is Agentic Coding?
  13. Retrieval-Augmented Generation
  14. Planning and Specs: Telling an Agent What to Build
  15. Context Engineering and Memory
  16. Project Context and Memory Files

Read them roughly in this order. See it on the concept map →

Why it matters

Every agent session starts with amnesia. Yesterday you spent ten minutes explaining that tally stores money as Decimal, that tests must never touch the real expenses.csv, and that the linter is ruff. Today's session knows none of it. Without help, the agent rediscovers some of these facts by reading code, guesses others, and gets a few wrong. You correct it again.

A memory file fixes this. It is a plain Markdown file in your project that the agent loads automatically at the start of every session: a briefing for a new colleague who forgets everything each night. Claude Code reads CLAUDE.md. Most other agents read AGENTS.md, an open format now stewarded by the Linux Foundation's Agentic AI Foundation. A short, accurate memory file is the single cheapest improvement you can make to an agent's work on a project.

The same mechanism has a cost. Everything in the file goes into the model's context window on every session, whether it is relevant or not. A bloated memory file wastes that space and buries the important rules. Writing a good one is an exercise in deciding what really needs saying.

The idea

A briefing, not a manual

Imagine onboarding a skilled contractor for one day of work. You would not hand them the company's 80-page style guide. You would tell them in five minutes: here is what this project is, here is how to run and test it, here is where things live, here are the few rules that matter, and watch out for these two traps. That is a memory file.

AGENTS.md (or CLAUDE.md) # tally Command-line expense tracker, Python, standard library only. ## Commands - Test: python -m pytest -q (must pass before you finish) - Lint: ruff check . && ruff format . - Types: mypy tally.py ## Layout - tally.py: parsing, storage, CLI in main() - expenses.csv, budgets.json: user data. Never edit. ## Conventions - Money is Decimal, never float; use parse_amount() - Logic in small functions that take a Path ## Gotchas - Tests must never touch the real expenses.csv ## Workflow - Don't change existing tests to make them pass - No new dependencies without asking Purpose one line: what this is Commands exact, copy-pasteable Layout where things live Conventions what it can't infer Gotchas traps it fell into before Workflow rules how you want to work loaded into every session, so every line costs context: keep it short and true
Fig. 1 The anatomy of a good memory file, using tally's. Six short sections: what the project is, exact commands, where things live, conventions the agent couldn't guess, traps it has fallen into before, and how you want it to work.

What earns a place in the file:

  • Commands, exact and copy-pasteable: how to set up, run, test, lint and type-check. This is the most valuable section, because it lets the agent check its own work.
  • Layout: a few lines on where things live, especially anything non-obvious.
  • Conventions the agent can't infer: "money is always Decimal", "errors go through parser.error()". If the agent would follow a rule anyway by imitating the existing code, you don't need to write it.
  • Gotchas: mistakes the agent has actually made. Each time you correct the same error twice, add one line.
  • Workflow rules: "don't modify existing tests to make them pass", "no new dependencies without asking", "specs live in docs/specs/".

What doesn't:

  • Things the agent can discover quickly, such as a full file listing or every function's purpose.
  • Long style guides. Use a formatter and linter, which enforce style mechanically and for free, and tell the agent to run them.
  • Anything secret. Memory files are committed and shared, and their contents are sent to the model.
  • Anything stale. A wrong instruction is worse than none: the agent will follow it confidently.

Claude Code's documentation suggests keeping each CLAUDE.md under about 200 lines, and notes that longer files reduce how reliably instructions are followed. A good test for each line: would removing it cause the agent to make a mistake? If not, cut it.

Key idea A memory file is context, not enforcement. The agent usually follows it, but nothing guarantees it. Rules that must never be broken, such as "never push to main" or "never read .env", belong in permission rules and hooks (Extending Your Agent: Skills, Hooks, MCP and Subagents), with the memory file explaining why.

How each tool finds its file (as of late 2026)

Tool Main file Notes
Claude Code CLAUDE.md in the project root (or .claude/CLAUDE.md) Also ~/.claude/CLAUDE.md for personal rules across all projects, CLAUDE.local.md for personal, uncommitted project notes, and .claude/rules/*.md. Reads AGENTS.md when no CLAUDE.md exists.
Codex CLI AGENTS.md Also ~/.codex/AGENTS.md. Reads one file per folder from the repository root down to the current folder; closer files take precedence.
Gemini CLI GEMINI.md The context.fileName setting can add AGENTS.md.
Cursor .cursor/rules/*.mdc Also reads AGENTS.md in the root and in subfolders.
GitHub Copilot .github/copilot-instructions.md Also .github/instructions/*.instructions.md and AGENTS.md.
Aider none by default Load a conventions file with aider --read CONVENTIONS.md.

If several tools are used on one project, keep one source of truth. The simplest arrangement is an AGENTS.md that every tool reads, plus a two-line CLAUDE.md that imports it:

@AGENTS.md

## Claude Code
- Use plan mode for any change to how data is stored.

The @path syntax is Claude Code's import: the named file is loaded as if its text were pasted in. (Imports organise a file but don't save context, since the imported text is loaded too.)

Nested and scoped instructions

Large projects need different rules in different places. Two mechanisms help:

  • Nested files. A CLAUDE.md or AGENTS.md inside a subfolder, such as web/AGENTS.md, applies to work in that folder. Claude Code loads subfolder files on demand, when it first touches a file there.
  • Path-scoped rules. In Claude Code, a path-scoped rule is a Markdown file in .claude/rules/ with a paths: list in its front matter. It is loaded only when the agent reads or edits a matching file:
---
paths:
  - "tests/**/*.py"
  - "test_*.py"
---
# Testing rules
- Use pytest's tmp_path for any file the code writes.
- One behaviour per test; name tests test_<function>_<behaviour>.

Both keep the main file short, because rules about one corner of the project only cost context when the agent is working in that corner. Cursor's .mdc rule files have a similar option to apply only to matching files.

Auto memory

Some agents also write memory themselves. Claude Code's auto memory (on by default for local sessions as of late 2026) saves notes about your corrections and preferences in a separate file, outside the repository, and loads the start of it into later sessions. You can review and switch it off with /memory. Treat it as a convenience for personal preferences. Project knowledge that everyone, and every tool, needs belongs in the committed file, where you can review it like code.

In practice

Writing the first version

  1. Run the agent's initialiser. In Claude Code, /init reads the repository and drafts a CLAUDE.md with the commands and structure it finds. Other agents will do the same if asked: "Read this repository and write an AGENTS.md for future coding agents: commands, layout, conventions, gotchas. Under 60 lines."
  2. Edit the draft hard. Initialisers tend to describe everything. Delete what is obvious from the code, check every command by running it, and add the conventions and traps only you know.
  3. Commit it. It is part of the project now, reviewed and versioned like code.

Keeping it current

Memory files rot like any documentation. Habits that help:

  • Add a line whenever you correct the same mistake twice. You can tell the agent, "add that to CLAUDE.md", and review its edit.
  • Update it in the same commit that changes a command or convention, so a reviewer sees both together.
  • Prune monthly. Ask the agent to "find instructions in CLAUDE.md that contradict each other or the code". In Claude Code, /context all shows exactly which memory files loaded, which is a quick check when an instruction seems ignored.

Managing the context window in long sessions

The memory file is the permanent part of the agent's context. The rest is the conversation: every file it read, every command output, every failed attempt. As a session goes on, that fills the context window, and output quality tends to drop well before the window is full (see Context Engineering and Memory on context rot).

system prompt + tools memory files (CLAUDE.md…) conversation summary Session start fresh, plenty of room After an hour old files, test output, dead ends After /compact the history becomes a summary After /clear new task, clean slate 0 context window limit The project memory file is re-read after /compact and at every new session. Anything said only in the conversation is summarised away or forgotten.
Fig. 2 How the context window fills during a session. Memory files are a small, permanent slice. The conversation grows with every file read and test run. /compact replaces the history with a summary; /clear empties it for a new task.

The controls, in Claude Code terms (other agents have equivalents):

  • /context shows what is using the window right now.
  • /clear between unrelated tasks. This is the most important habit. A new task deserves a clean start, and the memory file means you don't lose anything that matters.
  • /compact replaces the conversation so far with a summary, freeing space while keeping the thread. Give it a focus: /compact keep the budget spec decisions and the failing test names. Claude Code also compacts automatically when the window gets full.
  • Subagents for big searches. "Use a subagent to find every place amounts are parsed" sends the searching to a separate context and returns only the answer (Extending Your Agent: Skills, Hooks, MCP and Subagents).
  • A progress file for work that spans sessions. A progress file is a short Markdown note the agent updates as it goes: what is done, what is next, decisions made, open questions. A fresh session reads it and continues. It is a deliberate, reviewable alternative to one enormous conversation.

Worked example: tally's memory file

After four chapters, tally has a pattern of corrections. The agent twice used float for money, once wrote a test that appended to the real expenses.csv, and once "fixed" a failing test by changing its expected value. Here is the AGENTS.md that came out of /init plus fifteen minutes of editing:

# tally

Command-line expense tracker in Python, standard library only.

## Commands
- Setup: `python3 -m venv .venv && source .venv/bin/activate && pip install pytest ruff mypy`
- Run: `python tally.py add 12.50 lunch`, `python tally.py report --month 2026-11`
- Test: `python -m pytest -q` (all tests must pass before you say you're done)
- Lint and format: `ruff check . && ruff format .`
- Types: `mypy tally.py`

## Layout
- `tally.py`: parsing, storage (CSV and JSON) and the CLI in `main()`
- `test_tally.py`: pytest tests
- `expenses.csv`, `budgets.json`: the user's real data, git-ignored. Never read, edit or commit them.
- `docs/specs/`: one spec per feature. Read the relevant one before starting.

## Conventions
- Money is always `Decimal`, never `float`. Validate user input with `parse_amount()`.
- Categories are stored lower-case.
- Keep logic in small functions that take a `Path`, so tests can pass `tmp_path`.
- User-facing errors go through `parser.error()`.

## Gotchas
- Tests must never touch the real data files: pass `tmp_path`, or monkeypatch
  `DATA_FILE` / `BUDGET_FILE`.
- CSV dates are ISO `YYYY-MM-DD`; `--month` takes `YYYY-MM`.

## Workflow
- Don't modify existing tests to make them pass. If you think a test is wrong, stop and ask.
- No new dependencies without asking.
- Small commits, one logical change each.

It is 36 lines. Every command was run before it went in. Each gotcha is a mistake that really happened. The workflow rules are the ones that matter if the agent works unattended. Next to it, CLAUDE.md holds @AGENTS.md and one Claude-specific line, so Codex, Cursor or Copilot working on the same repository get the same briefing.

The difference shows immediately. A fresh session asked to "add an export --json command" now uses str(amount) for JSON output (because the file says money is Decimal), writes its test with tmp_path (because of the gotcha), and runs ruff and mypy before finishing (because the commands are listed), all without being told.

Common mistakes

  • Letting /init have the last word. Generated files are long and generic. Cut them by half.
  • Writing a manual. 600 lines of conventions means the important five get lost. Move topic-specific material to scoped rules or skills, which load only when needed.
  • Instructions that contradict the code. If the file says "use pytest fixtures" but every test uses tmp_path directly, the agent gets mixed signals and may pick either.
  • Vague rules. "Write clean code" changes nothing. "Functions over 40 lines should be split" changes something.
  • Rules that need enforcement. "Never run git push" in a memory file is a request. A deny rule is a guarantee. Use both.
  • One endless session instead of memory. If you find yourself unwilling to /clear because "it knows so much now", that knowledge belongs in the memory file or a progress file.

Watch out Memory files are instructions that agents follow, and they are often read from repositories you didn't write. A malicious AGENTS.md in a cloned project, or in a dependency's folder, is a prompt injection waiting to happen. Read the memory files of any repository before you run an agent in it with loose permissions.

Where it leads

Try it

  1. Run /init (or ask your agent to draft an AGENTS.md) on a project of yours. Then cut it to under 50 lines without losing anything an agent would get wrong. Run every command in it.
  2. Over the next week, every time you correct an agent, write the correction down. At the end of the week, decide which corrections belong in the memory file, which belong in a linter or test, and which were one-offs.
  3. Start a long task, and halfway through ask the agent to write a progress file. Run /clear, then ask a fresh session to continue from the progress file. What did it lose?

Hint for 2: a correction that a tool can check ("you forgot to format the file") belongs in a hook or linter. A correction about intent or judgment ("don't change the CSV format") belongs in the memory file.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. You have corrected the agent twice for using float for money in tally. Where does this correction belong?

  2. Your team must never push to main from an agent. Is writing "Never run git push" in CLAUDE.md enough?

  3. /init produced a 400-line CLAUDE.md listing every file and function. What should you do?

  4. Your project has testing rules that only matter when the agent edits test files. How can you avoid loading them in every session?

  5. A feature will take several sessions. How do you carry the work across /clear without one enormous conversation?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Docs

Claude Code: manage Claude's memory

Anthropic · Beginner · Free

Where CLAUDE.md files live (user, project, local, subfolders), how they load, @ imports, path-scoped rules in .claude/rules, and how to use AGENTS.md alongside them.

Docs

AGENTS.md

Agentic AI Foundation (Linux Foundation) · Beginner · Free

The open format for a README written for coding agents: what to put in it, how nested files work in monorepos, and the long list of agents that read it.

Article

Claude Code: Best practices for agentic coding

Anthropic · 2025 · Beginner · Free

Concrete workflows for coding agents: CLAUDE.md files, explore-plan-code-commit, test-driven loops, course-correcting early, and running agents safely.

Article

Effective context engineering for AI agents

Anthropic · 2025 · Intermediate · Free

Treats the context window as a limited attention budget: context rot, compaction, structured note-taking, sub-agents and just-in-time retrieval.

Docs

Cursor documentation

Anysphere · Beginner · Free

Docs for the AI code editor Cursor: its agent, project rules in .cursor/rules, AGENTS.md support, MCP, cloud agents and the command-line agent.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/agentic/project-memory.md