How to write an AGENTS.md or CLAUDE.md that coding agents follow
Every coding agent starts a session knowing nothing about your repository. An instruction file, AGENTS.md or CLAUDE.md, is the one piece of context it loads before it reads any code. Written well, it saves the agent from guessing your test command, inventing a folder layout, or "fixing" something that's broken on purpose. Written badly, it's 600 lines of advice the model skims and half-follows while you pay for those tokens on every request.
This guide covers which file to write, what belongs in it, and how to keep it useful once the repo changes.
AGENTS.md or CLAUDE.md?
AGENTS.md is the shared convention. The agents.md site lists Codex, Cursor, Gemini CLI, Aider, opencode, Zed, Warp, GitHub Copilot's coding agent, Jules, Devin, Junie and others as readers. CLAUDE.md is Claude Code's own file.
Claude Code reads both, with one catch. Per its memory docs, from v2.1.277 it reads AGENTS.md directly only when there's no CLAUDE.md, .claude/CLAUDE.md or CLAUDE.local.md in the working directory or above it. Once a CLAUDE.md exists, that's what it reads.
| Your repo has | Claude Code reads | Other agents read |
|---|---|---|
AGENTS.md only |
AGENTS.md |
AGENTS.md |
AGENTS.md and CLAUDE.md |
CLAUDE.md only |
AGENTS.md |
CLAUDE.md containing @AGENTS.md |
both, AGENTS.md first |
AGENTS.md |
If more than one tool touches the repo, keep the real content in AGENTS.md and add a two-line CLAUDE.md that imports it:
@AGENTS.md
## Claude Code
Use plan mode for changes under `src/billing/`.
The import is better than a symlink if anyone clones on Windows. Git checks a committed symlink out as a plain text file unless core.symlinks is on, so that clone ends up with a one-line CLAUDE.md containing a path and none of your instructions.
Avoid the third option people reach for: a CLAUDE.md that says "read AGENTS.md". That's a request, not an import. The agent sees the other file only if it decides to open it.
What belongs in the file
The test for every line: would the agent get this wrong without being told, and can it not find out cheaply by reading the code? If the answer is no, cut the line.
Things that pass that test:
- Exact commands. How to install, run, test a single file, lint and build.
bun test tests/api.test.js, not "run the tests". Agents run what you write, so make it copy-pasteable and include the one-file form; a full suite run after every edit burns time and tokens. - Where things live, when it isn't obvious. "Route handlers are in
server/routes/, one file per resource. Shared types are inpackages/types, never redefine them locally." - Conventions that differ from the default. If your codebase uses tabs, CommonJS, or a homegrown result type instead of exceptions, say so. The model's default is whatever's most common on GitHub.
- Traps. The generated file you must not edit, the migration that has to run before tests, the env var that silently switches to production. These are the lines that prevent the expensive mistakes.
- What done means. "A change is finished when
npm run checkpasses and the new behaviour has a test." Without this, agents stop when the code compiles.
Things that fail it:
- A project history or mission statement. Put that in the README.
- Style rules your formatter already enforces. The formatter wins anyway.
- A file-by-file tour. The agent can list directories; describe only the parts where the names mislead.
- Aspirations. "We aim for 90% coverage" when the repo has 40% teaches the agent that the file and reality disagree, and it starts trusting neither.
- Secrets, tokens and internal URLs. The file is committed and sent to a model provider on every request.
An example
This is an illustrative file for a made-up TypeScript API, not a template to paste. Yours should be shorter or longer depending on how many traps your repo has.
Orders API: Fastify + Postgres service. Node 22, pnpm.
## Commands
- Install: `pnpm install`
- Dev server: `pnpm dev` (port 4010, needs `docker compose up db` first)
- One test file: `pnpm vitest run test/orders.test.ts`
- Everything before you finish: `pnpm check` (typecheck + lint + tests)
## Layout
- `src/routes/`: one file per resource, registered in `src/app.ts`
- `src/db/queries/`: all SQL lives here; routes never import `pg` directly
- `src/generated/`: output of `pnpm codegen`. Never edit by hand.
## Conventions
- Errors: return `Result<T, AppError>` from services; only routes throw.
- Money is integer cents everywhere. Never use floats for amounts.
- New SQL needs a migration in `migrations/` named `NNNN_description.sql`.
## Don't
- Don't change `migrations/` files that are already merged; add a new one.
- Don't add dependencies without saying why in the PR description.
About 20 lines, and every one of them is something an agent would otherwise get wrong at least once.
Write instructions an agent can check
Models follow concrete instructions far more reliably than vague ones. Anthropic's docs give the same advice: "Use 2-space indentation" beats "format code properly", and "Run npm test before committing" beats "test your changes".
A few habits that help:
- Give the reason when the rule looks arbitrary. "Don't use
Date.now()insrc/billing/; invoices must use the injected clock so tests can freeze time." With the reason, the agent applies the rule to cases you didn't list. - Name the file or command. "Update the changelog" is ambiguous; "add a line under
## UnreleasedinCHANGELOG.md" isn't. - Remove contradictions. If one section says "prefer small PRs" and another says "update every call site in the same change", the model picks one at random. Claude Code's docs say this outright.
- Use a hook or CI for anything that must never happen. An instruction file is context, not enforcement. If committing to
mainor deletingmigrations/would be a disaster, block it in a pre-commit hook, a Claude CodePreToolUsehook, or branch protection. The file can still explain why.
Keep it short
Claude Code's docs suggest staying under 200 lines per file; longer files cost more context and get followed less consistently. The same pressure applies to every agent, because the whole file goes into the prompt on every turn.
When the file grows, split it by where the rules apply instead of trimming useful lines:
- Nested files. Put an
AGENTS.mdinpackages/web/for frontend rules. Agents that support nesting read the nearest file, and the agents.md spec says the closest one wins. Claude Code loadsCLAUDE.mdfiles above the working directory at launch, and loads ones in subdirectories when it works in them. - Path-scoped rules in Claude Code. A file in
.claude/rules/with apaths:list in its front matter loads only when Claude touches matching files:
---
paths:
- "src/api/**/*.ts"
---
- Every handler validates its body with the schema in `src/api/schemas/`.
- Errors use `sendError(reply, code, message)`, never `reply.send({ error })`.
Imports (@docs/testing.md) help you organise a long file, but they don't make it cheaper: imported files load alongside the file that imports them. Block-level HTML comments (<!-- note for maintainers -->) are stripped before Claude Code sends the file, so you can leave notes for humans there at no context cost.
Keep it true
Stale instructions are worse than none. An agent told to run make test after you moved to pnpm will run the dead command, see it fail, and start "fixing" your build.
- Add a line when an agent repeats a mistake. The second time it edits a generated file, that's a new entry under "Don't". This is how most good instruction files grow.
- Change the file in the same PR as the thing it describes. Renaming the test script and leaving the old name in
AGENTS.mdis the most common way these files rot. - Audit it. In Claude Code,
/doctor prompt-auditlooks for instructions that reference files or commands that no longer exist and for files that contradict each other. It proposes edits and changes nothing until you approve. - Test it cold. Start a fresh session and ask "how do I run one test file?" and "where should a new endpoint go?". If the answers are wrong, the file is the bug.
To start from nothing, /init in Claude Code scans the repository and drafts a CLAUDE.md with the build commands and conventions it can find, and suggests edits if one already exists. Treat the output as a first draft: it's good at commands and layout and can't know your traps, so those are the lines you add by hand.
What it costs per request
Your instruction file rides along with every model call in a session, so a 600-line file is paid for hundreds of times a day. Two things keep that cheap. The first is length, covered above. The second is stability: the instruction file sits near the start of the prompt, so when it doesn't change mid-session, providers with prompt caching can serve that prefix from cache at a lower rate.
If you run Claude Code through ChromaLab, the cache_control markers Claude Code sets are forwarded upstream, so that discount still applies on Anthropic-backed models. Setup is in Run Claude Code on any model through ChromaLab, and the Cursor, OpenCode and aider equivalents are in the docs.
Checklist
- One source file (
AGENTS.md), with@AGENTS.mdinCLAUDE.mdif Claude Code also has its own instructions. - Exact commands, including how to run a single test.
- Layout notes only where names mislead.
- Every convention that differs from the common default, with the reason when it looks arbitrary.
- A "don't" section for traps, and hooks or CI for anything that must never happen.
- Under about 200 lines, with the rest moved into nested files or path-scoped rules.
- Updated in the same PR as the code it describes, and re-tested in a fresh session.