CLAUDE.md Writing Guide: How to Communicate Project Rules to AI Agents
When first introducing an AI coding agent, the first barrier you encounter is the question, "Why are you ignoring my rules?" Every session involves repeating the process of explaining the project structure, advising against using certain libraries, and reiterating test commands. To address this issue, Claude Code introduced a directive file called CLAUDE.md. Since other AI coding tools, such as Cursor's .cursorrules and GitHub Copilot's .github/copilot-instructions.md, also support similar formats, most of the principles discussed in this article apply regardless of the tool.
After reading this article, you can write your own CLAUDE.md and commit it to your team's Git repository to ensure the AI agent understands the project context from the moment it starts a session. Writing a CLAUDE.md correctly enables the AI agent to accurately understand 'implicit context' that is difficult to detect even when scanning the codebase, and ensures consistent adherence to the team's coding conventions and architectural decisions.
If you have not yet installed Claude Code, please refer to the Official Documentation first.
Key Concepts
What is CLAUDE.md
CLAUDE.md is a Markdown directive file that Claude Code automatically reads at the start of a project session. It serves as a "permanent project manual" that conveys context to the AI that is difficult to grasp by scanning the codebase, such as build commands, coding conventions, the background of architectural decisions, and workflow rules.
CLAUDE.md — A Markdown directive file that Claude Code automatically loads per session. It continuously conveys team rules and project context to the AI.
The same concept works in other agents as well. OpenAI Codex, Cursor, GitHub Copilot, and others support similar instruction files in AGENTS.md or their respective formats. In 2025, Sourcegraph, OpenAI, Google, Cursor, and Factory collaborated to submit AGENTS.md as an open standard to the Agentic AI Foundation under the Linux Foundation, and it has already been adopted by over 60,000 repositories on GitHub.
File Hierarchy
CLAUDE.md consists of three levels, and the three files are merged and applied.
| Location | Purpose | Whether Git is managed |
|---|---|---|
~/.claude/CLAUDE.md |
Private Global Directives (Common to all projects) | Private dotfiles |
{프로젝트 루트}/CLAUDE.md |
Team Shared Project Context | Tracking Recommended |
{하위 디렉터리}/CLAUDE.md |
Scope instructions by submodule/package | Trace recommended |
Claude loads the subdirectory CLAUDE.md on demand when reading that directory. This hierarchy works particularly robustly in a monorepo environment.
/init command that automatically generates drafts
Instead of creating an empty file from scratch, run the claude CLI from the project root and enter the /init command; Claude will analyze the codebase and automatically generate a draft of CLAUDE.md. Reviewing this draft and removing unnecessary content is the fastest way to get started.
Core Principle: Less is More
It is advisable to ask yourself, "Will the AI make a mistake without this?" for every instruction line. Writing down actions that the AI already performs correctly is noise. Unnecessary instructions dilute important rules. Additionally, since CLAUDE.md consumes tokens every session, the more verbose the file becomes, the less context window is available for actual work. In practice, it is often recommended to keep it 200 lines or less.
Good things to include:
- Build, Test, and Deploy commands
- Architecture decisions that AI is prone to getting wrong
- Forbidden libraries or patterns
- Project directory structure (especially monorepo)
- Git Workflow
Things to exclude:
- Code formatting rules (those that can be delegated to linters, such as ESLint, Prettier, ruff, etc.)
- Actions that AI already performs correctly
- Entire document file content (can be replaced with a path reference)
- Frequently changing temporary memo
Pros and Cons Analysis
Before looking at practical examples, if you familiarize yourself with the limitations and precautions of CLAUDE.md in advance, you will be able to read the examples more critically.
Advantages
| Item | Content |
|---|---|
| Contextual Persistence | No need to re-explain the project in every session |
| Team Consistency | Managed with Git ensures the entire team experiences the same AI behavior |
| Monorepo Granular Control | Different rules can be applied independently to each service using directory-specific files |
| Onboarding Acceleration | You can automatically generate drafts by analyzing the codebase with the /init command |
| Agent Compatibility | Parallel use of the AGENTS.md standard allows you to reuse the same rules across multiple AI tools |
Disadvantages and Precautions
| Item | Content | Response Plan |
|---|---|---|
| Instruction Ignore Phenomenon | If the file is long, the model effectively ignores the middle content | Keep it under 200 lines and place key rules at the beginning and end |
| Token Cost | CLAUDE.md consumes a session token every time | Removes verbose descriptions and replaces documentation with path references |
| Inefficient code style directives | It is wasteful to write rules for ESLint, Prettier, and ruff to handle in CLAUDE.md | Delegate to the linter configuration file and do not mention them in CLAUDE.md |
| Directive Conflicts | Conflicting rules between the root and child CLAUDE.md cause unpredictable behavior | Clearly separate the scope of responsibility for each level |
| MCP Overload | When MCP contexts exceed 20,000 tokens, the number of actually available contexts drops sharply | Minimize the number of MCP tools and connect only what is necessary |
MCP (Model Context Protocol) — This is the protocol Claude uses when interacting with external tools (file systems, databases, APIs, etc.). The more MCP tools there are, the higher the context consumption per session.
The Most Common Mistakes in Practice
- Mistaking CLAUDE.md for a documentation tool — Listing all of the team's conventions will cause the file to exceed hundreds of lines. It is recommended to remove all actions that AI already performs correctly and rules processed by linters.
- Overlapping Roles Between Root and Sub-files — Repeating rules defined in the root file in sub-files leads to conflicts and makes management difficult. We recommend a structure where the root contains only general rules, and sub-files contain only rules specific to the respective package.
- Committing Drafts to Git Without Verification —
/initDrafts automatically generated by commands may contain inaccurate commands or incorrect paths. It is safer to verify the commands by running them directly in the actual project before committing.
Practical Application
Example 1: Small Team / Full-Stack Project (Recommended Starting Point)
This assumes a small team running a Next.js + FastAPI project. It is an example of a minimal structure containing only what is absolutely necessary. It is recommended to add comments to the Commands section to clearly distinguish which stack the command is executed on.
# Project: E-Commerce Platform
Next.js 14 (App Router) + FastAPI 0.111 + PostgreSQL 16
## Commands
# 프론트엔드 (프로젝트 루트에서 실행)
- Dev: `pnpm dev`
- Test: `pnpm test`
- Lint: `pnpm lint`
# 백엔드 (/api 디렉터리에서 실행)
- Dev: `uvicorn main:app --reload`
- Test: `pytest -x`
- Lint: `ruff check .`
## Conventions
- TypeScript strict mode, async/await only (no .then())
- Server Components by default; Client Components only when needed
- Python: PEP 8 via ruff, type hints required
- DB migrations: Alembic only, never raw ALTER TABLE
## Architecture
- `/app` — Next.js routes and Server Actions
- `/api` — FastAPI routers (thin, business logic in services/)
- `/packages/shared` — shared TypeScript types| Section | Role |
|---|---|
| Project Header | Allows you to grasp the technology stack at a glance |
| Commands | Eliminates the repetition of being asked for a command every time |
| Conventions | Specify patterns that AI is prone to misinterpreting (e.g., using .then()) |
| Architecture | Prevents code placement errors caused by misunderstanding directory roles |
Example 2: Monorepo / Large Team (Separation of rules by service)
In large-scale projects, it is effective to separate the root CLAUDE.md from the CLAUDE.md for each subdirectory.
/CLAUDE.md
/frontend/CLAUDE.md
/backend/CLAUDE.md
/infra/CLAUDE.mdThe contents of each file are separated as follows.
# /CLAUDE.md — 전체 공통
## Git
- 브랜치 전략: feature/*, fix/*, chore/*
- PR merge는 squash merge만 사용
## CI
- `pnpm build` → `pnpm test` → `pnpm lint` 순서로 실행# /frontend/CLAUDE.md — 프론트엔드 전용
## React Conventions
- Server Component 기본, Client Component는 최소화
- Tailwind 클래스 순서: layout → spacing → color → effect
## State Management
- Zustand 사용, Redux 도입 금지# /backend/CLAUDE.md — 백엔드 전용
## NestJS Patterns
- 비즈니스 로직은 Service에, Controller는 thin 유지
- DTO로 입력 검증 필수, custom exception filter 사용
- 직접 TypeORM QueryBuilder 사용 금지 (Repository 패턴 사용)# /infra/CLAUDE.md — 인프라 전용
## Terraform
- 리소스 명명: {env}-{service}-{resource} 패턴
- 환경 변수를 코드에 하드코딩 금지
- `terraform plan` 출력을 PR 설명에 반드시 포함Example 3: Important Rules / Placement of Highlights at the Beginning and End of Files
In practical experience, a frequently reported pattern is that AI models tend to pay more attention to the beginning and end of files. You can try utilizing a method of redundantly placing frequently violated rules at the very top and bottom of the file.
# ⚠️ CRITICAL RULES (읽는 즉시 적용)
- DB 마이그레이션은 반드시 Alembic 사용 (raw SQL ALTER TABLE 금지)
- 테스트 없이 서비스 레이어 코드 수정 금지
## Commands
- Dev: `pnpm dev` / `uvicorn main:app --reload`
- Test: `pnpm test` / `pytest -x`
## Architecture
- `/app` — Next.js routes and Server Actions
- `/api` — FastAPI routers (thin, business logic in services/)
# ⚠️ REMINDER (파일 끝 재강조)
- DB 마이그레이션은 반드시 Alembic 사용
- `pnpm test`로 테스트 통과 확인 후 코드 제출Example 4: Long Session / Compaction Response Pattern
Claude Code undergoes a compaction process that automatically summarizes and compresses older messages as conversations get longer. During this process, important decisions discussed early in the session may be lost. The pattern below specifies in CLAUDE.md the context that must be preserved even if compaction occurs, encouraging the AI to prioritize preserving it during summarization.
## Session Management
When compacting, always preserve:
- 현재 작업 중인 브랜치명과 목표
- 완료된 마이그레이션 파일 목록
- 이번 세션에서 결정된 아키텍처 변경 사항
- 의도적으로 보류한 리팩터링 항목과 그 이유This pattern is primarily needed for tasks where context accumulates within a single session, such as large-scale refactoring, multi-stage migrations, or adding features across multiple files. If you have ever experienced decisions made early in a session being reversed later, it is a good idea to incorporate this pattern.
In Conclusion
If you create a well-structured CLAUDE.md, you can move away from repetitive context explanations with AI agents and focus on actual code work. Please try it out yourself to see the benefits.
3 Steps to Start Right Now:
- Automatic Draft Generation — You can open the
claudeCLI from the project root and run the/initcommand. You can start by opening the generated file and manually correcting any incorrect commands or paths. - Apply "Would be wrong without AI" filter — While reviewing each line of the draft, it is recommended to remove rules handled by the linter and practices that the AI already follows well.
- Commit to Team Git Repository — By committing the verified CLAUDE.md to the project root, the entire team can share the same AI experience. If it is a monorepo, you might also consider a method of gradually separating it into
/frontend/CLAUDE.md,/backend/CLAUDE.md, etc.
Next Post: Claude Code’s MCP (Model Context Protocol) Configuration Guide — How AI Agents Securely Interact with Databases, File Systems, and External APIs
Reference Materials
- Best Practices for Claude Code | Claude Code Docs — Official Best Practices
- Using CLAUDE.MD files: Customizing Claude Code for your codebase | Anthropic Blog — Anthropic 공식 블로그
- Writing a good CLAUDE.md | HumanLayer Blog — Writing Guide from a Practical Perspective
- How to Write a Good CLAUDE.md File | Builder.io — Detailed Explanation of Structuring Strategies
- Creating the Perfect CLAUDE.md for Claude Code | Dometrain — Focused on practical examples
- AGENTS.md vs CLAUDE.md: What's the Difference and When to Use Each | The Prompt Shelf — 표준 비교
- .cursorrules vs CLAUDE.md vs AGENTS.md | The Prompt Shelf — Format Comparison by Tool
- How to Configure Every AI Coding Assistant | DeployHQ — Multi-tool Setup Guide
- 5 Patterns That Make Claude Code Actually Follow Your Rules | DEV Community — Patterns for Improving Rule Compliance
- Steering AI Agents in Monorepos with AGENTS.md | DEV Community (Datadog) — Monorepos Application Case
- Claude Code Best Practices: Lessons From Real Projects | Ran the Builder — Lessons from Real Projects
- GitHub — steipete/agent-rules — Claude Code / Cursor Public Rules Open Source
- GitHub — shanraisshan/claude-code-best-practice — Community Best Practices Collection