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
- Builds on
- 15 concepts →
- Quiz
- 5 questions ↓
The full path from zero — 15 concepts before this one
- What Is AI?
- Vectors
- Python for AI
- How Machines Learn
- Dot Product, Norms and Similarity
- Large Language Models, Explained Simply
- AI Fluency: Working Well with AI
- Prompt Engineering
- Using LLM APIs
- Asking Well: Everyday Prompting
- Embeddings and Semantic Search
- What Is Agentic Coding?
- Retrieval-Augmented Generation
- Planning and Specs: Telling an Agent What to Build
- Context Engineering and Memory
- 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.
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 throughparser.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.mdorAGENTS.mdinside a subfolder, such asweb/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 apaths: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
- Run the agent's initialiser. In Claude Code,
/initreads the repository and drafts aCLAUDE.mdwith 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." - 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.
- 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 allshows 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).
The controls, in Claude Code terms (other agents have equivalents):
/contextshows what is using the window right now./clearbetween 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./compactreplaces 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
/inithave 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_pathdirectly, 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
/clearbecause "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.mdin 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
- Tests as Guardrails: the Commands section matters most because tests are how an agent checks itself.
- Extending Your Agent: Skills, Hooks, MCP and Subagents: skills for procedures, hooks for rules that must always hold.
- Context Engineering and Memory: the general theory of budgeting a context window, compaction and long-term memory.
- Running Agents in Parallel and in the Background: a shared memory file keeps several agents consistent.
Try it
- Run
/init(or ask your agent to draft anAGENTS.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.- 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.
- 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.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Claude Code: manage Claude's memory
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.
AGENTS.md
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.
Claude Code: Best practices for agentic coding
Concrete workflows for coding agents: CLAUDE.md files, explore-plan-code-commit, test-driven loops, course-correcting early, and running agents safely.
Effective context engineering for AI agents
Treats the context window as a limited attention budget: context rot, compaction, structured note-taking, sub-agents and just-in-time retrieval.
Cursor documentation
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