Claude and Claude Code 2027Section 4 · lesson 1 of 4
1234section 4 lessons
Section 4. Context and Memory — CLAUDE.md, Session Hygiene, and Your Second Brain

Designing and Auditing CLAUDE.md and AGENTS.md — What Empowers an Agent and What Slows It Down

≈ 12 minNeuroBober

A stubborn myth persists in AI-assisted engineering: the more exhaustively you write out CLAUDE.md—eight hundred or a thousand lines peppered with all-caps IMPORTANT warnings and exclamation marks—the more disciplined your agent will be. In practice, the exact opposite happens. Bloated project instructions turn into noise, the model starts skipping half your requirements, gets tripped up by outdated workarounds, and burns its attention budget reading policy prose instead of analyzing code.

This lesson tackles the problem systematically. You will learn how CLAUDE.md and the cross-agent AGENTS.md standard are actually delivered under the hood, audit your instructions against the 200-line rule, and build a clean, modular instruction architecture that doesn't waste context.

Non-Deterministic Context: What CLAUDE.md Can Do—and What You Should Never Expect From It

The single biggest mistake when designing instructions is confusing roles: developers expect CLAUDE.md to behave like a compiler or a security policy engine. In reality, all memory files (CLAUDE.md, CLAUDE.local.md, AGENTS.md) are passed to the model as an ordinary user message right after the system prompt. They are non-deterministic context—a set of textual guidelines that the model weighs statistically, not a hard programmatic lock.

When you put a critical prohibition like "Never edit migrations manually" or "Always run the linter" into that file, the agent will obey nine times out of ten—and forget on the tenth under the weight of a long conversation. Shouting in all caps or adding IMPORTANT tags won't save you: in its current Best Practices guide, Anthropic explicitly marks that tactic as obsolete and counterproductive. Modern reasoning models treat aggressive emphasis as a cue to over-apply a rule rigidly, even when doing so actively hurts the task.

If breaking a rule is unacceptable under any circumstances—such as reading .env or modifying production config directories—textual pleading in CLAUDE.md is the wrong tool. File read and write restrictions belong in permissions.deny (for example, Read(./.env)) inside settings.json, while mandatory linter runs or dangerous-command blocks belong in deterministic lifecycle hooks (PreToolUse and Stop), which we will cover in detail in Section 5. Keep CLAUDE.md strictly for guidance that shapes the agent's engineering judgment and doesn't require OS-level enforcement.

Instruction Loading Hierarchy and the Cross-Agent AGENTS.md Standard

To keep rules from different scopes from bleeding into one big soup, Claude Code loads instructions along a strict hierarchy from the organization level down to individual subdirectories. At the top sits company-managed policy: the system file (/Library/Application Support/ClaudeCode/CLAUDE.md on macOS, /etc/claude-code/CLAUDE.md on Linux and WSL, C:\Program Files\ClaudeCode\CLAUDE.md on Windows) or the claudeMd field inside managed-settings.json. Next comes your personal user file ~/.claude/CLAUDE.md with your individual workflow preferences, followed by project layers: root ./CLAUDE.md or ./.claude/CLAUDE.md, and your personal, git-ignored ./CLAUDE.local.md.

All upper-level files found are merged at session startup, whereas CLAUDE.md files inside nested repository subdirectories use lazy loading. They don't consume memory from second zero; instead, they are pulled in only when the agent first reads, creates, or edits a file inside that directory. You can find the exact resolution order in the Claude Code memory documentation.

Loading hierarchy for CLAUDE.md and AGENTS.md and anatomy of an ideal sub-200-line file: @path/to/file imports, .claude/rules/, stripped HTML comments, and offloading prohibitions to hooks and permissions.deny.

When a team uses multiple tools in the same repository—say Claude Code, Codex, Cursor, Gemini CLI, Jules, Windsurf, or GitHub Copilot—maintaining a separate instruction file per agent quickly becomes unmanageable. The industry converged on the open AGENTS.md standard, now adopted across more than 60,000 open-source repositories. Starting with v2.1.277, Claude Code supports AGENTS.md natively via a built-in plugin, no custom workarounds required.

Pay close attention to the exact precedence logic so files don't clash or double-load. By default, Claude Code runs in claude-md-or-agents-md mode: it reads AGENTS.md or .claude/AGENTS.md only if there is no CLAUDE.md, .claude/CLAUDE.md, or even a personal CLAUDE.local.md in the working directory or any parent directory. Create a local CLAUDE.local.md and AGENTS.md silently stops loading—unless you explicitly switch the Project instructions setting in /config (or via pluginConfigs["cc-plugin-agents-md@builtin"].options.instructionFiles) to claude-md-and-agents-md.

