Claude Code Memory System: How CLAUDE.md Files Shape AI Behavior
Deep dive into Claude Code's CLAUDE.md memory system — file hierarchy, what to include, team conventions, per-directory overrides, and how memory shapes every interaction.
Why Memory Matters for AI Coding Assistants
Every time you start a new Claude Code session, it begins with zero knowledge of your project beyond what it can read from the filesystem. Without guidance, it will write code in its own style, use its own naming conventions, and make its own architectural choices — which may not match your project.
CLAUDE.md files solve this problem. They are Markdown documents that Claude Code reads automatically at the start of every session, providing persistent memory about your project's conventions, architecture, tech stack, and preferences. Think of them as a README that is written for your AI assistant rather than for human developers.
The CLAUDE.md Hierarchy
Claude Code reads CLAUDE.md files from multiple locations, building a layered context:
1. Global Memory (~/.claude/CLAUDE.md)
Applies to every project on your machine. Use this for personal preferences that apply regardless of the project.
# Global Preferences
## Style
- Always use early returns over deeply nested conditionals
- Prefer composition over inheritance
- Use meaningful variable names — no single-letter variables except loop counters
## Communication
- Explain architectural decisions briefly
- When fixing bugs, explain the root cause
- Do not add comments that restate what code does
2. Project Memory (~/project/CLAUDE.md)
Applies to the specific project. This is the most important CLAUDE.md file — it contains your tech stack, conventions, and architecture.
# Project: E-Commerce Platform
## Tech Stack
- Backend: Node.js 20, Express 4, TypeScript 5.3
- Database: PostgreSQL 16, Prisma ORM 5.x
- Frontend: Next.js 14 (App Router), React 18, Tailwind CSS
- Testing: Vitest, Playwright for E2E
- Deployment: Docker, Kubernetes (EKS)
## Project Structure
\`\`\`
src/
api/ # Express route handlers
services/ # Business logic (one service per domain)
models/ # Prisma schema and generated client
middleware/ # Auth, validation, error handling
utils/ # Shared utility functions
types/ # TypeScript type definitions
tests/
unit/ # Unit tests (vitest)
integration/ # API integration tests
e2e/ # Playwright E2E tests
\`\`\`
## Conventions
- All API responses follow: { success: boolean, data?: T, error?: string }
- Use zod for request validation in middleware
- Database queries go in services, never in route handlers
- Environment variables accessed only through src/config.ts
- Dates stored as UTC timestamps, displayed in user's timezone
## Commands
- Run all tests: npm test
- Run specific test: npx vitest run src/services/user.test.ts
- Database migration: npx prisma migrate dev
- Generate Prisma client: npx prisma generate
- Start dev server: npm run dev
3. Directory-Level Memory (~/project/src/api/CLAUDE.md)
Applies only when Claude Code is working with files in that directory or its subdirectories.
# API Routes Conventions
## Route Structure
Every route file follows this pattern:
1. Import dependencies
2. Create Express router
3. Define validation schemas (zod)
4. Define route handlers
5. Export router
## Error Handling
- Use the asyncHandler wrapper for all async route handlers
- Never catch errors in route handlers — let them propagate to the error middleware
- Return 400 for validation errors, 404 for not found, 409 for conflicts
## Authentication
- All routes require authentication unless explicitly marked as public
- Use requireAuth middleware: router.get("/", requireAuth, handler)
- Admin routes use requireRole("admin") middleware
Memory Loading Order
When you ask Claude Code to edit a file at src/api/users.ts, it loads:
~/.claude/CLAUDE.md(global)CLAUDE.md(project root)src/CLAUDE.md(if it exists)src/api/CLAUDE.md(if it exists)
Later files can override or supplement earlier ones. This layered system means you can have general project conventions at the root and specific API conventions in the API directory.
What to Include (and What to Skip)
Include
- Tech stack and versions — Claude Code needs to know which framework version you use to generate correct syntax
- Project structure — Where different types of files live
- Naming conventions — snake_case, camelCase, file naming patterns
- Testing commands — How to run tests, what framework you use
- Architecture patterns — Service layer patterns, dependency injection approach
- Error handling patterns — How errors are structured and propagated
- Database conventions — ORM usage, migration workflows, naming schemes
- Build and deploy commands — How to build, lint, deploy
- Forbidden patterns — Things Claude should never do (e.g., "never use any" in TypeScript)
Skip
- Obvious language features — Claude already knows Python, TypeScript, etc.
- Framework documentation — Claude has training data covering popular frameworks
- Lengthy code examples — CLAUDE.md is loaded into context every session; keep it concise
- Temporary task context — Do not put current task details in CLAUDE.md
Generating Your First CLAUDE.md
Claude Code can bootstrap a CLAUDE.md for you:
/init
This command analyzes your project and generates a starter file. Always review and customize it — Claude Code makes reasonable inferences, but it cannot know your team's preferred patterns.
Team Workflows with CLAUDE.md
When CLAUDE.md is committed to the repository, every team member's Claude Code sessions use the same conventions. This creates consistency:
- New team members get Claude Code sessions that match team conventions from day one
- Code reviews become simpler because AI-generated code follows the same patterns
- Cross-team contributions maintain consistency even when developers are unfamiliar with a codebase
Team CLAUDE.md Best Practices
# Team Conventions (committed to repo)
## Code Review Standards
- All functions longer than 30 lines should be refactored
- No magic numbers — use named constants
- Error messages must be user-facing friendly (no technical jargon)
## Git Workflow
- Branch naming: feature/TICKET-123-short-description
- Commit messages: conventional commits (feat:, fix:, refactor:, test:)
- Always squash merge to main
- PRs require at least one approval
## Security Requirements
- Never log PII (email, phone, SSN)
- All user input must be validated with zod
- SQL queries must use parameterized queries (enforced by Prisma)
- API keys and secrets go in environment variables, never in code
Advanced Patterns
Conditional Instructions
## When writing tests
- Use describe/it blocks, not test()
- Mock external services with vi.mock()
- Each test file tests one module
## When writing migrations
- Always include a rollback (down migration)
- Test migrations against a copy of production data shape
- Never drop columns in production — mark as deprecated first
Linking to Documentation
## API Documentation
- OpenAPI spec: docs/openapi.yaml
- Internal architecture doc: docs/ARCHITECTURE.md
- Database schema diagram: docs/schema.png
Claude Code can read these referenced files when it needs deeper context.
Negative Instructions
Telling Claude what NOT to do is often more effective than positive instructions:
## Never Do
- Never use `any` type in TypeScript — use `unknown` and narrow
- Never use string concatenation for SQL — always parameterized
- Never import from barrel files (index.ts) — import from specific modules
- Never use default exports — always named exports
- Never commit console.log statements — use the logger utility
- Never use var — always const or let
Measuring CLAUDE.md Effectiveness
How do you know if your CLAUDE.md is working? Track these indicators:
- First-attempt accuracy — How often does Claude Code generate code that matches your conventions without corrections?
- Review feedback — Are code reviewers finding convention violations in AI-generated code?
- Questions asked — Is Claude Code asking fewer clarifying questions about patterns?
If Claude Code consistently ignores a convention, the instruction might be too vague. Make it more specific and add an example.
Conclusion
CLAUDE.md is the single highest-leverage configuration you can make for Claude Code. A well-written memory file saves time on every session by eliminating the need to explain your conventions, architecture, and preferences repeatedly. Keep it concise, keep it current, and commit it to your repository so your entire team benefits from consistent AI-assisted development.
NYC News
Expert insights on AI voice agents and customer communication automation.
Try CallSphere AI Voice Agents
See how AI voice agents work for your industry. Live demo available -- no signup required.