Claude Code Guide

The complete guide to Claude Code setup. 100+ hours saved. 370x optimization. Production-tested patterns for skills, hooks, and MCP integration.

View the Project on GitHub ytrofr/claude-code-guide

Chapter 26: Claude Code Rules System

Official Documentation: https://code.claude.com/docs/en/memory

Overview

Claude Code automatically discovers .md files in .claude/rules/ directories. Rules provide persistent instructions that load automatically based on context, enabling domain-specific guidance without cluttering your main CLAUDE.md file.

Rule Hierarchy (Priority Order)

1. Enterprise rules: ~/.claude/enterprise/rules/  (organization-level)
2. User rules:       ~/.claude/rules/              (personal defaults)
3. Project rules:    .claude/rules/                (project-specific)

Higher priority rules override lower ones. This allows:

Directory Structure

.claude/rules/
├── INDEX.txt              # Index of all rules (.txt = not auto-loaded)
├── src-code.md            # Path-specific: src/**/*.js
├── tests.md               # Path-specific: tests/**/*
├── sacred/
│   └── commandments.md    # Core compliance rules
├── database/
│   └── patterns.md        # Database access patterns
├── api/
│   └── integrations.md    # External API standards
└── hebrew/
    └── preservation.md    # Cultural/i18n standards

File Discovery

Path-Specific Rules

Use YAML frontmatter to target specific file paths:

---
path_patterns:
  - "src/**/*.js"
  - "src/**/*.ts"
---

# Source Code Rules

## Modular Architecture

- Routes in src/routes/
- Controllers in src/controllers/
- Utilities in src/utils/

## Code Standards

- Use async/await (not callbacks)
- Prefer const over let
- Document public functions

This rule only loads when working with files matching the patterns.

Rule File Templates

Domain Rule Template

# [Domain] Rules - [Project Name]

**Authority**: [What this rule governs]
**Source**: [Reference documentation]

---

## Core Patterns

```yaml
Pattern_Name:
  Rule: "Description of the rule"
  Example: "Code or usage example"
  Violation: "What NOT to do"
```

Quick Reference

Pattern Usage
Pattern 1 When to use
Pattern 2 When to use

Skills Reference: [Related skills]


### Path-Specific Rule Template

```markdown
---
path_patterns:
  - "path/to/files/**/*"
---

# Rules for [Path]

## Standards
- Standard 1
- Standard 2

## Patterns
- Pattern 1
- Pattern 2

Best Practices

1. Keep Rules Focused

DO: One domain per file

.claude/rules/
├── database/patterns.md     # Database only
├── api/integrations.md      # API only
└── testing/standards.md     # Testing only

DON’T: Mix domains

.claude/rules/
└── everything.md            # Database + API + Testing (too broad)

2. Reference, Don’t Duplicate

DO: Point to authoritative sources

# Database Rules

**Full Reference**: See `CORE-PATTERNS.md` (authoritative source)

## Quick Summary

- Golden Rule: Always use `employee_id`
- Safety: `SELECT current_database()` before operations

DON’T: Copy entire documents

# Database Rules

[400 lines copied from CORE-PATTERNS.md] # Causes duplication!

3. Use INDEX.txt (Not README.md)

Important: Since Claude Code auto-loads all .md files in .claude/rules/, a README.md index file wastes context tokens on human navigation content. Rename it to INDEX.txt — Claude Code ignores non-.md files, but humans can still read it.

# Save ~700 tokens per session
mv .claude/rules/README.md .claude/rules/INDEX.txt

Include an INDEX.txt for quick navigation:

# Project Rules Index

| Rule File                | Domain   | Key Patterns           |
| ------------------------ | -------- | ---------------------- |
| `sacred/commandments.md` | Core     | 14 Sacred Commandments |
| `database/patterns.md`   | Database | Golden Rule, SQL       |
| `api/integrations.md`    | External | OAuth2, endpoints      |

**Last Updated**: YYYY-MM-DD

4. Version Your Rules

Track rule changes in your index:

## Changelog

### 2026-01-06

- Added: hebrew/preservation.md
- Updated: database/patterns.md (Cloud SQL credentials)

### 2025-12-15

- Initial rules structure created

Rules vs CLAUDE.md

Aspect CLAUDE.md .claude/rules/
Loading Always loaded Auto-discovered
Path-specific No Yes (YAML frontmatter)
Organization Single file Directory structure
Best for Core project instructions Domain-specific patterns
Size limit Keep concise Can be detailed

When to Use Each

Use CLAUDE.md for:

Use .claude/rules/ for:

Context Optimization

Problem: Context Bloat

Rules that duplicate content waste context tokens:

Solution: Cross-Reference Pattern

CROSS_REFERENCE_RULE:
  Primary_Source: CORE-PATTERNS.md (authoritative)
  Rules_Summary: .claude/rules/ (navigation)
  CLAUDE.md: Brief reference only (never duplicate)

Implementation

In CLAUDE.md:

## Sacred Compliance

→ See `.claude/rules/sacred/commandments.md` for details
→ Full reference: `CORE-PATTERNS.md`

In rules/sacred/commandments.md:

# Sacred Commandments Summary

**Full Reference**: CORE-PATTERNS.md (authoritative source)

| #   | Rule        | Quick Check            |
| --- | ----------- | ---------------------- |
| I   | Golden Rule | `employee_id` not `id` |
| II  | Real Data   | No hardcoding          |

...

Optimization Tips

1. Rename Non-Rule Files to .txt

Claude Code only auto-loads .md files. Any file that exists for human reference (indexes, changelogs, READMEs) should use .txt extension:

mv .claude/rules/README.md .claude/rules/INDEX.txt      # ~700 tokens saved
mv .claude/rules/CHANGELOG.md .claude/rules/CHANGELOG.txt  # if applicable

2. Trim Evidence from Rules

Rules should contain the rule itself, not the history of why it was created. Move evidence, dated lessons, and bug narratives to memory-bank/learned/:

# Before (bloated - 2,900 tokens)

## Sacred Commandment I

Rule: Use employee_id
Evidence: Dec 22, 2025 - Found bug where...
Lesson: The 0-employees bug occurred when...
Sprint-C: 4-hour debugging session led to...

# After (focused - 1,800 tokens)

## Sacred Commandment I

Rule: Use employee_id (NEVER just id)
Validation: grep -r 'record\.employee\.id' src/

3. Deduplicate Across Files

If the same rule appears in both .claude/rules/database/patterns.md and CORE-PATTERNS.md, keep the full version in one place and reference from the other:

# In database/patterns.md (condensed)

## Golden Rule (Sacred I)

→ See sacred/commandments.md for full rule
Quick check: always use employee_id, never id

4. Measure Your Token Budget

# Count tokens across all auto-loaded rules
total=0
for f in $(find .claude/rules -name "*.md" -type f); do
  chars=$(wc -c < "$f")
  tokens=$((chars / 4))
  total=$((total + tokens))
  echo "$tokens tokens | $f"
done | sort -rn
echo "TOTAL: $total tokens"

Target: Keep total rules under 15k tokens. Over 20k likely contains duplicated content.

Example: Complete Rules Setup

See the template/.claude/rules/ directory for a complete working example.

Validation Commands

# List all rule files
find .claude/rules -name "*.md" -type f

# Check rule file count
find .claude/rules -name "*.md" | wc -l

# Search for specific pattern
grep -r "Golden Rule" .claude/rules/

# Verify no duplication with CLAUDE.md
grep -c "Sacred Commandment" CLAUDE.md  # Should be < 3