Skip to content

CLAUDE.md and Agent-File Patterns ​

Verified on 2026-10-04 with Claude Code 2.1.289.

Book 1's CLAUDE.md and AGENTS.md covers the mechanics: where the files live, how they load, how AGENTS.md is picked up. This chapter is for the person who maintains those files for a team or across many repositories. It covers what the research says instruction files actually do, which rules change behavior, how to share one file between Claude Code and other agents, and how to audit the files before they rot.

The core principle from the first edition still holds: an instruction file is loaded into every session and paid for on every request, so more is not better. What changed in 2026 is that we now have measurements showing how little a typical file buys.

What the evidence says ​

  • Context files rarely raise success, and they always raise cost. Gloaguen and colleagues at ETH Zurich ("Evaluating AGENTS.md", February 2026) tested coding agents on SWE-bench tasks with LLM-generated context files and on real issues from repositories with developer-written ones. Providing context files "does not generally improve task success rates, while increasing inference cost by over 20% on average." Agents did follow the instructions. The repository overviews that many guides recommend were not helpful. The authors conclude that context files are useful "for specifying non-standard coding practices."
  • The same result with Claude Code and Codex. Prakhar Khatri's July 2026 ablation (288 evaluated runs, 17 real tasks, both agents) found that context strategy "does not measurably move correctness on either agent." The failures were about implementation skill (feature design, pattern selection, exact wiring), not missing repository knowledge that a context file could supply.
  • The docs agree on mechanics. CLAUDE.md content is delivered as a user message after the system prompt, and Claude treats it "as context, not enforced configuration." The docs recommend under 200 lines per file, because "longer files consume more context and reduce adherence."
  • Practitioners have converged too. Addy Osmani's August 2026 "Audit your Agent files" takes away this: "keep repository context files focused on things the model can't easily infer from the code: how to run the right checks, which operations are expensive, what must remain untouched, and where the unusual project conventions live."

The conclusion: an agent file is not a performance booster. It is a short list of facts the agent cannot infer and conventions where your project differs from the default. Everything else is cost. Treat any claim that a longer file helps as a hypothesis, and test it with the with-and-without method in Harness Engineering.

What belongs in the file ​

The test for every line, from the official best-practices guide: "Would removing this cause Claude to make mistakes?" If not, cut it.

KeepCut
Commands Claude cannot guess (pnpm, not npm; how to run one test)Anything Claude can learn by reading the code
The check to run before saying "done"Directory trees, dependency lists, architecture overviews
Conventions that differ from common defaultsStandard language conventions
What must not be touched, and whyDetailed docs for public libraries (link instead)
Operations that are slow, expensive or dangerousAnything that changes often
Environment quirks (required services, env vars)Self-evident advice ("write clean code")
Repository etiquette: branch names, commit formatLong explanations and tutorials

Here is a project file that passes the test. The project is fictional:

markdown
# Invoice service

## Commands
- Install with `pnpm install` (the lockfile is pnpm; npm breaks it)
- One test file: `pnpm vitest run path/to/file.test.ts`
- Before you say you are done: `pnpm check` (types, lint, unit tests)
- Tests need the dev database: `docker compose up db -d`

## Conventions that differ from defaults
- Money is integer cents (`amountCents`), never floating point
- Dates cross the API as UTC ISO strings; convert only in the UI
- Every new endpoint gets an integration test in `tests/api/`

## Do not touch
- Existing files in `db/migrations/`: add a new migration instead
- `src/gen/`: generated by `pnpm codegen`

## Slow or risky
- `pnpm test:e2e` takes a long time; run it only when asked
- Never run `pnpm db:reset` against anything but the local database

<!-- Maintainers: keep this under 60 lines. Architecture notes live in docs/architecture.md, not here. -->

Block-level HTML comments like the last line are stripped before the file reaches Claude, so you can leave notes for human maintainers at no token cost.

