PromptHub
Back to Blog
Developer Tools AI Engineering

disler/claude-code-hooks-mastery: Complete Hook Lifecycle & Agent Orchestration

B

Bright Coding

Author

11 min read 38 views
disler/claude-code-hooks-mastery: Complete Hook Lifecycle & Agent Orchestration

Claude Code hooks give developers deterministic control over AI-assisted coding workflows, but the official documentation leaves gaps between "hello world" examples and production-grade implementations. Most teams struggle with validation, security boundaries, and orchestrating multiple agents without descending into prompt-engineering chaos.

disler/claude-code-hooks-mastery bridges that gap. This open-source reference implementation captures all 13 Claude Code hook lifecycle events, demonstrates UV single-file script architecture, and provides working patterns for sub-agents, meta-agents, and team-based validation. With 3,829 stars and 628 forks, it has become the de facto community resource for developers who need Claude Code hooks that work reliably across environments.

This guide walks through what the repository contains, how to implement its patterns, and where it fits in the broader agentic coding landscape.

What is disler/claude-code-hooks-mastery?

disler/claude-code-hooks-mastery is a reference implementation and educational resource for Claude Code hooks—Anthropic's mechanism for intercepting and controlling Claude Code CLI behavior at specific lifecycle points. The repository is maintained by disler (Dan Isler, known for the IndyDevDan YouTube channel) and last updated March 4, 2026.

The project sits at the intersection of three technical categories: developer tooling, AI agent orchestration, and CLI automation. Its primary language is Python↗ Bright Coding Blog, and it leverages Astral UV for dependency management—a deliberate choice that keeps hook logic isolated from project dependencies.

What distinguishes this repository from scattered documentation or blog posts is its completeness. Rather than demonstrating one or two hooks, it implements all 13 lifecycle events with validated payloads, error handling, and real-world enhancements like TTS feedback, security blocking, and automatic logging. The repository also extends into adjacent Claude Code features: sub-agents with custom system prompts, the meta-agent pattern for generating new agents, and team-based builder/validator workflows using Claude Code's task system.

The repository's traction—nearly 4,000 stars in a niche developer tools category—reflects genuine demand for concrete hook implementations rather than theoretical explanations.

Key Features

Complete Hook Lifecycle Coverage

The repository implements all 13 Claude Code hooks with documented JSON payloads and behavioral characteristics:

Hook Blocking Capability Primary Use Case
UserPromptSubmit Yes Prompt validation, context injection, security filtering
PreToolUse Yes Block dangerous commands (rm -rf, .env access)
PostToolUse No Result validation, transcript conversion, logging
PostToolUseFailure No Structured error logging with full context
Notification No TTS alerts, async user notifications
Stop Yes Force continuation until tasks complete
SubagentStart No Subagent spawn logging, optional TTS
SubagentStop Yes Block subagent completion, force continuation
PreCompact No Transcript backup before compaction
SessionStart No Development context loading (git status, recent issues)
SessionEnd No Session cleanup, temp file removal
PermissionRequest No Permission auditing, auto-allow for read-only ops
Setup No Environment persistence, context injection

UV Single-File Script Architecture

All hooks live in .claude/hooks/ as standalone Python scripts with embedded dependency declarations using UV's single-file script feature. This provides isolation from project dependencies, automatic dependency resolution, and fast execution without virtual environment management.

Intelligent TTS System

Multi-provider text-to-speech with priority fallback: ElevenLabs → OpenAI → pyttsx3. Includes queue-based management to prevent overlapping audio and personalized announcements using engineer names from environment variables.

Security Enhancements

Multiple layers of protection: PreToolUse blocks dangerous commands via regex patterns; UserPromptSubmit validates for policy violations; PermissionRequest provides audit trails and auto-allows safe read-only operations.

Sub-Agent & Meta-Agent Patterns

Working implementations of specialized sub-agents with custom system prompts, plus a meta-agent that generates new agents from descriptions—enabling rapid scaling of agent development.

Team-Based Validation

Builder/validator agent pairs with automated code quality enforcement via Ruff and Ty validators triggered on PostToolUse hooks.

Use Cases

1. Secure Multi-Developer Environments

Teams sharing Claude Code access need guardrails. The PreToolUse hook blocks rm -rf variants, sudo rm, chmod 777, and writes to system directories before execution. The PermissionRequest hook auto-allows safe read-only operations (Read, Glob, Grep) while maintaining audit logs for compliance.

2. Context-Aware Development Sessions

The SessionStart hook loads git status, recent issues, and context files automatically. Engineers no longer waste prompts asking Claude to check branch status or recent commits—the context is injected before the first interaction.

