Freeze Worktree Creation Outside an Approved Branch Prefix
Worktrees are convenient for running agents on isolated copies of a repo, but a worktree created from an arbitrary branch can quietly fork production-adjacent work off a stale or unreviewed base. This requires the parent branch to match an approved prefix before the worktree is created at all.
1. Save this as the hook script
#!/usr/bin/env python3
"""WorktreeCreate hook — blocks worktree creation unless the parent branch
matches an approved prefix. Any non-zero exit fails creation."""
import json, re, sys
data = json.load(sys.stdin)
from_branch = data.get("from_branch", "")
APPROVED_PREFIXES = [r"^main$", r"^release/", r"^feature/"]
if not any(re.match(p, from_branch) for p in APPROVED_PREFIXES):
print(f"BLOCKED: worktree requested from branch '{from_branch}', which doesn't "
f"match an approved prefix (main, release/*, feature/*).", file=sys.stderr)
sys.exit(1)
sys.exit(0)
Save to a path inside your project, e.g. .claude/hooks/freeze-worktree-branch-prefix.sh, then chmod +x it.
2. Wire it into .claude/settings.json
{
"hooks": {
"WorktreeCreate": [
{
"hooks": [
{"type": "command", "command": "python3 .claude/hooks/freeze-worktree-branch-prefix.py"}
]
}
]
}
}
Before you use this
A hook runs with your local shell's permissions — review the script above before adding it, the same way you'd review any script you didn't write yourself. See our guide on hook security risks for the specific CVEs this category of feature has already produced.
Related hooks