16
Chapter 16 · 10 min read

By Vlad Podoliako ·
Updated

Hooks and Custom Subagents

From Autocomplete to Coworker

I once typed “please run prettier on this file” 47 times in one week. Then I learned about hooks. I haven’t typed it since.

That sentence is the entire pitch for this chapter. If you’ve ever found yourself nagging to do the same five things every turn — format, lint, run the test, write a sane commit message, ping you when it finishes — you don’t have a prompt problem. You have a policy problem. And the answer is two features most people skim past on day one: hooks and subagents.

Hooks turn ad-hoc prompting into policy. Subagents turn one model into a team. Together, they’re how you stop talking to Claude and start operating it.


What hooks actually are

A is a shell command (or HTTP endpoint, or short LLM prompt) that Claude Code runs automatically at specific points in its lifecycle. They live in your settings file, not in the chat. The model can’t forget them, can’t skip them, and can’t be sweet-talked out of them by a clever prompt injection.

There are a lot of events, but in practice you’ll spend 90% of your time on three:

The full list also includes SessionStart, UserPromptSubmit, PostToolUseFailure, PermissionRequest, TaskCompleted, WorktreeCreate, and a handful of others. Don’t enumerate them in your head — look them up when you need them. The three above pay for themselves in week one.


Where hooks live

Two locations:

Here’s the shape of a real PostToolUse hook that runs Prettier after every edit:

json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "f=$(jq -r '.tool_input.file_path') && prettier --write \"$f\"" }
        ]
      }
    ]
  }
}

The matcher field lists tool names — here, “Edit or Write.” A matcher with any character beyond letters, digits, _, -, spaces, commas and |, such as ^Notebook, is read as a regex instead; * on its own, or no matcher at all, matches every tool. Claude Code hands the hook the tool call as JSON on stdin, so jq -r '.tool_input.file_path' reads the file that was just edited; the same JSON carries the tool name and the session ID. For paths, $CLAUDE_PROJECT_DIR holds the project root. Most examples below read that JSON with jq.

That’s the whole concept. Now we make it useful.


Five hooks every team should run

1. format-on-save

json
{
  "matcher": "Edit|Write",
  "hooks": [
    { "type": "command", "command": "f=$(jq -r '.tool_input.file_path // empty'); [ -n \"$f\" ] || exit 0; prettier --write \"$f\" 2>/dev/null || ruff format \"$f\" 2>/dev/null; exit 0" }
  ]
}

Stops “please format this” forever. Picks Prettier first, falls back to Ruff. Failure is silent so non-JS/Python files don’t blow up the chain.

2. test-on-write

json
{
  "matcher": "Edit|Write",
  "hooks": [
    { "type": "command", "command": "f=$(jq -r '.tool_input.file_path // empty'); case \"$f\" in *.test.*) npx vitest run \"$f\" 1>&2 || exit 2;; esac" }
  ]
}

Wrote to a test file? Run that one test; on a failure, redirecting the output to stderr and exiting 2 hands the failing report back to Claude on PostToolUse even though the edit already ran. Tight feedback loop, no orchestration logic in the chat.

3. block-push-to-main

json
{
  "PreToolUse": [
    {
      "matcher": "Bash",
      "hooks": [
        {
          "type": "command",
          "command": "command=$(jq -er '.tool_input.command | strings') || { echo 'Blocked: cannot read hook input; check JSON and install jq.' >&2; exit 2; }; case \"$command\" in *'git push origin main'*) echo 'Blocked: push to main requires a human.' >&2; exit 2;; esac; exit 0"
        }
      ]
    }
  ]
}

This command requires jq and reads .tool_input.command from the JSON Claude Code sends on stdin. Exit 2 blocks the PreToolUse call; exit 1 with no JSON decision does not. Missing jq or unreadable input also returns 2. The stderr message goes back into the model’s context, so the agent reads “Blocked: push to main requires a human.” and adapts. This single hook has saved me from three “oh no” moments at Belkins this year.

This is a literal text check for git push origin main, not a shell parser: flags, aliases, other remotes or refspecs can bypass it, and quoted text can match. Use branch protection on your Git host for a complete branch policy. See the current hook contract.

4. commit-message-template

json
{
  "Stop": [
    {
      "hooks": [
        { "type": "command", "command": ".claude/hooks/draft-commit.sh" }
      ]
    }
  ]
}

Where draft-commit.sh runs git diff --cached, summarizes it (with a tiny local model or a templated heuristic), and writes the message to .git/COMMIT_EDITMSG. The agent ends its turn, you get a pre-filled commit message, you tweak and ship.

5. slack-notify-on-long-task

json
{
  "UserPromptSubmit": [
    {
      "hooks": [
        { "type": "command", "command": "s=$(jq -r '.session_id') && touch \"${TMPDIR:-/tmp}/cc-turn-$s\"; exit 0" }
      ]
    }
  ],
  "Stop": [
    {
      "hooks": [
        { "type": "command", "command": "s=$(jq -r '.session_id') && [ -n \"$(find \"${TMPDIR:-/tmp}/cc-turn-$s\" -mmin +2 2>/dev/null)\" ] && jq -nc --arg text \"CC turn finished: $s\" '{text: $text}' | curl -s -H 'Content-type: application/json' -d @- \"$SLACK_WEBHOOK\"; exit 0" }
      ]
    }
  ]
}

Claude Code doesn’t give a hook the turn’s duration, so the first hook touches a stamp file when each turn starts and the Stop hook posts only if that file is more than two minutes old. Two-minute threshold, Slack ping, done. Now I can launch a long refactor, walk away, and trust the buzz on my watch instead of polling the terminal like a madman.


