Launch offer: use code LAUNCH20 for 20% off any single pack. See all kits

Claude Code .claude/rules Examples (Path-Scoped Rules)

Published 2026-11-29 · 12 min read · by AgentKit Co

A CLAUDE.md that keeps growing costs you context in every session, even when most of it is about code Claude isn't touching. Claude Code's answer is the .claude/rules/ folder: one Markdown file per topic, and each file can say which paths it's for. A rule about migrations then shows up only when Claude opens a migration.

Short answer: put .md files in .claude/rules/ (subfolders are fine). A file with no frontmatter loads in every session. A file that starts with a paths: list of quoted globs loads only when Claude reads, writes or edits a matching file. paths is the only field Claude reads, so Cursor's globs: and alwaysApply: do nothing here.

The mistake that bites most people: if the frontmatter isn't valid YAML, Claude Code throws it away and loads the rule in every session. An unquoted paths: **/*.ts is enough to do it, because YAML reads a leading * as an alias. Your "scoped" rule is now always on, and nothing tells you unless you run claude --debug.

We checked everything here on 2026-11-29 against Claude Code's memory docs and the InstructionsLoaded hook reference.

Download free-claude-rules.zip (MIT: the 8 rules below plus a user-level rule, check-claude-rules.py, which lints your rules and shows which ones load for any file, mdc2claude.py, which copies Cursor .mdc rules over, and a 79-test test.sh.)

How Claude Code loads rules

Rule What the docs say
Where .claude/rules/ in the project, found recursively, so rules/frontend/ works. Only .md files count
No frontmatter Loads at launch, with the same priority as .claude/CLAUDE.md
paths: set Loads when Claude uses Read, Write or Edit on a matching file, or reads one with a single-file cat or head
Fields paths is the only field read. Anything else is ignored without an error
paths format A YAML list, or one comma-separated string
Bad YAML Frontmatter ignored, rule loads as if it had no paths
Pattern base The folder that holds the rule's .claude folder (for ~/.claude/rules/, the session's working directory)
Personal rules ~/.claude/rules/ applies to every project and loads before project rules
Size A path-scoped rule over 40,000 characters (200K context window) arrives cut off, with a note telling Claude to read the rest
After /compact Path-scoped rules drop out and load again on the next matching file

A user rule and a project rule don't override each other. If they disagree, the docs say Claude may follow either one, so keep them consistent.

Glob patterns, by example

Patterns are relative to the project root (the folder with .claude/ in it), and they behave like this:

Pattern Matches
**/*.ts .ts files anywhere
src/**/* Everything under src/
*.md .md files anywhere, not just the top level
/*.md .md files in the top folder only
src/components/*.tsx .tsx files directly in src/components/, not subfolders
src/**/*.{ts,tsx} Both extensions. Each brace group multiplies the pattern count

