Build This Now
Build This Now
What Is Claude Code?Claude Code InstallationClaude Code Native InstallerYour First Claude Code Project
CLAUDE.md MasteryClaude Code Rules DirectoryClaude Skills GuideA Central Library for Your .claude ConfigTeam Onboarding in Claude Code
Get Build This Now
speedy_devvkoen_salo
Blog/Handbook/Core/Claude Code Rules Directory

Claude Code Rules Directory

The .claude/rules/ directory breaks a monolithic CLAUDE.md into path-targeted markdown files that only load where they apply.

Problem: One CLAUDE.md is doing too much. It has React notes next to API conventions next to your testing bar, and every session pulls the whole thing in even when you are editing a migration file.

Quick Win: Spin up your first targeted rule file:

mkdir -p .claude/rules
echo "# Testing Rules
- Run tests before committing
- Mock external services in unit tests" > .claude/rules/testing.md

Claude now picks that rule up at session start, right alongside CLAUDE.md, with the two concerns cleanly separated.

What Is the Rules Directory?

As of Claude Code v2.0.64, you have another option for organizing instructions: the .claude/rules/ directory. Instead of one oversized memory file, you drop multiple markdown files inside, and Claude pulls each one into project memory at session start.

Critical detail from Anthropic: files inside .claude/rules/ load at the same high priority as CLAUDE.md. That matters, because Claude's context window is not flat. Different sources carry different weight during generation.

No config step. Any .md file under .claude/rules/ becomes part of the project context automatically.

.claude/rules/
├── code-style.md      # Formatting and conventions
├── testing.md         # Test requirements
├── security.md        # Security checklist
└── frontend/
    ├── react.md       # React-specific patterns
    └── styles.md      # CSS conventions

Separation of concerns, but at the instruction layer. Edit your security rules without bumping the styling file, or vice versa.

Path-Specific Rules: The Power Feature

This is where the directory earns its keep. A rule file can target specific file patterns through YAML frontmatter:

---
paths: src/api/**/*.ts
---
 
# API Development Rules
 
- All endpoints must validate input with Zod
- Return consistent error shapes: { error: string, code: number }
- Log all requests with correlation IDs

The rule wakes up only when Claude touches files that match src/api/**/\*.ts. Edit a React component and those API notes stay silent.

Multiple Path Patterns

One file can watch several patterns at once:

---
paths:
  - src/components/**/*.tsx
  - src/hooks/**/*.ts
---
 
# React Development Rules
 
- Use functional components exclusively
- Extract logic into custom hooks
- Memoize expensive computations

Common Path Patterns

PatternMatches
src/api/**/*.tsAll TypeScript files in src/api and subdirectories
*.test.tsAll test files in any directory
src/components/*.tsxOnly direct children of components (not nested)
**/*.cssAll CSS files anywhere in the project

Why Priority Matters: The Monolithic CLAUDE.md Problem

Not every token in Claude's context carries the same weight. Sources are ranked, and Anthropic is clear that CLAUDE.md and rules files sit at high priority. Claude treats both as authoritative guidance.

That created a trap with the old way of working. Piling every convention into one massive CLAUDE.md meant all of it got elevated treatment. API patterns fought for attention with React patterns, even when the job was a database migration.

High priority everywhere = priority nowhere.

Mark everything important and Claude can no longer tell what actually applies right now. Instructions drift out of focus, the context gets noisy, and behavior turns unpredictable.

The Context Priority Hierarchy

A quick map of how Claude weighs each source:

SourcePriority LevelImplication
CLAUDE.mdHighTreated as authoritative instructions
Rules DirectoryHighSame weight as CLAUDE.md
SkillsMedium (on-demand)Loaded only when triggered
Conversation historyVariableDecays over long sessions
File contents (Read tool)StandardNormal context, no special weight

The rules directory fixes the monolith by spreading high-priority guidance across narrowly scoped files. API rules stay at high priority, but only while Claude is in API files.

Path Targeting = Priority Scoping

A rule with a paths: entry only loads, and only gets elevated attention, when Claude is working on files that match:

