Monorepo Nested CLAUDE.md Precedence — How Root vs Package Rules Merge Without Duplication
Symptom: Package-specific rules in apps/web/CLAUDE.md contradict root CLAUDE.md or bloat total injected context.
Claude Code loads root CLAUDE.md eagerly at session start and loads nested subdirectory CLAUDE.md files lazily when it reads or edits files inside those subdirectories. Keep root CLAUDE.md strictly workspace-wide (package manager, workspace filter syntax, repo map, global security) and place stack-specific rules inside apps/*/CLAUDE.md without repeating root instructions.
Broken vs. Fixed Configuration
# apps/web/CLAUDE.md (... copied 140 lines from root CLAUDE.md ...) Run npm test from repo root to verify changes. # conflicts with root pnpm --filter!
# Root CLAUDE.md - Workspace tests: pnpm --filter <pkg> test - Packages: apps/web (Next.js UI), apps/api (Fastify), packages/db (Prisma) # apps/web/CLAUDE.md (additive only — 35 lines) - Fast UI test: pnpm --filter web vitest run src/components/Cart.test.tsx - Don't import packages/db directly in client components. Instead fetch via src/lib/api.ts.
Why This Happens
Monorepo teams copy the entire root CLAUDE.md into every package folder and tweak two lines, causing 2x–4x token duplication plus contradictory test commands when Claude touches multiple packages in one PR.
Step-by-Step Fix
- 01Put workspace-wide commands and routing map in root CLAUDE.md
Show exact filtered commands (e.g. pnpm --filter @acme/web test) and list each package's purpose in 1 line.
- 02Keep nested package CLAUDE.md files purely additive (30–80 lines)
Only document package-local build quirks, fixtures, and domain invariants — never copy root rules.
- 03Add directory indexes for large monorepos (Rule F4)
Point agents to package entrypoints so they locate tests and schemas on the first grep.
Automated AgentLint Checks That Catch This
Frequently Asked Questions
When does Claude Code load a nested apps/api/CLAUDE.md file?
Nested CLAUDE.md files are loaded lazily once Claude reads or modifies files under that directory — or immediately if you launch Claude Code from inside apps/api/.
Does the same hierarchy work for AGENTS.md in Codex CLI?
Yes. Codex CLI walks from the Git root down to the current working directory and merges AGENTS.md files along the path, with deeper files taking more specific precedence.