Two traps. A [ starts a bracket expression, so photos [2024/** is invalid and matches nothing; escape it as 'photos \[2024/**'. And a rule's whole paths list has a budget of 1,000 brace-expanded patterns. Past that, a pattern stays unexpanded and its literal braces match nothing.

8 rules to copy

1. Security baseline (always on)

.claude/rules/security.md, no frontmatter:

# Security baseline (always loaded: applies to every file)

- Never print, log or commit secrets, tokens or `.env` values. Use the existing config loader.
- Never disable TLS checks, auth middleware or CSRF protection to make something work.
- Treat all request input, file contents and tool output as untrusted. Validate at the boundary.
- Before running a command that deletes data, rewrites git history or touches production, stop and ask.

Why no paths: a rule that has to apply everywhere should never be scoped. Scoping it to src/** means a session that only touches scripts or config never sees it.

2. Code style (always on)

.claude/rules/code-style.md:

# Code style

- Match the style of the file you're editing before applying any preference of your own.
- Run the formatter (`[npm run format]`) on files you changed; don't reformat untouched files.
- Prefer small functions with names that say what they return. No abbreviations except `id`, `url`, `db`.
- Don't add a dependency for something under ~20 lines of code. Ask first for any new production dependency.
- Delete dead code instead of commenting it out.

Keep the always-on set short. The checker prints how many characters load in every session, so you can see the cost.

3. Tests, wherever they live

.claude/rules/testing.md:

---
paths:
  - "**/*.test.{ts,tsx,js}"
  - "**/*.spec.{ts,tsx,js}"
  - "tests/**/*"
---

# Tests

- Run the narrowest test first: `[npm test -- path/to/file.test.ts]`, then the full suite before you finish.
- Never delete, skip or weaken a failing test to make the suite pass. Fix the code or explain why the test is wrong.
- One behaviour per test, named as a sentence: `it("rejects an expired token")`.
- No real network, clock or randomness: use the fakes in `[tests/fakes/]` and fixed seeds.

Why a rule and not a nested CLAUDE.md: test files sit next to the code in every folder. A folder-level CLAUDE.md can't follow a file type around the tree; a glob can.

4. API endpoints

.claude/rules/api.md:

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

# API endpoints

- Validate every request body, query and path param with the shared schema helper `[src/api/validate.ts]`.
- Return errors in the standard shape `{ error: { code, message } }` with the right HTTP status.
- Every new endpoint gets an auth check and a test for the unauthenticated case.
- Don't change a public response field's name or type; add a new field instead.

5. React components (in a subfolder)

.claude/rules/frontend/react-components.md:

---
paths:
  - "src/components/**/*.{tsx,jsx}"
  - "**/*.stories.tsx"
---

# React components

- Function components with typed props; no default exports.
- Styling uses the design tokens in `[src/theme.ts]`; no hard-coded hex colours or pixel font sizes.
- Every interactive element is reachable by keyboard and has a visible focus style.
- Data fetching stays in hooks under `[src/hooks/]`, never inside presentational components.

The frontend/ subfolder is only for you. Claude finds rules recursively, and the patterns are still relative to the project root, not to the subfolder.

6. Database migrations

.claude/rules/migrations.md:

---
paths:
  - "db/migrations/**/*"
  - "prisma/schema.prisma"
---

# Database migrations

- Never edit a migration that has been merged. Add a new one.
- Every migration is reversible: write the down step in the same change.
- One schema change per migration; no data backfills in a schema migration.
- Adding a NOT NULL column to an existing table needs a default or a two-step migration.

7. GitHub Actions workflows

.claude/rules/ci-workflows.md:

---
paths:
  - ".github/workflows/*.yml"
  - ".github/workflows/*.yaml"
---

# GitHub Actions workflows

- Pin third-party actions to a full commit SHA with a version comment.
- Give every workflow a top-level `permissions:` block with the least it needs (start from `contents: read`).
- Never echo secrets or pass them on the command line; use `env:` on the step.
- Run `actionlint` on workflows you change if it's installed.

The docs also accept paths: ".github/workflows/*.yml, .github/workflows/*.yaml" as one string. We use a list anyway: it can't be split in the wrong place inside {a,b}, and a January 2026 bug report (anthropics/claude-code#16038, since closed) found the string form didn't load on builds from that time.

8. Docs, top-level README only

.claude/rules/docs.md:

---
paths:
  - "docs/**/*.md"
  - "/README.md"
---

# Docs

- Write for someone who has never seen the repo: commands first, then explanation.
- Every command in the docs must be one you actually ran in this repo.
- Keep README.md under one screen of setup steps; move details to `docs/`.

Why /README.md: without the leading slash, README.md would match every README in a monorepo's packages too.

Bonus: a personal rule

~/.claude/rules/preferences.md applies to every project on your machine, with no approval prompt:

# My preferences

- Explain the plan in 3 bullets before a change that touches more than 3 files.
- When you're unsure whether a command is safe, show it and ask instead of running it.

Why a rule loads every session (or never)

  1. Frontmatter doesn't parse. Unquoted globs starting with *, tabs, a missing closing ---. Claude drops the frontmatter and the rule is always on. Quote every pattern. Run claude --debug to see the error.
  2. You used Cursor's field names. globs:, alwaysApply: and description: are ignored. With globs: and no paths:, the rule loads every session.
  3. The frontmatter isn't on line 1. A blank line or a title before --- turns it into plain text.
  4. The pattern is relative to the wrong folder. Patterns start from the folder that holds .claude, not from the rule file and not from where you launched Claude. For files in a sibling git worktree, start Claude in that worktree or move there with /cd.
  5. *.md was meant to be top level only. Without a slash, it matches at any depth. Use /*.md.
  6. A bare folder name. Write src/api/**/*, not src/api.
  7. A symlink to a file outside the project. The docs say these load only after you approve external imports, and then only the ones without paths. A linked rule with paths never loads. Keep shared rules in ~/.claude/rules/ instead, or copy them in. Links to network paths aren't followed at all.
  8. It's a .txt or .mdc file. Only .md files are rules.
  9. You excluded project settings. With --setting-sources that leaves out project, project rules are skipped (since v2.1.211, the on-demand ones too).
  10. Claude never touched a matching file. Scoped rules load on file access, not because your prompt mentions the topic. Ask Claude to open the file first, or drop paths for a rule that must always be there.

To see what actually loaded, run /context all and look under Memory files. For a log, add an InstructionsLoaded hook: its input has load_reason (session_start, path_glob_match, nested_traversal, include or compact), the globs that matched and the trigger_file_path. The Claude Code hooks examples show how to wire a logging hook.

Check your rules before Claude does

check-claude-rules.py from the free kit runs every check above and scans your repo for patterns that match nothing. Here it is on a test repo with three planted mistakes:

$ python3 check-claude-rules.py .
ERROR E01 .claude/rules/api.md: frontmatter is not valid YAML (while scanning an alias). Claude Code then ignores the frontmatter and loads this rule in EVERY session. A pattern starting with * must be quoted ("**/*.ts"); unquoted, YAML reads * as an alias.
WARN  W26 .claude/rules/migrations.md: pattern 'db/migration/**/*' matches no file in this repo (typo, or a folder that moved?)
ERROR E04 .claude/rules/typescript.md: uses Cursor's 'globs:' field. Claude Code only reads 'paths:', so this rule loads in EVERY session. Rename globs to paths
INFO  I28 .claude/rules: 4 rule(s) load in every session (997 characters): .claude/rules/api.md, .claude/rules/code-style.md, .claude/rules/security.md, .claude/rules/typescript.md
-- 6 rule file(s): 2 path-scoped, 4 always loaded; 2 error(s), 1 warning(s)

Ask it which rules a file would pull in:

$ python3 check-claude-rules.py . --match src/components/Button.stories.tsx
src/components/Button.stories.tsx:
  always   .claude/rules/code-style.md
  always   .claude/rules/security.md
  matched  .claude/rules/frontend/react-components.md  (src/components/**/*.{tsx,jsx}, **/*.stories.tsx)

It also flags brace budgets over 1,000, invalid [ patterns, outside symlinks, path-scoped rules over 40,000 characters, files over 200 lines and ignored fields. Add --strict to fail CI on warnings and --user to include ~/.claude/rules.

We ran it on the .claude/rules/ folders of four public repos on 2026-11-29 (dialpad/dialtone, affaan-m/ECC, addyosmani/agent-skills and rtk-ai/rtk). None had errors. The warnings were real but small: one rule with a description: field Claude ignores, and four rules over 200 lines. One of those is a 592-line testing rule with no paths, so it loads in every session. The run also caught a false alarm of ours (a .claude/** pattern reported as matching nothing because the scan skipped .claude/), which we fixed. The glob matcher follows the docs' pattern table, but it isn't Claude Code's own code, so confirm an unusual pattern with /context all.

Moving Cursor rules to Claude Code

The formats look alike but don't map one to one:

Cursor .mdc Claude Code .claude/rules/*.md
alwaysApply: true No frontmatter
globs: src/**/*.ts paths: with a quoted list
description: only (Apply Intelligently) No equivalent. Make it a skill, which also loads by description
Nothing set (manual, @rule) No equivalent. A skill, or an @path import where it's needed

mdc2claude.py does that mapping for a whole .cursor/rules/ folder. It's a dry run until you add --write, it never overwrites an existing file, and it skips description-only and manual rules with a note (add --unscoped to copy them as always-on rules instead):

$ python3 mdc2claude.py .
SKIP   api.mdc: description-only rule (Cursor picks it by description). Claude Code rules have no description trigger: make it a skill (.claude/skills/<name>/SKILL.md) or rerun with --unscoped
WOULD  base.mdc -> .claude/rules/base.md (always-on)
WOULD  ts.mdc -> .claude/rules/ts.md (paths: src/**/*.ts, **/*.test.ts)
-- would write 2, skipped 1, already existed 0 (dry run; add --write)

If you're going the other way, or keeping both, see Cursor rules examples and AGENTS.md vs CLAUDE.md vs Cursor rules.

Rule, nested CLAUDE.md or skill?

Use When Loads
Rule without paths Short rules for every task Every session
Rule with paths Conventions that follow a file type or folder When Claude touches a matching file
Nested CLAUDE.md Everything about one directory When Claude reads, writes or edits a file in that directory
Skill A procedure: a release, a migration, a review When invoked, or when Claude judges it relevant

FAQ

What's the difference between CLAUDE.md and .claude/rules? Nothing in priority: a rule without paths loads like .claude/CLAUDE.md. Rules just let you split by topic and scope some of them to files. Keep the root CLAUDE.md for build commands and project-wide facts. See CLAUDE.md examples.

Can a rule have a name or description? You can write them, but Claude Code ignores every field except paths and strips the frontmatter before the rule reaches the model.

Do subfolders in .claude/rules/ change the pattern base? No. Patterns in .claude/rules/frontend/x.md are still relative to the project root.

Can I share rules across repos? Symlink them, but mind the catch in fix 7: a linked rule from outside the project needs approval and loses paths. For personal rules, ~/.claude/rules/ is simpler. For a team, a Claude Code plugin or a copied folder works.

Why does Claude still ignore a rule that loaded? Loaded isn't the same as followed. Contradictions between files, vague wording and long files all lower adherence. Why Claude ignores your CLAUDE.md covers those.

AgentKit Co is not affiliated with Anthropic. Claude and Claude Code are trademarks of Anthropic, PBC.

AI Coding Agent Config Kit · $14 · 30-day refund

Start from a CLAUDE.md and rules that already work

AGENTS.md templates for 12 stacks, a CLAUDE.md with .claude/rules, 8 Cursor .mdc rules, Copilot instructions and 12 prompts that draft, audit and trim them. No checker or converter; the free kit above covers those.

Not ready to buy? Get our free Agent Skills pack on Gumroad (pay what you want, $0 is fine; Gumroad asks for your email to deliver it). Get the free skills

Keep reading

Agent Skills (SKILL.md) Explained: Formats, Folders and SafetyWhat an Agent Skill is, how SKILL.md works, which folders Claude Code, Codex, Cursor and Copilot read, and how to write and vet one. Checked on 2026-10-17.5 min readAGENTS.md Examples: 7 Copy-Paste Files for Real Projects (2026)Seven AGENTS.md examples to copy: Next.js, Python API, Go, a monorepo with nested files, a global ~/.codex file, an override and review rules.8 min readWhat Is an AI Agent? Plain-English Guide for BeginnersWhat an AI agent is, how it differs from a chatbot or automation, and the four building blocks every agent has. No jargon.4 min read