3. Long-Running Task Orchestration

The /plan_w_team command demonstrates how to break complex work into parallel tasks with dependencies. Builders implement features while validators verify acceptance criteria, coordinated through Claude Code's TaskCreate/TaskUpdate/TaskList system rather than fragile bash loops.

4. Accessibility & Async Workflows

The Notification hook with TTS integration enables engineers to step away while Claude Code works. When human input is needed, the system announces "Your agent needs your input" rather than requiring constant terminal monitoring.

5. Deterministic Quality Gates

PostToolUse validators enforce Ruff linting and type checking on every Python file write. Code that fails quality checks blocks completion, forcing fixes rather than accumulating technical debt.

Installation & Setup

Prerequisites

The repository requires two core tools:

  • Astral UV — Fast Python package installer and resolver
  • Claude Code — Anthropic's CLI for Claude AI

Install UV (cross-platform):

curl -LsSf https://astral.sh/uv/install.sh | sh

Claude Code is distributed through Anthropic's official channels; follow their installation documentation.

Optional Integrations

The repository supports enhanced functionality through optional services:

Service Purpose Integration
ElevenLabs Premium TTS Direct API + MCP server
OpenAI Fallback LLM + TTS API key
Anthropic Primary LLM Claude Code default
Ollama Local LLM For offline agent naming, summaries
Firecrawl MCP Web scraping MCP server integration

Repository Setup

Clone and explore the structure:

git clone https://github.com/disler/claude-code-hooks-mastery.git
cd claude-code-hooks-mastery

Hook configuration lives in .claude/settings.json. The critical pattern for reliable path resolution:

{
  "UserPromptSubmit": [
    {
      "hooks": [
        {
          "type": "command",
          "command": "uv run $CLAUDE_PROJECT_DIR/.claude/hooks/user_prompt_submit.py --log-only"
        }
      ]
    }
  ]
}

Important: Always use $CLAUDE_PROJECT_DIR prefix for hook paths. This environment variable ensures hooks resolve correctly regardless of working directory changes during Claude Code sessions.

Enabling Hooks

Copy or symlink the .claude/ directory into your target project, then configure settings.json for the hooks you need. Each hook script declares its own dependencies via UV's inline metadata:

# /// script
# dependencies = [
#   "requests>=2.31.0",
#   "pydantic>=2.0.0",
# ]
# ///

UV automatically resolves and caches these dependencies on first execution.

Real Code Examples

Example 1: Blocking Dangerous Commands (PreToolUse)

The PreToolUse hook demonstrates exit code 2 blocking—preventing tool execution before it occurs:

import sys
import re
import json

def is_dangerous_rm_command(command: str) -> bool:
    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 directories
    ]
    for pattern in dangerous_patterns:
        if re.search(pattern, command, re.IGNORECASE):
            return True
    return False

# Read hook payload from stdin
payload = json.load(sys.stdin)
tool_name = payload.get("tool_name")
tool_input = payload.get("tool_input", {})

if tool_name == "Bash":
    command = tool_input.get("command", "")
    if is_dangerous_rm_command(command):
        print(f"BLOCKED: Dangerous rm command detected", file=sys.stderr)
        sys.exit(2)  # Blocks tool call, shows error to Claude

This pattern extends to any tool with parameterizable risk. The sys.exit(2) is critical: it feeds stderr back to Claude automatically, explaining why the operation was blocked.

Example 2: Forcing Task Completion (Stop Hook)

The Stop hook can prevent Claude Code from finishing until validation passes:

import sys
import json

def all_tests_passed() -> bool:
    # Implementation checks test results from session state
    # Returns True only if critical validations succeed
    ...

payload = json.load(sys.stdin)

if not all_tests_passed():
    output = {
        "decision": "block",
        "reason": "Tests are failing. Please fix failing tests before completing."
    }
    print(json.dumps(output))
    sys.exit(0)  # Exit 0 with decision: block prevents stopping

The JSON output control provides more nuance than raw exit codes. "decision": "block" prevents stopping while providing Claude a specific reason to continue working.

Example 3: Context Injection (UserPromptSubmit)

Adding project context that Claude sees with every prompt:

import sys
import json
import subprocess
from datetime import datetime

payload = json.load(sys.stdin)
original_prompt = payload.get("prompt", "")

# Gather context
git_branch = subprocess.run(
    ["git", "branch", "--show-current"],
    capture_output=True, text=True
).stdout.strip()

context = f"""Project Context:
- Branch: {git_branch}
- Timestamp: {datetime.utcnow().isoformat()}
- Standards: Follow REST conventions and OpenAPI 3.0

User Request: {original_prompt}
"""

