All posts

Mastering Claude Code with Hooks and Validation

Stop micromanaging AI. Learn how hooks, validators, and sub-agents transform Claude Code from a tool you command into a partner that delivers.

Abstract visualization of AI hooks and validation systems

Make verification part of the agent's workflow.

There's a fundamental problem with how most people use AI coding assistants: they treat them like interns who need constant supervision. Every command is a micro-instruction. Every response requires verification. The human becomes a bottleneck, and the AI never gets the chance to demonstrate what it's actually capable of.

What if there was a better way?

The Repository That Changed Everything

Credit where it's due: this article draws heavily from disler's claude-code-hooks-mastery repository—a masterclass in agentic engineering. If you're serious about Claude Code, clone it immediately.

What makes this repository brilliant isn't just the code. It's the philosophy: build systems that constrain and empower simultaneously.

The Hook Lifecycle: Your Control Surface

Claude Code exposes 13 lifecycle hooks—moments where you can intercept, validate, modify, or block operations. Think of them as circuit breakers in an electrical system. They don't run the show; they ensure the show runs safely.

Here's the flow:

Session Start → User Prompt → Claude Processes → Tool Use → Stop → Session End
       ↓              ↓              ↓            ↓        ↓
    [HOOK]         [HOOK]        [HOOKS]      [HOOKS]  [HOOK]

The 13 hooks:

  1. Setup - Repository initialization
  2. SessionStart - New session begins
  3. UserPromptSubmit - Before Claude sees your prompt
  4. PreToolUse - Before any tool executes
  5. PermissionRequest - When permissions are needed
  6. PostToolUse - After tool completion
  7. PostToolUseFailure - When tools fail
  8. SubagentStart - When sub-agents spawn
  9. SubagentStop - When sub-agents complete
  10. Notification - System notifications
  11. Stop - When Claude finishes responding
  12. PreCompact - Before context compaction
  13. SessionEnd - Session termination

Each hook receives JSON input via stdin and can return structured JSON to control flow. Exit code 2 is your emergency brake—it blocks the current operation and feeds your error message back to Claude.

The Two Hooks That Matter Most

PreToolUse: The Guardian

This hook fires before any tool executes. It's your security layer:

# Block dangerous commands before they run
dangerous_patterns = [
    r'rm\s+.*-[rf]',        # rm -rf variants
    r'sudo\s+rm',           # sudo rm commands
    r'chmod\s+777',         # Dangerous permissions
    r'>\s*/etc/',           # Writing to system dirs
]

for pattern in dangerous_patterns:
    if re.search(pattern, command, re.IGNORECASE):
        print(f"BLOCKED: {pattern} detected", file=sys.stderr)
        sys.exit(2)  # Blocks tool, shows error to Claude

Notice what's happening: you're not telling Claude what to do. You're defining what it can't do. Everything else? Fair game. This is the difference between micromanagement and governance.

Stop Hook: The Quality Gate

The stop hook fires when Claude thinks it's done. This is where validation lives:

# Ensure tests pass before completion
if not all_tests_passed():
    output = {
        "decision": "block",
        "reason": "Tests are failing. Fix them before completing."
    }
    print(json.dumps(output))
    sys.exit(0)

When you block the stop, Claude receives your reason and continues working. It's not punishment—it's feedback. The agent learns what "done" actually means in your codebase.

Sub-Agents: Delegation Without Abdication

Here's where it gets interesting. Claude Code can spawn sub-agents—specialized AI instances with their own system prompts, tool restrictions, and context windows.

The information flow:

You → Primary Agent → Sub-Agent → Primary Agent → You

Sub-agents never talk to you directly. They report to the primary agent, which synthesizes and presents results. This architecture enables something powerful: task specialization without context pollution.

The Builder/Validator Pattern

The repository demonstrates a two-agent team:

AgentToolsPurpose
BuilderAll toolsImplement features
ValidatorRead-onlyVerify the work

