Module 6: Context Management for Large Projects
CLAUDE.md and Project Context Files
CLAUDE.md and Project Context Files
Capsule description
CLAUDE.md is possibly the most underused tool of Claude Code. It's a file that gives Claude Code an understanding of the project without including all the files: architecture overview, naming conventions, file structure, key abstractions, common patterns. It's the "briefing" that makes each session productive from the first message.
Invest 30 minutes in a good CLAUDE.md and each future session will be significantly more productive. Without CLAUDE.md, each session starts from scratch. With CLAUDE.md, Claude Code already "knows" your project.
What CLAUDE.md Is
The concept
CLAUDE.md is a markdown file at the root of your project (or in .claude/) that Claude Code reads automatically at the start of each session. It contains information Claude Code needs to work effectively with your project but that isn't explicit in the code.
What CLAUDE.md is NOT
- ❌ It's not documentation for humans (README.md is for that)
- ❌ It's not a copy of the code (that consumes context unnecessarily)
- ❌ It's not a task list (use TodoWrite for that)
- ❌ It's not configuration (settings.json is for that)
What CLAUDE.md IS
- ✅ Project context that isn't in the code
- ✅ Conventions Claude Code should follow
- ✅ Structure that helps Claude Code navigate
- ✅ Patterns Claude Code should use when generating code
- ✅ Information that avoids repetitive questions
Structure of a Good CLAUDE.md
Base template
# Project: [Name]
## Architecture
[2-3 paragraphs describing the general architecture:
layers, main components, data flow]
## Structure
src/ api/ → HTTP routes (FastAPI) services/ → Business logic models/ → SQLAlchemy models repositories/ → Data access utils/ → Pure utility functions tests/ → pytest tests (mirrors src/ structure)
## Conventions
- Naming: snake_case for functions, PascalCase for classes
- Error handling: raise HTTPException in routes, raise custom exceptions in services
- Imports: absolute imports only, no relative
- Testing: pytest with fixtures, mock external services
## Key Abstractions
- BaseService: all services inherit from this
- BaseRepository: all repos inherit, provides CRUD
- ResponseModel: Pydantic base for API responses
## Patterns
- Service Layer: routes call services, services call repos
- Repository Pattern: all DB access through repos
- Dependency Injection: FastAPI Depends() for services
## Common Tasks
- Adding new endpoint: create route, service, tests
- Adding new model: create model, migration, repository
- Running tests: `pytest` (all), `pytest tests/test_X.py` (specific)
## Do NOT
- Do not use global variables for state
- Do not import from tests/ in src/
- Do not use `print()` for logging (use `logger`)
Generating CLAUDE.md with Claude Code
# Prompt to generate CLAUDE.md:
> "Analyze this project and generate a CLAUDE.md that includes:
1. Architecture overview (2-3 paragraphs)
2. Directory structure with the purpose of each folder
3. Naming conventions the project uses
4. Key patterns (service layer, repository, etc.)
5. Common tasks (how to add an endpoint, model, test)
6. Do NOT list (what NOT to do in this project)"
Iterating on the CLAUDE.md
# After working with the project for a while:
> "Based on our conversation and the problems
we found, update CLAUDE.md with:
- The error handling convention we agreed on
- The naming pattern for tests
- The migrations structure"
Advanced CLAUDE.md
Sections for large projects
## Module Map
| Module | Owner | Purpose | Dependencies |
|--------|-------|---------|-------------|
| auth | Team A | Authentication + authorization | users, sessions |
| orders | Team B | Order lifecycle | products, payments, users |
| payments | Team C | Payment processing | stripe, orders |
## API Conventions
- All endpoints return `{"data": ..., "meta": {...}}`
- Pagination: `?page=1&per_page=20`
- Auth: Bearer token in Authorization header
- Errors: `{"error": {"code": "...", "message": "..."}}`
## Database
- PostgreSQL 15
- Migrations: Alembic in `migrations/`
- Naming: tables plural (`users`), models singular (`User`)
- Always use `created_at` and `updated_at` timestamps
## Environment
- Python 3.11+
- Poetry for dependencies
- Docker for local development
- CI: GitHub Actions
CLAUDE.md for refactoring (specific to this guide)
## Refactoring in Progress
Currently refactoring the order module:
- Phase 1: Extract OrderValidator from OrderService (DONE)
- Phase 2: Move pricing logic to PricingEngine (IN PROGRESS)
- Phase 3: Standardize error handling (PENDING)
## Tech Debt
- user_service.py has circular import with auth_service.py
- 3 functions in utils/helpers.py are never called (dead code)
- payment_processor.py uses deprecated stripe.Charge API
## Test Coverage
- Overall: 72%
- services/: 85%
- api/routes/: 60% (needs improvement)
- models/: 90%
Multiple Context Files
Hierarchical structure
.claude/
CLAUDE.md → Global project context
project-root/
CLAUDE.md → Override/additions for the project
src/
payments/
CLAUDE.md → Specific context for the payments module
Claude Code reads the CLAUDE.md files in cascade: global → project → module. The most specific one has priority.
Keeping CLAUDE.md Up to Date
When to update
- After a significant refactoring
- When you add a new pattern or convention
- When a new team member joins and asks something that should be documented
- When you detect that Claude Code repeats an error that CLAUDE.md should prevent
Prompt for updating
> "Based on the changes we made today (extracting
PricingEngine, changing the error handling pattern),
update CLAUDE.md to reflect the new state
of the project."
Connection with the Project
In the Module Project (capsule 05), creating a CLAUDE.md is one of the main deliverables. It's the artifact that lets you work with the 100K+ project effectively.
Troubleshooting
Problem 1: CLAUDE.md is too long
Solution: Maximum 200 lines. If you need more, use hierarchical CLAUDE.md files per module.
Problem 2: CLAUDE.md is outdated
Solution: Add it to your workflow: after each significant refactoring, update CLAUDE.md.
Problem 3: Claude Code doesn't seem to read CLAUDE.md
Solution: Verify that it's in the right location (project root or .claude/). Verify that Claude Code runs from that directory.
Exercises
Exercise 1: Write a basic CLAUDE.md (Easy)
Write a 50-line CLAUDE.md for a FastAPI project with 3 modules: users, products, orders.
See solution
# Project: E-Commerce API
## Architecture
FastAPI REST API with service layer pattern. Routes handle HTTP,
services handle business logic, repositories handle database.
## Structure
src/
api/routes/ → FastAPI endpoints
services/ → Business logic
models/ → SQLAlchemy models
repositories/ → Database queries
tests/ → pytest (mirrors src/)
## Conventions
- snake_case functions, PascalCase classes
- Services raise custom exceptions, routes catch and return HTTP errors
- All models have created_at, updated_at fields
- Tests use factory_boy for test data
## Key Patterns
- Service Layer: routes → services → repositories
- Dependency Injection: FastAPI Depends()
- Response Models: Pydantic for all API responses
## Common Commands
- Run: uvicorn src.main:app --reload
- Test: pytest
- Migrate: alembic upgrade head
## Do NOT
- Do not put business logic in routes
- Do not import models directly in routes (use services)
- Do not use print() (use structlog)
Exercise 2: Generate CLAUDE.md with Claude Code (Medium)
Write the complete prompt for Claude Code to analyze a project and generate CLAUDE.md.
See solution
> "Analyze the complete structure of this project and
generate a CLAUDE.md file that includes:
1. Architecture (2-3 paragraphs: what it is, what patterns it uses,
how the data flows)
2. Directory structure (tree with the purpose of each folder)
3. Naming conventions (that you observe in the current code)
4. Key abstractions (base classes, shared interfaces)
5. Common patterns (how endpoints, models, tests are created)
6. Database info (which DB, ORM, table naming)
7. Testing (framework, patterns, how to run)
8. Do NOT list (anti-patterns the project avoids)
Base EVERYTHING on what you observe in the real code,
not on assumptions. If you're not sure about something,
don't include it."
Summary
- CLAUDE.md is project context that Claude Code reads automatically
- Invest 30 minutes and each future session is significantly more productive
- Include: architecture, conventions, patterns, common tasks, do-not list
- Don't include: code, documentation for humans, configuration
- Maximum 200 lines — concise is better than exhaustive
- Update after each significant refactoring
- Hierarchical: global → project → module for large projects
Next capsule: Project — Context Strategy for a 100K+ Project.
Additional Resources
- Claude Code - CLAUDE.md - Official documentation
- ADR - Architecture Decision Records - A complement to CLAUDE.md for decisions
- README Best Practices - To compare README vs CLAUDE.md
- Project Documentation - The Write the Docs community
Module 6, Capsule 04 — Refactoring & Legacy Code with Claude Code Guide