DEV Community

Vildanden
Vildanden

Posted on

Stop a Claude Code subagent from handing off a dirty diff with a SubagentStop hook

A parent session can look clean while a subagent leaves trailing whitespace, conflict markers, or a half-finished edit in the tree. A SubagentStop hook runs when the subagent finishes, so you can refuse the handoff until git diff --check is clean.

The hook should name the problem and exit 2.

The hook

Save this as .claude/hooks/subagent_stop_check.py and make it executable:

#!/usr/bin/env python3
import subprocess
import sys

def git(*args: str) -> subprocess.CompletedProcess[str]:
    try:
        return subprocess.run(
            ["git", *args],
            text=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.DEVNULL,
            timeout=4,
        )
    except (OSError, subprocess.SubprocessError):
        return subprocess.CompletedProcess(args=["git", *args], returncode=0, stdout="", stderr="")

inside = git("rev-parse", "--is-inside-work-tree")
if inside.returncode != 0 or inside.stdout.strip() != "true":
    sys.exit(0)

check = git("diff", "--check")
if check.returncode != 0:
    print("SubagentStop: git diff --check failed. Fix whitespace or conflict markers before merging the handoff.")
    sys.exit(2)

status = git("status", "--porcelain")
paths = [line for line in (status.stdout or "").splitlines() if line.strip()]
print(f"SubagentStop: {len(paths)} changed path(s). Verify assumptions, tests, and secret boundaries before merging the handoff.")
Enter fullscreen mode Exit fullscreen mode

Wire it in .claude/settings.json under SubagentStop with command set to python3 .claude/hooks/subagent_stop_check.py.

Why this beats a pasted prompt

Hooks run on the event, not when you remember to say "check the subagent's diff." The parent transcript is a poor place to notice a whitespace error or a conflict marker the subagent left behind. If the hook fires, fix the tree in the subagent's work or in a follow-up edit; do not merge the handoff and hope a later review catches it.

Tips

  • Keep the hook local, fast, and free of network calls.
  • Pair it with a Stop hook that refuses "done" while the build or tests are still red, so both the subagent handoff and the parent turn have a mechanical check.
  • If a generated file trips git diff --check, fix or exclude that path rather than deleting the hook.

Want the rest of the setup?

I keep copy-ready Claude Code configs (CLAUDE.md templates, slash commands, hooks, permission rules) in Vildanden Agent Config. There's a free sample: https://justly-mia-429.rehost.page/

Top comments (0)