The builder has full capabilities. The validator can only read—it can't accidentally "fix" something and claim success. This separation increases compute to increase trust.

The Meta-Agent: Building the Builders

Perhaps the most ingenious piece: an agent that creates other agents.

"Build a new sub-agent that analyzes pull requests for security issues"

Claude delegates to the meta-agent, which generates a properly formatted agent definition. It's the "thing that builds the thing"—the compound effect that accelerates capability development.

Why This Approach Works

Traditional AI interaction is synchronous and imperative:

Human: Do X
AI: [does X]
Human: Now do Y
AI: [does Y]
Human: That's wrong, do it this way
AI: [tries again]

The hooks approach is asynchronous and declarative:

Human: [Defines constraints via hooks]
Human: [Defines agents for specialized tasks]
Human: "Build the feature"
AI: [Works autonomously within constraints]
AI: [Delegates to sub-agents as needed]
AI: [Validates own work against stop hooks]
AI: [Reports completion when actually complete]

The human sets up the system once. The system enforces standards continuously. Claude has freedom to explore solutions, but guardrails prevent catastrophic failures.

Setting Up Your Hook Infrastructure

Directory Structure

.claude/
├── settings.json          # Hook configuration
├── hooks/
│   ├── pre_tool_use.py    # Security validation
│   ├── post_tool_use.py   # Result logging
│   ├── stop.py            # Completion validation
│   └── validators/
│       ├── ruff_validator.py   # Python linting
│       └── test_validator.py   # Test runner
├── agents/
│   ├── builder.md         # Implementation agent
│   ├── validator.md       # Verification agent
│   └── meta-agent.md      # Agent generator
└── commands/
    └── plan_w_team.md     # Team orchestration

The Settings File

{
  "hooks": {
    "PreToolUse": [{
      "type": "command",
      "command": "uv run $CLAUDE_PROJECT_DIR/.claude/hooks/pre_tool_use.py"
    }],
    "Stop": [{
      "type": "command",
      "command": "uv run $CLAUDE_PROJECT_DIR/.claude/hooks/stop.py"
    }]
  }
}

The $CLAUDE_PROJECT_DIR prefix ensures hooks resolve correctly regardless of working directory.

UV Single-File Scripts

The repository uses Astral UV for hook execution—a fast Python package manager that handles dependencies inline:

# /// script
# requires-python = ">=3.11"
# dependencies = ["anthropic", "rich"]
# ///

import sys
import json

def main():
    data = json.load(sys.stdin)
    # Your hook logic here

if __name__ == "__main__":
    main()

Each hook is self-contained. No virtual environment management. No dependency conflicts with your main project.

The Philosophical Shift

Here's what changes when you adopt this approach:

Before: You are the executor. Claude is the tool. After: You are the architect. Claude is the executor.

You define what success looks like (stop hooks). You define what's forbidden (pre-tool hooks). You define specialized capabilities (sub-agents). Then you step back and let the system work.

This isn't about trusting AI blindly. It's about building systems where trust is verified continuously. Every tool call is logged. Every completion is validated. Every dangerous operation is blocked before execution.

Getting Started

  1. Clone the hooks mastery repository
  2. Review the hook implementations in .claude/hooks/
  3. Study the agent definitions in .claude/agents/
  4. Run a session and watch the logs/ directory populate
  5. Customize hooks for your specific needs

Start simple: implement logging in PostToolUse. Add a dangerous command blocker in PreToolUse. Create a basic test validator in the Stop hook.

Then iterate. Add sub-agents for specialized tasks. Create custom slash commands for common workflows. Build the meta-agent to accelerate your agent development.

The End of Micromanagement

The best engineering isn't about doing everything yourself. It's about building systems that produce reliable outputs. The hooks architecture transforms Claude Code from a tool you operate to a system you orchestrate.

Stop barking orders. Start building guardrails.

The AI will surprise you with what it can accomplish when you give it room to work.


Further reading: Claude Code Hooks Documentation, Astral UV, The original repository