print(context)  # stdout becomes visible to Claude

This demonstrates the UserPromptSubmit hook's unique capability: modifying what Claude receives without changing what the user typed.

Advanced Usage & Best Practices

Hook Execution Environment

All hooks run with these constraints: 60-second timeout, parallel execution for matching hooks, inherited Claude Code environment variables, and current project directory as working directory. Design hooks to be stateless and idempotent where possible.

Flow Control Priority

When multiple control mechanisms combine, precedence is: "continue": false > "decision": "block" > Exit Code 2 > Other exit codes. Understanding this hierarchy prevents unexpected behavior when layering multiple hooks.

Avoiding Infinite Loops

The Stop hook's ability to force continuation carries risk. Always check stop_hook_active flags and implement maximum iteration guards. The repository's examples include safety patterns for legitimate continuation without runaway behavior.

TTS Queue Management

For teams using audio feedback, the tts_queue.py utility prevents overlapping announcements. This matters when multiple hooks fire in rapid succession—without queueing, notifications become unintelligible noise.

Agent Description Engineering

Sub-agent effectiveness depends heavily on the description field in agent YAML frontmatter. This tells the primary agent when to delegate. Phrases like "use PROACTIVELY" or trigger words ("if they say TTS") improve delegation accuracy significantly.

Validation Hook Performance

PostToolUse validators (Ruff, Ty) execute synchronously on every relevant tool use. For large codebases, consider whether full type checking belongs in hooks or in CI. The repository's approach prioritizes immediate feedback over raw speed.

Comparison with Alternatives

Approach Strengths Trade-offs vs. disler/claude-code-hooks-mastery
Raw Claude Code (no hooks) Zero configuration, always current No deterministic control, no custom validation, relies entirely on LLM reasoning
Custom shell wrappers Simple to implement, language-agnostic No lifecycle integration, cannot intercept internal tool use, fragile string parsing
[INTERNAL_LINK: MCP servers] Standardized protocol, growing ecosystem Different abstraction layer—complementary rather than replacement; hooks control Claude Code behavior, MCP extends tool capabilities
disler/claude-code-hooks-mastery Complete lifecycle coverage, validated patterns, agent orchestration Python/UV specific, requires understanding Claude Code internals, maintenance burden for custom hooks

The repository does not replace MCP servers or custom wrappers—it occupies a distinct layer. Hooks control how Claude Code behaves; MCP servers extend what tools Claude Code can access. Sophisticated workflows combine both: hooks for governance and quality gates, MCP for external tool integration.

FAQ

What license covers this repository? The repository does not specify a license in its metadata. Check the GitHub repository directly for any license file added after the last commit.

Do hooks work with all Claude Code versions? Hooks are an official Anthropic feature, but specific payload schemas evolve. The repository was last updated March 4, 2026—verify compatibility with your Claude Code version.

Can I use hooks without UV? Technically yes, but you lose the single-file dependency isolation. You would need to manage Python environments and dependencies manually.

What's the performance impact of running 13 hooks? Hooks execute in parallel where possible, with 60-second timeouts. The TTS and LLM-enhanced hooks add latency proportional to external API response times.

How do sub-agents differ from the primary agent? Sub-agents operate with separate context windows, custom system prompts, and optional tool restrictions. They never communicate directly with users—only through the primary agent.

Is the meta-agent safe to use in production? The meta-agent generates agent files from descriptions. Review generated agents before deployment, as with any code generation tool.

Can hooks access my codebase? Hooks run in the project directory with inherited environment variables. They can execute arbitrary code—audit hook scripts before enabling them.

Conclusion

disler/claude-code-hooks-mastery delivers what the Claude Code ecosystem needed: a complete, working reference for deterministic AI agent control. It moves beyond documentation into validated implementation, covering all 13 lifecycle hooks with real security, quality, and orchestration patterns.

The repository serves three audiences particularly well: teams adopting Claude Code at scale who need governance guardrails; individual developers seeking deeper control over their AI-assisted workflows; and engineers building agent systems who want to study concrete sub-agent and meta-agent patterns rather than abstract theory.

The 3,829 stars and active fork community suggest this fills a genuine gap—not as a product to consume passively, but as a foundation to adapt. The UV architecture, validation patterns, and team orchestration workflows are designed to be extracted into your own projects.

Start with the hooks most relevant to your workflow—typically PreToolUse for security and UserPromptSubmit for context injection—then expand as needs grow. The full implementation awaits at https://github.com/disler/claude-code-hooks-mastery.

Comments (0)

Comments are moderated before appearing.

No comments yet. Be the first to share your thoughts!

Recommended Prompts

View All
All tools