Vibe coding with Claude Code course Β· Module 15: Advanced Claude Code
Crew rules: CLAUDE.md for the team, path rules and settings
In this lesson9
Treasure Map keeps growing and so does its CLAUDE.md. After a few weeks of adding lines it runs past a hundred: half of it describes directories, the rules for API routes sit between the rules for components, and yesterday Claude wrote a route without checking the session, although that rule stood on line 112. On top of that a second person is joining the project, and you do not want them to receive your notes about the local database. One long file has stopped being a map and become a heap of parchments.
What you already know
In lesson 1_7 you generated CLAUDE.md with the /init command, imported AGENTS.md with the line @AGENTS.md and learned that the work after that is mostly crossing things out. In lesson 8_4 you shut .env with a deny rule in .claude/settings.json, and in lesson 10_5 you added ask rules for deployments. In lessons 14_1 and 14_2 you wrote scripts with claude -p. Now you set the same order for the crew: who reads which rules, when, and from whose file.
Four levels of memory
Claude Code looks for instruction files in four places. Here they are, from the widest reach to the narrowest:
/Library/Application Support/ClaudeCode/CLAUDE.md # organisation policy (macOS), installed by the IT department
~/.claude/CLAUDE.md # you, in all projects
treasure-map/CLAUDE.md # the whole crew, in the repository
treasure-map/CLAUDE.local.md # you, this project only, outside GitThe files do not overwrite each other, they are joined into one text: the wider ones first, and CLAUDE.local.md at the end of its level. When two files say different things, Claude may pick either version, so keeping them consistent is your job. You cannot switch off an organisation policy on your machine, but Treasure Map has none, because it applies to company computers. A CLAUDE.md in a subdirectory, for example app/api/CLAUDE.md, loads only when Claude touches a file in that directory.
Request for Claude Code
You order the tidying instead of doing it by hand. In a session in the treasure-map folder write:
Review @CLAUDE.md. Remove the lines you could read from the code or from package.json,
including the description of directories. Move the rules for app/api to .claude/rules/api.md
and the ones for components/ to .claude/rules/components.md, each with a paths header.
Move my notes about the local database to CLAUDE.local.md and add it to .gitignore.
Done when CLAUDE.md has fewer than 30 lines. At the end list what you removed and where you moved it.The request names three targets and gives a measure of the end, so Claude knows when to stop and you know what to check.
What Claude wrote: a short CLAUDE.md
Open CLAUDE.md in Cursor. After the tidying ours was left like this:
@AGENTS.md
# Check commands
- One test file: `npm run test -- --run lib/pins.test.ts`
- All tests: `npm run test -- --run`
- Types: `npx tsc --noEmit`, lint: `npm run lint`
# Pitfalls
- The database from `npx prisma dev` starts separately; without it the routes in app/api return 500.
- `getCurrentUserId()` from `lib/session.ts` is a fake login from the `demo-user` cookie.
# Decisions
- We do not edit migrations in `prisma/migrations/`; a schema change is a new migration.Every line says something Claude will not see in the code: how to check the work, where the code misleads and what the crew has agreed. The directory description and the list of libraries are gone, because Claude reads the repository anyway. The @AGENTS.md import stayed at the top, as in lesson 1_7. Just remember that an import tidies but does not slim down: the imported file loads together with CLAUDE.md and takes the same amount of room in the context.
What Claude wrote: rules with paths
The rules for parts of the code went into the .claude/rules/ folder. A rule is an ordinary Markdown file with frontmatter, that is, settings between --- lines, like the skill from lesson 6_1:
---
paths:
- "app/api/**/*.ts"
---
# API routes
- Every route that changes data first calls `getCurrentUserId()`: no session is 401, someone else's board is 403.
- Check the input with a Zod schema from `lib/`, never with a hand-written `typeof`.
- The test of a route lies next to it and mocks `@/lib/session`.paths is the only field Claude Code reads from a rule. The pattern is counted from the project folder: ** means any depth, and *.ts every TypeScript file. According to the documentation such a rule enters the context only when Claude reads, writes or edits a matching file, while a rule without paths loads at the start, like CLAUDE.md. We checked it: Claude read app/api/boards/[id]/pins/route.ts, api.md appeared in the context and components.md did not. It also noticed at once that this route checks pinId with a hand-written typeof, against the second rule.
Personal notes went to CLAUDE.local.md, and one line with the name of that file was added to .gitignore:
CLAUDE.local.mdClaude reads this file like any other CLAUDE.md, but Git does not see it, so your notes will not sail off to the crew.
Captain's review
Open the diff of CLAUDE.md in the Source Control panel and check:
- The test of every line. Would Claude find it in the code? If so, the line is to be crossed out.
- The pattern hits files.
app/api/**/*.tsmatches the Treasure Map routes. A patternsrc/app/api/**copied from another project matches nothing, because there is nosrcfolder here, and the rule will quietly never load. Ask Claude to read one route and ask which rules from.claude/rulesit now has in the context. - The private file is private.
git check-ignore -v CLAUDE.local.mdprints the.gitignoreline that hides it. An empty answer means the file will go into the commit.
A typical agent mistake: "while tidying", Claude writes back a section like # Project structure with a tree of app/, lib/ and components/. You will recognise it in the diff by the green directory tree. The official best practices say outright that you do not describe the architecture and file layout, because Claude reads the repository itself. For a periodic review there is /doctor prompt-audit: Claude looks through CLAUDE.md, rules, skills and agents for outdated and contradictory instructions, and changes nothing until you ask it to.
Settings: who has the last word
Memory tells Claude how to work, and settings tell Claude Code what to allow. There are also several settings files. When the same key stands in two of them, the higher one wins, counting from the top:
- the organisation's managed settings;
- the command line, that is
--settingsat start; .claude/settings.local.json: you, this project;.claude/settings.json: the crew, in the repository;~/.claude/settings.json: you, all projects.
Lists such as permissions.allow do not overwrite each other, they merge. This is how the crew file looks in Treasure Map:
{
"permissions": {
"allow": ["Bash(npm run test *)", "Bash(npm run lint)", "Bash(npx tsc --noEmit)"],
"ask": ["Bash(npx prisma migrate *)", "Bash(git push *)"],
"deny": ["Read(./.env)", "Read(./.env.*)"]
}
}allow lets tests, lint and types through without asking, ask makes Claude ask about migrations and push, and deny from lesson 8_4 shuts the secrets. For every call Claude Code checks the rules in the same order: deny first, then ask, allow last, no matter which file they come from. When no rule matches, the permission mode decides. So your allow for git push in the user settings will not beat the crew's ask, and a deny from any file beats every allow. Your own exceptions go in the local file:
{
"permissions": {
"allow": ["Bash(npx prisma studio)"]
}
}This is also where Claude Code saves your answer "Yes, and don't ask again", and on the first write it protects this file from a commit by itself. A file you created by hand, add to .gitignore yourself. One more rule for the crew: the allow rules from .claude/settings.json work only after you accept the folder trust dialog, while deny and ask work at once, because they only restrict. Our claude -p run in an untrusted folder printed: Ignoring 3 permissions.allow entries from .claude/settings.json: this workspace has not been trusted.
When a rule works differently than you think, type /permissions: this command shows every rule together with the file it comes from. /status shows only which settings files were loaded.
Scripts with arguments: $1 and "$*"
The crew rules are also useful in the scripts from lesson 14_2. An argument is a word typed after the script name: Bash puts the first one into $1 and all of them together into "$*". A component generator needs one name:
NAME=$1
if [ -z "$NAME" ]; then
echo "Give the component name, e.g.: bash scripts/generate-component.sh BoardBadge"
exit 1
fiAfter bash scripts/generate-component.sh BoardBadge the variable NAME is BoardBadge, and with no argument the script ends before you pay for an empty run. Further on, the name goes into the command:
claude -p "Create a React component $NAME in TypeScript in components/$NAME.tsx and a Vitest test in components/$NAME.test.tsx. Follow the rules from .claude/rules/components.md." \
--model sonnet --allowedTools "Write" --max-turns 6Why does the request point to the rule directly? A rule with paths loads when a matching file is read, written or edited, and the new component does not exist until Claude writes it. --allowedTools "Write" approves writing new files, as in lesson 14_1. In the editor task you will add a third file, .stories.tsx for Storybook, a tool that shows components in isolation.
A code search, on the other hand, needs a whole sentence, so it takes all the arguments:
QUERY="$*"
claude -p "Find the code in the project that concerns: $QUERY. Answer with a list: file:line and one sentence on what happens there." \
--model sonnet --tools "Read,Grep,Glob" --max-turns 6After bash scripts/ai-search.sh where we check the board owner a script with $1 would pass Claude just "where", and with "$*" the whole sentence. The quotes are a good habit: when $* without quotes stands in a command as an argument, Bash splits the text into words and turns an asterisk from the question into a list of files. On a dummy claude the question where * we check turned for us into "where AGENTS.md CLAUDE.local.md CLAUDE.md README.md app ...". The tools Read,Grep,Glob are enough, because in -p mode Claude reads without asking.
Next step
Add a third rule and check it at once:
Add .claude/rules/testing.md with the Vitest testing rules and paths for *.test.ts and *.test.tsx.
Then read lib/pins.test.ts and list the rules from .claude/rules that you have in the context now.Ask for a commit, for example "Crew rules: short CLAUDE.md, rules and settings", and check in Source Control that it contains neither CLAUDE.local.md nor .claude/settings.local.json. In the editor next to the lesson you will pick a file from Treasure Map and see which memory files and rules enter the context then, and for a chosen command which permission rule decides about it and which file it comes from.
Remember: on the map for the crew you mark the reefs, not every wave.
Code for this lesson: App.tsx
// Map of crew rules: which instructions Claude sees for a given file and which rule decides about a command
import { useState } from 'react';
export interface MemoryFile {
path: string;
scope: string;
paths?: string[];
}
export const MEMORY: MemoryFile[] = [
{ path: '~/.claude/CLAUDE.md', scope: 'you, all projects' },
{ path: 'CLAUDE.md', scope: 'the crew, in the repository' },
{ path: 'CLAUDE.local.md', scope: 'you, this project, outside Git' },
{ path: '.claude/rules/api.md', scope: 'a rule with paths', paths: ['app/api/**/*.ts'] },
{ path: '.claude/rules/components.md', scope: 'a rule with paths', paths: ['components/**/*.tsx'] },
{ path: '.claude/rules/testing.md', scope: 'a rule with paths', paths: ['**/*.test.ts', '**/*.test.tsx'] },
];
export const FILES = [
'app/api/pins/route.ts',
'app/api/boards/[id]/pins/route.ts',
'components/PinCard.tsx',
'lib/pins.ts',
'lib/pins.test.ts',
'prisma/schema.prisma',
];
const SPECIAL = '.+?^$()[]{}|\\';
export function globToRegExp(glob: string): RegExp {
let re = '';
for (let i = 0; i < glob.length; i++) {
const ch = glob[i];
if (ch === '*' && glob[i + 1] === '*') {
if (glob[i + 2] === '/') {
re += '(?:.*/)?';
i += 2;
} else {
re += '.*';
i += 1;
}
} else if (ch === '*') {
re += '[^/]*';
} else if (SPECIAL.includes(ch)) {
re += '\\' + ch;
} else {
re += ch;
}
}
return new RegExp('^' + re + '$');
}
export interface Loaded {
path: string;
scope: string;
status: 'start' | 'file' | 'no';
note: string;
}
export function loadedFor(file: string, apiPattern: string): Loaded[] {
return MEMORY.map((m) => {
if (!m.paths) {
return { path: m.path, scope: m.scope, status: 'start', note: 'loads at the start of the session' };
}
const patterns = m.path === '.claude/rules/api.md' ? [apiPattern] : m.paths;
const hit = patterns.some((p) => globToRegExp(p).test(file));
return hit
? { path: m.path, scope: m.scope, status: 'file', note: 'loads when Claude reads, writes or edits this file (paths: ' + patterns.join(', ') + ')' }
: { path: m.path, scope: m.scope, status: 'no', note: 'does not match ' + patterns.join(', ') };
});
}
export type Decision = 'deny' | 'ask' | 'allow';
export interface Rule {
decision: Decision;
pattern: string;
source: string;
}
export const RULES: Rule[] = [
{ decision: 'allow', pattern: 'Bash(git push *)', source: '~/.claude/settings.json' },
{ decision: 'allow', pattern: 'Bash(npm run test *)', source: '.claude/settings.json' },
{ decision: 'allow', pattern: 'Bash(npm run lint)', source: '.claude/settings.json' },
{ decision: 'ask', pattern: 'Bash(npx prisma migrate *)', source: '.claude/settings.json' },
{ decision: 'ask', pattern: 'Bash(git push *)', source: '.claude/settings.json' },
{ decision: 'deny', pattern: 'Read(./.env)', source: '.claude/settings.json' },
{ decision: 'allow', pattern: 'Bash(npx prisma studio)', source: '.claude/settings.local.json' },
];
export const COMMANDS = [
'npm run test -- --run',
'npm run lint',
'npx prisma migrate dev',
'git push origin main',
'cat .env',
'npx prisma studio',
'npm install',
];
export function ruleMatches(pattern: string, command: string): boolean {
const m = /^(\w+)\((.*)\)$/.exec(pattern);
if (!m) return false;
const tool = m[1];
const arg = m[2];
if (tool === 'Read') {
const parts = command.split(' ');
return parts[0] === 'cat' && parts[1] === arg.replace(/^\.\//, '');
}
if (arg.endsWith(' *')) {
const prefix = arg.slice(0, -2);
return command === prefix || command.startsWith(prefix + ' ');
}
return command === arg;
}
export interface Verdict {
decision: Decision | 'mode';
rule?: Rule;
text: string;
}
export function decide(command: string, rules: Rule[], trusted: boolean): Verdict {
const order: Decision[] = ['deny', 'ask', 'allow'];
let skipped = false;
for (const decision of order) {
for (const r of rules) {
if (r.decision !== decision || !ruleMatches(r.pattern, command)) continue;
if (decision === 'allow' && !trusted && r.source === '.claude/settings.json') {
skipped = true;
continue;
}
const texts: Record<Decision, string> = {
deny: 'Refused. deny is checked first and beats every allow, from any file.',
ask: 'Claude Code asks for consent. ask comes before allow, so no allow beats it.',
allow: 'No asking.',
};
return { decision, rule: r, text: texts[decision] };
}
}
return {
decision: 'mode',
text: skipped
? 'The allow rule from .claude/settings.json waits for folder trust, so the permission mode decides.'
: 'No rule matches, so the permission mode decides.',
};
}
const STATUS_CLASS: Record<Loaded['status'], string> = {
start: 'text-sky-300',
file: 'text-emerald-400',
no: 'text-slate-500',
};
const DECISION_CLASS: Record<Verdict['decision'], string> = {
deny: 'text-rose-400',
ask: 'text-amber-400',
allow: 'text-emerald-400',
mode: 'text-slate-300',
};
export default function App() {
const [file, setFile] = useState(FILES[1]);
const [apiPattern, setApiPattern] = useState('app/api/**/*.ts');
const [command, setCommand] = useState(COMMANDS[3]);
const [trusted, setTrusted] = useState(true);
const loaded = loadedFor(file, apiPattern);
const verdict = decide(command, RULES, trusted);
return (
<div className="min-h-screen space-y-4 bg-slate-950 p-4 text-slate-100">
<h1 className="text-xl font-bold">Crew rules in Treasure Map</h1>
<section className="space-y-2">
<h2 className="font-semibold">Memory and rules for a file</h2>
<label className="block text-sm">
Claude works with the file{' '}
<select className="rounded bg-slate-800 p-1" value={file} onChange={(e) => setFile(e.target.value)}>
{FILES.map((f) => (
<option key={f} value={f}>{f}</option>
))}
</select>
</label>
<label className="block text-sm">
paths in .claude/rules/api.md{' '}
<input className="rounded bg-slate-800 p-1 font-mono" value={apiPattern} onChange={(e) => setApiPattern(e.target.value)} />
</label>
<ul className="space-y-1 text-sm">
{loaded.map((l) => (
<li key={l.path} className="rounded border border-slate-800 p-2">
<strong className={STATUS_CLASS[l.status]}>{l.path}</strong> ({l.scope}): {l.note}
</li>
))}
</ul>
</section>
<section className="space-y-2">
<h2 className="font-semibold">Who decides about a command</h2>
<div className="flex flex-wrap items-center gap-3 text-sm">
<select className="rounded bg-slate-800 p-1 font-mono" value={command} onChange={(e) => setCommand(e.target.value)}>
{COMMANDS.map((c) => (
<option key={c} value={c}>{c}</option>
))}
</select>
<label className="flex items-center gap-2">
<input type="checkbox" checked={trusted} onChange={(e) => setTrusted(e.target.checked)} />
I accepted the folder trust dialog
</label>
</div>
<p role="status" className="rounded border border-slate-700 p-2 text-sm">
<strong className={DECISION_CLASS[verdict.decision]}>{verdict.decision}</strong>{' '}
{verdict.rule ? verdict.rule.pattern + ' from the file ' + verdict.rule.source + '. ' : ''}
{verdict.text}
</p>
<ul className="font-mono text-xs text-slate-400">
{RULES.map((r, i) => (
<li key={i}>{r.decision} {r.pattern} ({r.source})</li>
))}
</ul>
</section>
</div>
);
}Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. The rules concern only the routes in app/api of Treasure Map. Where do you write them so that Claude has them in context only when working with those files?
2. Which line is worth removing from the Treasure Map CLAUDE.md?
These are 2 of 10 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Vertical ordering
Arrange the lines of the .claude/rules/api.md file from the top, as in the lesson:
- Vertical ordering
Arrange the parts of the short Treasure Map CLAUDE.md from the top: first the import, then how to check the work, then pitfalls, and last the crew decisions:
- Code editor
In commands.sh write the smart-commit.sh script: take the staged diff (git diff --cached), ask claude -p for a message in Conventional Commits format, show it, ask for approval (read) and run git commit -m.
- Vertical ordering
Arrange the CLAUDE.md files from the widest reach to the narrowest, that is, in the order in which Claude Code joins them in the context:
- Code editor
In commands.sh write the generate-component.sh script: take the component name from $1 and ask claude -p for three files in src/components: <Name>.tsx, <Name>.test.tsx and <Name>.stories.tsx (Storybook).
- Vertical ordering
The same key stands in several settings files. Arrange the sources from the one that wins to the one that loses:
- Code editor
In commands.sh write the ai-search.sh script: take the query from the script arguments ($1 or "$*") and pass it to claude -p so that Claude finds the matching code itself and lists files and line numbers.
- Vertical ordering
Arrange the order in which Claude Code checks the permission rules for one tool call:
- Horizontal ordering
Arrange the ask rule that makes Claude Code ask for consent on every Prisma migration command:
- Click in order
Click the elements in order to check which .gitignore line hides your private notes:
- Click in order
Click the elements in order to build a paths pattern that matches every .ts file in app/api, also in subfolders:
Tasks after this lesson
- QuestionQuiz: A rule for API routes
- Put in orderSorting: A rule file with paths
- Put in orderSorting: Parts of the Treasure Map CLAUDE.md
- Coding taskPractice: Smart commit generator
- QuestionQuiz: A line to cross out of CLAUDE.md
- Put in orderSorting: Memory levels from the widest
- Coding taskPractice: Component generator
- QuestionQuiz: Private notes in a project
- QuestionQuiz: An import and the context size
- Put in orderSorting: Precedence of settings files
- Coding taskPractice: Plain-language code search
- QuestionQuiz: An ask rule and an allow from another file
- Put in orderSorting: The order of rule checks
- Put in orderSorting: An ask rule for migrations
- QuestionQuiz: A personal rule in a project
- Click in orderSequence: Is the private file hidden
- QuestionQuiz: The source of a permission rule
- QuestionQuiz: Allow rules and folder trust
- Click in orderSequence: A paths pattern for routes
- QuestionQuiz: When a rule with paths loads
- QuestionQuiz: $1 versus "$*" in a script