Memory files are automatically loaded at session startup, consuming tokens from your 200k context window. Every instruction competes with Claude Code's ~50 built-in instructions, leaving ~100-150 effective instruction slots for your customizations.
Two approaches available:
- CLAUDE.md - Single file, simpler, best for small projects
- .claude/rules/ - Modular files with optional path-scoping, best for large projects
Or create manually at project root:
# Project Name
## Tech Stack
- [Primary language/framework]
- [Key libraries]
## Commands
- `bun run dev` - Start development
- `npm test` - Run tests
- `bun run build` - Build for production
## Code Conventions
- [2-3 critical conventions]
## Important Context
- [1-2 architectural decisions worth knowing]
Running Claude in foo/bar/ loads:
foo/bar/CLAUDE.mdfoo/CLAUDE.md- Root-level files
Claude also discovers CLAUDE.md in SUBTREES when reading files in those directories.
root/
├── CLAUDE.md # Universal: tech stack, git workflow
├── apps/
│ ├── web/CLAUDE.md # Frontend-specific patterns
│ └── api/CLAUDE.md # Backend-specific patterns
└── packages/
└── shared/CLAUDE.md # Shared library conventions
Root file defines WHEN to use patterns; subtree files define HOW.
- Project has many distinct concerns (testing, security, API, frontend)
- Different rules apply to different file types
- Team members maintain different areas
- You want to update one concern without touching others
Use CLAUDE.md when:
- Project is small/simple
- All rules are universal
- You prefer a single source of truth
.claude/rules/
├── code-style.md # Formatting and conventions
├── testing.md # Test requirements
├── security.md # Security checklist
├── frontend/
│ ├── react.md # React-specific patterns
│ └── styles.md # CSS conventions
└── backend/
├── api.md # API development rules
└── database.md # Database conventions
Key points:
- All
.mdfiles are discovered recursively - No imports or configuration needed
- Same priority as CLAUDE.md
- Supports symlinks for sharing rules across projects
---
paths:
- 'src/api/**/*.ts'
---
# API Development Rules
- All API endpoints must include input validation
- Use the standard error response format
Path patterns supported:
| Pattern | Matches |
|---|---|
**/*.ts |
All TypeScript files in any directory |
src/**/* |
All files under src/ directory |
src/components/*.tsx |
React components in specific directory |
src/**/*.{ts,tsx} |
TypeScript and TSX files (brace expansion) |
{src,lib}/**/*.ts |
Files in multiple directories |
Syntax note: The paths field must be a YAML array (list format with - prefix and quoted strings).
Rules without paths frontmatter load unconditionally for all files.
~/.claude/rules/
├── preferences.md # Your coding preferences
├── workflows.md # Your preferred workflows
└── git.md # Your git conventions
User-level rules load before project rules, giving project rules higher priority for overrides.
# Symlink a shared rules directory
ln -s ~/shared-claude-rules .claude/rules/shared
# Symlink individual rule files
ln -s ~/company-standards/security.md .claude/rules/security.md
Circular symlinks are detected and handled gracefully.
WHAT - Project Context: Tech stack, directory structure, architecture WHY - Purpose: Architectural decisions, why patterns exist HOW - Workflow: Commands, testing, git workflow, verification steps
## Tech Stack
- Next.js 15 with App Router
- PostgreSQL via Prisma ORM
## Architecture Decisions
- Server Components for data fetching
- All forms use TanStack Form
## Commands
- `pnpm dev` - Start dev server
- `pnpm test:ci` - Run tests
- `pnpm build` - Production build
## Git Workflow
- Branch: `feature/name` or `fix/name`
- Run tests before committing
See references/section-templates.md for complete templates.
| Keyword | Use For | Example |
|---|---|---|
| CRITICAL | Non-negotiable rules | **CRITICAL**: Never commit secrets |
| NEVER | Absolute prohibitions | NEVER: Push directly to main |
| ALWAYS | Mandatory behaviors | ALWAYS: Run tests before pushing |
| IMPORTANT | Significant guidance | IMPORTANT: Keep components under 300 lines |
| YOU MUST | Explicit requirements | YOU MUST: Use TanStack Form for forms |
**CRITICAL**: Always run tests before pushing code
Capitalized emphasis:
IMPORTANT: Do not commit environment variables
YOU MUST: Follow the git workflow outlined below
NEVER: Include API keys in code
ALWAYS: Use TypeScript strict mode
Strikethrough for forbidden options:
- `pnpm test:ci` - Run tests (use this)
- ~~`pnpm test`~~ - NEVER use (interactive mode)
Visual markers (use sparingly):
⚠️ WARNING: This affects production data
🔒 SECURITY: Never commit secrets to git
- First items in each section (put critical rules first)
- Repeated items across sections (repeat critical rules in context)
- Emphasized items with CRITICAL/NEVER/ALWAYS keywords
Structure your file with critical rules first:
## Code Conventions
### Critical Rules
- **NEVER** commit .env files
- **ALWAYS** run tests before pushing
- **CRITICAL**: Use TanStack Form for ALL forms
### General Guidelines
- Prefer Server Components
- Keep components under 300 lines
## Forms
**CRITICAL**: Use TanStack Form for ALL forms
## Before Editing
- **CRITICAL**: Use TanStack Form for forms
## Code Review Checklist
- [ ] Forms use TanStack Form (**CRITICAL**)
❌ VAGUE:
- Format code properly
- Write good tests
- Follow best practices
✅ SPECIFIC:
- Run `pnpm lint` before committing (Prettier configured)
- Write tests in `__tests__/` using Vitest
- Use TanStack Form for all forms (see `src/features/form/`)
❌ TELLING:
Use conventional commits with type and description.
✅ SHOWING:
## Commit Format
feat(auth): implement JWT authentication
Add login endpoint and token validation
Types: feat, fix, refactor, docs, test, chore
| Ambiguous | Clear Alternative |
|---|---|
| "Try to..." | "Always..." or "Never..." |
| "Should probably..." | "Must..." or "May optionally..." |
| "Generally..." | "Always... except when [condition]" |
| "Consider..." | "If [condition], then [action]" |
❌ INCOMPLETE:
Run tests before pushing.
✅ COMPLETE:
## Testing
- Run `pnpm test:ci` before pushing
- If tests fail, fix before committing
- New features require tests in `__tests__/`
- Minimum 80% coverage for new code
## Component Choice
**Use Server Component when:**
- Data fetching only
- No user interaction needed
**Use Client Component when:**
- User interaction required
- Browser APIs needed (localStorage, window)
## API Development
### Must Have
- Input validation with Zod
- Error handling for all endpoints
### Nice to Have
- Pagination for list endpoints
- Caching headers
### Must Not
- Expose internal errors to clients
- Log sensitive data
- Ideal: 100-200 lines maximum
- Practical max: 300 lines before splitting
- Universal items: Under 60 lines
Why these limits matter:
- Claude reliably follows ~150-200 total instructions
- Claude Code's system prompt uses ~50 instructions
- Leaves ~100-150 slots for YOUR instructions
- Irrelevant content degrades instruction-following
- Move task-specific details to separate files
- Link from CLAUDE.md with descriptions
- Use progressive disclosure pattern
## Detailed Guides
- **API Routes**: See [docs/api-patterns.md](docs/api-patterns.md)
- **Testing**: See [docs/testing-guide.md](docs/testing-guide.md)
- **Deployment**: See [docs/deployment.md](docs/deployment.md)
## External References
@docs/coding-standards.md
@~/.claude/my-global-preferences.md
@./team-conventions.md
- Supports relative and absolute paths
- Home directory expansion with
~ - Recursive imports up to 5 levels deep
- NOT evaluated inside code blocks or backticks
Secrets - NEVER include API keys, database URLs, tokens, credentials
Too Much Content - Link to docs instead of embedding 500+ lines
Extensive Code - Reference files instead (code examples become outdated)
Vague Instructions - Be specific (see <writing_effective_instructions>)
❌ BAD:
- Use 2-space indentation (use Prettier instead)
- DATABASE_URL=postgresql://... (never include secrets)
- [500 lines of API docs] (link to external file)
- Format code properly (too vague)
✅ GOOD:
- ESLint/Prettier configured (see .eslintrc)
- Credentials in `.env` (never committed)
- API guide: See [docs/api.md](docs/api.md)
- Run `pnpm lint` before committing
- Minimal example: references/section-templates.md (templates section)
- Comprehensive SaaS: references/comprehensive-example.md
- Project-specific: references/project-patterns.md (Next.js, Express, Python, Monorepo)
Before creating or updating memory files, ask the user:
Do you want to use a single CLAUDE.md file or split into separate
.claude/rules/files?Option 1: Single CLAUDE.md - All instructions in one file (simpler, best for small projects) Option 2: Modular .claude/rules/ - Split by concern with optional path-scoping (better for large projects)
Use AskUserQuestion to present these options before proceeding.
Decision guide:
- Choose CLAUDE.md if: < 100 lines of instructions, simple project, universal rules
- Choose .claude/rules/ if: 100+ lines, multiple file types with different rules, team maintains different areas
- Start with
/initor minimal template - Add tech stack and commands first
- Add conventions as you encounter friction
- Test with real tasks
- Iterate based on Claude's behavior
- Create
.claude/rules/directory - Start with one file per major concern:
general.md- Universal project rulestesting.md- Testing conventionscode-style.md- Code conventions
- Add path-scoped rules as needed:
--- paths: - 'src/api/**/*.ts' --- # API rules here - Test with real tasks in different file contexts
- Split or merge files based on usage patterns
- Review quarterly (or when project changes significantly)
- Remove outdated instructions
- Add patterns that required repeated explanation
- Keep CLAUDE.md under 200 lines (or split to .claude/rules/)
- Use
#for quick additions during work
When CLAUDE.md exceeds 200 lines:
- Identify distinct sections (testing, API, frontend, etc.)
- Create
.claude/rules/directory - Move each section to its own file
- Add
pathsfrontmatter where rules are file-type specific - Keep only universal essentials in CLAUDE.md (or delete it)
- Test to ensure rules load correctly
| Problem | Solution |
|---|---|
| Claude ignores instructions | Reduce file size, add emphasis (CRITICAL, NEVER) |
| Context overflow | Use /clear, split into .claude/rules/ files |
| Outdated information | Review quarterly, remove stale content |
| Instructions conflict | Consolidate, use hierarchy (root vs subtree) |
| Rules not loading | Check file is .md, in correct directory |
| Path rules not applying | Verify glob pattern matches target files |
- Personal shortcuts and aliases
- Editor-specific settings
- Local testing commands
settings.json: Permissions, allowed tools, environment variablesCLAUDE.md: Context, conventions, workflow instructions
## References
- **Database**: See [docs/database.md](docs/database.md)
- **API**: See [docs/api.md](docs/api.md)
For CLAUDE.md approach:
- Loads in under 200 lines
- Contains only project-specific context (not general knowledge)
- Uses emphasis for critical rules (CRITICAL, NEVER, ALWAYS)
- Avoids code style rules (use linters)
- Contains NO secrets or credentials
- Provides clear commands for common tasks
- Follows WHAT-WHY-HOW structure
For .claude/rules/ approach:
- Each file focused on one concern (testing, API, security, etc.)
- Path-scoped rules use accurate glob patterns
- No duplicate rules across files
- Files organized in logical subdirectories
- Symlinks used for shared rules across projects
Both approaches:
- Gets updated as project evolves
- Improves Claude's first-try accuracy on tasks
- User was asked which approach they prefer before implementation
- Rules directory guide: references/rules-directory-guide.md - Complete guide to .claude/rules/ with official documentation, path-scoping, YAML syntax, and examples
- Prompting techniques: references/prompting-techniques.md - Master guide for writing effective instructions, emphasis strategies, clarity techniques
- Comprehensive example: references/comprehensive-example.md - Full production SaaS CLAUDE.md
- Section templates: references/section-templates.md - Copy-paste templates for each section
- Common patterns by project type: references/project-patterns.md - Next.js, Express, Python, Monorepo patterns