Home / Guides / Claude Code subagents + hooks

Claude Code subagents, hooks and slash commands: a working setup

Short answer: Subagents are Markdown files in .claude/agents/ with YAML frontmatter (name, a description that says when to delegate, optional tools; give reviewers Read, Grep, Glob only). Hooks go in .claude/settings.json under "hooks": a PreToolUse hook on Bash gets the tool call as JSON on stdin, and exit code 2 blocks it and sends your stderr back to Claude. Each .claude/commands/*.md file becomes a slash command. The free copy-paste hook that blocks rm -rf and force-push is further down.

CLAUDE.md tells Claude Code what to do. Subagents, hooks and slash commands are how you make it actually happen: focused reviewers with limited tools, shell scripts that enforce your rules instead of hoping the model remembers them, and one-word commands for your workflow.

Subagents: .claude/agents/*.md

A subagent is a Markdown file with YAML frontmatter: name, a description that tells Claude when to delegate (write “Use PROACTIVELY after…” to get it used automatically), and an optional tools list. Each subagent runs in its own fresh context, so it does not clutter the main conversation, and it does not see that conversation either: pass it the exact files and goal.

Run /agents in Claude Code to list, create and edit them.

Hooks: rules the model cannot skip

Hooks live in .claude/settings.json under "hooks". Each event (PreToolUse, PostToolUse, Stop, and others) has a matcher on the tool name (Bash, Edit|Write) and a command. The hook gets the tool call as JSON on stdin. Exit code 2 blocks the action and sends your stderr message back to Claude; exit 0 allows it.

Hooks run with your user's permissions. Read every script before enabling it and keep them in version control. Pair them with permissions.deny entries in the same file for a second layer.

Want more? See 7 copy-paste Claude Code hooks examples: auto-format, protect .env, notifications, context after /compact and more.

Slash commands: .claude/commands/*.md

Each file becomes /filename. Use $ARGUMENTS for what you type after the command, and frontmatter such as description, argument-hint and allowed-tools. Good commands chain your subagents: /feature = plan → implement → test-writer → tests → code-reviewer → summary.

Free snippet: copy it

.claude/hooks/block-dangerous-bash.sh
#!/usr/bin/env bash
# PreToolUse (matcher: Bash). Exit 2 = block; stderr is shown to Claude.
cmd=$(jq -r '.tool_input.command // ""')
cmd=${cmd//$'\\\n'/ }      # join "\" line continuations
# Flag checks read a copy (v1.0.5, thanks marco-ai-agent, issue #44): bash strips quotes,
# so "--force" is --force to git, and a flag glued to ; && | still ends there (-f;echo).
P=$(printf '%s' "${cmd//[\"\']/}" | sed -E 's/[;&|]+/ & /g')
B='(^|[^[:alnum:]_-])'      # start of a word
A='([^;&|]*[[:space:]])?'   # other args in the same command
E='([[:space:]]|$)'         # end of a flag
G='([[:space:]]+-[^[:space:]]+([[:space:]]+[^-[:space:]][^[:space:]]*)?)*'  # git options (-C dir)
# rm with recursive + force in any order, force-push in any form, hard reset (v1.0.1)
patterns=(
  "${B}rm[[:space:]]${A}(-[a-zA-Z]*([rR][a-zA-Z]*f|f[a-zA-Z]*[rR])[a-zA-Z]*|(-[a-zA-Z]*[rR][a-zA-Z]*|--recursive)[[:space:]]${A}(-[a-zA-Z]*f[a-zA-Z]*|--force)|(-[a-zA-Z]*f[a-zA-Z]*|--force)[[:space:]]${A}(-[a-zA-Z]*[rR][a-zA-Z]*|--recursive))${E}"
  "${B}git${G}[[:space:]]+push[[:space:]]${A}(-[a-zA-Z]*f[a-zA-Z]*|--force[^[:space:]]*|\+[^[:space:]]+)${E}"
  "${B}git${G}[[:space:]]+reset[[:space:]]${A}--hard${E}"
  # git clean with -f in any spelling (-fd, -df, -xfd, -f -d, --force) (v1.0.2)
  "${B}git${G}[[:space:]]+clean[[:space:]]${A}(-[a-zA-Z]*f[a-zA-Z]*|--force)${E}"
  # git push --mirror overwrites every remote ref (v1.0.2)
  "${B}git${G}[[:space:]]+push[[:space:]]${A}--mirror${E}"
)
for p in "${patterns[@]}"; do
  if printf '%s\n' "$P" | grep -qE -- "$p"; then
    echo "Blocked by .claude/hooks/block-dangerous-bash.sh: recursive forced rm, force-push or hard reset is destructive. Explain why it's needed and ask the human to run it." >&2
    exit 2
  fi
done
norm=$(printf '%s' "$cmd" | tr -s '[:space:]' ' ')   # "DROP  TABLE" = "DROP TABLE" (v1.0.2)
deny=(
  'DROP DATABASE' 'DROP TABLE' 'TRUNCATE ' 'supabase db reset' 'prisma migrate reset'
  'alembic downgrade base' 'chmod -R 777' 'mkfs' 'dd if=' ':(){'
)
for p in "${deny[@]}"; do
  if printf '%s' "$norm" | grep -qiF -- "$p"; then
    echo "Blocked by .claude/hooks/block-dangerous-bash.sh: '$p' is destructive. Explain why it's needed and ask the human to run it." >&2
    exit 2
  fi
done
if printf '%s' "$cmd" | grep -qE '(curl|wget)[^|]*\|[[:space:]]*(sudo([[:space:]]+-[^[:space:]]+)*[[:space:]]+)?(env[[:space:]]+)?((ba|z|da|k|fi)?sh|python[0-9.]*|perl|ruby|node)([[:space:]]|$)' ||
   printf '%s' "$cmd" | grep -qE '(ba|z)?sh[[:space:]]+<\([[:space:]]*(curl|wget)'; then
  echo "Blocked: piping a download into a shell. Download, inspect, then ask." >&2; exit 2
fi
if printf '%s\n' "$P" | grep -qE -- "${B}git${G}[[:space:]]+push[[:space:]][^&;|]*[[:space:]:+](refs/heads/)?(main|master)${E}"; then
  echo "Blocked: pushing to main/master. Push a branch and open a PR." >&2; exit 2
fi
# Writes to secret files through Bash (v1.0.4). protect-files.sh only sees Edit/Write,
# so also catch > / >> redirects, tee, sed -i, perl -i, cp/mv/install/ln/rsync, truncate, dd of=.
# Case-insensitive; .env.example/.sample/.template stay writable; plain reads (cat .env.example) pass.
secret() {
  local b=${1##*/}
  case "$b" in
    .env.example|.env.sample|.env.template) return 1 ;;
    .env|.env.*|.envrc|*.pem|*.key|*.p12|*.pfx|id_rsa*|id_ecdsa*|id_ed25519*|credentials|credentials.json|.netrc|.npmrc|.pypirc|secrets.json|secrets.y*ml) return 0 ;;
  esac
  return 1
}
lc=$(printf '%s' "$cmd" | tr '[:upper:]' '[:lower:]')
low=$(printf '%s' "$lc" | tr -d "\"'\\\\")
hit=""
# Redirect targets: >file, >> file, >|file, 1>file, &>file.
while IFS= read -r t; do
  t=${t#*>}; t=${t#>}; t=${t#|}; t=${t#"${t%%[![:space:]]*}"}; t=$(printf '%s' "$t" | tr -d "\"'\\\\")
  [ -n "$t" ] && secret "$t" && hit=$t
done < <(printf '%s\n' "$lc" | grep -oE '>{1,2}\|?[[:space:]]*("[^"]*"|'"'"'[^'"'"']*'"'"'|[^[:space:];&|<>()]+)+')
# Writer commands: any argument that is a secret file.
while IFS= read -r seg; do
  read -ra w <<<"$seg"
  i=0
  while [ $i -lt ${#w[@]} ] && { [[ ${w[$i]} == *=* && ${w[$i]} != -* ]] || [[ ${w[$i]} =~ ^(sudo|env|command|exec|nohup|time|xargs)$ ]] || [[ ${w[$i]} == -* && $i -gt 0 ]]; }; do i=$((i+1)); done
  c=${w[$i]##*/}
  case "$c" in
    tee|cp|mv|install|ln|rsync|truncate|dd) writer=1 ;;
    sed|gsed) writer=0; for a in "${w[@]:$i}"; do [[ $a =~ ^(-[a-z]*i|--in-place) ]] && writer=1; done ;;
    perl) writer=0; for a in "${w[@]:$i}"; do [[ $a =~ ^-[a-z]*i ]] && writer=1; done ;;
    *) writer=0 ;;
  esac
  [ "$writer" = 1 ] || continue
  for a in "${w[@]:$((i+1))}"; do a=${a#of=}; [[ $a == -* ]] && continue; secret "$a" && hit=$a; done
done < <(printf '%s\n' "$low" | tr ';&|\n' '\n\n\n\n')
if [ -n "$hit" ]; then
  echo "Blocked by .claude/hooks/block-dangerous-bash.sh: this command writes to '$hit', which may hold secrets. Edit .env.example instead and ask the human to set real values." >&2
  exit 2
fi
exit 0

It blocks recursive forced rm in any spelling (-rf, -fr, -Rf, -r -f, --recursive --force), force-push anywhere in the command (-f, --force, --force-with-lease, +branch) and git reset --hard. rm -r build, rm -f a.txt and git reset --soft still run. Quoted flags ("--force") and flags glued to ;, && or | are caught too, thanks to marco-ai-agent in issue #44.

FAQ

Where do Claude Code subagents live?

Project subagents go in .claude/agents/ as Markdown files with YAML frontmatter (name, description, optional tools). Personal ones go in ~/.claude/agents/. Use /agents to manage them.

How do I block dangerous commands in Claude Code?

Add a PreToolUse hook with matcher Bash in .claude/settings.json. The script reads the tool call JSON from stdin and exits with code 2 to block it; its stderr is shown to Claude. Add matching permissions.deny rules as a second layer.

What does exit code 2 mean in a Claude Code hook?

Exit 2 blocks the action (for PreToolUse) or tells Claude to keep working (for Stop), and stderr is fed back to Claude. Exit 0 means no objection: the normal permission flow still applies. Other codes are non-blocking errors shown to you.

How do I make Claude Code run tests before it finishes?

Use a Stop hook that runs your test command when code changed and exits 2 on failure. Check the stop_hook_active field in the input and exit 0 when it is true, so the hook cannot loop forever.

Do subagents see the main conversation?

No. Each subagent starts with a fresh context window and only gets the task you hand it, so include file paths and the goal in the delegation.

Want the whole drawer?

The Claude Code Kit ($24) ships a fill-in CLAUDE.md, 6 least-privilege subagents, 10 slash commands, a settings.json with permissions and hook wiring, and 4 tested hooks (dangerous Bash, secret files, lockfiles, format, tests-before-stop).

Not ready for a full pack? Start with One-File Agent Rules ($9), one universal AGENTS.md for any stack, or download the free Starter AGENTS.md (no email needed).

14-day refund, no questions.

FREE · 1 FILE · WORKS IN EVERY AGENT

Get the free Starter AGENTS.md

A 40-line rules file that makes Cursor, Claude Code, Codex and Windsurf plan first, keep diffs small and run your tests before saying "done". We email it to you instantly, plus one follow-up and a short note when a new pack ships. Unsubscribe anytime. Privacy