The first edition offered four long templates (web app, API, Python library, monorepo) with architecture sections. Given the evidence above, drop the architecture sections and keep the commands, the non-default conventions and the "do not touch" list. A monorepo gets a short root file plus nested files and path-scoped rules, described next.

Rules that actually change behavior ​

Make the rule checkable ​

The docs' examples are the right shape: "Use 2-space indentation" instead of "Format code properly"; "Run npm test before committing" instead of "Test your changes"; "API handlers live in src/api/handlers/" instead of "Keep files organized." If you cannot tell from the output whether a rule was followed, Claude cannot either.

Load it only where it applies ​

A rule that matters for one part of the codebase should not be in every session. Put it in .claude/rules/ with a paths field, and it loads only when Claude reads or edits a matching file:

markdown
---
paths:
  - "src/api/**/*.ts"
---

# API rules
- Validate every request body with the schemas in `src/api/schemas/`
- Errors use the `ApiError` shape in `src/api/errors.ts`

paths is the only frontmatter field Claude Code reads from a rule file. Rules without it load at launch like .claude/CLAUDE.md. Multi-step procedures belong in a skill, which loads only when invoked or relevant. A subdirectory's own CLAUDE.md loads when Claude reads files in that directory.

Enforce what must always happen ​

Instructions are advisory. If a rule must hold every time, make it a hook or a permission rule and keep at most a one-line reminder in the file. The memory docs give this split for organizations, and it works for any team:

ConcernWhere it goes
Block specific tools, commands or file pathspermissions.deny in settings
Something that must run at a fixed point (after each edit, before stopping)A hook
Code style, quality guidelines, behavioral guidanceCLAUDE.md or rules

Verification and Evals at Scale shows a Stop hook that replaces "always run the tests before you finish."

Do not fight the built-ins ​

Claude Code adds its own guidance for some tasks. If your file sets commit or pull request rules, the docs suggest turning off the built-in ones with the includeGitInstructions setting and setting attribution text with the attribution setting, so two sets of instructions do not compete.

Remove conflicts ​

All discovered files are concatenated, not merged: content is ordered from the filesystem root down to your working directory, and CLAUDE.local.md comes after CLAUDE.md at each level. Nothing overrides anything. "If two instructions contradict each other, Claude may pick one arbitrarily." The same goes for a user rule in ~/.claude/rules/ against a project rule. Write nested files as additions, never as exceptions to a parent.

Use emphasis once ​

The best-practices guide: "If Claude keeps skipping one instruction, add emphasis such as 'IMPORTANT' to that line alone. If you emphasize many lines, none of them stands out." If you still need emphasis after that, the file is too long or the rule should be a hook.

Put review rules where reviewers read them ​

The managed Code Review service for GitHub reads CLAUDE.md (and flags new violations as nits) plus a REVIEW.md used only for reviews. Rules like "new API routes must have an integration test" land more reliably in REVIEW.md than in a long CLAUDE.md, because every review agent receives it directly. Code Review also flags when a PR makes a CLAUDE.md statement outdated, which keeps the file honest.

Check that it worked ​

Start a fresh session, give Claude a task that exercises the rule (for the file above: "add an endpoint that returns an invoice total"), and look at the result. The rule works if the output follows it without you mentioning it. For a stronger test, run the same task with and without the rule using the script in Harness Engineering. If behavior does not change, delete the rule.

AGENTS.md interop ​

AGENTS.md is an open format for agent instructions, now stewarded by the Agentic AI Foundation under the Linux Foundation. Its site lists more than 20 tools that read it, including OpenAI Codex, Cursor, GitHub Copilot, VS Code, Jules, Devin, Zed and Warp. Since version 2.1.277, Claude Code reads it too.

What Claude Code reads by default ​

Your repository hasClaude reads
An AGENTS.md and no CLAUDE.md or CLAUDE.local.md in the working directory or above itYour AGENTS.md
An AGENTS.md and a CLAUDE.md or CLAUDE.local.md in the working directory or above itYour CLAUDE.md files only
A CLAUDE.md that imports @AGENTS.mdYour CLAUDE.md, with AGENTS.md included through the import

