Brainfile › Claude Code Rules Files Guide
Claude Code Deep Dive

Claude Code Rules Files
The Complete Guide to .claude/rules/

Most developers put everything in CLAUDE.md and hit a wall. The .claude/rules/ directory is how serious teams keep Claude Code sharp across complex projects.

What Are Rules Files → See Real Examples
In this guide

What Are .claude/rules/ Files?

The .claude/rules/ directory is a subdirectory inside your project’s .claude/ folder. Any .md file you place there is automatically loaded by Claude Code and included in the system prompt alongside your main CLAUDE.md.

Think of it as modular configuration. Instead of one long project instruction file, you split Claude’s behavioral rules into separate, focused files by topic — each with its own name, scope, and ownership.

your-project/ ├── CLAUDE.md # main project context + high-level rules ├── .claude/ │ ├── settings.json # tool permissions, allowed directories │ ├── settings.local.json # local overrides (gitignored) │ └── rules/ # <-- this is what we're covering │ ├── testing-rules.md │ ├── deploy-rules.md │ ├── coding-standards.md │ ├── api-rules.md │ └── workflow-rules.md └── src/ └── ...

Every .md file in .claude/rules/ gets read on session start. Claude treats their contents as additional standing instructions — exactly as authoritative as what’s in CLAUDE.md, just organized into separate files.

Key Fact

Rules files don’t require any special format. A plain markdown file with bullet points, headers, or prose all work. Claude reads them as instructions, not as documentation.

This feature is part of Claude Code’s broader context engineering system, which gives teams fine-grained control over what Claude knows and follows without polluting the context window with a wall of text.

CLAUDE.md vs .claude/rules/ — When to Use Each

The distinction matters once your project has more than one person, more than one workflow, or more than one domain of concern. They serve different jobs.