---
paths: src/api/**/*.ts
---
 
# These instructions get high priority ONLY during API work

That is the real insight. You are not just filing things tidily. You are picking when instructions get extra weight.

Rules vs CLAUDE.md vs Skills

Which one picks up which job?

FeaturePriorityBest ForLoads When
CLAUDE.mdHighUniversal operational workflowsEvery session
Rules DirectoryHighDomain-specific instructionsEvery session (filtered by path)
SkillsMediumReusable cross-project expertiseOn-demand when triggered

CLAUDE.md holds what applies everywhere: routing logic, quality bars, coordination protocols. Keep it short. Every line in here fights for the same high-priority budget.

Rules hold what applies to one area: API rules for API files, test rules for test files. Path targeting keeps that high priority scoped to the right moment.

Skills hold what applies across projects: deploy playbooks, review checklists, brand guides. They stay quiet at lower priority until something triggers them.

Practical Examples

Security Rules for Sensitive Directories

---
paths:
  - src/auth/**/*
  - src/payments/**/*
---
 
# Security-Critical Code Rules
 
- Never log sensitive data (passwords, tokens, card numbers)
- Validate all inputs at function boundaries
- Use parameterized queries exclusively
- Require explicit authorization checks before data access

Test File Standards

---
paths: **/*.test.ts
---
 
# Test Writing Standards
 
- Use descriptive test names: "should [action] when [condition]"
- One assertion per test when possible
- Mock external dependencies, never real APIs
- Include edge cases: empty inputs, null values, boundaries

Database Migration Rules

---
paths: prisma/migrations/**/*
---
 
# Migration Safety Rules
 
- Always include rollback instructions
- Test migrations on a copy of production data first
- Never delete columns in the same migration that removes code using them
- Add columns as nullable first, populate, then add constraints

Migration from Monolithic CLAUDE.md

A bloated CLAUDE.md is usually the symptom of priority saturation. Everything is marked important, so nothing is. The fix is to lift domain-specific sections out and drop each one into a path-targeted rule:

Before (single 400-line CLAUDE.md):

# Project Context
 
...
 
## API Guidelines
 
- Validate inputs with Zod
- Return consistent errors
  ...
 
## React Patterns
 
- Use functional components
- Extract hooks
  ...
 
## Testing Rules
 
- Mock external services
  ...

After (lean CLAUDE.md + modular rules):

# CLAUDE.md - Operational Core Only
 
## Routing Logic
 
- Simple tasks: execute directly
- Complex tasks: delegate to sub-agents
 
## Quality Standards
 
- Correctness > Maintainability > Performance
.claude/rules/
├── api-guidelines.md      # API section with paths: src/api/**/*
├── react-patterns.md      # React section with paths: src/components/**/*
└── testing-rules.md       # Testing section with paths: **/*.test.*

CLAUDE.md keeps its focus on how you operate. Domain knowledge moves into targeted rules that only get high priority when the active files match.

Priority saturation is what you are really solving. Core operational guidance is always on. Domain rules only raise their voice when Claude is editing files in their lane. Everywhere else, silence.

User-Level Rules: Personal Defaults Across All Projects

Project rules are not the only layer. Personal rules that follow you into every project live at ~/.claude/rules/:

~/.claude/rules/
├── preferences.md     # Your personal coding preferences
├── workflows.md       # Your preferred workflows
└── shortcuts.md       # Custom patterns you always want

User rules load first, then project rules land on top. So your personal defaults travel with you, but any project can still overrule them when it needs to.

Useful for anything that reflects how you work: indentation style, commit message shape, favored test patterns, small habits you always want in place regardless of codebase.

Brace Expansion in Path Patterns

Path patterns handle brace expansion, so one entry can cover several extensions or directories at once:

---
paths:
  - "src/**/*.{ts,tsx}"
  - "{src,lib}/**/*.ts"
---
 
# TypeScript/React Rules
 
- Use strict TypeScript
- Prefer interfaces over type aliases for public APIs