Two details catch teams out. Your ~/.claude/CLAUDE.md, a managed CLAUDE.md and .claude/rules/ files do not count for this check and still load alongside AGENTS.md. But a CLAUDE.local.md does count, so a developer who adds one for personal notes silently stops Claude from reading the shared AGENTS.md. Claude Code also never reads AGENTS.local.md, AGENTS.override.md, or anything under .agents/.

To change the default, open /config and set Project instructions to claude-md-or-agents-md (the default), claude-md-and-agents-md, claude-md or managed-only. The same value can live in user or managed settings (project and local settings files ignore it):

json
{
  "pluginConfigs": {
    "agents-md@builtin": {
      "options": { "instructionFiles": "claude-md-and-agents-md" }
    }
  }
}

Three ways to share one file ​

Pattern A: AGENTS.md only. No CLAUDE.md anywhere on the path. Simplest, and every AGENTS.md-aware tool reads the same file. It requires version 2.1.277 or later, and before 2.1.281 some sessions (Amazon Bedrock, or telemetry turned off) did not read AGENTS.md at all. If anyone on the team runs older versions, use pattern B.

Pattern B: CLAUDE.md imports AGENTS.md. Works on every version and lets you add Claude-specific lines:

markdown
@AGENTS.md

## Claude Code
- Use plan mode for changes under `src/billing/`.

Claude reads the imported file first, then the rest. Keeping the import never makes Claude read AGENTS.md twice.

Pattern C: symlink. ln -s AGENTS.md CLAUDE.md works, with two costs: the Edit and Write tools refuse to write through a symlink, and Windows clones without core.symlinks get a one-line text file instead of your instructions. Prefer pattern B if anyone uses Windows.

If you set up a workaround before Claude Code read AGENTS.md natively, remove a SessionStart hook that prints AGENTS.md: it now adds a second copy to context. A CLAUDE.md that tells Claude in words to read AGENTS.md should become a real @AGENTS.md import, because otherwise Claude sees the file only if it decides to open it.

Differences between tools ​

The shared file is read differently by different agents, so write it for the strictest reader:

  • Nesting. The AGENTS.md site says "the closest AGENTS.md to the edited file wins." Codex's docs describe merging from the repository root down, with closer files overriding earlier guidance. Claude Code concatenates every file and lets none override another. A nested file that contradicts its parent therefore behaves differently in each tool. Write nested files as additions only.
  • Size. Codex stops adding instruction files once the combined size reaches project_doc_max_bytes, 32 KiB by default. Staying well under the 200-line target keeps you clear of that limit.
  • Overrides. Codex reads AGENTS.override.md; Claude Code does not. Do not put shared rules in an override file.
  • Codex reading CLAUDE.md. If your repository already standardized on CLAUDE.md, Codex can be pointed at it with project_doc_fallback_filenames in ~/.codex/config.toml.
  • Hooks. The InstructionsLoaded hook does not fire for an AGENTS.md that Claude reads directly through the Project instructions setting. It does fire for one imported from a CLAUDE.md.

Portability covers the rest of a multi-tool setup: skills, MCP servers and model routing.

Migrating from other tools ​

/init reads Cursor rules (.cursor/rules/, .cursorrules) and Copilot's .github/copilot-instructions.md into the CLAUDE.md it generates. /import codex, /import gemini or /import cursor (or claude import <source> --dry-run from the shell) brings another agent's instruction files, MCP servers, commands, subagents and skills into Claude Code. /import requires version 2.1.213 or later; Cursor import requires 2.1.265.

Check that it worked ​

Start a session and look at the first lines. When Claude reads AGENTS.md directly, an interactive session shows a line such as no CLAUDE.md found; AGENTS.md loaded: /path/to/repo/AGENTS.md. Then run /memory and check that the path is in the list. For pattern B, run /context and confirm CLAUDE.md appears under Memory files.