Dimension CLAUDE.md .claude/rules/*.md
Purpose Project-wide context: what this codebase is, how it’s structured, key commands Behavioral rules by domain: how Claude should act in specific scenarios
Granularity One file covering the whole project Many files, each covering one concern (testing, deploy, style, API, etc.)
Ownership Usually owned by project lead / tech lead Each file can be owned by a different team member or squad
Typical contents Tech stack, repo structure, common commands, architecture decisions, critical laws Testing requirements, deploy gates, naming conventions, API usage rules, PR workflow
Update frequency Changes when architecture or project fundamentals change Changes when specific workflows evolve; can be updated independently
Checkin Always committed to git Usually committed; can create local-only rules files too (add to .gitignore)
Conflict behavior Both are loaded — Claude sees all instructions. More specific rules files generally take precedence where there’s overlap. Same — Claude sees all. Write rules to be complementary, not contradictory.

The mental model: CLAUDE.md answers “what is this project?” Rules files answer “how should you behave in specific situations?”

Common Mistake

Developers dump everything into CLAUDE.md — project context, coding standards, testing rules, deploy process, PR workflow, API conventions — until it’s 800+ lines and Claude starts ignoring the bottom half. Rules files solve this by keeping each domain tight and readable.

For a full breakdown of all memory layers in Claude Code, see the Claude Code Memory Guide.

How Claude Code Loads Rules Files

Understanding the loading mechanism helps you write better rules and debug unexpected behavior.

  1. 1

    Session start scan

    When you start a Claude Code session in a project directory, Claude scans for CLAUDE.md in the current directory and parent directories, then reads all .md files found in .claude/rules/.

  2. 2

    All files injected into system prompt

    The contents of every rules file are concatenated and injected into Claude’s system prompt. Claude sees them as one continuous block of instructions alongside your CLAUDE.md. There’s no lazy loading — everything in .claude/rules/ is always active.

  3. 3

    File order

    Files are loaded in filesystem order (typically alphabetical). If you need a specific rule to appear first, prefix filenames: 00-core-rules.md, 01-testing-rules.md, 02-deploy-rules.md.

  4. 4

    Rules stay active for the full session

    Unlike conversation context that can be compacted away, rules files are re-read at session start and stay active. They don’t degrade as the session gets long.

  5. 5

    Token budget consideration

    Every rule file consumes context window tokens. Total context from CLAUDE.md + all rules files is typically in the 500–3,000 token range for well-structured projects. Avoid making rules files into documentation repositories — keep rules actionable and concise.

How it fits the full hierarchy

Load order: global ~/.claude/CLAUDE.md → project CLAUDE.md.claude/rules/*.md.claude/settings.json permissions → conversation context. Each layer adds to the previous; nothing is overwritten until conversation context where specifics win.

Why Modular Rules Files Beat a Monolith CLAUDE.md

Once you’ve used modular rules files on a real project, going back to a single CLAUDE.md feels like writing your entire codebase in one file. The benefits compound with team size and project complexity.

Separation of concerns

Each file does one job

Testing rules stay in testing-rules.md. Deploy rules stay in deploy-rules.md. Updates to one don’t risk clobbering the other. Grep is trivial.

No more hunting through 600 lines of CLAUDE.md to find where you wrote the API rate limit rules.
Team ownership

Distributed authorship

Your backend engineer owns api-rules.md. Your DevOps engineer owns deploy-rules.md. Your QA lead owns testing-rules.md. No merge conflicts on the same file.

Git blame works correctly — you know exactly who wrote each rule and when.
Version control clarity

Clean diffs

When deploy-rules.md changes, the PR diff is focused on deploy rules only. Reviewers can evaluate the change without reading unrelated rules.

Compare this to a CLAUDE.md diff that touches 40 lines spanning testing, style, and API rules mixed together.
Conditional activation

Enable or disable by file

Need to temporarily disable database migration rules? Rename the file or move it. No surgical editing of a monolith. Add a .disabled extension and rules files won’t be picked up.

Useful for onboarding: add a beginner-friendly rules file, remove it when the dev ramps up.

There’s also a cognitive benefit for Claude. A well-named file like testing-rules.md signals to Claude that the following instructions are specifically about testing. That context — file name included — appears in the system prompt and helps Claude apply the right rules to the right actions.

5 Rules Files With Full Contents

These are production-quality examples you can adapt directly. Each file follows the same structure: clear heading, actionable bullet rules, no filler text. Claude responds best to direct imperatives, not explanations of why a rule exists.

1. testing-rules.md

.claude/rules/testing-rules.md
# Testing Rules ## Coverage Requirements - Every new function or method MUST have at least one unit test before the PR is considered complete. - Minimum 80% line coverage on all new files. Do not merge if coverage drops below current baseline. - Integration tests are required for any code that touches the database, file system, or external APIs. - Snapshot tests for React components are acceptable but must be accompanied by at least one behavior test. ## Test Structure - Use describe() blocks to group related tests. Nest at most two levels deep. - Test names must describe the behavior being tested: "returns null when input is empty", not "test 1". - Each test asserts exactly one behavior. Split multi-assertion tests into separate tests. - Use beforeEach() to set up state; never rely on test execution order. ## Mocking Policy - Mock at the module boundary, not at the implementation detail. Mock the HTTP client, not the internal fetch call. - Never mock the module under test itself. - All mocks MUST be cleared in afterEach(). Use jest.clearAllMocks() in the global setup. - Prefer msw (Mock Service Worker) over manual fetch mocking for API tests. ## What NOT to Test - Don't write tests for third-party library internals. - Don't test TypeScript type definitions — the compiler handles that. - Don't snapshot-test third-party component output. ## Running Tests - Run `npm test` before suggesting any code is complete. - Run `npm run test:coverage` when adding new files and report the coverage delta.

2. deploy-rules.md

.claude/rules/deploy-rules.md
# Deploy Rules ## Hard Gates — Never Skip These - NEVER deploy directly to production. All deploys go through staging first. - NEVER run `git push --force` to main or production branches. - NEVER run database migrations in the same deployment as application code unless explicitly approved. - NEVER remove feature flags that are still referenced in code. ## Pre-Deploy Checklist - All CI checks green on the source branch before deploying. - Run `npm run build` locally and confirm zero errors. - Run `npm run lint` — zero errors, warnings acceptable. - Confirm all environment variables for the target environment are documented in `.env.example`. - Any dependency upgrade (major version) requires a staging soak of at least 24 hours before production. ## Rollback Protocol - Know the rollback command before you deploy. For this project: `./scripts/rollback.sh <version>`. - Database migrations that cannot be rolled back automatically require a manual rollback plan documented in the PR. - If a deploy causes an error rate spike > 1% within 10 minutes, roll back immediately. ## Secrets Management - Never commit secrets, tokens, or API keys to the repository. - All secrets live in the secret manager (see docs/secrets.md for access). - If you see a hardcoded secret anywhere in the codebase, flag it immediately — do not work around it. ## Branch Strategy - Feature branches: `feature/TICKET-description` - Hotfix branches: `hotfix/TICKET-description` - Release branches: `release/vX.Y.Z` - Squash commits when merging feature branches to main. Keep history clean.

3. coding-standards.md

.claude/rules/coding-standards.md
# Coding Standards ## Language: TypeScript - Strict mode always on (`"strict": true` in tsconfig). No exceptions. - No `any` types. If a type is genuinely unknown, use `unknown` and narrow it explicitly. - Return types must be explicit on all exported functions. - Prefer `interface` for object shapes, `type` for unions, intersections, and utility types. - Use `readonly` on arrays and objects that should not be mutated. ## Naming Conventions - Components: PascalCase — `UserProfile.tsx`, `OrderSummary.tsx` - Hooks: camelCase with `use` prefix — `useUserData`, `useOrderStatus` - Utilities: camelCase — `formatCurrency`, `parseDate` - Constants: SCREAMING_SNAKE_CASE — `MAX_RETRY_COUNT`, `API_BASE_URL` - Boolean variables: prefix with `is`, `has`, `should`, `can``isLoading`, `hasError` ## File Organization - One exported component per file. No exceptions. - Co-locate tests with source: `UserProfile.tsx` + `UserProfile.test.tsx` in the same directory. - Import order: 1) React / framework, 2) third-party, 3) internal, 4) styles. Separate groups with blank lines. - No relative imports that go more than two levels up (`../../..` is a code smell — use path aliases). ## Function Design - Functions must do one thing. If you need to describe it with "and," split it. - Maximum function length: 50 lines. Beyond that, extract helper functions. - Pure functions over stateful functions where possible. - Throw specific error types, not generic `Error`. See `src/errors.ts` for the error registry. ## Comments Policy - Comment the why, not the what. Code explains what; comments explain why. - Every exported function needs a JSDoc comment with at minimum a description and @returns note. - TODO comments must include a ticket number: `// TODO(ENG-1234): fix edge case with empty arrays` - Dead code is deleted, not commented out. Use git if you need to recover it.

4. api-rules.md

.claude/rules/api-rules.md
# API Rules ## REST API Design - Use plural nouns for resource endpoints: `/users`, `/orders`, not `/user`, `/order`. - HTTP verbs map strictly: GET (read), POST (create), PUT (replace), PATCH (partial update), DELETE (remove). - All endpoints return JSON. Content-Type header is always `application/json`. - Error responses must follow the project error schema: `{ "error": { "code": "...", "message": "...", "details": {} } }` - Paginated responses use: `{ "data": [...], "pagination": { "page", "limit", "total", "next_cursor" } }` ## Versioning - All API routes are versioned in the URL path: `/api/v1/users` - Breaking changes require a new version. Non-breaking additions go in the existing version. - Old versions are deprecated with a sunset header before removal: `Sunset: Sat, 01 Jan 2027 00:00:00 GMT` ## Authentication - All authenticated endpoints require a Bearer token in the Authorization header. - Token validation happens in the `authMiddleware` — never inline in route handlers. - Never log the raw token. Log the user ID after validation if needed. ## Rate Limiting & Quotas - Public endpoints: 100 req/min per IP. - Authenticated endpoints: 1,000 req/min per API key. - Rate limit headers must be returned on every response: `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`. - When limit is exceeded, return HTTP 429 with Retry-After header. ## Third-Party API Usage - All outbound API calls go through the service layer, never directly from route handlers. - Wrap third-party calls with circuit breakers. See `src/utils/circuit-breaker.ts`. - Log third-party call latency and errors to the observability stack, not just console.error. - Retry on 429 and 5xx with exponential backoff. Max 3 retries.

5. workflow-rules.md

.claude/rules/workflow-rules.md
# Workflow Rules ## Before Writing Any Code - Re-read the request carefully. What exactly is being asked? What file, what section, what behavior? - Check if this pattern already exists in the codebase. Never reimplement something that already exists. - If the change touches more than 3 files, write out the plan before starting. ## Git Discipline - Commit messages must follow Conventional Commits: `feat:`, `fix:`, `refactor:`, `docs:`, `chore:`, `test:` - Commit message body explains the why, not the what (the diff shows the what). - Each commit should be a single logical change. Don't bundle unrelated fixes in one commit. - Never commit directly to `main` or `develop`. Branch first. ## Pull Requests - PR title follows the same Conventional Commits format as commit messages. - PR description must include: What changed, Why it changed, How to test it. - Link the PR to the relevant ticket with a closing keyword: `Closes ENG-1234` - Request review from at least one other engineer before merging. - Self-reviews are allowed for hotfixes only, with a comment explaining why. ## Code Review Standards - Comment on logic, not style. Style is handled by the linter. - Distinguish blocking vs non-blocking feedback: prefix blocking with `[BLOCKING]`, suggestions with `[NIT]`. - Approve when the code is production-ready, not perfect. Perfect is the enemy of shipped. ## Documentation - Update README.md when adding or removing a feature visible to users or other engineers. - Update `docs/architecture.md` when adding a new service, integration, or major component. - New environment variables must be added to `.env.example` with a description comment. - Deprecated APIs must be marked with JSDoc `@deprecated` and reference the replacement.

Best Practices for Structuring Rules Files

After working with rules files across different project types, these patterns consistently produce better Claude behavior and easier maintenance.

Keep files focused and short

A rules file covering exactly one domain should be 50–150 lines. Beyond that, you’re probably mixing concerns. If coding-standards.md starts covering deploy process, split it. Each file should pass the test: “Can I describe what this file covers in five words or less?”

Write imperatives, not explanations

Claude responds to direct instructions. Write rules as imperatives (“Always do X”, “Never do Y”, “Use Z when…”), not as rationale (“The reason we use X is because of historical context involving…”). Save rationale for comments in the codebase itself.

Weak rule (avoid)
# We've historically had issues with test pollution because developers # were sharing state between tests. After a painful debugging session in # Q3 2024, we decided it was best to ensure mocks are always cleared...
Strong rule (use this)
- Clear all mocks in `afterEach()`. Use `jest.clearAllMocks()` in the global setup file.

Use numbered prefixes for ordering

When rule precedence matters, control the load order with filename prefixes:

.claude/rules/ ├── 00-critical-laws.md # hard blockers, safety rules — loaded first ├── 01-coding-standards.md # base style rules ├── 02-testing-rules.md # testing requirements ├── 03-api-rules.md # API design rules ├── 04-deploy-rules.md # deploy gates └── 05-workflow-rules.md # PR and git workflow

Separate hard rules from guidelines

Within each file, use clear visual hierarchy to distinguish non-negotiable rules from preferences. Claude reads and respects this hierarchy:

Structuring hard rules vs guidelines
## Hard Rules — Never Violate - NEVER commit secrets or API keys to the repository. - NEVER deploy without passing CI. - NEVER force-push to main. ## Preferred Patterns - Prefer async/await over Promise chains. - Prefer named exports over default exports. - Prefer early returns over deeply nested conditionals. ## Guidelines (use judgment) - Keep functions under 50 lines when practical. - Consider adding a performance test for any data processing over 10k records.

Reference, don’t duplicate

If something is already in CLAUDE.md, don’t repeat it in a rules file. Reference it: “See CLAUDE.md for the full architecture overview.” Duplication creates maintenance burden and creates confusion when the two copies drift.

Review and prune quarterly

Rules files accrete over time. A rule added for a specific incident six months ago may no longer apply. Schedule a quarterly pass: does each rule still reflect actual practice? Is it enforced by tooling now (linter, CI) and no longer needs to be in a rules file? Delete stale rules. Claude performing worse on a rule is sometimes a sign the rule is wrong, not Claude.

Tip: Self-referential rules

It’s valid to write a rule about the rules system itself. Example: "Before adding a new rule, check if it’s already covered by an existing rule file. Duplicate rules are worse than no rule." This keeps the system from bloating.

Team Workflows and Version Control

Rules files become significantly more valuable on teams than they are for solo developers. Here’s how to structure them for collaborative use.

Commit rules files to git

All rules files in .claude/rules/ should be committed. They’re part of the project’s definition of how work gets done — as important as .eslintrc or jest.config.js. New team members cloning the repo automatically get the full Claude configuration.

Local-only rules files

For personal Claude preferences that don’t belong in the shared project config, create a .claude/rules/local/ subdirectory and add it to .gitignore. Use this for personal debugging shortcuts, experimental rules you’re testing, or role-specific preferences that don’t apply to the whole team.

Rules file PR reviews

Changes to .claude/rules/ should go through code review like any other file. A rule change affects how Claude behaves for everyone on the team. Treat it with the same rigor as changing a linting rule — it has broad behavioral impact.

A useful PR description template for rules changes:

PR description template for rules changes
## What changed Updated `testing-rules.md` to require integration tests for database operations. ## Why Three recent bugs slipped through that would have been caught by integration tests. The unit tests were mocking at too low a level. ## Expected Claude behavior change Claude will now suggest or write integration tests when writing code that queries the database, rather than only unit tests with mocked repositories. ## Does this affect any existing patterns? Yes — current pattern of mocking the DB layer in unit tests is still valid, but Claude will now proactively add an integration test in addition.

Layering with global Claude settings

Your team’s project-level .claude/rules/ files layer on top of each developer’s personal ~/.claude/CLAUDE.md. This means individual developers can have personal preferences (response format, verbosity level, preferred tools) without those preferences touching the shared project rules. Team rules win on any overlap. For more on this layering, see the memory hierarchy guide.

Bootstrapping a new project

When starting a new project, a minimal rules setup is better than a comprehensive one. Start with:

Add more files as specific pain points emerge. Rules files added reactively tend to be more accurate and more followed than rules files written speculatively. The same principle applies to CLAUDE.md templates — start lean and evolve.

The rules files audit habit

At the end of a project sprint, ask: did Claude do anything repeatedly wrong that isn’t covered by a rules file? If yes, that’s your next rules file entry. If Claude violated an existing rule, the rule probably needs to be rewritten to be more explicit. Rules files get better through iteration, not upfront perfection.

Get Pre-Built Rules Files for Your Role

Skip the rules file engineering. Brainfile packages include production-ready .claude/rules/ files for 18 professional roles — tested with real Claude Code workflows.

$49 / month — cancel anytime

Free: Claude Rules Files & Templates

Ready-to-use .claude/rules/ templates, CLAUDE.md examples, and Claude Code best practices. Free weekly.

No spam. Unsubscribe anytime.