Require a Clean Working Tree Before Creating a Worktree

A worktree branches off the current state of a repo — creating one while the parent has uncommitted changes means the new isolated copy may not actually reflect what either the agent or a human expects it to. This blocks creation until the parent tree is clean.

Worktree & Git Safety Event: WorktreeCreate Claude Code Open source · Free

1. Save this as the hook script

#!/usr/bin/env python3
"""WorktreeCreate hook — blocks creation if the parent repo has
uncommitted changes. Any non-zero exit fails creation."""
import json, subprocess, sys

data = json.load(sys.stdin)
parent_path = data.get("parent_path", ".")

try:
    result = subprocess.run(["git", "status", "--porcelain"], cwd=parent_path,
                             capture_output=True, text=True, timeout=10)
except Exception:
    sys.exit(0)

if result.stdout.strip():
    print(f"BLOCKED: {parent_path} has uncommitted changes. Commit or stash "
          f"before branching a worktree off it.", file=sys.stderr)
    sys.exit(1)

sys.exit(0)

Save to a path inside your project, e.g. .claude/hooks/require-clean-tree-before-worktree-create.sh, then chmod +x it.

2. Wire it into .claude/settings.json

{
  "hooks": {
    "WorktreeCreate": [
      {
        "hooks": [
          {"type": "command", "command": "python3 .claude/hooks/require-clean-tree-before-worktree-create.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

← All hooks
FEEDBACK