Hooks return values matter

This is the part most people miss. Hooks aren’t fire-and-forget. For a PreToolUse command hook with no JSON decision on stdout:

Valid JSON on stdout can also control the decision. Other events have their own output rules; SessionStart, for example, adds plain-text stdout to Claude’s context. See the official reference.

Which means a hook is also a way to talk back to Claude. Two patterns I lean on:

Hooks aren’t just guardrails. They’re a side-channel for policy.


Subagents — the 90-second mental model

A is a child instance you spawn from your main session. It has:

Claude Code ships with built-ins. The names you’ll see:

Three-subagent fan-out (opens full size)
Three-subagent fan-out Main CC session dispatching general-purpose, Explore, and Plan in a single Agent batch, with three result summaries returning in parallel.

Custom subagents — writing your own

Subagents are Markdown files with YAML frontmatter. Two locations, same rules as hooks:

Here’s a code-reviewer subagent I use across Belkins and Folderly:

mdx
---
name: code-reviewer
description: Reviews diffs for security, performance, style. Use when user says
  "review this PR", "check this diff", or "is this code safe?". Read-only.
tools: Read, Grep, Glob
---

You are a senior code reviewer. Given a diff, return:
1. Three highest-impact issues, ranked by severity.
2. Two style nits, with line numbers.
3. One suggestion the original author would not have considered.

Do not edit. Do not run shell. Read-only review only.

Three things to notice. The description is what the orchestrator reads to decide when to delegate — write it like an instruction, not like a tagline. The tools line is a tool allow-list — by stripping Edit, Write, and Bash, I’ve made it physically impossible for this subagent to mutate the repo. And the body is just the system prompt: short, opinionated, formatted output enforced.


Spawning subagents — the practical move

In your main session, you say (or the model decides on its own):

Spawn 3 code-reviewer subagents in parallel: one on src/auth, one on src/billing, one on src/api. Then merge their findings into a single ranked list.

The orchestrator dispatches all three in one tool batch. Each runs in its own context, reads its slice, and returns a summary. The orchestrator merges them. You get the union of three focused reviews in roughly the time of one — and your main context isn’t polluted with three full diffs.

This is the move. Three reviewers in parallel beats one reviewer reading 9,000 lines, every time.


The exploration/editing split

There’s a second subagent move that matters more in a large codebase than the parallel-review one, and Anthropic calls it out explicitly as a recommended pattern: don’t explore and edit in the same session.

The shape:

  1. Spin up a read-only subagent with its own context window. Its only job: map the subsystem. How does auth flow through this service? Where does the retry logic live? What calls what?
  2. The subagent writes its findings to a file — .claude/scratch/auth-map.md — not back into the orchestrator’s context.
  3. The main agent reads that file and does the edit with the full picture, on a context window that never got burned by the 40 files the explorer had to open to produce the map.

Why this beats “just let the one agent figure it out”: exploration is expensive and messy. It opens dead ends, reads files it won’t touch, follows imports that don’t matter. If that all happens in your editing session, the editing context is polluted with exploration noise by the time the model starts writing code. The split keeps the cost where it belongs. The explorer pays it; the editor inherits a clean summary.

The explorer-writes-to-disk, editor-reads-from-disk handoff is the same disk-handoff discipline from the anti-patterns section below, applied to the highest-value case. Treat .claude/scratch/ like a message queue and the pattern composes with everything else in this chapter.


The four parallel-dispatch patterns

Chapter 6 covered the why of parallel dispatch — context isolation, throughput, blast radius. This chapter is the how to wire them. Quick re-cap of the four shapes:

If you can name the shape before you dispatch, you’ll write better orchestrator prompts.


Subagent anti-patterns

Spawning a subagent for a task that fits in one tool call. Subagent dispatch has overhead — context setup, prompt parsing, summary generation. If the task is “read this one file and tell me the export,” just read the file. Subagents pay off when the work is non-trivial or when isolation matters.

Forgetting to specify the output format. If you don’t tell each subagent exactly what shape to return — three bullets, JSON, ranked list — you’ll get N different shapes and your merge step becomes a parsing nightmare. Pin the format in the subagent body or in the dispatch prompt. Both is fine.

Letting subagents share state via the orchestrator’s context. If subagent A produces something subagent B needs, write it to disk and pass the path. Don’t try to thread it through orchestrator memory. Disk handoffs are debuggable, replayable, and don’t melt your context window. Use /tmp or a .claude/scratch/ directory and treat it like a message queue.


Hooks + subagents = real systems

Now wire them together. Concrete example, from my own setup, for a release flow on the Newsletter publishing repo:

That’s a real system. The agent does the boring work. The hooks enforce the rules. The subagents keep the context clean. And the human (me) only shows up at the one moment where judgment matters: the push to main.

Hooks plus subagents — a real release flow (opens full size)
Hooks plus subagents — a real release flow A .claude/settings.json open on the left showing the three hooks, and a .claude/agents/ directory listing on the right with code-reviewer.md, changelog-writer.md, version-bumper.md, and smoke-test-runner.md.

Cite this chapter

Vlad Podoliako. “Hooks and Custom Subagents.” Vlad's Playbook, chapter 16, 2026. https://dive.vladyslavpodoliako.com/chapters/16-hooks-subagents/

Licensed CC BY-NC-SA 4.0

Spotted something wrong, missing, or sharper? Email Vlad with feedback on this chapter →
Stay close

The next edition lands when this list says it does.

No course. No paywall. Operator playbooks weekly. 10K+ subscribers.