← Back to learning path
Level 2

Level 2: CLAUDE.md Configuration

The definitive guide to teaching Claude Code your rules, conventions, and project context -- so it follows your standards every session…

Level 2: CLAUDE.md Configuration

The definitive guide to teaching Claude Code your rules, conventions, and project context -- so it follows your standards every session without being told twice.


Table of Contents

  1. Overview & Goal
  2. The Memory Hierarchy
  3. Getting Started: /init
  4. The 5-Question Framework
  5. Writing Effective Rules
  6. Modular Rules with .claude/rules/
  7. Advanced Features
  8. Team Collaboration Patterns
  9. Complete Example CLAUDE.md Files
  10. Self-Check Checklist
  11. Exercises
  12. Pro Tips from Boris Cherny
  13. Anti-Patterns
  14. Official Documentation Links

1. Overview & Goal

Why CLAUDE.md Matters

Every time you start a new Claude Code session, Claude starts fresh. It does not remember your last conversation. It does not know your project uses Prettier with single quotes. It does not know your team runs pnpm instead of npm. It does not know that src/legacy/ should never be modified.

CLAUDE.md is how you solve this. It is a plain Markdown file that gets loaded into Claude's context at the start of every session. Think of it as a permanent onboarding document for an infinitely patient team member who reads it cover to cover before writing a single line of code.

The "Onboarding a Team Member" Analogy

Imagine hiring a senior developer. On their first day, you would not hand them a laptop and say "figure it out." You would:

  1. Explain what the project is and what it does
  2. Show them how to build, test, and run things
  3. Walk them through the team's coding standards
  4. Warn them about the tricky parts and historical landmines
  5. Describe how the team prefers to collaborate

That is exactly what CLAUDE.md does. Each session is day one for Claude. Your CLAUDE.md file is the onboarding packet that makes day one productive instead of wasteful.

The Goal of This Level

By the end of this guide, you will be able to:


2. The Memory Hierarchy

Claude Code loads instructions from multiple locations in a specific order. Understanding this hierarchy is essential -- it determines which rules take effect and who sees them.

The Six Memory Layers

Priority (highest to lowest):

1. Managed Policy CLAUDE.md     -- Organization-wide, cannot be overridden
2. Project CLAUDE.md            -- Team-shared, committed to git
3. Project Rules (.claude/rules/) -- Modular, topic-specific, committed to git
4. User CLAUDE.md               -- Personal, applies to all projects
5. Project Local (CLAUDE.local.md) -- Personal, this project only
6. Auto Memory                  -- Claude's own notes, per-project

Layer 1: Managed Policy CLAUDE.md

Purpose: Organization-wide instructions enforced by IT or DevOps. These cannot be overridden by any other layer.

File locations:

Who uses this: Enterprise teams that need to enforce company-wide coding standards, security policies, or compliance requirements across every developer's machine.

Example content:

# Company Policy

- All code must pass security scanning before commit
- Never use dynamic code execution functions
- All API endpoints must include rate limiting
- Follow OWASP Top 10 guidelines for web applications
- Use approved open-source licenses only (MIT, Apache 2.0, BSD)

Git status: Not in any repository. Deployed via MDM, Ansible, or other configuration management.

Layer 2: Project CLAUDE.md

Purpose: Team-shared instructions that travel with the project repository. This is the most commonly used layer.

File locations (either works, not both):

Who uses this: Every team member working on the project. These rules are committed to version control and shared via git.

Example content:

# MyApp

A Next.js 14 e-commerce platform using TypeScript, Prisma, and PostgreSQL.

## Commands
- Build: `pnpm build`
- Test: `pnpm test`
- Lint: `pnpm lint`
- Dev server: `pnpm dev`

## Rules
- Use TypeScript strict mode everywhere
- Components go in src/components/ with PascalCase filenames
- API routes go in src/app/api/ following Next.js App Router conventions
- All database queries go through Prisma -- never write raw SQL

Git status: Committed to the repository.