Beyond loading mode, native AGENTS.md support has three structural quirks that often catch teams off guard during migration:

  1. Exclusions and hooks. When AGENTS.md loads through the built-in plugin, InstructionsLoaded hooks do not fire, and the file is not loaded from extra directories passed via --add-dir (even with CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1 enabled).
  2. Unsupported filename variants. Claude Code does not read AGENTS.local.md, AGENTS.override.md, or a hidden .agents/ directory—only root AGENTS.md and .claude/AGENTS.md are supported.
  3. Retiring old workarounds. If your team previously used a SessionStart hook to print AGENTS.md to stdout, remove that hook after upgrading to v2.1.277 or newer, otherwise the file gets injected into context twice. By contrast, a direct @AGENTS.md import inside CLAUDE.md is completely safe and will not duplicate the file.

The 200-Line Rule: Why Deleting 80% of Your Rules Boosts Model Accuracy

Instructions rot faster than the code itself. Over six months on a live project, "prompt debt" piles up: developers append step-by-step reasoning hints, prescribe which to pick, and add dozens of crutches for limitations of older-generation models. When stronger reasoning models like Opus 5.5 or Sonnet 5.5 arrive, those legacy guardrails constrict their internal planning loop and introduce rule conflicts.

At a Y Combinator talk, Claude Code creator Boris Cherny formulated a radical hygiene principle: every few months, run an ablation—temporarily strip away your instruction layer, watch how the new model handles typical tasks unassisted, and restore only the lines without which it genuinely makes mistakes. When Anthropic's own team adapted its system prompt for Opus 5, they cut instruction volume by roughly 80%, and task accuracy climbed noticeably.

In practice, wiping out your entire CLAUDE.md in a commercial repository is rarely practical—a full ablation on a live codebase burns huge token budgets on repeated test runs. A revealing experiment on the complex open-source Archon repository pinpointed exactly where the boundary of usefulness lies. When CLAUDE.md and custom skills were completely removed from the project, the model's architectural decisions didn't degrade—they actually became more flexible, with the agent finding cleaner refactoring paths on its own. What broke immediately were local team conventions: variable naming, commit formats, folder placement, and calls to internal API wrappers.

That experiment yields a strict selection rule: keep every CLAUDE.md file under 200 lines (anything larger than 4 MiB is silently skipped altogether). Keep only what the agent cannot infer from the codebase and package.json: exact build commands, non-standard test invocations, tricky legacy modules, branching rules, and non-obvious recurring fixes. Directory trees, dependency lists, and lectures on "clean code" can be deleted without regret—the model reads the file tree itself.

