Cap Subagent Fan-Out Depth

A subagent spawning a subagent spawning a subagent is both a cost risk and a governance risk — delegation chains get harder to review the deeper they go. This tracks spawn depth via a simple counter file and flags once a configured ceiling is crossed.

Subagent & Multi-Agent Safety Event: SubagentStart Claude Code Open source · Free

1. Save this as the hook script

#!/usr/bin/env python3
"""SubagentStart hook — warns once nested-agent depth exceeds a ceiling.
Depth is tracked in a counter file keyed by session_id."""
import json, sys
from pathlib import Path

data = json.load(sys.stdin)
session_id = data.get("session_id", "unknown")
DEPTH_CEILING = 3
counter_path = Path(data.get("cwd", ".")) / ".claude" / f"subagent_depth_{session_id}.txt"

depth = int(counter_path.read_text()) + 1 if counter_path.exists() else 1
counter_path.parent.mkdir(parents=True, exist_ok=True)
counter_path.write_text(str(depth))

if depth > DEPTH_CEILING:
    print(f"WARNING: subagent fan-out depth is now {depth}, past the "
          f"configured ceiling of {DEPTH_CEILING}. Review this delegation chain.", file=sys.stderr)
    sys.exit(1)

sys.exit(0)

Save to a path inside your project, e.g. .claude/hooks/cap-subagent-fanout-depth.sh, then chmod +x it.

2. Wire it into .claude/settings.json

{
  "hooks": {
    "SubagentStart": [
      {
        "hooks": [
          {"type": "command", "command": "python3 .claude/hooks/cap-subagent-fanout-depth.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