Objectives: LO-13.1, LO-13.2, LO-13.3
Prerequisites: the Module 13 reading
Time: about 2.5 hours
In this lab you write the configuration of a coding agent for the course’s starter repository:
a CLAUDE.md, a rule scoped to paths, a review skill, permission and hook settings, and a
deny-only hook. Then you check each one in Python, including the hook, which you test by piping
sample events into it.
No cell starts a coding agent or calls a model. The events are sample data in the shape the reading describes, and nothing you write here is installed into a real Claude Code setup.
Each exercise ends with a check cell that prints passed or fails with a message that says what
is wrong. Run the cells in order, from the top, in a fresh kernel. The checks fail until you
finish the exercise above them.
Setup¶
import sys
import json
from pathlib import PurePosixPath
import subprocess
import yaml
read_event = {"hook_event_name": "PreToolUse", "tool_name": "Bash",
"tool_input": {"command": "python -m unittest discover -v"}}
unknown_event = {"hook_event_name": "PreToolUse", "tool_name": "Bash",
"tool_input": {"command": "sample-action"}}
print("Python", sys.version.split()[0])Inspect an event¶
Here are two sample PreToolUse events for the Bash tool, in the shape a hook reads on standard
input: tool_name names the tool, and tool_input holds its arguments. The first proposes the
project’s test command, and the second an unfamiliar command. Predict what a deny-only hook
should print for each, then run the cell.
print(json.dumps([read_event, unknown_event], indent=2))Exercise L13.1 (LO-13.1, ★★, about 25 minutes)¶
Write two instruction files. Write instructions(). Return a dictionary that maps the paths
"CLAUDE.md" and ".claude/rules/fixtures.md" to each file’s text. The project instructions
must name the integer cents convention, with the words “integer cents”, and the test command,
python -m unittest discover -v. Give the rule front matter, between --- lines, whose only key
is paths, set to a list containing "data/**", and add guidance that applies only to
fixtures.
def instructions():
raise NotImplementedError("L13.1")files = instructions()
assert {"CLAUDE.md", ".claude/rules/fixtures.md"} <= set(files), \
"Return both files, keyed by CLAUDE.md and .claude/rules/fixtures.md."
assert "integer cents" in files["CLAUDE.md"], \
'CLAUDE.md should state the money convention with the words "integer cents".'
assert "python -m unittest discover -v" in files["CLAUDE.md"], \
"CLAUDE.md should give the test command, python -m unittest discover -v, exactly."
rule = files[".claude/rules/fixtures.md"]
assert yaml.safe_load(rule.split("---", 2)[1]) == {"paths": ["data/**"]}, \
'Start the rule with front matter between --- lines whose only key is paths: ["data/**"].'
print("passed")Exercise L13.2 (LO-13.1, ★★, about 25 minutes)¶
Resolve a small set of path scopes. Write matches(path, pattern). Return True when
pattern is the same relative path as path, or when pattern is a folder followed by /**
and path lies somewhere inside that folder. Compare whole path components, the names between
slashes, using PurePosixPath, so database/ doesn’t count as data/. A /** pattern needs a
file inside the folder: the folder’s own path doesn’t match. This checker handles only these two
forms; Claude Code’s matching has more.
def matches(path, pattern):
raise NotImplementedError("L13.2")assert matches("data/archive/tickets.json", "data/**"), \
"data/** should match a file at any depth under data/."
assert not matches("database/records.json", "data/**"), \
"Compare whole path components: database isn't the folder data."
assert not matches("data", "data/**"), \
"data/** needs a path inside data/, not the folder's own path."
assert matches("repair_shop.py", "repair_shop.py"), "An exact path should match itself."
print("passed")Exercise L13.3 (LO-13.2, ★★, about 25 minutes)¶
Describe a review skill. Write skill(). Return the complete text of a SKILL.md file. Its
YAML front matter, between --- lines, sets name to review-labels and gives a
description. Its body lists steps that use the words “diff”, “regression”, and “evidence”:
inspect the diff, run the regression tests, and summarize the evidence. In your notes, write
down one bounded task you would delegate to a subagent, and one you would keep.
def skill():
raise NotImplementedError("L13.3")text = skill()
front = yaml.safe_load(text.split("---", 2)[1])
assert front["name"] == "review-labels", "Set name to review-labels in the front matter."
assert front["description"].strip(), "Give the skill a description that isn't empty."
needed = {"diff", "regression", "evidence"}
words = set("".join(c if c.isalpha() else " " for c in text.lower()).split())
assert needed <= words, \
f"Use the words diff, regression, and evidence in the steps; missing {sorted(needed - words)}."
print("passed")Exercise L13.4 (LO-13.3, ★★, about 25 minutes)¶
Set a permission rule. Write settings(). Return a settings dictionary, shaped like
.claude/settings.json, whose permissions allow list holds only the exact test command, in
Bash(...) syntax. Under hooks, add one PreToolUse entry whose matcher is Bash, with a
command hook that runs the project script .claude/hooks/review_command.py with Python. In
your notes, explain what this hook does, and what changes if you remove it.
def settings():
raise NotImplementedError("L13.4")config = settings()
assert config["permissions"]["allow"] == ["Bash(python -m unittest discover -v)"], \
"The allow list should hold one rule: Bash(python -m unittest discover -v)."
rule = config["hooks"]["PreToolUse"][0]
assert rule["matcher"] == "Bash", "Match the Bash tool: the matcher is the exact name Bash."
assert rule["hooks"][0]["type"] == "command", 'The handler\'s type should be "command".'
assert "review_command.py" in rule["hooks"][0]["command"], \
"The handler's command should run .claude/hooks/review_command.py."
print("passed")Exercise L13.5 (LO-13.3, ★★, about 25 minutes)¶
Test a deny-only hook. Write hook_source(). Return the full source of a Python script that
reads one JSON event from standard input. For the exact PreToolUse Bash event that proposes
the test command, it prints nothing. For any other event, and for input it can’t read as an
event, it prints one JSON object whose hookSpecificOutput holds hookEventName
"PreToolUse", permissionDecision "deny", and a permissionDecisionReason. It exits with
status 0 either way. The check pipes events into the script in a Python subprocess. The script
examines the command string and never runs it.
def hook_source():
raise NotImplementedError("L13.5")def run_hook(payload):
process = subprocess.run([sys.executable, "-c", hook_source()], input=payload,
capture_output=True, text=True, timeout=5)
assert process.returncode == 0, \
f"Exit with status 0 for {payload!r}; got {process.returncode}.\n{process.stderr}"
return process.stdout
output = run_hook(json.dumps(read_event))
assert output == "", \
f"Print nothing for the exact test command, so it gets no decision; got {output!r}."
for payload in (json.dumps(unknown_event), "{", "[]", '{"tool_input": null}'):
output = run_hook(payload)
try:
decision = json.loads(output)["hookSpecificOutput"]
except (ValueError, KeyError, TypeError):
raise AssertionError(f"For {payload!r}, print one JSON object with a hookSpecificOutput "
f"key; got {output!r}.") from None
assert decision["hookEventName"] == "PreToolUse", \
f"For {payload!r}, set hookEventName to PreToolUse."
assert decision["permissionDecision"] == "deny", \
f"For {payload!r}, set permissionDecision to deny."
assert decision["permissionDecisionReason"], \
f"For {payload!r}, give a permissionDecisionReason that says why."
print("passed")Summary¶
CLAUDE.mdholds what every task needs, and a rule withpathsadds guidance only when Claude works on matching files.A skill packages a repeated review, with a description that says when it applies.
Permission rules and hook settings are data that Claude Code enforces, not text the model weighs.
A deny-only hook stays silent for the one command it lets through, denies everything else, malformed input included, and is tested by piping sample events into it.