"Only edit files in your own copy of the project" is an instruction agents follow most of the time, and most of the time isn't good enough. Claude Code lets an agent definition carry its own hooks, which run only while that agent is active. My coder's definition carries a hook that blocks any edit outside its assigned copy. The roles that only read get a stricter version that blocks every write inside the project, so they can't leave stray test files behind.
Add the hook to the agent's frontmatter, and change --seat for each role:
hooks:
PreToolUse:
- matcher: "Edit|Write|NotebookEdit|Bash"
hooks:
- type: command
command: 'python3 /path/to/fence.py --seat coder'
Name the copy's full path in every brief you send the agent. The hook reads the agent's own conversation record (Claude Code passes its location to the hook) and finds the path in the brief. That's how it knows which copy belongs to this agent.
A minimal fence:
#!/usr/bin/env python3
import json, os, re, sys, tempfile
def deny(reason):
print(json.dumps({"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": reason}}))
sys.exit(0)
def main():
seat = sys.argv[sys.argv.index("--seat") + 1] if "--seat" in sys.argv else "coder"
data = json.load(sys.stdin)
tool, inp = data.get("tool_name", ""), data.get("tool_input") or {}
# The brief is the first message in this agent's own record.
try:
with open(data.get("transcript_path") or "", errors="replace") as f:
head = f.read(5_000_000)
except OSError:
head = ""
slugs = set(re.findall(r"\.claude/worktrees/([A-Za-z0-9._-]+)", head))
slug = slugs.pop() if len(slugs) == 1 else None # none or several: no worktree writes
def allowed(path):
p = os.path.realpath(os.path.join(data.get("cwd") or os.getcwd(), path))
if p.startswith(os.path.realpath(tempfile.gettempdir()) + os.sep):
return True # scratch space
if "/.claude/runs/" in p + "/":
return True # run notes, progress log
return seat == "coder" and slug is not None \
and f"/.claude/worktrees/{slug}/" in p + "/"
if tool in ("Edit", "Write", "NotebookEdit"):
target = inp.get("file_path") or inp.get("notebook_path")
if target and not allowed(target):
deny(f"Blocked: {target} is outside your area. Do not try another "
"route. Stop and end your report with NEEDS-OUTSIDE-WORKTREE: "
"what you need changed and why, in plain English.")
if tool == "Bash" and re.search(
r"\bgit\s+(push|clean|checkout|reset\s+--hard)\b", inp.get("command", "")):
deny("Blocked: revert with `git restore -- <path>`; never push or delete.")
try:
main()
except SystemExit:
raise
except Exception:
deny("Blocked: the fence hit an internal error, so this call is refused.")