Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Module 13: Configuring a coding agent

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.

MechanismWho acts on itWhat it gives you
CLAUDE.md and rulesThe model reads themGuidance in every session, or for matching files
SkillsThe model, or you with /nameA packaged procedure, loaded when needed
SubagentsThe model delegates to themA task in a separate context, returned as a summary
Permission rulesClaude Code enforces themAllow, ask, or deny for each tool call
HooksClaude Code runs themYour 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 sessionRules in context afterward
The session startsstyle.md
Claude reads test_repair_shop.pystyle.md, python.md
Claude edits data/handbook/sections.jsonstyle.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:

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 *)"]
  }
}
CommandFirst match, checking deny, then ask, then allowOutcome
python -m pytest -qBash(python -m pytest *), allowRuns without asking
git push --force origin mainBash(git push --force *), denyBlocked
git push origin main --forceBash(git push *), askPrompts you
python -m pytest -q && git push origin mainBash(git push *), ask, for the second partPrompts you
python -m pip install requestsNoneThe 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 hookExpected standard outputExit status
Edit with file_path repair_shop.pyNothing0
Edit with file_path data/tickets.jsonA deny decision with a reason0
Write with no file_path in tool_inputA deny decision with a reason0
The text {, which isn’t valid JSONA deny decision with a reason0

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

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

Summary

Self-check

Answer each question before you open its answer.

  1. Where should the integer-cents convention apply?

    Answer

    Put it in CLAUDE.md if 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.

  2. A task edits only repair_shop.py. Does the rule with paths: ["data/**"] load?

    Answer

    No. A path-scoped rule loads only when Claude reads, writes, or edits a file under data/, and repair_shop.py isn’t one.

  3. 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.

  4. 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.

  5. 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.

  6. A settings file denies Bash(git push *), and your personal settings allow Bash(git push origin feature-x). Can Claude run git push origin feature-x without 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