{ts,tsx} pulls in both .ts and .tsx. {src,lib} covers both src/ and lib/. Your frontmatter stays compact when a rule spans related file types or folders.

Symlinks: Sharing Rules Across Projects

Symlinks work inside .claude/rules/, which lets you keep one canonical rules source and share it across repositories:

# Symlink a shared rules directory
ln -s ~/shared-claude-rules .claude/rules/shared
 
# Symlink individual rule files
ln -s ~/company-standards/security.md .claude/rules/security.md

Linked files resolve and load the same as local ones. Circular symlinks are caught and handled, so an infinite loop is not something you need to guard against.

Good fit for teams that share coding standards across projects. Keep the canonical rules repo in one place. Symlink it into every project that needs it.

Recursive Subdirectory Discovery

Subdirectories are fair game. Every .md file in the tree gets picked up:

.claude/rules/
├── frontend/
│   ├── react.md
│   └── styles.md
├── backend/
│   ├── api.md
│   └── database.md
└── general.md

Nested or flat, the loader walks the whole directory. Group related files however you like without losing discoverability.

Best Practices

Keep rules focused: one concern per file. Security in one place, styling in another.

Use descriptive filenames: api-validation.md is worth more than rules1.md.

Lean on path targeting: rules without paths: load everywhere. Add a pattern the moment a rule starts bleeding into unrelated work.

Version control everything: rules are code. Review them in PRs, track history, revert the ones that backfire.

Document rule purpose: open each file with a line explaining when it should apply.

Next Steps

  1. Audit your CLAUDE.md: flag sections that really only apply to certain file types
  2. Extract one rule: lift your most domain-specific block into .claude/rules/
  3. Add path targeting: point that rule at the files it actually serves
  4. Iterate: whenever Claude loads context you did not need, extract another rule

For the wider memory architecture and why one giant file causes trouble, see CLAUDE.md Mastery. For how priority fits into a broader context strategy, read about context management and memory optimization.

Remember: the goal is to hand Claude exactly the high-priority guidance that matches the files on screen. Nothing more. Attention where it matters, quiet everywhere else. Pair that with a skills architecture that loads domain knowledge on demand, and your context window stays lean while your instructions keep their weight.

More in this guide

  • Agent Fundamentals
    Five ways to build specialized agents in Claude Code, from sub-agents to .claude/agents/ definitions to perspective prompts.
  • Agent Patterns
    Orchestrator, fan-out, validation chain, specialist routing, progressive refinement, and watchdog. Six ways to wire sub-agents in Claude Code.
  • Agent Teams Best Practices
    Battle-tested patterns for Claude Code agent teams. Troubleshooting, limitations, plan mode quirks, and fixes shipped from v2.1.33 through v2.1.45.
  • Agent Teams Controls
    Stop your agent team lead from grabbing implementation work. Configure delegate mode, plan approval, hooks, and CLAUDE.md for teams.
  • Agent Teams Prompt Templates
    Ten tested Agent Teams prompts for Claude Code. Code review, debugging, feature builds, architecture calls, and campaign research. Paste and go.

Stop configuring. Start building.

SaaS builder templates with AI orchestration.

Get Build This Now

CLAUDE.md Mastery

CLAUDE.md is your AI's operating system, not documentation.

Claude Skills Guide

Load on-demand folders of instructions that give Claude workflows, checklists, and domain know-how per task.

On this page

What Is the Rules Directory?
Path-Specific Rules: The Power Feature
Multiple Path Patterns
Common Path Patterns
Why Priority Matters: The Monolithic CLAUDE.md Problem
The Context Priority Hierarchy
Path Targeting = Priority Scoping
Rules vs CLAUDE.md vs Skills
Practical Examples
Security Rules for Sensitive Directories
Test File Standards
Database Migration Rules
Migration from Monolithic CLAUDE.md
User-Level Rules: Personal Defaults Across All Projects
Brace Expansion in Path Patterns
Symlinks: Sharing Rules Across Projects
Recursive Subdirectory Discovery
Best Practices
Next Steps

Stop configuring. Start building.

SaaS builder templates with AI orchestration.

Get Build This Now