Auditing agent files ​

Instruction files decay. Commands get renamed, directories move, models change, and rules written to correct an old model's habits keep costing tokens long after the habit is gone. Audit when the model changes, after large refactors, and otherwise every few months.

1. See what actually loads ​

Run /context and read the Memory files list. Run /memory to see every location, including ones that do not exist yet. Claude Code warns at startup, and in /status, when an instruction file is over the recommended length or when files that are each fine add up past a combined limit.

Lazy loading (nested files, path-scoped rules) is harder to see. The InstructionsLoaded hook fires every time an instruction file loads and reports why. This entry in .claude/settings.local.json logs every load:

json
{
  "hooks": {
    "InstructionsLoaded": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "jq -c '{file_path, memory_type, load_reason}' >> \"$HOME/.claude/instructions-loaded.log\""
          }
        ]
      }
    ]
  }
}

load_reason is one of session_start, nested_traversal, path_glob_match, include or compact. After a day of normal work, a rule file that never appears in the log is either scoped wrong or not needed.

2. Run the prompt audit ​

text
/doctor prompt-audit

Requires version 2.1.283 or later. Claude checks your CLAUDE.md, CLAUDE.local.md and AGENTS.md files plus rules, skills, commands, subagents and output styles under .claude/ and ~/.claude/. It looks for instructions written for older models, references to files or commands that do not exist, and files that contradict each other. You get findings with proposed edits, and nothing changes until you ask. Pass a path to audit one file or directory, for example /doctor prompt-audit .claude/rules. The audit runs through the bundled /claude-api skill, so it is unavailable if that skill is turned off.

3. Run the checkup ​

Plain /doctor (alias /checkup) includes instruction-file work: it removes duplication between local and checked-in CLAUDE.md files, trims checked-in files by cutting what Claude can derive from the codebase (directory layouts, dependency lists, architecture overviews) while keeping pitfalls, rationale and non-default conventions, and moves the remaining always-loaded guidance into skills and nested files that load on demand. It reports first and asks before changing anything.

4. Test removals ​

Tools can tell you what is stale. Only a test tells you what is useless. For each rule you are unsure about, remove it on a branch and run a task that should exercise it, in a fresh session. Osmani suggests the same with skills: disable them and try the task with the plain model. If nothing changes, the rule goes.

5. Keep personal and shared apart ​

Personal preferences go in ~/.claude/CLAUDE.md or a gitignored CLAUDE.local.md, not in the shared file. In a monorepo where other teams' files get picked up, a claudeMdExcludes list in .claude/settings.local.json skips them on your machine. Organization-wide rules belong in a managed CLAUDE.md (or the claudeMd key in managed settings), which individuals cannot exclude.

Treat the file like code ​

The first edition's team advice still applies: keep the file in version control, change it through pull requests, and review changes the way you review code, because a bad line affects every session on the team. Add a rule when Claude makes the same mistake twice or when review catches something Claude should have known. Remove one when an audit or a test shows it does nothing.

Check that it worked ​

After an audit, compare three things with the numbers from before: the line count of each instruction file, the /context total at session start, and the result of one representative task. The audit worked if the first two went down and the third did not get worse.

Key takeaways ​

  • Studies in 2026 found context files rarely improve success and raise cost by about a fifth. Keep only what the agent cannot infer.
  • Good rules are checkable, scoped to where they apply, and backed by a hook or permission rule when they must always hold.
  • Claude Code concatenates instruction files; other tools let the closest file win. Write nested files as additions, never exceptions.
  • Share one file across tools with AGENTS.md alone, or with @AGENTS.md imported from CLAUDE.md. Watch for CLAUDE.local.md, which turns off the AGENTS.md fallback.
  • Audit with /context, the InstructionsLoaded hook, /doctor prompt-audit and /doctor, then test removals.

Sources ​

Released under CC BY-SA 4.0.