Layer 3: Project Rules (.claude/rules/*.md)

Purpose: Modular, topic-specific instructions. Instead of one large CLAUDE.md, you can split rules into focused files.

File location: ./.claude/rules/*.md (supports subdirectories)

Directory structure example:

.claude/rules/
  code-style.md        # Formatting and naming conventions
  testing.md           # Test patterns and requirements
  security.md          # Security-related rules
  git-conventions.md   # Commit messages, branch naming
  frontend/
    react.md           # React-specific patterns
    styles.md          # CSS/styling rules
  backend/
    api.md             # API design rules
    database.md        # Database conventions

All .md files in .claude/rules/ are automatically loaded as project memory. They share the same priority as .claude/CLAUDE.md.

Git status: Committed to the repository.

Layer 4: User CLAUDE.md

Purpose: Your personal preferences that apply across every project you work on.

File location: ~/.claude/CLAUDE.md

Who uses this: Just you. This file is not in any repository. Use it for preferences that follow you everywhere.

Example content:

# Personal Preferences

- I prefer functional programming patterns over class-based approaches
- When writing commit messages, use conventional commits format
- Always explain your reasoning before making changes
- I use VS Code -- reference VS Code shortcuts when relevant
- When asked to refactor, preserve all existing behavior unless told otherwise

Git status: Not in any repository. Lives in your home directory.

Layer 5: Project Local (CLAUDE.local.md)

Purpose: Your personal preferences for a specific project. Perfect for things your teammates do not need to see.

File location: ./CLAUDE.local.md (project root)

Who uses this: Just you. This file is automatically added to .gitignore by Claude Code.

Example content:

# My Local Settings

- My dev API key is in .env.local (already gitignored)
- I run the dev server on port 3001 because 3000 conflicts with another project
- My test database is at localhost:5433 (non-standard port)
- Skip the E2E tests when I say "run tests" -- they take 10 minutes.
  Only run them when I explicitly ask.

Git status: Automatically gitignored. Never committed.

Layer 6: Auto Memory

Purpose: Notes that Claude writes for itself based on what it learns during sessions. This is not a file you author -- Claude maintains it automatically.

File location: ~/.claude/projects/<project>/memory/

Directory structure:

~/.claude/projects/<project>/memory/
  MEMORY.md              # Main index -- first 200 lines loaded at startup
  debugging.md           # Notes about debugging patterns
  api-conventions.md     # API design decisions Claude observed
  build-issues.md        # Build problems and their solutions

How it works:

Opt-in/out:

export CLAUDE_CODE_DISABLE_AUTO_MEMORY=1  # Force off
export CLAUDE_CODE_DISABLE_AUTO_MEMORY=0  # Force on

Git status: Not in any repository. Stored in your home directory under ~/.claude/.

Load Order and Precedence

Claude loads all memory files at the start of every session. The rule is: more specific instructions take precedence over broader ones.

1. Managed policy CLAUDE.md     (loaded first, highest authority)
2. CLAUDE.md files from parent directories (recursive upward from cwd)
3. Project CLAUDE.md or .claude/CLAUDE.md
4. .claude/rules/*.md files
5. User ~/.claude/CLAUDE.md
6. CLAUDE.local.md
7. Auto memory (first 200 lines of MEMORY.md)

If your user CLAUDE.md says "use tabs" but your project CLAUDE.md says "use 2-space indentation," the project rule wins because it is more specific to the current context.

CLAUDE.md files in child directories (subdirectories below your working directory) are not loaded at startup. They are loaded on demand when Claude reads files in those subdirectories.

Which Files to Commit vs. Gitignore

File Commit to Git? Reason
CLAUDE.md Yes Team-shared project rules
.claude/CLAUDE.md Yes Team-shared project rules (alternate location)
.claude/rules/*.md Yes Team-shared modular rules
CLAUDE.local.md No (auto-gitignored) Personal project preferences
~/.claude/CLAUDE.md N/A (not in repo) Personal global preferences
~/.claude/projects/*/memory/ N/A (not in repo) Auto-generated by Claude

3. Getting Started: /init

What /init Does

The /init command is the fastest way to bootstrap a CLAUDE.md for your project. When you run it inside Claude Code, Claude will:

  1. Scan your project structure -- look at directories, file types, configuration files
  2. Read key configuration files -- package.json, pyproject.toml, Makefile, tsconfig.json, etc.
  3. Identify patterns -- detect frameworks, languages, build tools, test runners
  4. Generate a CLAUDE.md -- produce a ready-to-use file with project context, commands, and reasonable defaults

Running /init

# Inside Claude Code, just type:
> /init

Claude will generate a CLAUDE.md file in your project root (or .claude/CLAUDE.md depending on your project structure).

What /init Generates

A typical /init output includes:

Example /init Output

For a Next.js project, /init might generate:

# MyStore

E-commerce platform built with Next.js 14, TypeScript, and Prisma.

## Tech Stack
- Framework: Next.js 14 (App Router)
- Language: TypeScript (strict mode)
- Database: PostgreSQL via Prisma ORM
- Styling: Tailwind CSS
- Testing: Vitest + React Testing Library
- Package Manager: pnpm

## Commands
- Install: `pnpm install`
- Dev: `pnpm dev`
- Build: `pnpm build`
- Test: `pnpm test`
- Lint: `pnpm lint`
- Type check: `pnpm tsc --noEmit`
- Database migrate: `pnpm prisma migrate dev`

## Project Structure
- `src/app/` - Next.js App Router pages and API routes
- `src/components/` - React components
- `src/lib/` - Utility functions and shared logic
- `prisma/` - Database schema and migrations
- `public/` - Static assets

When to Use /init vs. Manual Creation

Scenario Recommendation
New project, getting started quickly Use /init then customize
Existing project with established conventions Manual creation for precision
You want a starting point to iterate on Use /init as a first draft
Your team has a CLAUDE.md template Start from the template
Simple script or small project Manual -- /init might over-generate

Customizing After /init

The generated file is always a starting point. After /init, you should:

  1. Remove anything wrong -- /init infers, and inference can be wrong
  2. Add your team's specific conventions -- naming patterns, code review rules, etc.
  3. Add warnings about gotchas -- things that trip people (and Claude) up
  4. Add workflow instructions -- how you prefer to work with Claude
  5. Trim the fat -- remove obvious or redundant information

The worst thing you can do is run /init and never touch the file again. The best CLAUDE.md files are living documents maintained over time.


4. The 5-Question Framework

A well-structured CLAUDE.md answers five fundamental questions. This framework comes from the same onboarding analogy -- these are the five things any new team member needs to know on day one.

Question 1: What Is This Project?

Give Claude the 30-second pitch. What does this project do? What technologies does it use? What is the architecture?

Why it matters: Without this, Claude guesses. It might assume a different framework, a different architecture pattern, or a different target audience.

Good example:

# ShipTracker

Real-time cargo ship tracking platform. Users monitor vessel locations,
view route histories, and receive ETA notifications.

## Architecture
- Monorepo with apps/web (Next.js) and apps/api (Express)
- PostgreSQL for persistent data, Redis for real-time vessel positions
- WebSocket connections for live map updates
- AIS data ingested from MarineTraffic API every 30 seconds

Bad example:

# My Project
A web app.

Question 2: How Do You Run Things?

List every command Claude might need. Build, test, lint, deploy, database migrations, code generation -- all of it. Claude will use these commands constantly, and getting them wrong wastes time.

Why it matters: Claude frequently needs to run your test suite, build your project, or check for lint errors. If it does not know the exact commands, it will guess (often wrong) or ask you every time.

Good example:

## Commands

### Development
- Install dependencies: `pnpm install`
- Start dev server: `pnpm dev` (runs on port 3000)
- Start API server: `pnpm --filter api dev` (runs on port 4000)

### Testing
- Run all tests: `pnpm test`
- Run single test file: `pnpm test -- path/to/file.test.ts`
- Run tests in watch mode: `pnpm test:watch`
- Run E2E tests: `pnpm test:e2e` (requires dev server running)

### Code Quality
- Lint: `pnpm lint`
- Type check: `pnpm tsc --noEmit`
- Format: `pnpm format`

### Database
- Generate migration: `pnpm prisma migrate dev --name <name>`
- Apply migrations: `pnpm prisma migrate deploy`
- Reset database: `pnpm prisma migrate reset`
- Open Prisma Studio: `pnpm prisma studio`

Bad example:

## Commands
- npm test

Question 3: What Are Your Rules?

This is where you define coding standards, naming conventions, file organization, and any other patterns Claude should follow.

Why it matters: Without explicit rules, Claude falls back to general best practices. Those might not match your project. Your team uses named exports? Claude might use default exports. Your API returns snake_case? Claude might return camelCase.

Good example:

## Code Style

### TypeScript
- Use named exports, never default exports
- Prefer `interface` over `type` for object shapes
- Use `const` assertions for literal types
- All function parameters must be typed -- no implicit `any`
- Prefer early returns over nested conditionals

### React
- Functional components only -- no class components
- Use named function declarations, not arrow functions, for components
- Props interfaces go in the same file, named `{ComponentName}Props`
- State management: use Zustand for global state, useState for local
- Never use useEffect for data fetching -- use React Query

### API
- All endpoints return `{ data, error, meta }` envelope
- Use HTTP status codes correctly (201 for creation, 204 for deletion)
- Validate all inputs with Zod schemas
- Error responses include a machine-readable `code` field

### File Organization
- Components: `src/components/{ComponentName}/{ComponentName}.tsx`
- Tests: colocated as `{ComponentName}.test.tsx`
- Hooks: `src/hooks/use{HookName}.ts`
- Utils: `src/utils/{utilName}.ts`

Bad example:

## Rules
- Write clean code
- Follow best practices

Question 4: What Trips You Up?

Every project has landmines -- legacy code that looks wrong but works, workarounds for bugs in dependencies, files that must not be touched. Document them here.

Why it matters: Claude is eager to help. If it sees code that looks "wrong," it might try to fix it. If that code is a deliberate workaround, Claude just broke your app.

Good example:

## Gotchas

IMPORTANT: Do NOT modify anything in src/legacy/. This code is scheduled for
removal in Q3 but is still in production. It looks broken but works correctly.

IMPORTANT: The `formatCurrency()` function in src/utils/currency.ts has
intentional floating-point handling that looks like a bug. It compensates for
a rounding issue in Stripe's API. Do not "fix" it.

- The test database uses a non-standard port (5433) to avoid conflicts with
  the production Postgres instance that some developers run locally.
- `pnpm install` must be run from the repo root, not from individual
  packages. The workspace configuration requires it.
- The CI pipeline runs tests against Node 18, not Node 20. Some Node 20
  features are not available.
- Environment variables prefixed with `NEXT_PUBLIC_` are exposed to the
  browser. Never put secrets in them.

Bad example:

## Notes
- Be careful with the code

Question 5: How Do We Work?

Define the collaboration model. How should Claude communicate changes? Should it explain before acting? Should it commit directly or wait for review?

Why it matters: Some developers want Claude to explain everything. Others want it to just make changes silently. Some want atomic commits. Others want a single big commit at the end. Spell it out.

Good example:

## Workflow

- Before making changes, briefly explain what you plan to do and why.
- Make changes in small, atomic steps. Commit after each logical change.
- Always run `pnpm lint` and `pnpm tsc --noEmit` after making changes.
- When creating commits, use conventional commit format:
  `type(scope): description`
  Types: feat, fix, refactor, test, docs, chore
- When I ask you to fix a bug, first write a failing test that reproduces it,
  then fix the bug, then verify the test passes.
- If you are unsure about a change, ask. Do not guess.
- When refactoring, never change behavior. If I ask for a refactor that would
  change behavior, flag it and ask for confirmation.

Complete Example: React/Next.js Project

Here is a full CLAUDE.md that answers all five questions for a React project:

# TaskFlow

Project management SaaS built with Next.js 14, TypeScript, Prisma, and PostgreSQL.
Users create workspaces, invite team members, and manage tasks on Kanban boards.

## Commands
- Install: `pnpm install`
- Dev: `pnpm dev` (port 3000)
- Build: `pnpm build`
- Test: `pnpm test`
- Test single: `pnpm test -- path/to/file.test.ts`
- Lint: `pnpm lint`
- Type check: `pnpm tsc --noEmit`
- DB migrate: `pnpm prisma migrate dev --name <name>`
- DB seed: `pnpm prisma db seed`

## Code Style
- TypeScript strict mode everywhere
- Named exports only -- no default exports
- React: functional components with named function declarations
- Props: `interface {Name}Props` in same file
- State: Zustand for global, useState for local
- Data fetching: React Query, never useEffect
- API responses: `{ data, error, meta }` envelope
- All inputs validated with Zod
- File naming: PascalCase for components, camelCase for utils

## File Structure
- `src/app/` -- pages and API routes (App Router)
- `src/components/` -- shared components
- `src/features/` -- feature-specific components and logic
- `src/hooks/` -- custom hooks
- `src/lib/` -- utility functions, configs, constants
- `prisma/` -- schema and migrations

## Gotchas
IMPORTANT: The `src/lib/auth.ts` file uses a custom JWT implementation
because next-auth did not support our multi-tenant workspace model. Do not
replace it with next-auth.

- The `workspace_id` column in the tasks table has a trigger that auto-sets
  it from the parent board. Never set it manually in application code.
- Tests use a separate test database. Run `pnpm db:test:reset` if tests
  fail with schema errors.

## Workflow
- Explain changes briefly before making them
- Run `pnpm lint && pnpm tsc --noEmit` after every change
- Use conventional commits: `type(scope): description`
- When fixing bugs, write a failing test first
- Ask before modifying any file in `src/lib/auth.ts` or `prisma/schema.prisma`

Complete Example: Python CLI Project

# logparse

CLI tool for parsing, filtering, and analyzing structured log files.
Supports JSON, logfmt, and Common Log Format. Outputs to stdout, CSV, or JSON.

## Commands
- Install (dev): `pip install -e ".[dev]"`
- Run: `python -m logparse <logfile> [options]`
- Test: `pytest`
- Test single: `pytest tests/test_parsers.py::test_json_parser`
- Test with coverage: `pytest --cov=logparse --cov-report=term-missing`
- Lint: `ruff check .`
- Format: `ruff format .`
- Type check: `mypy logparse/`

## Code Style
- Python 3.11+ -- use modern syntax (match/case, type unions with |)
- Type hints on all function signatures -- no untyped public functions
- Docstrings: Google style on all public functions and classes
- Prefer dataclasses over plain dicts for structured data
- Use pathlib.Path, never os.path
- Imports: stdlib first, third-party second, local third (ruff handles sorting)
- Error handling: raise specific exceptions from logparse/exceptions.py
- Never use print() for output -- use the OutputWriter abstraction

## File Structure
- `logparse/` -- main package
- `logparse/parsers/` -- one parser per log format
- `logparse/formatters/` -- output formatters (csv, json, table)
- `logparse/cli.py` -- CLI entry point (Click)
- `tests/` -- mirrors the package structure
- `tests/fixtures/` -- sample log files for testing

## Gotchas
IMPORTANT: The Common Log Format parser in `logparse/parsers/clf.py`
handles a non-standard timestamp format used by legacy Apache configs.
The regex looks wrong but matches real-world data. Do not simplify it.

- The `--follow` flag uses inotify on Linux and kqueue on macOS. Tests
  for this feature are skipped in CI (no filesystem events in containers).
- Some test fixtures contain intentionally malformed log lines. They are
  there to test error handling -- do not "fix" them.

## Workflow
- Always run `pytest` and `ruff check .` after changes
- Type check with `mypy logparse/` before committing
- Write tests for all new parsers and formatters
- When adding a new parser, also add fixture files in tests/fixtures/
- Use conventional commits: `type: description`

5. Writing Effective Rules

The quality of your CLAUDE.md rules directly determines how well Claude follows them. Vague rules get vague compliance. Specific rules get specific compliance.

Use IMPORTANT for Emphasis

When a rule is critical and must never be violated, prefix it with IMPORTANT:. Claude Code treats this keyword with higher priority.

IMPORTANT: Never modify files in the src/generated/ directory. These files
are auto-generated by the GraphQL codegen tool and will be overwritten.

IMPORTANT: All API endpoints must validate input with Zod schemas before
processing. No exceptions.

Do not overuse IMPORTANT:. If everything is important, nothing is important. Reserve it for rules that, if broken, would cause real problems.

Specific Is Better Than Vague

Every rule should be actionable. Claude should be able to read it and know exactly what to do (or not do).

Vague (bad):

- Write good tests
- Use proper error handling
- Follow coding standards
- Keep the code clean

Specific (good):

- Every new function must have at least one unit test
- Catch errors at the API boundary and return { error: { code, message } }
- Use 2-space indentation, single quotes, no semicolons
- Functions must be under 50 lines. If longer, extract helper functions.

Include Examples of What You Want AND Do Not Want

Showing both sides makes rules unambiguous.

## Component Naming

Components use PascalCase with descriptive names.

Good:
  - UserProfileCard.tsx
  - PaymentMethodSelector.tsx
  - OrderSummaryTable.tsx

Bad:
  - userprofilecard.tsx (wrong case)
  - Card.tsx (too generic)
  - UPC.tsx (abbreviation)
## Error Handling

Good:
  try {
    const user = await getUser(id);
    return { data: user };
  } catch (error) {
    logger.error('Failed to get user', { userId: id, error });
    return { error: { code: 'USER_NOT_FOUND', message: 'User does not exist' } };
  }

Bad:
  try {
    const user = await getUser(id);
    return user;
  } catch (e) {
    console.log(e);
    return null;
  }

Keep Under 30 Core Instructions

Claude's context window is large but not infinite. Every instruction in CLAUDE.md takes up space that could be used for reasoning about your actual code. Aim for a focused, high-signal document.

Guidelines for staying lean:

The 60-Second Readability Test

Read your CLAUDE.md from top to bottom. If it takes more than 60 seconds to read and understand, it is probably too long. A new team member should be able to skim it and start being productive.

If you need extensive documentation, use @imports (covered in Advanced Features) to reference external docs instead of inlining everything.

Rule Writing Checklist

For each rule you write, verify:

  1. Is it specific? Can Claude take action on it without asking follow-up questions?
  2. Is it necessary? Does Claude need to be told this, or would it do it anyway?
  3. Is it testable? Could you check whether Claude followed it?
  4. Is it consistent? Does it conflict with any other rule in the file?
  5. Is it scoped? Does it apply to the whole project, or should it be in a rules/ file?

6. Modular Rules with .claude/rules/

For larger projects, one big CLAUDE.md can become unwieldy. The .claude/rules/ directory lets you split instructions into focused, topic-specific files.

Directory Structure

your-project/
  .claude/
    CLAUDE.md              # High-level project overview (keep short)
    rules/
      code-style.md        # Formatting, naming, patterns
      testing.md           # Test conventions and requirements
      git-conventions.md   # Commit messages, branch naming
      security.md          # Security requirements
      frontend/
        react.md           # React-specific patterns
        styles.md          # CSS and styling rules
      backend/
        api.md             # API design rules
        database.md        # Database conventions

All .md files in .claude/rules/ are discovered recursively. Subdirectories are supported for better organization.

File Naming Conventions

Example: code-style.md

# Code Style Rules

## TypeScript
- Use `interface` for object shapes, `type` for unions and intersections
- Prefer `const` over `let`. Never use `var`
- Use template literals over string concatenation
- Destructure function parameters when there are 3+ properties

## Naming
- Variables and functions: camelCase
- Types and interfaces: PascalCase
- Constants: SCREAMING_SNAKE_CASE
- Files: camelCase for utilities, PascalCase for components
- Database columns: snake_case

## Formatting
- 2-space indentation
- Single quotes for strings
- No semicolons (enforced by Prettier)
- Max line length: 100 characters

Example: testing.md

# Testing Conventions

## Structure
- Test files are colocated with source: `Button.test.tsx` next to `Button.tsx`
- Use `describe` blocks to group related tests
- Test names should describe the expected behavior:
  `it('renders error message when form is invalid')`

## Patterns
- Use React Testing Library for component tests
- Query elements by role or text content, never by class name or test ID
- Use `userEvent` over `fireEvent` for user interactions
- Mock API calls with MSW (Mock Service Worker), not jest.fn()
- Each test should be independent -- no shared mutable state between tests

## Coverage
- All new code must have tests
- Bug fixes must include a regression test
- Aim for 80% branch coverage on critical paths (auth, payments, data mutations)

Example: git-conventions.md

# Git Conventions

## Commit Messages
Format: `type(scope): description`

Types:
- feat: new feature
- fix: bug fix
- refactor: code restructuring without behavior change
- test: adding or updating tests
- docs: documentation changes
- chore: tooling, dependencies, config

Scope: the area of the codebase (auth, payments, ui, api, db)

Examples:
- `feat(auth): add password reset flow`
- `fix(payments): handle Stripe webhook retry correctly`
- `refactor(api): extract validation middleware`

## Branches
- Feature branches: `feature/TICKET-short-description`
- Bug fixes: `fix/TICKET-short-description`
- Always branch from `main`

Path-Scoped Rules with YAML Frontmatter

Rules can be scoped to specific files using YAML frontmatter with a paths field. These conditional rules only load when Claude is working with files that match the specified glob patterns.

---
paths:
  - "src/api/**/*.ts"
---

# API Development Rules

- All API endpoints must include input validation with Zod
- Use the standard error response format from src/lib/errors.ts
- Include OpenAPI documentation comments on every endpoint
- Rate limiting is required on all public endpoints
- Authentication middleware must be applied to all non-public routes
---
paths:
  - "**/*.test.ts"
  - "**/*.test.tsx"
  - "**/*.spec.ts"
---

# Test File Rules

- Use describe/it blocks, not test()
- One assertion per test when possible
- Mock external services, never call real APIs in tests
- Use factories for test data, not inline object literals

Rules without a paths field are loaded unconditionally and apply to all files.

Supported Glob Patterns

Pattern Matches
**/*.ts All TypeScript files in any directory
src/**/* All files under src/
*.md Markdown files in the project root only
src/components/*.tsx React components in a specific directory
src/**/*.{ts,tsx} Both .ts and .tsx files under src/
{src,lib}/**/*.ts TypeScript files in either src/ or lib/

Symlinks

The .claude/rules/ directory supports symlinks. This is useful for sharing common rules across multiple projects:

# Symlink a shared rules directory
ln -s ~/company-claude-rules/shared .claude/rules/shared

# Symlink an individual rule file
ln -s ~/company-claude-rules/security.md .claude/rules/security.md

User-Level Rules

You can also create personal rules at ~/.claude/rules/ that apply to all your projects:

~/.claude/rules/
  preferences.md       # Your personal coding preferences
  workflows.md         # Your preferred work patterns

User-level rules are loaded before project rules, giving project rules higher priority when they conflict.

When to Use rules/ vs. Main CLAUDE.md

Content Where to Put It
Project overview, architecture Main CLAUDE.md
Build/test/run commands Main CLAUDE.md
Key gotchas and warnings Main CLAUDE.md
Language-specific coding standards .claude/rules/code-style.md
Testing conventions .claude/rules/testing.md
Git workflow rules .claude/rules/git-conventions.md
API-only rules (path-scoped) .claude/rules/api.md with frontmatter
Test-only rules (path-scoped) .claude/rules/testing.md with frontmatter

Rule of thumb: If it applies to everything, put it in CLAUDE.md. If it applies to a specific topic or file type, put it in a rules file.


7. Advanced Features

@ Imports for Referencing External Docs

CLAUDE.md files can import additional files using @path/to/file syntax. This keeps your CLAUDE.md lean while giving Claude access to detailed documentation.

# MyProject

See @README.md for project overview and @package.json for available commands.

## Additional Instructions
- Follow the API design guidelines in @docs/api-design.md
- Git workflow is documented at @docs/git-workflow.md
- Component patterns are described in @docs/component-patterns.md

Key details:

Example with home directory imports:

If you work across multiple git worktrees, CLAUDE.local.md only exists in one. Use a home-directory import so all worktrees share the same personal instructions:

# Individual Preferences
- @~/.claude/my-project-instructions.md

Path-Scoped Rules (YAML Frontmatter with Globs)

As covered in the Modular Rules section, rules files can include YAML frontmatter to scope them to specific file patterns. This is one of the most powerful features for large codebases.

Multiple patterns:

---
paths:
  - "src/**/*.ts"
  - "lib/**/*.ts"
  - "tests/**/*.test.ts"
---

# TypeScript Rules
Use strict mode. Prefer interfaces over types for object shapes.

Brace expansion:

---
paths:
  - "src/**/*.{ts,tsx}"
  - "{src,lib}/**/*.ts"
---

Auto Memory

Auto memory is Claude's own notebook. Unlike CLAUDE.md files that contain instructions you write, auto memory contains notes Claude writes for itself.

What Claude remembers automatically:

Managing auto memory:

How the directory structure works:

~/.claude/projects/<project>/memory/
  MEMORY.md              # Index file -- first 200 lines loaded at startup
  debugging.md           # Detailed debugging notes (loaded on demand)
  api-conventions.md     # API patterns (loaded on demand)

Claude keeps MEMORY.md concise by moving detailed notes into separate topic files that it reads on demand when needed.

The /memory Command

Run /memory during a session to open a file selector showing all your memory files (both CLAUDE.md files and auto memory). You can select any file to open it in your system editor for direct editing.

This is useful for:

settings.json vs. CLAUDE.md: What Goes Where

These two configuration systems serve different purposes. Do not confuse them.

CLAUDE.md is for instructions and context:

settings.json is for system behavior:

Settings file locations:

~/.claude/settings.json               # Personal, all projects
.claude/settings.json                 # Project, committed to git
.claude/settings.local.json           # Personal project overrides, gitignored

Managed settings (enterprise):

macOS:      /Library/Application Support/ClaudeCode/managed-settings.json
Linux/WSL:  /etc/claude-code/managed-settings.json
Windows:    C:\Program Files\ClaudeCode\managed-settings.json

Example settings.json:

{
  "$schema": "https://json.schemastore.org/claude-code-settings.json",
  "permissions": {
    "allow": [
      "Bash(pnpm test *)",
      "Bash(pnpm lint)",
      "Bash(pnpm build)",
      "Bash(git status)",
      "Bash(git diff *)"
    ],
    "deny": [
      "Bash(rm -rf *)",
      "Bash(git push --force *)"
    ]
  }
}

Rule of thumb: If it changes what Claude knows, it goes in CLAUDE.md. If it changes what Claude is allowed to do, it goes in settings.json.


8. Team Collaboration Patterns

Sharing CLAUDE.md via Git

The project CLAUDE.md (either ./CLAUDE.md or ./.claude/CLAUDE.md) and all files in .claude/rules/ are designed to be committed to version control. This means every team member gets the same instructions automatically.

Workflow:

  1. One person creates the initial CLAUDE.md (or run /init)
  2. The team reviews it in a PR, just like any other code change
  3. Merge it to main
  4. Everyone on the team now has the same Claude instructions
  5. Update it like any other living document -- PRs, reviews, iteration

Team Conventions for CLAUDE.md Maintenance

Establish ground rules for how your team maintains the file:

## CLAUDE.md Maintenance

- Changes to CLAUDE.md require a PR review, just like code changes
- When you discover a new gotcha, add it immediately and commit
- Review CLAUDE.md quarterly to remove outdated rules
- If Claude repeatedly makes the same mistake, add a rule for it
- Tag CLAUDE.md changes with the `docs` type:
  `docs: add API validation rule to CLAUDE.md`

Using .claude/rules/ for Different Concerns

Different team members often care about different concerns. The rules directory lets you divide ownership:

.claude/rules/
  code-style.md         # Owned by: tech lead
  testing.md            # Owned by: QA engineer
  security.md           # Owned by: security team
  api-design.md         # Owned by: backend lead
  accessibility.md      # Owned by: frontend lead
  deployment.md         # Owned by: DevOps

Each file can be reviewed and maintained by the person most knowledgeable about that topic.

Resolving Conflicts Between Team Members' Preferences

Inevitably, team members will have different preferences. Handle this with the hierarchy:

Team-shared rules go in project CLAUDE.md or .claude/rules/:

# These are team conventions -- everyone follows these
- Use Prettier for formatting (config in .prettierrc)
- Commit messages use conventional commits format
- Tests are required for all new features

Personal preferences go in CLAUDE.local.md:

# My personal preferences -- only I see these
- I prefer verbose explanations before code changes
- When I say "run tests," skip the E2E suite unless I specify
- I like to see the diff before you commit

Using CLAUDE.local.md for Personal Overrides

CLAUDE.local.md is automatically gitignored. Use it for:

Example:

# Local Overrides

- My local API runs on port 4001 (team default is 4000)
- I use Docker for PostgreSQL: `docker compose up -d db`
- When running tests, use `--reporter=verbose` so I can see individual test names
- I prefer TypeScript errors shown inline, not in a separate panel

Git Tagging Pattern

Tag your CLAUDE.md at significant versions so you can track how your instructions evolve:

# After a major CLAUDE.md update
git tag claude-md-v2 -m "Added API validation rules and testing conventions"

Fix Mistakes in Real Time

When Claude does something wrong because of a missing or unclear rule:

  1. Correct Claude in the current session
  2. Immediately add the rule to CLAUDE.md
  3. Commit the change
  4. The next session (and every session after) will get it right

This is the "fix the root cause" approach. Do not just correct Claude once and move on -- add the rule so it never happens again.


9. Complete Example CLAUDE.md Files

Example 1: React/Next.js Web Application

# Acme Dashboard

Internal business intelligence dashboard built with Next.js 14, TypeScript,
and Tremor for data visualization. Connects to a PostgreSQL analytics database
via Prisma.

## Commands
- Install: `pnpm install`
- Dev: `pnpm dev` (port 3000)
- Build: `pnpm build`
- Test: `pnpm test`
- Test single file: `pnpm test -- path/to/file.test.tsx`
- Lint: `pnpm lint`
- Type check: `pnpm tsc --noEmit`
- Storybook: `pnpm storybook` (port 6006)
- DB migrate: `pnpm prisma migrate dev --name <name>`
- DB seed: `pnpm prisma db seed`

## Architecture
- `src/app/` -- Next.js App Router (pages, layouts, API routes)
- `src/components/` -- shared UI components
- `src/features/` -- feature modules (each has components/, hooks/, utils/)
- `src/lib/` -- shared utilities, database client, auth helpers
- `prisma/` -- schema and migrations

## Code Style
- TypeScript strict mode, no `any` types
- Named exports only
- React: functional components with named function declarations
- Props: `interface {Name}Props` in same file, above the component
- Hooks: `use{Name}` in `src/hooks/` or feature-specific `hooks/` directory
- State: Zustand stores in `src/stores/`, local state with useState
- Data fetching: React Query, never useEffect
- Styling: Tailwind CSS utility classes, no inline styles, no CSS modules
- Charts: Tremor components, custom charts use Recharts

## API Routes
- All routes return `{ data, error }` envelope
- Input validation: Zod schemas in `src/lib/validators/`
- Auth: check session with `getServerSession()` at the top of every route
- Error format: `{ error: { code: string, message: string } }`

## Testing
- Framework: Vitest + React Testing Library
- Colocated tests: `Component.test.tsx` next to `Component.tsx`
- Query by role or text, never by test ID
- Mock API responses with MSW handlers in `src/mocks/`
- Database tests use a separate test database (see .env.test)

## Gotchas
IMPORTANT: Do not modify `src/lib/legacy-auth.ts`. It handles SSO for
clients still on the legacy auth system. Replacement is planned for Q3.

IMPORTANT: The `analytics_events` table uses partitioning by month. Always
include a date range filter in queries to avoid full table scans.

- Tremor components have limited customization. If you need something custom,
  use Recharts directly instead of fighting Tremor's API.
- The `seed.ts` file generates deterministic fake data. If you change the
  seed, snapshot tests will fail.
- CI runs on Node 18. Do not use Node 20+ features.

## Workflow
- Explain planned changes before implementing
- Run `pnpm lint && pnpm tsc --noEmit` after every change
- Conventional commits: `type(scope): description`
- When fixing bugs, write a failing test first

Example 2: Python CLI Tool

# deployer

CLI tool for deploying applications to Kubernetes clusters. Reads deploy
manifests from YAML files, validates them, and applies them using kubectl.

## Commands
- Install: `pip install -e ".[dev]"`
- Run: `python -m deployer <manifest.yaml> [options]`
- Test: `pytest`
- Test verbose: `pytest -v`
- Test single: `pytest tests/test_validators.py -k test_name`
- Coverage: `pytest --cov=deployer --cov-report=term-missing`
- Lint: `ruff check .`
- Format: `ruff format .`
- Type check: `mypy deployer/`
- Build: `python -m build`

## Architecture
- `deployer/` -- main package
  - `cli.py` -- Click-based CLI entry point
  - `manifest.py` -- YAML manifest parsing and validation
  - `k8s/` -- Kubernetes client wrappers
  - `validators/` -- manifest validation rules
  - `formatters/` -- output formatters (table, json, yaml)
  - `exceptions.py` -- custom exception hierarchy
- `tests/` -- mirrors package structure
  - `fixtures/` -- sample YAML manifests for testing
  - `conftest.py` -- shared fixtures and mocks

## Code Style
- Python 3.11+ -- use modern syntax (match/case, `X | Y` unions, `Self`)
- Type hints on all function signatures
- Google-style docstrings on all public functions and classes
- dataclasses for structured data, never plain dicts for domain objects
- pathlib.Path everywhere, never os.path
- Use specific exceptions from `deployer/exceptions.py`
- No print() -- use `click.echo()` for CLI output, `logging` for debug
- Prefer composition over inheritance
- Limit function length to 40 lines

## Testing
- pytest with fixtures defined in conftest.py
- Use `tmp_path` fixture for file operations
- Mock kubectl calls -- never invoke real kubectl in tests
- Factory functions for test data in `tests/factories.py`
- Parametrize tests when testing multiple input variations
- All new validators must have both valid and invalid test cases

## Gotchas
IMPORTANT: The kubectl wrapper in `deployer/k8s/client.py` uses subprocess,
not the Python kubernetes library. This is intentional -- the Python library
has version compatibility issues with newer cluster versions.

- Some YAML fixtures in `tests/fixtures/` are intentionally invalid (they
  test error handling). Do not fix them.
- The `--dry-run` flag must ALWAYS work without a real cluster connection.
  Tests for dry-run mode should never mock a cluster.
- The manifest schema in `deployer/manifest.py` supports both v1 and v2
  formats. Both must be maintained until v1 deprecation in Q4.

## Workflow
- Run `pytest && ruff check . && mypy deployer/` after every change
- Write tests for all new validators and formatters
- Use conventional commits: `type: description`
- If adding a new CLI option, update both the `--help` text and README.md

Example 3: Mobile App (React Native)

# FitLog

Fitness tracking mobile app built with React Native (Expo), TypeScript,
and Firebase. Available on iOS and Android. Users log workouts, track
progress, and follow training programs.

## Commands
- Install: `npx expo install`
- Start: `npx expo start`
- iOS: `npx expo run:ios`
- Android: `npx expo run:android`
- Test: `jest`
- Test single: `jest path/to/file.test.tsx`
- Lint: `npx eslint .`
- Type check: `npx tsc --noEmit`
- EAS build (dev): `eas build --profile development`
- EAS build (prod): `eas build --profile production`

## Architecture
- `app/` -- Expo Router file-based routing
  - `(tabs)/` -- main tab navigation
  - `(auth)/` -- authentication flow
  - `workout/` -- workout logging screens
- `components/` -- shared UI components
- `features/` -- feature-specific logic (hooks, utils, types)
- `services/` -- Firebase services, API clients
- `stores/` -- Zustand state stores
- `constants/` -- app-wide constants, theme, config

## Code Style
- TypeScript strict mode
- Functional components with named function declarations
- Props interface: `{Name}Props` in same file
- Navigation: Expo Router, never React Navigation directly
- State: Zustand for global state, useState for component state
- Async storage: use the `useStorage` hook from `hooks/useStorage.ts`
- Styling: StyleSheet.create() at bottom of component file
- Colors, spacing, fonts: always use constants from `constants/theme.ts`
- Animations: Reanimated 3 for gesture-based, LayoutAnimation for simple

## Firebase Rules
- Auth: Firebase Auth with email/password and Google Sign-In
- Database: Firestore with the following collections:
  - `users/{uid}` -- user profile
  - `users/{uid}/workouts/{id}` -- workout logs
  - `users/{uid}/programs/{id}` -- training programs
  - `exercises` -- global exercise database (read-only for users)
- Storage: Firebase Storage for profile photos only
- All Firestore reads/writes go through `services/firestore.ts`

## Testing
- Jest + React Native Testing Library
- Test files colocated: `Component.test.tsx`
- Mock Firebase with `__mocks__/firebase/` directory
- Use `renderWithProviders()` from `tests/utils.tsx` for components
  that need navigation or store context
- Snapshot tests only for static UI components (not interactive ones)

## Gotchas
IMPORTANT: Never import directly from `firebase/firestore`. Always use
the wrapper functions in `services/firestore.ts` which handle offline
persistence and error logging.

IMPORTANT: The `exercises` collection is seeded from a CSV file during
deployment. Do not write to it from the app. It is read-only.

- Expo SDK upgrades require careful testing on both platforms. Do not
  upgrade the SDK without explicit instruction.
- The workout timer uses `react-native-background-timer` for background
  execution. It behaves differently on iOS and Android -- test both.
- Push notifications use Expo Notifications, not Firebase Cloud Messaging
  directly. The FCM token is bridged through Expo's API.
- The `useWorkoutTimer` hook has a known race condition when the app
  backgrounds and foregrounds rapidly. There is a workaround in place --
  do not refactor the timer logic without understanding the issue.

## Workflow
- Test on both iOS and Android when making UI changes
- Run `jest && npx tsc --noEmit` after every change
- Use conventional commits: `type(scope): description`
  Scopes: workout, auth, profile, programs, ui
- When adding a new screen, create the route file in app/ first,
  then build the screen component in the feature directory

10. Self-Check Checklist

Run through this checklist after creating or updating your CLAUDE.md.

Content Coverage

Quality

Organization

Maintenance

Git Hygiene


11. Exercises

Exercise 1: Bootstrap with /init and Customize

  1. Open Claude Code in a project you are actively working on
  2. Run /init to generate a starter CLAUDE.md
  3. Read the generated file critically -- what did it get right? What is missing?
  4. Add at least 3 rules specific to your team's conventions
  5. Add at least 2 gotchas that Claude would not have discovered from scanning files
  6. Remove any generic advice that does not add value
  7. Run the Self-Check Checklist against your result

Exercise 2: The 5-Question Audit

Take an existing project and write a CLAUDE.md from scratch using only the 5-Question Framework:

  1. Write the "What is this?" section (2-3 sentences max)
  2. Write the "How do you run things?" section (every command you use in a typical day)
  3. Write the "What are your rules?" section (10-15 specific rules)
  4. Write the "What trips you up?" section (at least 3 gotchas)
  5. Write the "How do we work?" section (your preferred collaboration style)
  6. Have Claude use the file for a real task and evaluate whether it followed the rules

Exercise 3: Modular Rules Refactor

Take a CLAUDE.md that is over 150 lines and refactor it into modular rules:

  1. Identify 3-5 distinct topics in the file
  2. Create .claude/rules/ directory
  3. Move topic-specific rules into separate files
  4. Add YAML frontmatter with paths to at least one file
  5. Verify the main CLAUDE.md is now under 80 lines
  6. Test that Claude still follows all the rules

Exercise 4: Team vs. Personal Split

  1. Review your current CLAUDE.md
  2. Identify which rules are team conventions (should be shared) and which are personal preferences (should be local)
  3. Move personal preferences to CLAUDE.local.md
  4. Move cross-project personal preferences to ~/.claude/CLAUDE.md
  5. Verify that the project CLAUDE.md contains only team-shared rules

Exercise 5: The Mistake-Driven Rule

  1. Start a Claude Code session with your current CLAUDE.md
  2. Give Claude a task and observe where it deviates from your expectations
  3. For each deviation, write a specific rule that would prevent it
  4. Add the rules to your CLAUDE.md
  5. Start a new session and give Claude the same task
  6. Verify that the new rules fixed the behavior

Exercise 6: Path-Scoped Rules

  1. Create a .claude/rules/ directory in your project
  2. Write a rule file scoped to your API files:
    ---
    paths:
      - "src/api/**/*.ts"
    ---
    # API-specific rules here
    
  3. Write a rule file scoped to your test files:
    ---
    paths:
      - "**/*.test.ts"
      - "**/*.test.tsx"
    ---
    # Testing-specific rules here
    
  4. Verify that the API rules are applied when Claude works on API files
  5. Verify that the testing rules are applied when Claude works on test files
  6. Verify that neither set of rules interferes with general work

Exercise 7: Import-Based Documentation

  1. Identify a detailed document in your project (API spec, architecture doc, style guide)
  2. Instead of duplicating its content in CLAUDE.md, reference it with an import:
    Follow the API design guidelines in @docs/api-design.md
    
  3. Verify that Claude can access and follow the imported document
  4. Compare this approach to inlining the content -- which keeps CLAUDE.md leaner?

12. Pro Tips from Boris Cherny

Boris Cherny is an engineer at Anthropic who works on Claude Code. His publicly documented workflow includes several insights about CLAUDE.md usage.

Tip 1: Team Shares a Single CLAUDE.md on Git

Your project CLAUDE.md should be committed and shared like any other source file. Every Claude Code instance across the team reads the same instructions. This creates consistency -- Claude follows the same rules whether your frontend developer or your backend developer is using it.

Tip 2: Fix Mistakes in Real Time

When Claude does something wrong, do not just correct it in conversation and move on. Add a rule to CLAUDE.md immediately. If Claude used npm instead of pnpm, add: "Use pnpm, not npm, for all package management commands." Commit the change. Now every future session (for you and your team) gets it right.

Tip 3: Use CLAUDE.md for Shared Context, Not Just Rules

Beyond coding standards, CLAUDE.md is excellent for current project context that multiple Claude sessions need:

## Current Sprint Context
- Working on: User Authentication (Sprint 14)
- API base URL: /api/v2
- Database: PostgreSQL with Prisma ORM
- Active feature flags: ENABLE_SSO, ENABLE_MFA

Tip 4: Keep It Lean

Boris runs multiple parallel Claude sessions. Every token in CLAUDE.md is loaded into every session. A 500-line CLAUDE.md consumed across 5 sessions is 2,500 lines of context overhead. Keep the main file focused and use @imports or .claude/rules/ for detailed documentation.

Tip 5: Tag on GitHub

When you make significant changes to your CLAUDE.md, tag the commit. This lets you track how your instructions evolve over time and roll back if a rule causes problems.

Tip 6: Reference External Docs Instead of Duplicating

Instead of copying your API documentation into CLAUDE.md, reference it:

See @docs/API_REFERENCE.md for endpoint specifications.
See @docs/DATABASE_SCHEMA.md for table definitions.

This prevents CLAUDE.md from becoming a maintenance burden where changes need to be made in two places.

Tip 7: Slash Commands for Repetitive Patterns

If you find yourself giving Claude the same instructions repeatedly (like a specific commit-push-PR workflow), create a custom slash command instead of putting it in CLAUDE.md. CLAUDE.md is for persistent context and rules, not for scripting workflows.


13. Anti-Patterns

Anti-Pattern 1: The Novel

Problem: A 500+ line CLAUDE.md that covers every possible scenario.

Why it fails: Every line consumes context window. Claude may miss important rules buried in a wall of text. Contradictions become likely as the file grows.

Fix: Keep the main file under 200 lines. Use .claude/rules/ for detailed topic-specific rules. Use @imports for reference documentation.

Anti-Pattern 2: Vague Instructions

Problem:

- Write clean code
- Follow best practices
- Make sure the code works
- Use proper error handling

Why it fails: These are not actionable. Claude already tries to write working code. You have not told it anything useful.

Fix: Be specific:

- Functions must be under 50 lines
- All errors must be caught at the API boundary and returned as { error: { code, message } }
- No any types in TypeScript
- All async functions must have try/catch blocks

Anti-Pattern 3: Duplicating Default Behavior

Problem:

- Write syntactically valid code
- Use proper variable names
- Import dependencies before using them
- Do not write code with bugs

Why it fails: Claude does these things by default. You are wasting context on things that do not need to be said.

Fix: Only include rules that make YOUR project different from generic best practices.

Anti-Pattern 4: Contradictory Rules

Problem:

- Always use arrow functions for components
...
(200 lines later)
...
- Use named function declarations for components

Why it fails: Claude picks one randomly, or worse, alternates between the two inconsistently.

Fix: Review for contradictions periodically. Use the Self-Check Checklist.

Anti-Pattern 5: Stale Instructions

Problem: Rules that reference files, patterns, or tools that no longer exist in the project.

Why it fails: Claude tries to follow the instruction and either fails or creates confusion. "Use the formatDate() helper from src/utils/dates.ts" -- but that file was deleted three months ago.

Fix: Review CLAUDE.md when you make significant changes to the project. Treat it like a living document.

Anti-Pattern 6: Putting Settings in CLAUDE.md

Problem:

- Allow Claude to run `npm test` without asking
- Block Claude from using `rm -rf`

Why it fails: Permission rules belong in settings.json, not CLAUDE.md. CLAUDE.md is for instructions and context, not system configuration.

Fix: Use settings.json for permissions:

{
  "permissions": {
    "allow": ["Bash(npm test *)"],
    "deny": ["Bash(rm -rf *)"]
  }
}

Anti-Pattern 7: Personal Preferences in Project CLAUDE.md

Problem: Committing your personal preferences to the shared project CLAUDE.md.

- I like verbose explanations before code changes
- Skip E2E tests when I say "run tests"
- My dev server runs on port 3001

Why it fails: Your teammates now get your personal preferences in their sessions.

Fix: Personal preferences go in CLAUDE.local.md (project-specific, gitignored) or ~/.claude/CLAUDE.md (global, all projects).

Anti-Pattern 8: The Entire Documentation

Problem: Pasting your entire README, API docs, and architecture docs into CLAUDE.md.

Why it fails: Massive context consumption. Claude spends tokens processing documentation it may not need for the current task.

Fix: Use @imports to reference external docs. Keep CLAUDE.md focused on rules and conventions. Claude can read referenced files on demand when it needs them.

Anti-Pattern 9: Never Updating After /init

Problem: Running /init, committing the generated file, and never touching it again.

Why it fails: /init generates a reasonable starting point, but it cannot know your team's conventions, your project's gotchas, or your workflow preferences. The file becomes stale quickly.

Fix: Treat /init as a first draft. Customize immediately. Update continuously as you discover what Claude gets wrong.


14. Official Documentation Links

Primary References

Quick Reference

Topic Documentation URL
Memory & CLAUDE.md https://code.claude.com/docs/en/memory
Settings & Permissions https://code.claude.com/docs/en/settings
Best Practices https://code.claude.com/docs/en/best-practices
Sub-Agents https://code.claude.com/docs/en/sub-agents
Hooks https://code.claude.com/docs/en/hooks
MCP Servers https://code.claude.com/docs/en/mcp
Common Workflows https://code.claude.com/docs/en/common-workflows
Full Documentation Index https://code.claude.com/docs/llms.txt

Community Resources


Last Updated: 2026-02-20 Compiled from official Anthropic documentation, Boris Cherny's published workflow, and community best practices