Objectives: LO-13.1, LO-13.2, LO-13.3
Prerequisites: Module 12
Time: about 6 hours: 2 for this reading, 2.5 for Lab 13, and 1.5 for the
practice; Self-test 3 follows, and takes about 2
more
Module 12 put everything the agent needed into each task prompt. Some of it belongs to every task in a repository, such as the test command, or the rule that money is stored in integer cents. This module moves that guidance into files Claude Code loads on its own, and moves the rules that can’t have exceptions into settings Claude Code enforces.
Anthropic’s best practices for Claude Code name
the difference. A prompt, a CLAUDE.md file, or a skill is a non-deterministic instruction: the
model reads it and decides how to follow it. A permission rule or a hook is deterministic: Claude
Code, the harness, applies it every time, whatever the model decided.
| Mechanism | Who acts on it | What it gives you |
|---|---|---|
CLAUDE.md and rules | The model reads them | Guidance in every session, or for matching files |
| Skills | The model, or you with /name | A packaged procedure, loaded when needed |
| Subagents | The model delegates to them | A task in a separate context, returned as a summary |
| Permission rules | Claude Code enforces them | Allow, ask, or deny for each tool call |
| Hooks | Claude Code runs them | Your own check at a fixed point, such as before a tool call |
Lab 13 writes each of these as text or data and checks it in Python. It starts no agent.
Project instructions in CLAUDE.md¶
Claude Code loads project instructions from CLAUDE.md or .claude/CLAUDE.md when a session
starts. Anthropic’s guide to how Claude remembers your project
also describes CLAUDE.local.md, for personal preferences you add to .gitignore. A CLAUDE.md
in a subdirectory loads later, once Claude reads, writes, or edits a file there.
The guide says Claude treats these files as context, not enforced configuration, and strict compliance isn’t guaranteed, especially for vague or conflicting instructions. So write instructions concrete enough to verify. The guide’s target is under 200 lines per file, because a longer file takes more context and Claude adheres to it less closely. The best-practices page adds a test for each line: write down only what Claude can’t find by reading the repository, or would otherwise rediscover every session.
Worked example: revising a CLAUDE.md¶
A second repository at the shop tracks the parts in stock. Its first CLAUDE.md reads:
This project has stock.py, with count_items and reorder, and a tests folder.
Be careful with the stock list. Always write good tests.The first line repeats what Claude can read for itself. The second can’t be checked: no one can say whether “careful” or “good” was followed. A revision:
# Commands
- Run the tests: python -m pytest -q
# Conventions
- Store counts as whole numbers of items, never as fractions or strings.
- The Friday count rewrites data/stock-list.csv; never edit that file by hand.Each line is a command the agent needs to check its work, or a fact the code doesn’t show, and you
can tell whether a session followed it. Exercise L13.1 writes a CLAUDE.md for the starter
repository.
Rules scoped to paths¶
A project can split its instructions into Markdown rules under .claude/rules/, one topic per
file. A rule’s front matter decides when it loads. A rule without paths loads when a session
starts, as .claude/CLAUDE.md does. A rule with paths loads only when Claude reads, writes, or
edits a file that matches one of its patterns, so a task that never touches those files never sees
it. The patterns are globs, wildcard patterns for file paths, relative to the project folder:
data/** matches every file under data/, and **/*.py matches every Python file.
---
paths: ["data/**"]
---
Fixture IDs are a letter and two digits, such as T07. Never reuse an ID.With this rule in .claude/rules/fixtures.md, a task that edits data/tickets.json loads it, and a
task that edits only repair_shop.py doesn’t. The memory guide adds a trap: if the front matter’s
YAML doesn’t parse, Claude Code loads the rule as if it had no paths, so a typo makes a scoped
rule load everywhere.
The lab implements exact path and directory-prefix checks for this subset. Full Claude Code path
matching has more forms, such as braces that list alternatives (src/**/*.{ts,tsx}), and a
pattern with no folder, such as *.md, matches at any depth. Test scope examples against the
configuration you intend to maintain.
Worked example: which rules load, and when¶
A project has three rules: style.md with no paths, fixtures.md with paths: ["data/**"],
and python.md with paths: ["**/*.py"]. Follow one session:
| Step in the session | Rules in context afterward |
|---|---|
| The session starts | style.md |
Claude reads test_repair_shop.py | style.md, python.md |
Claude edits data/handbook/sections.json | style.md, python.md, fixtures.md |
Reading notes/data/summary.md wouldn’t load fixtures.md: data/** is relative to the project
folder, so it matches only the top-level data/. Exercise L13.2 writes a matcher for exact paths
and /** prefixes.
Skills: package a repeated workflow¶
A skill packages a recurring procedure, such as a release or a review, in a SKILL.md file in
its own folder under .claude/skills/. Anthropic’s skills guide
describes its YAML front matter: name defaults to the folder’s name, and description is what
Claude uses to decide when to apply the skill. Claude sees the descriptions, so it knows which
skills exist, but a skill’s body loads only when the skill is used. You can start a skill yourself
by typing / and its name.
For a workflow with side effects, the best-practices page recommends
disable-model-invocation: true, so the skill runs only when you start it. The skills guide
suggests keeping SKILL.md under 500 lines, with detailed reference material in files beside it.
Worked example: a stock-count skill¶
The stock repository’s weekly count becomes .claude/skills/friday-count/SKILL.md:
---
name: friday-count
description: "Friday stock count: compare scanned counts with data/stock-list.csv."
disable-model-invocation: true
---
1. Check that the working tree is clean. If it isn't, stop and ask.
2. Run python tools/scan_counts.py, which prints each item's scanned count.
3. Report each item whose count differs from data/stock-list.csv. Don't edit any file.The description is in double quotes because it contains a colon followed by a space, which unquoted YAML would read as the start of a new key. Exercise L13.3 writes a review skill and checks its front matter.
Subagents: delegate a bounded task¶
A subagent is a helper with its own context window, system prompt, tool access, and
permissions. Anthropic’s subagents guide says it
works in that separate context and returns only a summary, so long search results stay out of the
main conversation. Project subagents are Markdown files in .claude/agents/, with a required
name and description.
A subagent starts without your conversation history or the files already read. A custom
subagent still loads the project’s CLAUDE.md files, though the built-in Explore and Plan
subagents start without them. Its task message must carry everything else it needs, like a
Module 12 task prompt. The guide suggests a subagent for self-contained work with verbose
output, and the main conversation for back-and-forth, shared context, or a quick change.
Worked example: what to delegate¶
A change to the stock repository’s count format raises two questions:
“List every test that reads
data/stock-list.csv, with its file and line.” This suits a subagent: it is self-contained, its search output is long, and a list is all you need back.“Should the count format change at all?” This stays in the main conversation: it is a decision that needs your judgment and the whole discussion.
Delegate a bounded review, such as of test coverage, when an isolated context helps. Keep product decisions and the integration of results with the main task.
Permission rules¶
Instructions and skills describe expected behavior; permissions and hooks enforce it. Permission
rules allow, ask about, or deny tool operations, and they live under permissions in
.claude/settings.json. Anthropic’s guide to
configuring permissions says Claude Code enforces
them, not the model, so no prompt or CLAUDE.md line changes them.
A Bash rule names a command: Bash(python -m pytest -q) matches exactly that command, and
Bash(python -m pytest *) matches it with any arguments or none. The space before the * counts:
Bash(ls *) matches ls -la but not lsof. A compound command joined by &&, ;, or | runs
without a prompt only if every part is allowed, and a deny or ask rule applies if any part matches.
Claude Code checks deny rules first, then ask rules, then allow rules, and the first match decides,
so a broad deny beats a narrower allow. The same holds across the settings files that the
settings guide lists: yours in
~/.claude/settings.json, the project’s shared .claude/settings.json, your overrides in
.claude/settings.local.json, and an organization’s managed settings. Their permission lists
merge, and a deny in any of them beats an allow in another.
Worked example: which rule decides?¶
A project’s settings hold three rules:
{
"permissions": {
"allow": ["Bash(python -m pytest *)"],
"ask": ["Bash(git push *)"],
"deny": ["Bash(git push --force *)"]
}
}| Command | First match, checking deny, then ask, then allow | Outcome |
|---|---|---|
python -m pytest -q | Bash(python -m pytest *), allow | Runs without asking |
git push --force origin main | Bash(git push --force *), deny | Blocked |
git push origin main --force | Bash(git push *), ask | Prompts you |
python -m pytest -q && git push origin main | Bash(git push *), ask, for the second part | Prompts you |
python -m pip install requests | None | The permission mode decides |
The third row is a gap: the deny pattern expects --force right after push, so a flag at the end
slips past it. The permissions guide warns that Bash patterns that try to constrain arguments are
fragile. Exercise L13.4 writes the permission rule and hook settings for the starter repository.
Hooks¶
A hook is trusted code that Claude Code runs at a configured event. Hooks live in the same settings file, nested by event, then by a matcher that names the tools, then by the handlers to run. This example allows one test command and runs a script before every edit:
{
"permissions": {
"allow": ["Bash(python -m pytest -q)"]
},
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "python .claude/hooks/check_paths.py" }
]
}
]
}
}A matcher made of tool names separated by | lists exact names, so Edit|Write matches those
two tools and Bash matches only Bash; a matcher with other characters is a regular expression.
A PreToolUse hook runs before the tool does. It reads a JSON event on standard input, with the
tool’s name in tool_name and its arguments in tool_input. To refuse the call, it prints one
JSON object and exits with status 0:
{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": "Edits under data/ need a reviewed fixture change."
}
}Claude Code then blocks the call and shows Claude the reason, so write a reason that says what to
do instead. A hook that prints nothing and exits with status 0 makes no decision: the call
continues through the normal permission rules, so silence doesn’t approve it. Exit status 2 also
blocks the call, with the hook’s standard error as the message. Nor does a hook’s "allow"
override the rules: the hooks reference says deny and
ask rules still apply, whatever the hook returns.
Hooks fail open. By default, a hook that crashes, exits with any other nonzero status, prints
invalid JSON, or runs past its timeout (600 seconds for a command hook) counts as an error, and
the tool call goes ahead. A deny-only hook must therefore catch its own errors and print a deny
decision for any event it can’t read. (Claude Code v2.1.295 and later also offer an onFailure
setting that makes a failed hook block the call.)
Review hooks before enabling them, because a command hook runs a program on your machine at its configured event. In the lab, the hook reads standard input and prints a deny decision for anything except the exact test command, malformed events included. For the expected command it prints nothing, deferring to the normal permissions and other controls. Printing nothing isn’t a security sandbox, and it isn’t evidence that a command ran.
Worked example: testing a hook by piping events¶
Anthropic’s hooks guide suggests testing a hook by
piping sample JSON into it, outside any session. For check_paths.py, which should deny edits
under data/ and stay silent otherwise, the test plan is a table:
| Event piped to the hook | Expected standard output | Exit status |
|---|---|---|
Edit with file_path repair_shop.py | Nothing | 0 |
Edit with file_path data/tickets.json | A deny decision with a reason | 0 |
Write with no file_path in tool_input | A deny decision with a reason | 0 |
The text {, which isn’t valid JSON | A deny decision with a reason | 0 |
One row as a command, with the exit status printed after it:
echo '{"hook_event_name": "PreToolUse", "tool_name": "Edit",
"tool_input": {"file_path": "data/tickets.json"}}' | python .claude/hooks/check_paths.py
echo "exit $?"The last two rows matter most, because that is where a hook fails open. The guide also warns that
a permissionDecision printed outside hookSpecificOutput is ignored without an error, so check
the output’s shape, not only that something was printed. Exercise L13.5 tests a deny-only Bash
hook this way.
What configuration can and can’t prevent¶
Instructions shape what Claude tries, and Claude may judge that a guideline doesn’t apply. The best-practices page says a line that Claude keeps missing despite added emphasis belongs in a hook.
Permission rules match the command text Claude writes. The permissions guide shows that a deny rule
Bash(curl *)stopscurl https://example.combut not/usr/bin/curlorsh -c 'curl …', and points to sandboxing for limits that don’t depend on the command text.Hooks see only the events their matcher names. A
Bashhook never sees anEdit, and the hooks guide notes that an edit hook doesn’t stop changes made through shell commands. An incorrect matcher, a different tool, or an inactive configuration can leave a condition unchecked, so test the handler with sample events and check the effective settings separately.
Module 11’s lesson applies. An agent that reads untrusted text, such as an issue comment, can be steered by an injection in it, and the deterministic layer is what still holds: deny rules give least privilege, and ask rules are the approval gate.
Common misconceptions¶
“A line in
CLAUDE.mdis a rule Claude must obey.” It is context, not enforced configuration. “Never editdata/stock-list.csv” works most of the time; a deny rule works every time.“A more specific allow overrides a broad deny.” Deny rules are checked first. With
Bash(git push *)denied, an allow forBash(git push origin main)changes nothing.“A hook that prints nothing approved the call.” It made no decision, and the call goes on to the permission rules, which may still ask or deny.
“A hook that crashes blocks the call.” By default, a crash, a timeout, or invalid JSON lets the call through.
“Path-scoped rules load at session start.” Only rules without
pathsdo. In the worked example,fixtures.mdarrives when Claude first edits a file underdata/.
Summary¶
CLAUDE.mdand rules withoutpathsload when a session starts. A rule withpathsloads when Claude reads, writes, or edits a file that matches one of its patterns. Both are context, not enforcement.A skill packages a repeated workflow, loaded when used, and a subagent takes a bounded task with its own context and returns a summary.
Permission rules allow, ask about, or deny tool calls, checked in that order: deny, then ask, then allow. A deny in any settings file beats an allow in another.
A
PreToolUsehook can deny a call with a reason. A silent hook decides nothing, and a hook that fails lets the call through, so test the hook with sample events, malformed ones included.
Self-check¶
Answer each question before you open its answer.
Where should the integer-cents convention apply?
Answer
Put it in
CLAUDE.mdif all changes must follow it, since that file loads in every session. Put fine-grained fixture conventions in a rule scoped to the relevant paths, so they cost context only when Claude works on those files.A task edits only
repair_shop.py. Does the rule withpaths: ["data/**"]load?Answer
No. A path-scoped rule loads only when Claude reads, writes, or edits a file under
data/, andrepair_shop.pyisn’t one.Which part of the diff review is a bounded subagent task?
Answer
Reviewing whether a named diff covers the specified test cases: it is self-contained, and a summary of the gaps is all the main task needs back. Keep the decision to accept the diff with the main task, which holds the context and your judgment.
Does an empty hook result authorize a command?
Answer
No. It gives no decision, so the permission rules, the permission mode, and any other controls still apply.
A deny-only hook raises an exception on an event it can’t parse. Is the tool call blocked?
Answer
No. Hooks fail open: an error lets the call through. Catch the error in the hook and print a deny decision instead.
A settings file denies
Bash(git push *), and your personal settings allowBash(git push origin feature-x). Can Claude rungit push origin feature-xwithout asking?Answer
No. Deny rules from every settings file are checked before allow rules, and the first match decides, so the broad deny blocks the push. An allow can’t carve an exception out of a deny.
Further reading¶
Anthropic, How Claude remembers your project. Where
CLAUDE.mdfiles and rules live, when each loads, and how to write instructions Claude follows.Anthropic, Extend Claude with skills. Skill folders, front matter, and who can start a skill.
Anthropic, Create custom subagents. What a subagent starts with, what it returns, and when to use one.
Anthropic, Configure permissions. Rule syntax, the order of evaluation, and what a Bash rule doesn’t match.
Anthropic, Hooks reference and Automate actions with hooks. Every event’s input and output, the exit codes, and worked hook scripts.
Anthropic, Settings files and precedence. Which settings file applies to whom, and how the layers combine.