AGENTS.md and context
10 min read
By the end you can write an AGENTS.md in which every line earns its place, and run agent sessions that stay sharp.
TL;DR
- AGENTS.md is team infrastructure: short rules for documented needs and failures, reviewed like code and owned by one champion.
- Keep it concise and scoped: commands, key conventions, pitfalls and pointers. About 200 lines is a useful guideline, not a proven cutoff. The agent reads before it cites; you grep what it names.
- Context is working memory. One unit of work per session, durable state in files; when drift appears, diagnose the cause before compacting or restarting.
What is AGENTS.md?¶
AGENTS.md is the team's agreement with the agent, committed in git.
It is a Markdown file for project instructions. A compatible client loads it according to its own discovery and configuration rules; some clients need explicit loading. The text records what the team wants the agent to follow, reviewable in a pull request. It is the manually owned layer of Memory from Chapter 1, not an enforced permission policy.
AGENTS.md vs CLAUDE.md: what's the difference?¶
The discipline is shared; loading depends on the agent and version.
The shared filename does not imply identical loading. This compatibility summary was checked October 23, 2026; verify the installed version and effective context.
| Client | Filename and configuration | Scope and precedence | Inspect what loaded |
|---|---|---|---|
| Codex CLI | AGENTS.md; AGENTS.override.md takes precedence in a directory; fallback names configurable |
Global guidance, then repository root toward working directory; closer instructions override earlier ones; combined size limit configurable | Ask for active sources and inspect session/TUI logs when auditing |
| Claude Code | CLAUDE.md default; direct AGENTS.md from v2.1.277 |
Default AGENTS fallback only when the working-directory/ancestor path contains no CLAUDE.md, .claude/CLAUDE.md or CLAUDE.local.md; a CLAUDE file can import @AGENTS.md; AGENTS override/local filenames are not Codex equivalents |
/memory; direct AGENTS listings require v2.1.280+, with early exceptions fixed in v2.1.281 |
| Gemini CLI | GEMINI.md default; configure context.fileName to include AGENTS.md |
Global, workspace/ancestor and relevant directory context, subject to trusted-root rules; not Codex's precedence model | /memory show, then /memory reload after changes |
| Aider | Explicit aider --read AGENTS.md; persist read: AGENTS.md in .aider.conf.yml |
Included read-only chat context; no implied AGENTS ancestor-discovery hierarchy | Startup confirmation and /ls |
Primary documentation and version limits are in Appendix C. Test one distinctive instruction in a fresh session rather than assuming the file was discovered or has identical authority in every client.
The story: one convention, three supports
A team I worked with had used a coding agent for six months when a senior engineer brought me a complaint. "Every time we generate an API endpoint, I have to fix the validation. Always the same fix. The agent puts it in the wrong layer."
"Why isn't the rule written down?"
"We never wrote it down. We just keep fixing it."
The senior repeatedly corrected the same validation placement during endpoint reviews. The original account included endpoint counts and a time estimate, but the underlying review records are not available here, so this edition makes no precise monthly saving claim.
We documented the convention in AGENTS.md, added a PR-template reminder and identified correct endpoints as reference examples. Subsequent reviews reportedly needed fewer corrections of that kind. The intervention was that combination; the account does not isolate the instruction's contribution.
| Case note | What this account establishes |
|---|---|
| Provenance | Author-reported, anonymized engagement |
| Evidence | A recurring review problem and a reported improvement; underlying review/time records are not published |
| Comparison | Before/after observations of a combined instruction, reminder and reference-example change |
| Limitations | No isolated instruction effect, controlled task mix or defensible monthly time saving |
| Transfer | Write a scoped convention, support reviewers and examples, then measure recurring corrections |
Six rules for the file
Six rules, each with a test you can apply to any line.
| # | Rule | You met it when |
|---|---|---|
| 1 | One line, one checkable constraint | It names the layer, the mechanism and an example |
| 2 | A documented need or failure | You can explain the risk, missing convention or repeated correction |
| 3 | Task-relevant contents | Key conventions, commands, pitfalls, glossary and pointers |
| 4 | Concise and scoped | Every always-loaded line earns its cost; start well below 200 lines |
| 5 | Treat it as code | Git, PR review, one rotating champion |
| 6 | Read before cite | Every name was read this session or found by grep |
Rule 1: write rules the agent can check
A rule the agent cannot check is decoration.
| The rule | |
|---|---|
| Bad | "Always follow our coding standards. Be careful with validation. Use the right architecture." |
| Good, for this project's HTTP entry path | "Controller DTOs establish request-shape guarantees through Bean Validation before service calls; follow UserCreateController. Other entry points establish the same guarantees. Service/domain code still enforces business invariants; use service method validation where required by that boundary." |
The bad version leaves the architecture unspecified. The scoped version identifies an entry boundary, its guarantee, a mechanism and an example without declaring services universally safe to trust arbitrary input. Spring supports service method validation too. A portable pattern is: "Within [scope], [entry boundary] establishes [input guarantee] using [mechanism]; follow [reference]. Other entries establish the same guarantee; [owner] maintains domain invariants." Appendix B.2 is a project-specific starting point.
Rules 2 and 5: justified by need, owned like code¶
A rule earns its place through a concrete need, and a champion keeps the file honest.
- Review it like code. The agent works against these instructions. Ask which non-obvious convention, preventive constraint or repeated failure justifies each line, and keep the rationale. A documented access restriction need not wait for an incident; vague speculative best practices still pile up into bloat.
- Keep a mistake journal. One entry per real incident, with the rule that prevents a repeat and an evidence pointer, the commit or the incident; B.2 has a sample entry.
- Name a champion. One person owns the file and the journal; everyone edits through pull requests and the champion curates. Each quarter the champion asks of every entry whether it saved anyone in the last three months, and retires those whose underlying problem is gone, with the reason in the commit message; a rule that still prevents a rare failure stays. Then the role rotates.
Rules 3 and 4: scoped contents, a size guideline¶
Keep the instructions the agent needs; link to the detail.
- Forbidden patterns, conventions and journal entries, one line each.
- Exact build and test commands. Without them the agent guesses, and guesses are sometimes wrong.
- A domain glossary. In pretraining "transfer" means many things; in your bank it means one, and a "wire" is only the inter-bank kind.
- One pointer line: "Repository layout and module map:
docs/architecture.md. Read it before touching a module you have not seen this session."
Avoid a repository dump. The revised context-file study found no general success improvement from generated files and over 20% more inference cost in its tested settings; developer-written files helped slightly, without a statistically significant average gain. That does not establish that all instructions harm or all maps are useless. Keep non-obvious conventions and useful pointers here; put a long architecture map in docs/architecture.md, read on demand (Chapter 7).
Aim short; treat 200 lines as a guideline. The file loads at session start, so every line spends context. There is no universal line count at which a model stops following rules. Remove duplication and stale instructions, and scope conventions to the paths or skills that need them. Keep rare but important constraints while their underlying risk remains.
A banking team's file grew to about nine hundred lines in six months and the agent began ignoring the newest rules. We cut it to ninety, moving conventions into skills that load on detection and past-mistake history into the architecture document, and compliance jumped within a week. That is one team's observation, not a measured threshold; the useful habit is deciding what belongs in every session.
Rule 6: when the agent confidently lies
The agent invents files, functions and options, so make it prove what it cites.
It will cite a file that does not exist, a function the library never exposed, an option deprecated three versions ago. The output looks plausible and is wrong; the agent pattern-matches against similar code and does not know it is guessing. Three mechanical tactics:
- Read before cite. Anything the agent references must have been read this session. AGENTS.md can say so: "Before referencing any function, read the file that defines it. Citations without preceding reads are drafts to verify."
- Grep every new name. No hits means the function probably does not exist, or lives in a vendored dependency the agent cannot see. It takes seconds and catches the most common fabrications.
- Hook the citations. If the agent cites a file and line, a few lines of bash in a hook can verify the line exists (Chapter 2).
Context hygiene¶
The window is the agent's working memory, so load what the task needs and nothing else.
Everything in the window competes for the same bounded attention. Stale or conflicting context is one way a long session can lose track of the task. Four habits help manage that risk.
- Pointers over payloads. Link the architecture document from AGENTS.md, do not paste it. Keep the always-loaded layer small and load scoped detail when it matters.
- One coherent unit of work per session. Stay in the session while the shared context remains useful. Before a handoff or restart, save the decisions, constraints, changed files and useful evidence the next session needs in a task note, PR or other suitable place; commit when repository practice calls for it.
- Watch for signs of drift. The agent re-answers a settled question, cites a stale file version, forgets a constraint or makes poorer edits late in the session. These symptoms prompt diagnosis: conflicting requirements, stale source material or missing access can also explain them. Resolve the cause; preserve the needed state before restarting or compacting.
- Treat compaction as a handoff. Summarization can retain conversational decisions but omit or distort details, so save indispensable decisions, constraints and evidence durably. Give the compactor a keep-list: the plan, open questions, implementation deviations and exact commands that worked. Then check that the resulting context contains what the next step needs.
The client determines what it summarizes, retains and reloads; Claude Code's compaction documentation describes those distinctions. Check the behavior of the client and version you use.
When it breaks
- The file is a request, not a wall. The agent can still violate AGENTS.md. Required restrictions need enforced permissions, isolation or protected review gates; a hook helps only on the paths it covers (Chapter 2).
- Old entries turn into folklore. An entry with no evidence pointer is hard to retire, and a graveyard of rules is almost as useless as none: the team stops trusting any of them.
Do this Monday
- [ ] Inspect the repository's current instructions. Add a documented missing convention, justified constraint or recurring correction; include commands and pointers where they save guessing. There is no quota of lines or rules to fill.
- [ ] Find your own validation story: a correction you keep making in review. Write it as one checkable line and add it to the PR template as a reviewer prompt.
- [ ] Check unfamiliar names against their definitions and sources. Add a read-before-cite rule if it corrects an observed problem, and name an owner for instruction maintenance.
- [ ] In your next long session, watch for drift. Preserve the state needed for a handoff, then recover, compact or restart as appropriate; commit according to repository practice.
Go deeper
- Templates: Appendix B.2, the AGENTS.md skeleton (it carries the precedence line); B.7, context hygiene on one page; B.11, bootstrapping the file on a repository.
- Deep dive: Appendix D, Chapter 6 - the context-files study, the rule-count cliff, instruction counts, mistake-journal mechanics, the compaction and cache measurements, and HumanLayer's context warnings.
- Sources: Appendix C.