Source: raw/The_CLAUDE.md_file.md — Anthropic-published YouTube primer (https://www.youtube.com/watch?v=O0FGCxkHM-U, fetched 2026-05-20); extended 2026-07-16 with ai-research/claude-blog-using-claude-md-files.md — Anthropic first-party blog post “Using CLAUDE.md files: Customizing Claude Code for your codebase” (claude.com/blog/using-claude-md-files, published November 25, 2025 — the publish date predates this wiki’s ingest of it, surfaced via a 2026-07-16 watchlist sweep; Steering Claude Code had already flagged it as a linked-but-unfetched companion post).
The canonical Anthropic-side primer on the CLAUDE.md file — what it is, where it lives, how it loads, and the practice patterns to keep it useful instead of bloated. Originally a short-form YouTube explainer framing CLAUDE.md as “an onboarding script for your code base”; this article now also folds in Anthropic’s longer written guide to the same file, which adds a worked example, a deeper /init workflow, and three additional practices (custom slash commands, subagent isolation, and context hygiene) the video didn’t cover.
Key Takeaways
- Definition.
CLAUDE.mdis a markdown file that Claude Code reads automatically at every session start; its contents become part of Claude’s system prompt. Without it, Claude has to re-explore the codebase every session and may guess wrong about stack, conventions, or commands. /initscaffolds one — and can refine an existing one too. Run it on a fresh project to generate a starter file by inspecting package files, docs, configs, and code structure. Run it again on a project that already has aCLAUDE.mdand “Claude will review the current file and suggest improvements based on what it learns from exploring your codebase.” Treat the output as a starting point, not a finished product.- Three-level hierarchy of memory files: project-level (
<repo>/CLAUDE.md, shared via version control, written for the team), user-level (~/.claude/CLAUDE.md, personal preferences that travel across every project on your machine), and directory-level (<subdir>/CLAUDE.md, local scope tied to a specific subdirectory) — the blog adds the monorepo framing of parent-directory files providing shared context above multiple sub-projects. @<path>reference syntax loads another doc on demand (Coding standards are in @./standards/coding-style.md) instead of inlining it — the video’s specific syntax for the blog’s broader “break information into separate markdown files and reference them” advice.- Two starting philosophies that reconcile, not contradict. The video: “start without a CLAUDE.md initially so you can see where you actually need to course-correct.” The blog: run
/initimmediately, then trim. Both converge on the same end state — the blog’s own closing section says “start simple, expand deliberately” and “resist the urge” to front-load a comprehensive file. They differ only on whether the very first draft is empty or/init-generated; neither recommends shipping a large speculative file. - The
#key adds instructions on the fly. Mid-session, typing#followed by an instruction you find yourself repeating saves it intoCLAUDE.mddirectly — the concrete mechanism behind the video’s “course-correct, then save” principle. - Never put secrets in it.
CLAUDE.mdbecomes part of the system prompt and is typically committed to version control — no API keys, credentials, connection strings, or vulnerability detail belongs in it. Treat it as documentation that could be shared publicly.
A Worked Example
The blog’s full sample CLAUDE.md for a FastAPI project — useful as a structural template:
# Project Context
When working with this codebase, prioritize readability over cleverness. Ask clarifying questions before making architectural changes.
## About This Project
FastAPI REST API for user authentication and profiles. Uses SQLAlchemy for database operations and Pydantic for validation.
## Key Directories
- `app/models/` - database models
- `app/api/` - route handlers
- `app/core/` - configuration and utilities
## Standards
- Type hints required on all functions
- pytest for testing (fixtures in `tests/conftest.py`)
- PEP 8 with 100 character lines
## Common Commands
```bash
uvicorn app.main:app --reload # dev server
pytest tests/ -v # run tests
```
## Notes
All routes use `/api/v1` prefix. JWT tokens expire after 24 hours.No required format — the recommendation is to keep it concise and human-readable, “documentation that both humans and Claude need to understand quickly.” Each addition should solve a real problem already encountered, not a theoretical one.
How to Structure a CLAUDE.md
Three sub-patterns from the blog’s structuring guide:
-
Give Claude a map. A project summary plus a high-level directory tree (even a simple
tree-style output) gives Claude immediate orientation. Document main dependencies, architectural patterns (domain-driven design, microservices, specific frameworks), and non-standard organizational choices — Claude uses this to decide where to look and where to change things. -
Connect Claude to your tools. Document custom deployment/testing/codegen scripts with usage examples — tool names, basic patterns, when to invoke them, and whether a
--helpflag exists. Claude Code is also an MCP client: configure servers through project settings, global configuration, or a checked-in.mcp.json, and use--mcp-debugto troubleshoot when tools don’t appear. Document usage constraints for each MCP server, not just its existence — the post’s worked example:### Slack MCP - Posts to #dev-notifications channel only - Use for deployment notifications and build failures - Do not use for individual PR updates (those go through GitHub webhooks) - Rate limited to 10 messages per hour -
Define standard workflows. Claude jumping straight into code changes without planning causes rework — a missed requirement, the wrong architectural approach, a change that breaks something else. A workflow instruction should force four questions before edits start: (1) is this a question about current state requiring investigation first? (2) does it need a plan before implementation? (3) what information is missing? (4) how will effectiveness be tested? Concrete patterns: explore-plan-code-commit for features, test-driven development for algorithmic work, visual iteration for UI changes. Document testing requirements, commit message format, and approval steps so Claude matches your team’s actual process instead of guessing.
Three Additional Techniques
- Keep context fresh with
/clear. Long sessions accumulate irrelevant file contents, stale command output, and tangential conversation that drags down signal-to-noise. Run/clearbetween distinct tasks (e.g., after finishing an authentication debug session, before starting a new API endpoint) — it resets the conversation while preservingCLAUDE.md. - Use a subagent for a distinct phase, specifically for isolation. The post’s example: after implementing a payment processor, tell Claude to “use a sub-agent to perform a security review of that code” rather than continuing in the same conversation — otherwise the implementation context colors the review, causing it to overlook issues or over-focus on already-resolved ones. This is the same isolation rationale Steering Claude Code gives for reaching for a subagent over a skill.
- Create custom slash commands for repeated prompts. Markdown files in
.claude/commands/become/command-namein every conversation, with$ARGUMENTSor numbered$1/$2placeholders for passing files or parameters. You don’t have to hand-write the file — ask Claude directly (“Create a custom slash command called /performance-optimization that analyzes code for database query issues…”) and it writes the markdown to.claude/commands/performance-optimization.mditself.
Update (2026-07-29): Two additions on keeping the file lean. (1) Config self-audit — a community report (per
raw/reddit-1v98lgu.md, inspired by Boris Cherny’s YC talk) asked Claude to audit the project CLAUDE.md and its skills for unnecessary instructions: the audit cut a 90-line file to ~50, flagged two skills as “honestly unnecessary,” and the same copy-pasted prompt then reportedly finished in about a minute where the pre-audit setup had floundered — the poster’s read being that Opus 5 needs less direction, so guardrails that once helped may now be introducing problems (unverified, single user). (2) Cherny’s own reusable-verbatim one-liner for persistent behavior shaping (perraw/x-account-bcherny-2080731329990377755.md):echo "Avoid code comments unless you are explicitly asked to add comments" >> CLAUDE.md.
Why this matters
“The difference between a frustrating Claude Code session and a productive one comes down to the context, and the CLAUDE.md file is how you provide that context.”
Anthropic’s framing positions CLAUDE.md as the highest-ROI single artifact in a Claude Code setup. The hierarchy means you don’t have to choose between team-shared and personal — you can have both layered together.
How this complements existing wiki coverage
- The wiki’s Memory Architectures Compared article covers the advanced memory systems (automemory, memarch, Hermes three-file pattern) that extend
CLAUDE.md. This article covers the primer-layer Anthropic positioning the advanced systems sit on top of. - Steering Claude Code gives the broader seven-way decision framework (
CLAUDE.mdvs rules vs skills vs subagents vs hooks vs output styles vs system-prompt appending) and the “keep it under 200 lines, give it an owner, review changes like code” cap this primer lacked on its own — this article is the deep-dive specifically on theCLAUDE.mdfile itself, underneath that broader framework. - The Architect Certification Technical Reference includes the hierarchy in its certification-prep material; this article gives the canonical Anthropic-side framing the certification expects.
A rule worth adding: prefer Edit over scripted string replacement (2026-08-05 addition)
[Reddit signal — r/ClaudeCode 2026-08-04, score 27/15 comments — community report] Source: raw/reddit-1vfroof.md.
A user annoyed that Claude Code kept reaching for Python scripts to edit files asked it why, and got a self-diagnosis worth encoding as a CLAUDE.md rule:
Python’s
str.replace()fails silently on no-match.Editfails loudly.
The model’s stated reason for the habit was “momentum, plus the convenience of batching several replacements into one call,” and it judged the trade bad — the poster reports it named four separate times in one session where a silent no-match cost real debugging time (three endSegment() call sites that never matched, caught only because a debug print showed every separator was null; a BLAME_JOIN that surfaced much later as no such column: ab.value).
This is the fail-loudly-over-fail-silently principle applied to tool choice, and it generalizes past Python: any batch-replacement approach (sed -i, perl -pe, a one-off script) trades a loud per-edit failure for a silent whole-batch one. The failure is expensive precisely because it is invisible at the point of failure and only surfaces as a confusing downstream symptom.
A one-line rule in CLAUDE.md covers it:
Prefer the Edit tool over scripted string replacement (python str.replace, sed -i).
Edit fails loudly on no-match; scripted replacement fails silently and the error
surfaces later as a confusing downstream symptom.Caveat: this is one model’s self-explanation of its own behaviour, which is exactly the class of claim the model-behaviour literature warns is post-hoc rationalization rather than an accurate account of cause. The stated mechanism is independently checkable and correct (str.replace genuinely is a no-op on no-match; Edit genuinely errors), so the rule stands on its own merits regardless of whether “momentum” was the real reason.
Try It
- Run
/initat the root of any project you use Claude Code on — including one that already has aCLAUDE.md, to get Claude’s own suggested improvements. - Trim it. Remove anything the model can infer trivially. Keep only load-bearing context: stack version pins, command shortcuts, non-obvious conventions.
- Add a user-level
CLAUDE.md(~/.claude/CLAUDE.md) for personal preferences that should apply to every project without polluting team-shared files. - Practice the course-correct loop.
When you correct a repeated mistake, press— superseded 2026-07-24: Anthropic now states “we used to encourage users to save things to Claude’s memory, by using the#and type the rule#hotkey to write to their CLAUDE.md automatically. Instead, Claude now automatically saves memories that are relevant to the work and to you.” Let auto-memory handle it, or say “save this to memory” explicitly. See The New Rules of Context Engineering for Claude 5 Models. - Use
@<path>to reference docs on demand instead of inlining them. - Document your MCP servers’ usage constraints, not just their presence — channel restrictions, rate limits, when-not-to-use notes (see the Slack MCP example above).
- Write a custom slash command for the prompt you find yourself retyping most often — ask Claude to create the
.claude/commands/*.mdfile directly. - Run
/clearbetween unrelated tasks to keep signal-to-noise high, and reach for a subagent when a phase (like a post-implementation security review) needs isolation from what came before. - Never write secrets into
CLAUDE.md— treat it like documentation that could be shared publicly.
Related
- Claude Code Memory Architectures Compared — built-in automemory vs memarch vs Hermes three-file pattern; sits on top of the
CLAUDE.mdprimer here. - Architect Certification Technical Reference — includes the three-level hierarchy and common exam trap (“instructions placed in user-level not project-level”).
- Claude Code Hooks —
InstructionsLoadedevent fires whenCLAUDE.mdloads; use it for context-injection workflows. - Claude Code Best Practices — broader Anthropic guidance on Claude Code workflow.
- Claude Code CLI Reference —
claude init/claude --initflags. - Karpathy Techniques for Claude Code — applies the
CLAUDE.mdprimitive to a notable real-world workflow. - Everything Claude Code (ECC) — Affaan Mustafa — community tooling that audits
CLAUDE.mdfor security and bloat. - Steering Claude Code: When to Use CLAUDE.md, Rules, Skills, Subagents, and Hooks — the broader first-party decision framework this primer sits underneath.
- The New Rules of Context Engineering for Claude 5 Models — the 2026-07-24 first-party update that supersedes the
#-hotkey practice here and reframes what belongs in CLAUDE.md vs skills vs references. - Claude Code Subagents — the deep-dive on subagent mechanics behind the “isolation for distinct phases” technique above.
Open Questions
- Resolved 2026-07-16 (first pass): Anthropic’s steering-Claude-Code post gives the first-party cap the memory-architecture comparison’s “~200 lines” figure lacked — “keep CLAUDE.md under 200 lines, give it an owner, and review changes to it like code.”
- Resolved 2026-07-16 (second pass): the blog post now folded into this primer — “Using CLAUDE.md files” (
claude.com/blog/using-claude-md-files, published Nov 25, 2025) — was the companion post Steering Claude Code flagged as “linked inline but not yet fetched.” Confirmed as a genuinely additive first-party source (worked example, MCP documentation pattern, custom slash commands,/cleardiscipline, secrets warning) rather than a duplicate of either existing article, so it was folded into this primer rather than spun into a separate one. - Order of precedence when project-level and user-level
CLAUDE.mdfiles contradict each other (e.g., project says 2-space indent, user says 4-space) — not stated in either source. - Whether custom slash commands (
.claude/commands/) and skills (.claude/skills/) are meant for different granularities of repeated task, or simply compete for the same use case — the blog introduces custom commands without reconciling them against skills; not resolved by this ingest either.