Setting Up Context: Rules Files and Project Config
On this page 14 sections
- What a rules file is
- Where Claude Code looks for it
- What goes in: facts the code can’t tell the agent
- What to leave out
- Keep it short
- Settings: what the agent may run
- Lint your rules file
- Try it yourself
- Common beginner mistakes
- Questions you will face in production
- Check your understanding
- What to remember
- What to study next
- Further reading
You open a coding agent in the Kitebase ticket service. That’s a small Python codebase for the made-up project-tracking app used across this site. You ask it to “add a --status filter to search_tickets”.
Say it writes the filter, then runs pytest to check its work. That fails with No module named 'kitebase', so it starts “fixing” imports that aren’t broken. On this project, the tests only run as python -m pytest. Nobody told it.
Nothing is wrong with the model. That fact just isn’t anywhere in the code. The fix comes in two parts:
- Write such facts down once, in a file the tool reads at the start of every session.
- Add a few settings that decide what the agent may run without asking you.
What you’ll build: three things for the Kitebase ticket service, none of which need an API key:
- a 20-line
CLAUDE.mdand a settings file - a 223-line bad
CLAUDE.mdto compare it with - a small linter that catches the common mistakes in rules files
What a rules file is
A rules file is a Markdown file of standing instructions for a coding agent. It says things like how to run the tests, which conventions to follow and what not to touch.
The tool reads it at the start of a session and puts its text into the model’s context window. The context window is the fixed amount of text the model can see in one request.
That’s the whole mechanism. The tool doesn’t parse the file or check it. In Claude Code, the file’s contents arrive as a user message right after the system prompt, which is the tool’s own built-in instructions.
So a rules file is context, and like any context, the model can still get it wrong. As article 01 put it, the context decides the quality of what comes out. The rules file is the part of it you write in advance.
Each tool reads its own file name. At the time of writing:
| Tool | Main rules file | Scoped rules |
|---|---|---|
| Claude Code | CLAUDE.md (reads AGENTS.md when there’s no CLAUDE.md) | nested CLAUDE.md, .claude/rules/*.md |
| Cursor | AGENTS.md, or .mdc files in .cursor/rules/ | nested AGENTS.md, rules scoped to file patterns |
| Windsurf | AGENTS.md, or .md files in .windsurf/rules/ | nested AGENTS.md, rules scoped to file patterns |
| Other agents | AGENTS.md, a shared convention across tools | nested AGENTS.md; the nearest one wins |
Windsurf’s docs now call the product Devin Desktop and prefer .devin/rules/, though .windsurf/rules/ is still read. The rest of this article uses Claude Code for the details. The ideas carry over to every row.
Where Claude Code looks for it
Four places matter day to day. Each has a scope, meaning who it applies to:
- User:
~/.claude/CLAUDE.md. Your personal preferences for every project on your machine. - Project:
CLAUDE.md(or.claude/CLAUDE.md) in the repo. It’s committed, so the whole team gets it. - Local:
CLAUDE.local.mdnext to it. Personal notes for this one project. Add it to.gitignoreyourself. - Nested: a
CLAUDE.mdin a subfolder, liketests/CLAUDE.md. It’s loaded only when the agent reads a file in that folder.
At launch, Claude Code loads CLAUDE.md and CLAUDE.local.md from the folder you started it in, and from every folder above it. These files are joined, not overridden. Every file goes into the context, broadest first, so the file closest to your working folder is read last. Nested files in subfolders wait until the agent opens something there.
To see what loaded, run /context in a session and look under Memory files. Check that first when the agent seems to ignore your file.
One common surprise: if you started Claude Code in the parent folder of your repo, the repo’s CLAUDE.md counts as nested. It waits until the agent reads a file inside the repo.
/init writes a first draft from the codebase, with the build and test commands it finds. Treat it as a start. It can only write down what’s in the code, and the valuable lines are the ones that aren’t.
CLAUDE.md or AGENTS.md: which one should I write?
If your team uses more than one tool, write AGENTS.md. Cursor, Windsurf and Claude Code all read it.
Claude Code reads AGENTS.md only when there’s no CLAUDE.md in the folder or above it (from version 2.1.277). If you also want Claude-specific lines, keep both files. Start the CLAUDE.md with the line @AGENTS.md to pull the shared file in, and put the Claude-only rules below it.
An @path in a CLAUDE.md is an import. The tool pastes that file in at launch.
What goes in: facts the code can’t tell the agent
Every line has to pass one test. Would a capable engineer, new to this repo, get it wrong without being told? If they’d work it out from the code, leave it out. If they’d only learn it by breaking something, write it down.
Here’s the whole rules file for the Kitebase ticket service:
# Kitebase ticket service
CLI and library for searching Kitebase tickets. Python 3.10+.
## Commands
- Run the tests: `python -m pytest -q` from this folder. Plain `pytest` fails with `No module named 'kitebase'`.
- Try the CLI: `python -m kitebase search "login" --assignee maya`
## Conventions
- Search filters are keyword-only arguments on `search_tickets`, defaulting to `None` for "don't filter". Copy how `assignee` works.
- A new filter needs three things: the argument, a flag in `kitebase/cli.py`, and a test in `tests/test_search.py`.
- Statuses are stored snake_case (`in_progress`). Pass anything a person typed through `normalize_status()` in `kitebase/status.py` before comparing.
## Gotchas
- Standard library only. No new dependencies: this runs on customers' locked-down servers where we can't pip install.
- Archived tickets never appear in search results, whatever the filters. Support's exports rely on it.
- `data/tickets.json` is demo data for the CLI. Tests build their own tickets and must not read it.
That’s twenty lines, about 258 tokens. A token is the unit models read and bill in, roughly four characters of English. Each line blocks a specific way the --status task can go wrong. The file has three sections, and each does a different job.
The test command comes first. An agent that can run your tests can check its own work. Here the obvious guess is wrong. This is what a plain pytest prints:
$ pytest -q
ImportError while loading conftest '.../kitebase-tickets/tests/conftest.py'.
tests/conftest.py:3: in <module>
from kitebase.tickets import Ticket
E ModuleNotFoundError: No module named 'kitebase'
python -m pytest -q prints 9 passed. That’s because python -m puts the current folder on Python’s import path, and bare pytest doesn’t. The rule names the error too, so the agent recognises it instead of “fixing” it.
Conventions say which existing code to copy. “Copy how assignee works” points at the right pattern in one line.
The status rule stops a subtle bug. People type “In progress”, but the data says in_progress, so a raw comparison finds nothing:
>>> [t.id for t in load_tickets() if t.status == "In progress"]
[]
>>> [t.id for t in load_tickets() if t.status == normalize_status("In progress")]
['KB-102', 'KB-105']
An agent that reads status.py may find normalize_status() on its own. The rule makes sure it looks before writing its own version.
Gotchas carry the why. “No new dependencies” on its own is a rule an agent might weigh against a good reason to add click. “Customers’ servers can’t pip install” is a fact it can’t argue with. And no file in the repo says it.
The left column isn’t a transcript of one run. A good agent might avoid some of it. It’s the set of mistakes this repo makes easy, and each one costs a wasted turn or a review comment. The rules file makes them unlikely.
What to leave out
A rules file that nobody prunes fills up with the wrong things. The companion’s examples/bad-CLAUDE.md is that kind of file: 223 lines, about 1,601 tokens. Here are parts of it:
You are an expert senior Python engineer with 20 years of experience. You write
clean, maintainable, production-quality code. You always follow best practices.
KITEBASE_DB_URL=postgres://admin:hunter2@staging-db.kitebase.example:5432/tickets
## Project structure
kitebase-tickets/
├── CLAUDE.md
├── data/
...
## Code reference
Here is the current code so you don't have to look it up.
It makes five mistakes:
- Pasted source code. The “code reference” copies four files, about 100 lines. The agent can read them itself, and the copy goes stale the first time someone edits the real file. Then the model sees two versions of
search_ticketsand can’t tell which is current. - A file tree and a dependency list. The agent can list files. Claude Code’s own
/doctorcheck suggests cutting exactly these, along with architecture overviews. - Vague rules and a persona. “Write clean code”, “never make mistakes”, “you are an expert senior engineer”. Nobody can check them, so they change nothing. Claude Code’s docs give the fix: rules concrete enough to verify. For example, “run
npm testbefore committing” instead of “test your changes”. - Secrets. There’s a database URL with a password, and an API token. The file is committed, and its whole content goes to the model provider every session. Keep secrets in a gitignored
.env, and name the variable instead: “the staging database URL is inKITEBASE_DB_URL”. - No test command. “Make sure the code is well tested” isn’t a command.
Keep it short
Everything in a rules file loads in every session, whether the task needs it or not. So every tool sets a limit:
- Claude Code’s docs target under 200 lines per
CLAUDE.md. Longer files use more context and reduce adherence, meaning the agent follows the rules less reliably. It warns at startup when a file is too long. - Cursor’s docs, at the time of writing, say to keep each rule under 500 lines.
- Windsurf’s docs cap each workspace rule file at 12,000 characters.
The cost isn’t mostly money, since 1,601 tokens is small. The real cost is that three rules which matter sit among forty that don’t. Nothing tells the model which are which.
When a file grows, move rules closer to where they apply:
- Nested files for rules about one folder, like
tests/CLAUDE.md. - Path-scoped rules for rules about one kind of file. These are Markdown files in
.claude/rules/withpaths:frontmatter. Frontmatter is a YAML block between---lines at the top of the file. A path-scoped rule loads only when the agent reads a matching file:
---
paths:
- "tests/**/*.py"
---
Every new filter gets one test in test_search.py and one CLI test in test_cli.py.
An @path import doesn’t help here, because imported files load at launch too.
One trick is free. Block-level HTML comments (<!-- like this -->) in a CLAUDE.md are stripped before the text reaches the model. So notes for human maintainers cost no tokens.
The rules file for this website is a real example. It’s 310 lines, and the companion linter flags it for length and for a 42-line file tree. What earns its place is what no file in the repo could say. It lists features that were tried and removed, each with its reason, so no session adds them back.
Settings: what the agent may run
A rules file is advice. “Don’t read .env” is a sentence the model will usually follow. Claude Code’s docs say it plainly: CLAUDE.md shapes what the agent tries to do, but it isn’t an enforcement layer.
Settings are the enforcement layer. They’re JSON files the tool enforces, whatever the model decides. They have the same scopes as the rules files:
~/.claude/settings.json: you, every project..claude/settings.json: the project, committed..claude/settings.local.json: you, this project. When you answer a permission prompt with “Yes, and don’t ask again”, Claude Code saves the rule here. It keeps this file out of git for you.
When several files have lists, they’re combined, not replaced. Here’s the Kitebase project’s .claude/settings.json:
{
"$schema": "https://json.schemastore.org/claude-code-settings.json",
"permissions": {
"allow": ["Bash(python -m pytest *)", "Bash(python -m kitebase *)"],
"ask": ["Bash(pip install *)"],
"deny": ["Read(./.env)", "Read(./.env.*)"]
}
}
Each entry is a permission rule. A permission rule is a tool name plus a pattern for what it may do.
Bash(python -m pytest *) matches any command starting with python -m pytest. The * has a space before it, so it matches the bare python -m pytest too. The $schema line gives your editor autocomplete for the file.
The order matters. Deny is checked first, then ask, then allow, and the first match decides. So a deny in any file beats an allow in any other.
In the default permission mode, a shell command that no rule matches gets a prompt. The exception is a built-in set of read-only commands like ls.
The allow list is where the day-to-day value is. With the test command allowed, the agent runs python -m pytest -q after every change without waiting for you. Allow what you’d approve every time, like tests, linters and your CLI. Allow nothing that deploys, pushes or deletes.
Claude Code’s permissions docs point out three gotchas:
- Committed allow rules wait for trust. Claude Code asks you to trust a folder the first time you open it. The project’s allow rules apply only after that, so a cloned repo can’t grant itself permissions. Deny and ask rules apply straight away.
- Rules split compound commands.
Bash(python -m pytest *)doesn’t approvepython -m pytest && git push. Each part has to match on its own. - A
Readdeny isn’t a sandbox. It stops Claude’s file tools, and shell commands it recognises, likecat .env. It doesn’t stop a Python script that opens the file itself. For a hard guarantee, Claude Code’s sandbox blocks the path at the operating-system level.
Keeping lockfiles and generated code out of the agent’s searches is a separate job, done with ignore files. That’s in article 05: Context Management.
Lint your rules file
Rules files rot like any docs, and nobody reviews them closely. So the companion includes a linter. It reads a CLAUDE.md or AGENTS.md and flags the problems above. Here’s its check for a missing test command:
TEST_RUNNERS = re.compile(
r"\b(pytest|unittest|npm (run )?test|yarn test|pnpm (run )?test|go test|cargo test"
r"|make test|rspec|mvn test|gradle test|gradlew test|tox|nox|jest|vitest|phpunit|dotnet test)\b"
)
def check_test_command(lines: list[str]) -> list[Problem]:
code = [span for line in lines for span in re.findall(r"`([^`]+)`", line)]
for first, last in fenced_blocks(lines):
code += lines[first - 1 : last]
if any(TEST_RUNNERS.search(snippet) for snippet in code):
return []
return [Problem("warn", "no-tests", "", "no test command in backticks.")]
It only looks inside backticks and code blocks, because that’s where commands live. So “make sure the code is well tested” still fails.
The pasted-code check reads the repo next to the rules file. It flags any code block where 60% of the lines appear in one source file. Here’s the linter on both examples:
CLAUDE.md: 20 lines, about 258 tokens
looks good
bad-CLAUDE.md: 223 lines, about 1,601 tokens
ERROR secret line 37: looks like a credential. Move it to .env.
ERROR secret line 38: looks like a credential. Move it to .env.
WARN too-long 223 lines. Aim for under 200.
WARN restates lines 43-56: a 14-line file tree. The agent can list files.
WARN restates lines 82-124: copies kitebase/tickets.py. Point at the file.
...
WARN no-tests no test command in backticks.
WARN vague lines 11, 15, 16, 22, 24, 219, 220, 221, 223: rules nobody can check.
10 problem(s)
Secrets are errors, and they make the script exit with 1. That means you can run it in CI, the automated checks on every pull request.
The checks are rough on purpose. A regex can’t judge whether a rule is useful. But it catches the mistakes that slip through review.
One companion test is worth copying. It runs the Kitebase test suite with the exact command the CLAUDE.md gives. If someone changes how the tests run and forgets the rules file, that test fails. A wrong command is worse than none.
Try it yourself
The companion example has three parts, and none needs an API key:
- the Kitebase repo, with its rules files and settings
- the bad example, kept outside the repo so no tool loads it
- the linter
Download the runnable example (zip)
cd 03-setting-up-context
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
python main.py
Then try these:
- In
kitebase-tickets/, runpytest -q, thenpython -m pytest -q. The first fails. The second prints9 passed. - Open Claude Code in
kitebase-tickets/and trust the folder. Run/contextand check thatCLAUDE.mdis listed under Memory files. Then ask it to “add a--statusfilter tosearch_tickets”. Check three things: the diff usesnormalize_status(), it adds a CLI flag and a test, and the tests ran without a permission prompt. - Run
python main.py path/to/your/CLAUDE.mdon a rules file from your own work, and fix what it flags.
pytest -q runs the offline tests.
Common beginner mistakes
- No test command, or the wrong one. The agent can’t check its work, or it burns turns on a failure that isn’t a bug.
- Treating it as documentation. Overviews, file trees and pasted code belong in the code and the README.
- Relying on it for safety. “Never read
.env” is advice. A deny rule in.claude/settings.jsonis enforced. - Committing secrets to it. It’s in git and in every session. Name the environment variable instead.
- Never pruning it. Add a line when the agent makes the same mistake twice, as Claude Code’s docs suggest. Delete lines that no longer match the code.
Questions you will face in production
“What do we commit, and what stays personal?”
Commit CLAUDE.md and .claude/settings.json, and review changes to them like code. Personal preferences go in ~/.claude/CLAUDE.md, CLAUDE.local.md and .claude/settings.local.json. Article 09: Team Workflows and Guardrails covers the team side.
“The agent keeps ignoring a rule. What now?” Work through these in order:
- Run
/contextto check the file loaded. - Look for a conflict: two files, or a rule and the code, saying different things. The docs warn the model may pick either.
- Make the rule concrete. “Use
normalize_status()” beats “handle statuses carefully”. - If it must be guaranteed, make it a permission rule or a hook. A hook is a script Claude Code runs at fixed points, like before every tool call.
Check your understanding
A teammate's agent keeps running plain pytest in the Kitebase repo, though CLAUDE.md says python -m pytest -q. What do you check first?
Whether the file loaded. Run /context and look under Memory files.
A common cause is starting Claude Code in the folder above the repo. That makes kitebase-tickets/CLAUDE.md a nested file, which loads late. If it did load, look for another file that contradicts it.
Someone adds "Never run git push" to CLAUDE.md. Is that enough?
No. It’s advice the model will usually follow. If a push must not happen, add a deny rule like Bash(git push *) to .claude/settings.json, which the tool enforces.
Keep branch protection on the server too. The docs note that a push written another way, like git -C . push, isn’t matched.
You added Bash(python -m pytest *) to .claude/settings.json, but Claude Code still asks before every test run. Why?
There are two likely causes:
- The folder isn’t trusted yet, and a committed file’s allow rules wait for that.
- The agent runs a command the rule doesn’t match, like
python3 -m pytestorpytest.
The prompt shows the exact command, so compare it with the rule.
Your frontend rules are 150 lines and only matter in web/. Where do they go?
Out of the root file. You have two options:
- Put them in
web/CLAUDE.md, which loads only when the agent reads a file inweb/. - Put them in
.claude/rules/frontend.mdwithpaths: ["web/**"].
Either way, backend sessions don’t pay for them.
What to remember
- A rules file is text the tool puts into the context at the start of every session. It’s advice, not config.
- Claude Code joins user, project and local
CLAUDE.mdfiles at launch. It loads nested ones when the agent works in that folder./contextshows what loaded. - Write down what the code can’t say: the test command, the conventions to copy, and the gotchas with their reasons.
- Leave out pasted code, file trees, vague rules and secrets. Aim for under 200 lines, and move folder-specific rules into nested files.
- What must be enforced goes in
.claude/settings.json. Allow the commands you’d always approve, and deny what must never happen.
What to study next
A rules file carries the context that’s true for every task. Each request still needs the context for this task: what done looks like, which files matter, and how to check it. That’s article 04: Prompting Coding Agents, which works through the same Kitebase --status task.
Further reading
- Claude Code: How Claude remembers your project. Where
CLAUDE.mdfiles live, load order, imports,.claude/rules/,AGENTS.md, and troubleshooting. The source for the Claude Code details above. - Claude Code: Configure permissions. Allow, ask and deny rules, pattern syntax and what a rule doesn’t match.
- Cursor: Rules. Project rules in
.cursor/rules/, rule types,AGENTS.mdand nested rules. - Devin Desktop (formerly Windsurf): Memories and rules. Rules folders, activation modes and size limits.
- agents.md. The cross-tool
AGENTS.mdconvention and what to put in it.
Where this article comes from. This is a synthesis of common practice in AI engineering as of 2026, not a citation of any single paper. The sources above are where the mechanics come from; the Claude Code details were checked against version 2.1.281 and its docs. If you find an error or have a better source for a claim, the article gets fixed within a day, send me a note.