Path-Specific Rules in Claude Code: paths Globs, When a Rule Loads and the Glob That Matches Nothing
A rule file with a paths glob joins Claude's context only when Claude reads, writes or edits a matching file. We read four globs against five files, run a stand-in matcher on four file paths, and fix a glob that matched nothing.
What you will learn
- Explain when a .claude/rules file with paths loads: on a read, write or edit of a matching file, not at launch
- Read glob patterns: ** crosses folders, * stays in one, a leading / means the base folder
- Debug a glob that matches nothing, and spot a misspelled paths key
- Choose one glob rule over many folder CLAUDE.md files for conventions that span folders
Before you start
- What CLAUDE.md is and where Claude Code looks for it
- Splitting CLAUDE.md into .claude/rules files
Ben has just joined the shop-app team, and something bothers him: why do the test rules load when I edit a web file? Asha, who looks after the app, wants the testing rules on test files and nowhere else.
The tool for this is a rule file in .claude/rules/ with a paths glob. If you haven't split a CLAUDE.md into rule files yet, start with splitting CLAUDE.md with @import and rules files. Here we look closely at the glob: when it's checked, what it matches, and what to do when it matches nothing.
Tests everywhere, rules only for them
The shop app keeps tests next to the code. There's api/orders_test.py beside api/orders.py, and infra/deploy_test.py beside infra/deploy.yaml. The web/ folder has app.js and no test at all.
Asha's testing rules (use pytest, one behaviour per test, no network calls) belong on those two test files. web/app.js isn't a test and needs none of it. So the rule should follow the kind of file, not the folder.
Picture a warehouse. One way is a "wear gloves" note on every shelf: three shelves, three copies, all kept in step by hand. The other way is a gloves sticker on each parcel of glass. The rule is stuck to the glass wherever the glass sits. A paths glob is the sticker.
The rule file
Here is .claude/rules/testing.md:
---
paths:
- "**/*_test.py"
---
# Testing rules
- Use pytest. One behaviour per test function.
- Name tests test_<thing>_<expected result>.
- No network calls; use fakes, never the live service.
pathsis the only frontmatter field Claude Code reads from a rule file. Any other field is ignored.- Each glob is a quoted string in a list. Several globs fit in one list, and brace expansion such as
*.{ts,tsx}works too. - Below the frontmatter is plain Markdown. Claude Code removes the frontmatter before the rule is loaded.
The project's second rule, infra.md, uses "infra/**/*".
When a rule loads: on touch, not at launch
At launch, only the project CLAUDE.md is in the context. Both rule files have a paths line, so they wait.
Ben asks Claude to work on api/orders_test.py. Claude reads the file, and the globs are checked against its path. testing.md matches, infra.md doesn't, so testing.md joins the context. Later Claude reads web/app.js. No glob matches, nothing new joins, and no extra tokens are spent.
paths wait at launch. A matching read, write or edit brings them in.Which files does a glob match?
Patterns are relative to the folder that holds .claude. Take five files: api/orders_test.py, infra/deploy_test.py, infra/deploy.yaml, web/app.js and README.md.
| Glob | Matches | Why |
|---|---|---|
**/*_test.py | api/orders_test.py, infra/deploy_test.py | Two stars cross folders |
infra/**/* | infra/deploy_test.py, infra/deploy.yaml | Everything under infra/ |
api/*.py | api/orders_test.py (files directly in api/ only) | One star stays inside one folder |
/*.md | README.md | A leading slash means the base folder only |
The short version: ** crosses folders, a single * stays in one, and a leading / anchors to the base folder.
A stand-in that shows the matching
You can't watch Claude Code's loader directly, so the lecture's project has a small Python stand-in, rule_loader.py. To be clear: Claude Code does the real loading itself. This file only imitates the matching so we can see it. Here are its key functions:
import re
from pathlib import Path
ROOT = Path(__file__).parent
RULES = ROOT / ".claude" / "rules"
def read_paths(rule):
"""The paths globs from the frontmatter, or [] when there are none."""
text = rule.read_text(encoding="utf-8")
if not text.startswith("---"):
return []
head = text.split("---")[1]
return re.findall(r'^\s*-\s*"(.+)"\s*$', head, re.M)
def to_regex(glob):
"""** crosses folders, a single * stays inside one folder."""
out, i = "", 0
while i < len(glob):
if glob.startswith("**/", i):
out, i = out + "(?:.*/)?", i + 3
elif glob.startswith("**", i):
out, i = out + ".*", i + 2
elif glob[i] == "*":
out, i = out + "[^/]*", i + 1
else:
out, i = out + re.escape(glob[i]), i + 1
return re.compile(out + "$")
def matches(glob, file):
if "/" not in glob: # no slash: match anywhere
glob = "**/" + glob
return to_regex(glob.lstrip("/")).match(file) is not None
def rules_loaded(file, rules=RULES):
"""Rule files that join the context when Claude touches this file."""
return [r.name for r in sorted(rules.glob("*.md"))
if any(matches(g, file) for g in read_paths(r))]
read_pathspulls the quoted globs out of the frontmatter.to_regexturns**/into "any number of folders", and*into "anything except a slash".matchestreats a glob with no slash as "match anywhere".rules_loadedkeeps the rule files whose glob matches the touched file.
The file also has a folder_memory function that lists folder CLAUDE.md files on the way up from the touched file, so we can compare the two approaches. The project has one: api/CLAUDE.md.
Four files, four outcomes
Running python rule_loader.py prints this (no API is called):
at launch: CLAUDE.md (both rule files have paths, so they wait)
Claude reads api/orders_test.py
path rules : ['testing.md']
folder file: ['api/CLAUDE.md']
Claude reads infra/deploy_test.py
path rules : ['infra.md', 'testing.md']
folder file: none
Claude reads infra/deploy.yaml
path rules : ['infra.md']
folder file: none
Claude reads web/app.js
path rules : none
folder file: none
diagnose examples/testing-broken.md
tests/**/*_test.py vs api/orders_test.py: no match
hint: the glob starts in tests/, the file is not there
diagnose .claude/rules/testing.md
**/*_test.py vs api/orders_test.py: match
api/orders_test.py: the testing rule matches, andapi/CLAUDE.mdloads too because the file sits in that folder.infra/deploy_test.py: the glob finds this test as well. Butinfra/has no folder file, so a folder-based setup would give this test nothing.infra/deploy.yaml: only the infra rule.web/app.js: nothing extra loads.
The last two blocks are the broken glob and its fix, which we come to next.
One glob beats many folder files
Why not a CLAUDE.md in every folder? Look at the run again. api/CLAUDE.md loads for any file in api/, test or not. infra/ has no folder file, so its test misses the rules. And you keep one copy per folder, so one change means many edits.
One rule with **/*_test.py matches the test in api/ and the test in infra/, and there's one file to maintain. A folder CLAUDE.md follows the folder. A path rule follows the file.
The glob that matches nothing
Here's the broken rule, examples/testing-broken.md:
---
paths:
- "tests/**/*_test.py"
---
# Testing rules
- Use pytest. One behaviour per test function.
The glob expects a tests/ folder. There isn't one: the tests sit next to the code. So the rule never shows up, and nothing tells you why. Don't guess a glob. Run three checks:
- Test the glob against the real path, written from the folder that holds
.claude. The stand-in does exactly this:tests/**/*_test.py vs api/orders_test.py: no match, with the hint that the glob starts intests/and the file isn't there. - Check that Claude touched a matching file. A path rule loads on a read, write or edit, never at launch. Starting a session and asking a general question won't load it.
- Log it with an
InstructionsLoadedhook, so you can see which instruction files actually loaded.
The fix is **/*_test.py, and the stand-in now reports a match.
One more trap points the other way. If you misspell the key (say, path: instead of paths:), the field is ignored. The rule then has no paths, so it loads at launch for every task: the opposite of what you wanted.
How this shows up in a question
Expect a scenario with conventions that follow a file type across many folders, such as test files spread through a codebase. The answer that fits is a .claude/rules/ file with a paths glob, because it loads only when matching files are edited and covers every folder from one place. Folder CLAUDE.md files miss folders and load for unrelated files.
Common mistakes
| Symptom | Cause | Fix |
|---|---|---|
| The rule never loads | The glob names a folder that doesn't exist (tests/**/...) | Test the glob against a real path; use **/*_test.py |
| The rule isn't there at session start | Expected behaviour: path rules wait | Have Claude read or edit a matching file |
| The rule loads for every task | Misspelled paths key, so no paths are read | Spell it paths: |
api/*.py misses api/v2/x.py | One star stays in one folder | Use api/**/*.py |
| Some tests get no rules | Rules kept in folder CLAUDE.md files | One glob rule for the file type |
Quick recap
| Idea | Remember |
|---|---|
| Where | .claude/rules/*.md, with paths in the frontmatter (the only field read) |
| When | When Claude reads, writes or edits a matching file, not at launch |
| Globs | ** crosses folders, * stays in one, leading / = base folder |
| Debug | Glob vs real path, did Claude touch a match, InstructionsLoaded hook |
| Choose | Spread across folders? One glob rule beats many folder files |
The project files and rule_loader.py for this lesson are in the community, free to join.
Try it yourself
Add a third rule, web.md, with paths: ["web/**/*.js"]. Before running the stand-in, predict which of the four files will load it. Then change the glob to web/*.js, add a file at web/lib/cart.js to the list in rule_loader.py, and check whether your prediction holds.
Related course on Udemy
Claude Certified Architect - Foundations (CCAR-F) Exam Prep
Agentic loops, tools, MCP, Claude Code, prompts, structured output and context.View on Udemy ↗: Claude Certified Architect - Foundations (CCAR-F) Exam Prep (paid course, opens in a new tab)Related posts
CLAUDE.md, settings.json and Plugins: Which Claude Code File Advises, Which Enforces, Which Packages
Three needs in one repo: a test command, a rule that Claude must never read .env, and a shared deploy skill. See which file each belongs in, how the settings layers merge, and what a plugin manifest carries.
Authoring a Claude Skill: SKILL.md, Frontmatter, Progressive Disclosure and the Description That Triggers It
Pack a support team's ticket-triage routine into one skill folder, then watch three requests load one, two or all three levels: the catalog, the SKILL.md body, and a script whose code never enters the context.
One Change, Four Environments: Where a Claude Config Edit Lands in Dev, Staging, Prod and CI
Change one line in a repo and ask where it lands. A small resolver for bookshop-bot shows that a new model id in settings.json reaches only CI, a prompt bump reaches dev and CI, and a prod block edit reaches only prod.
Claude in the SDLC: Prompts in Git, a Change Gate by Path, a Claude Review That Advises and a Person Who Merges
Follow one prompt edit from a branch to a merge: version prompts and the model pin like code, keep the API key in GitHub Secrets, gate changes by path, let Claude review the diff, and leave the merge to a person.