Rule categoryWhere it belongsWhy
Build, test, lint commands, and obscure CLI flagsRoot CLAUDE.mdThe agent can't guess a non-standard pipeline and will get flags wrong every time
Non-obvious legacy quirks and team commit conventionsRoot CLAUDE.md or AGENTS.mdTeam conventions cannot be derived from language syntax
Instructions for a specific service, API route, or frontend moduleSubdirectory CLAUDE.md or .claude/rules/*.mdLoaded lazily only when editing matching files, keeping other tasks clean
Long specs, and Separate .md files via @path/to/file or skillsKeeps the main file scannable and groups reference docs cleanly
Bans on reading secrets (.env), , and build artifactspermissions.deny in settings.jsonHard enforcement with zero model attention cost and zero leak risk
Mandatory runs, test gates, or dangerous-command blocksPreToolUse and PostToolUse hooksDeterministic exit code control the model cannot ignore
Verbose "think first" pep talks and folder-tree summariesDelete during auditReasoning models do this natively, and extra lines dilute accuracy

Rather than pruning by guesswork, use Claude Code's built-in diagnostics. Run these checks whenever you audit an existing project:

  1. Run /init in a fresh project—or with CLAUDE_CODE_NEW_INIT=1 so the agent automatically migrates existing rules from .cursor/rules/, .github/copilot-instructions.md, AGENTS.md, .devin/rules/, .windsurf/rules/, and .clinerules.
  2. Once you have commit history, run /doctor—it analyzes your CLAUDE.md against Git and flags redundant directory overviews and dependency lists for removal.
  3. On v2.1.283+, run the dedicated /doctor prompt-audit check (optionally passing a path). It inspects CLAUDE.md, CLAUDE.local.md, AGENTS.md, rule files, skills, and subagents for obsolete model-specific workarounds, broken references, and internal contradictions.
  4. Inspect the actual list of loaded memory files with /context all and /memory to verify no duplicates or forgotten local notes are sneaking into the session.

Clean File Architecture: HTML Comments and @path/to/file Imports

Even a lean CLAUDE.md breaks down in a large monorepo when frontend, billing, and mobile teams all start appending their own rules to the root. Conflicting requirements creep in, and the combined size of on-demand subdirectory rules hits hard truncation ceilings: 40,000 characters on a 200K window, 200,000 characters on generation 4.6 models with a 1M window, and 150,000 characters on current 1M-window models.

To keep the root file under two hundred lines without paying a context tax for other teams' modules, the large codebases guide recommends four engineering patterns:

  • @path/to/file imports. Split long specs into separate files and pull them into CLAUDE.md using @docs/architecture.md (spaces in paths are escaped with a backslash: @Design\ Docs/api.md; quotes don't work, and backticked `@README` stays literal text). Imports resolve recursively up to 4 hops deep. One key caveat: imports organize files for humans, but they do not save tokens—the imported content is expanded straight into context alongside the parent file.
  • Path-scoped modular rules (.claude/rules/*.md). If a rule applies only to APIs or tests, move it into .claude/rules/ and add the only supported field paths:—for example, paths: ["src/api/**/*.ts"] (brace expansion supports up to 1,000 patterns and 4 MiB per file). That file loads only when the agent opens or edits a matching file via built-in tools or Bash commands like cat and head.
  • claudeMdExcludes and noise blocking. In a monorepo, a service engineer can hide unrelated teams' instructions in .claude/settings.local.json using an array of absolute claudeMdExcludes: ["**/packages/web/**"] (note that this exclusion does not override enterprise managed files). Generated and vendored code should be blocked via Read(...) rules in permissions.deny so the agent never wastes time reading compiled , paired with for code intelligence instead of blind .
  • Block HTML comments for . Whenever you need to leave context inside CLAUDE.md for teammates ("why we added this ban after the DB incident" or an internal ticket link), wrap it in <!-- ... -->.
HTML Comments Cost Zero Tokens

Before injecting CLAUDE.md into the model's context window, Claude Code automatically strips all block HTML comments (<!-- ... -->). You can freely document change history and rule rationale for humans right inside the file—the agent never sees that noise and spends zero tokens on it. Still, check comments inside imported nested code blocks or unclosed tags via /memory during an audit.

Here is what a clean, concise CLAUDE.md looks like in practice for a TypeScript service, combining @ imports for shared specs with stripped HTML comments for maintainer notes. Use this template as a baseline before rewriting your own:

<!-- Audited 2027-02-10: moved style rules to PostToolUse hook and secrets to settings.json -->
# Billing Service (TypeScript / Node.js 22)

## Verification Commands
- Build & typecheck: `pnpm --filter billing typecheck && pnpm --filter billing build`
- Integration tests (requires local test Postgres on port 5433): `pnpm --filter billing test:int`

## Engineering Constraints
- Use only the `src/lib/db-client.ts` wrapper; direct `pg.Pool` calls are forbidden.
- Create files in `src/migrations/` exclusively via the migration generator; never hand-edit applied revisions.
- Update the OpenAPI schema in `specs/billing.yaml` whenever public endpoints change.

## Modular References
@docs/billing-webhooks.md

Notice the economy of this template: the entire file is under twenty lines, has zero occurrences of IMPORTANT, no obvious folder-tree walkthrough, and no "write clean code" lectures. The top HTML comment records the audit date for the team and is stripped before reaching the model. Run commands specify the exact monorepo filter and non-standard test database port, while the full webhook spec lives in @docs/billing-webhooks.md so the main rulebook stays lean.

To lock this in on your own repository right now, open a terminal at the project root and run a quick check: type /context all and /memory to see which instruction files actually made it into memory, then run /doctor prompt-audit (on Claude Code v2.1.283+) to surface immediate removal candidates. If your root CLAUDE.md exceeds 200 lines, cut everything the agent can read from the code itself and move hard file-read bans into permissions.deny.

Apply Right Now

  • Run /context all and /memory in your active repository to inspect every loaded instruction file and confirm AGENTS.md isn't double-loading alongside a legacy SessionStart hook.
  • Run /doctor prompt-audit (or /doctor), collect outdated workarounds written for older models, and trim your root CLAUDE.md or AGENTS.md under the 200-line ceiling.
  • Move directory-specific rules into .claude/rules/*.md with paths: YAML frontmatter, and shift read bans for generated code and .env into permissions.deny.
  • Document the rationale behind non-obvious rules inside <!-- ... --> block HTML comments so teammates retain context without spending tokens.