---
title: "Claude Code Hooks Mastery"
description: "[Claude Code Hooks](https://docs.anthropic.com/en/docs/claude-code/hooks) - Quickly master how to use Claude Code hooks to add deterministic (or non-deterministic) control over Claude Code's behavior. Plus learn about [Claude Code Sub-Agents](#claude-code-sub-agents), the powerful [Meta-Agent](#the-meta-agent), and [Team-Based Validation](#team-based-validation-system) with agent orchestration."
type: skill
canonical_url: https://claudary.paisolsolutions.com/skills/readme-122
source: "Claudary"
difficulty: intermediate
author: "Claude Code Knowledge Pack"
date: 2026-07-10T11:36:07.671Z
license: CC-BY-4.0
attribution: "Claude Code Hooks Mastery — Claudary (https://claudary.paisolsolutions.com/skills/readme-122)"
---

# Claude Code Hooks Mastery
[Claude Code Hooks](https://docs.anthropic.com/en/docs/claude-code/hooks) - Quickly master how to use Claude Code hooks to add deterministic (or non-deterministic) control over Claude Code's behavior. Plus learn about [Claude Code Sub-Agents](#claude-code-sub-agents), the powerful [Meta-Agent](#the-meta-agent), and [Team-Based Validation](#team-based-validation-system) with agent orchestration.

## Overview

# Claude Code Hooks Mastery

[Claude Code Hooks](https://docs.anthropic.com/en/docs/claude-code/hooks) - Quickly master how to use Claude Code hooks to add deterministic (or non-deterministic) control over Claude Code's behavior. Plus learn about [Claude Code Sub-Agents](#claude-code-sub-agents), the powerful [Meta-Agent](#the-meta-agent), and [Team-Based Validation](#team-based-validation-system) with agent orchestration.

<img src="images/hooked.png" alt="Claude Code Hooks" style="max-width: 800px; width: 100%;" />

## Table of Contents

- [Prerequisites](#prerequisites)
- [Hook Lifecycle & Payloads](#hook-lifecycle--payloads)
- [What This Shows](#what-this-shows)
- [UV Single-File Scripts Architecture](#uv-single-file-scripts-architecture)
- [Key Files](#key-files)
- [Features Demonstrated](#features-demonstrated)
- [Hook Error Codes & Flow Control](#hook-error-codes--flow-control)
- [UserPromptSubmit Hook Deep Dive](#userpromptsubmit-hook-deep-dive)
- [Claude Code Sub-Agents](#claude-code-sub-agents)
- [Team-Based Validation System](#team-based-validation-system)
- [Output Styles Collection](#output-styles-collection)
- [Custom Status Lines](#custom-status-lines)

## Prerequisites

This requires:
- **[Astral UV](https://docs.astral.sh/uv/getting-started/installation/)** - Fast Python package installer and resolver
- **[Claude Code](https://docs.anthropic.com/en/docs/claude-code)** - Anthropic's CLI for Claude AI

### Optional Setup:

Optional:
- **[ElevenLabs](https://elevenlabs.io/)** - Text-to-speech provider (with MCP server integration)
- **[ElevenLabs MCP Server](https://github.com/elevenlabs/elevenlabs-mcp)** - MCP server for ElevenLabs
- **[Firecrawl MCP Server](https://www.firecrawl.dev/mcp)** - Web scraping and crawling MCP server (my favorite scraper)
- **[OpenAI](https://openai.com/)** - Language model provider + Text-to-speech provider
- **[Anthropic](https://www.anthropic.com/)** - Language model provider
- **[Ollama](https://ollama.com/)** - Local language model provider

## Hook Lifecycle & Payloads

This demo captures all 13 Claude Code hook lifecycle events with their JSON payloads:

### Hook Lifecycle Overview

```mermaid
flowchart TB
    subgraph SESSION["🟢 Session Lifecycle"]
        direction TB
        SETUP[["🔧 Setup<br/>(init/maintenance)"]]
        START[["▶️ SessionStart<br/>(startup/resume/clear)"]]
        END[["⏹️ SessionEnd<br/>(exit/sigint/error)"]]
    end

    subgraph MAIN["🔄 Main Conversation Loop"]
        direction TB
        PROMPT[["📝 UserPromptSubmit"]]
        CLAUDE["Claude Processes"]

        subgraph TOOLS["🛠️ Tool Execution"]
            direction TB
            PRE[["🔒 PreToolUse"]]
            PERM[["❓ PermissionRequest"]]
            EXEC["Tool Executes"]
            POST[["✅ PostToolUse"]]
            FAIL[["❌ PostToolUseFailure"]]
        end

        subgraph SUBAGENT["🤖 Subagent Lifecycle"]
            direction TB
            SSTART[["🚀 SubagentStart"]]
            SWORK["Subagent Works"]
            SSTOP[["🏁 SubagentStop"]]
        end

        NOTIFY[["🔔 Notification<br/>(Async)"]]
        STOP[["🛑 Stop"]]
    end

    subgraph COMPACT["🗜️ Maintenance"]
        PRECOMPACT[["📦 PreCompact"]]
    end

    SETUP --> START
    START --> PROMPT
    PROMPT --> CLAUDE
    CLAUDE --> PRE
    PRE --> PERM
    PERM --> EXEC
    EXEC --> POST
    EXEC -.-> FAIL
    CLAUDE -.-> SSTART
    SSTART --> SWORK
    SWORK --> SSTOP
    POST --> CLAUDE
    CLAUDE --> STOP
    CLAUDE -.-> NOTIFY
    STOP --> PROMPT
    STOP -.-> END
    PROMPT -.-> PRECOMPACT
    PRECOMPACT -.-> PROMPT
```

### 1. UserPromptSubmit Hook
**Fires:** Immediately when user submits a prompt (before Claude processes it)  
**Payload:** `prompt` text, `session_id`, timestamp  
**Enhanced:** Prompt validation, logging, context injection, security filtering

### 2. PreToolUse Hook
**Fires:** Before any tool execution  
**Payload:** `tool_name`, `tool_input` parameters  
**Enhanced:** Blocks dangerous commands (`rm -rf`, `.env` access)

### 3. PostToolUse Hook  
**Fires:** After successful tool completion  
**Payload:** `tool_name`, `tool_input`, `tool_response` with results

### 4. Notification Hook
**Fires:** When Claude Code sends notifications (waiting for input, etc.)  
**Payload:** `message` content  
**Enhanced:** TTS alerts - "Your agent needs your input" (30% chance includes name)

### 5. Stop Hook
**Fires:** When Claude Code finishes responding  
**Payload:** `stop_hook_active` boolean flag  
**Enhanced:** AI-generated completion messages with TTS playback (LLM priority: OpenAI > Anthropic > Ollama > random)

### 6. SubagentStop Hook
**Fires:** When Claude Code subagents (Task tools) finish responding  
**Payload:** `stop_hook_active` boolean flag  
**Enhanced:** TTS playback - "Subagent Complete"

### 7. PreCompact Hook
**Fires:** Before Claude Code performs a compaction operation  
**Payload:** `trigger` ("manual" or "auto"), `custom_instructions` (for manual), session info  
**Enhanced:** Transcript backup, verbose feedback for manual compaction

### 8. SessionStart Hook
**Fires:** When Claude Code starts a new session or resumes an existing one
**Payload:** `source` ("startup", "resume", or "clear"), session info
**Enhanced:** Development context loading (git status, recent issues, context files)

### 9. SessionEnd Hook
**Fires:** When Claude Code session ends (exit, sigint, or error)
**Payload:** `session_id`, `transcript_path`, `cwd`, `permission_mode`, `reason`
**Enhanced:** Session logging with optional cleanup tasks (removes temp files, stale logs)

### 10. PermissionRequest Hook
**Fires:** When user is shown a permission dialog
**Payload:** `tool_name`, `tool_input`, `tool_use_id`, session info
**Enhanced:** Permission auditing, auto-allow for read-only ops (Read, Glob, Grep, safe Bash)

### 11. PostToolUseFailure Hook
**Fires:** When a tool execution fails
**Payload:** `tool_name`, `tool_input`, `tool_use_id`, `error` object
**Enhanced:** Structured error logging with timestamps and full context

### 12. SubagentStart Hook
**Fires:** When a subagent (Task tool) spawns
**Payload:** `agent_id`, `agent_type`, session info
**Enhanced:** Subagent spawn logging with optional TTS announcement

### 13. Setup Hook
**Fires:** When Claude enters a repository (init) or periodically (maintenance)
**Payload:** `trigger` ("init" or "maintenance"), session info
**Enhanced:** Environment persistence via `CLAUDE_ENV_FILE`, context injection via `additionalContext`


## What This Shows

- **Complete hook lifecycle coverage** - All 13 hook events implemented and logging (11/13 validated via automated testing)
- **Prompt-level control** - UserPromptSubmit validates and enhances prompts before Claude sees them
- **Intelligent TTS system** - AI-generated audio feedback with voice priority (ElevenLabs > OpenAI > pyttsx3)
- **Security enhancements** - Blocks dangerous commands and sensitive file access at multiple levels
- **Personalized experience** - Uses engineer name from environment variables
- **Automatic logging** - All hook events are logged as JSON to `logs/` directory
- **Chat transcript extraction** - PostToolUse hook converts JSONL transcripts to readable JSON format
- **Team-based validation** - Builder/Validator agent pattern with code quality hooks

> **Warning:** The `chat.json` file contains only the most recent Claude Code conversation. It does not preserve conversations from previous sessions - each new conversation is fully copied and overwrites the previous one. This is unlike the other logs which are appended to from every claude code session.

## UV Single-File Scripts Architecture

This project leverages **[UV single-file scripts](https://docs.astral.sh/uv/guides/scripts/)** to keep hook logic cleanly separated from your main codebase. All hooks live in `.claude/hooks/` as standalone Python scripts with embedded dependency declarations.

**Benefits:**
- **Isolation** - Hook logic stays separate from your project dependencies
- **Portability** - Each hook script declares its own dependencies inline
- **No Virtual Environment Management** - UV handles dependencies automatically
- **Fast Execution** - UV's dependency resolution is lightning-fast
- **Self-Contained** - Each hook can be understood and modified independently

This approach ensures your hooks remain functional across different environments without polluting your main project's dependency tree.

## Key Files

- `.claude/settings.json` - Hook configuration with permissions
- `.claude/hooks/` - Python scripts using uv for each hook type
  - `user_prompt_submit.py` - Prompt validation, logging, and context injection
  - `pre_tool_use.py` - Security blocking and logging
  - `post_tool_use.py` - Logging and transcript conversion
  - `post_tool_use_failure.py` - Error logging with structured details
  - `notification.py` - Logging with optional TTS (--notify flag)
  - `stop.py` - AI-generated completion messages with TTS
  - `subagent_stop.py` - Simple "Subagent Complete" TTS
  - `subagent_start.py` - Subagent spawn logging with optional TTS
  - `pre_compact.py` - Transcript backup and compaction logging
  - `session_start.py` - Development context loading and session logging
  - `session_end.py` - Session cleanup and logging
  - `permission_request.py` - Permission auditing and auto-allow
  - `setup.py` - Repository initialization and maintenance
  - `validators/` - Code quality validation hooks
    - `ruff_validator.py` - Python linting via Ruff (PostToolUse)
    - `ty_validator.py` - Python type checking (PostToolUse)
  - `utils/` - Intelligent TTS and LLM utility scripts
    - `tts/` - Text-to-speech providers (ElevenLabs, OpenAI, pyttsx3)
      - `tts_queue.py` - Queue-based TTS management (prevents overlapping audio)
    - `llm/` - Language model integrations (OpenAI, Anthropic, Ollama)
      - `task_summarizer.py` - LLM-powered task completion summaries
- `.claude/status_lines/` - Real-time terminal status displays
  - `status_line.py` - Basic MVP with git info
  - `status_line_v2.py` - Smart prompts with color coding
  - `status_line_v3.py` - Agent sessions with history
  - `status_line_v4.py` - Extended metadata support
  - `status_line_v5.py` - Cost tracking with line changes
  - `status_line_v6.py` - Context window usage bar
  - `status_line_v7.py` - Session duration timer
  - `status_line_v8.py` - Token usage with cache stats
  - `status_line_v9.py` - Minimal powerline style
- `.claude/output-styles/` - Response formatting configurations
  - `genui.md` - Generates beautiful HTML with embedded styling
  - `table-based.md` - Organizes information in markdown tables
  - `yaml-structured.md` - YAML configuration format
  - `bullet-points.md` - Clean nested lists
  - `ultra-concise.md` - Minimal words, maximum speed
  - `html-structured.md` - Semantic HTML5
  - `markdown-focused.md` - Rich markdown features
  - `tts-summary.md` - Audio feedback via TTS
- `.claude/commands/` - Custom slash commands
  - `prime.md` - Project analysis and understanding
  - `plan_w_team.md` - Team-based build/validate workflow
  - `crypto_research.md` - Cryptocurrency research workflows
  - `cook.md` - Advanced task execution
  - `update_status_line.md` - Dynamic status updates
- `.claude/agents/` - Sub-agent configurations
  - `crypto/` - Cryptocurrency analysis agents
  - `team/` - Team-based workflow agents
    - `builder.md` - Implementation agent (all tools)
    - `validator.md` - Read-only validation agent
  - `hello-world-agent.md` - Simple greeting example
  - `llm-ai-agents-and-eng-research.md` - AI research specialist
  - `meta-agent.md` - Agent that creates other agents
  - `work-completion-summary.md` - Audio summary generator
- `logs/` - JSON logs of all hook executions
  - `user_prompt_submit.json` - User prompt submissions with validation
  - `pre_tool_use.json` - Tool use events with security blocking
  - `post_tool_use.json` - Tool completion events
  - `post_tool_use_failure.json` - Tool failure events with error details
  - `notification.json` - Notification events
  - `stop.json` - Stop events with completion messages
  - `subagent_stop.json` - Subagent completion events
  - `subagent_start.json` - Subagent spawn events
  - `pre_compact.json` - Pre-compaction events with trigger type
  - `session_start.json` - Session start events with source type
  - `session_end.json` - Session end events with reason
  - `permission_request.json` - Permission request audit log
  - `setup.json` - Setup events with trigger type
  - `chat.json` - Readable conversation transcript (generated by --chat flag)
- `ai_docs/` - Documentation resources
  - `cc_hooks_docs.md` - Complete hooks documentation from Anthropic
  - `claude_code_status_lines_docs.md` - Status line input schema and configuration
  - `user_prompt_submit_hook.md` - Comprehensive UserPromptSubmit hook documentation
  - `uv-single-file-scripts.md` - UV script architecture documentation
  - `anthropic_custom_slash_commands.md` - Slash commands documentation
  - `anthropic_docs_subagents.md` - Sub-agents documentation
- `ruff.toml` - Ruff linter configuration for Python code quality
- `ty.toml` - Type checker configuration for Python type validation

Hooks provide deterministic control over Claude Code behavior without relying on LLM decisions.

## Features Demonstrated

- Prompt validation and security filtering
- Context injection for enhanced AI responses
- Command logging and auditing
- Automatic transcript conversion  
- Permission-based tool access control
- Error handling in hook execution

Run any Claude Code command to see hooks in action via the `logs/` files.

## Hook Error Codes & Flow Control

Claude Code hooks provide powerful mechanisms to control execution flow and provide feedback through exit codes and structured JSON output.

### Exit Code Behavior

Hooks communicate status and control flow through exit codes:

| Exit Code | Behavior           | Description                                                                                  |
| --------- | ------------------ | -------------------------------------------------------------------------------------------- |
| **0**     | Success            | Hook executed successfully. `stdout` shown to user in transcript mode (Ctrl-R)               |
| **2**     | Blocking Error     | **Critical**: `stderr` is fed back to Claude automatically. See hook-specific behavior below |
| **Other** | Non-blocking Error | `stderr` shown to user, execution continues normally                                         |

### Hook-Specific Flow Control

Each hook type has different capabilities for blocking and controlling Claude Code's behavior:

#### UserPromptSubmit Hook - **CAN BLOCK PROMPTS & ADD CONTEXT**
- **Primary Control Point**: Intercepts user prompts before Claude processes them
- **Exit Code 2 Behavior**: Blocks the prompt entirely, shows error message to user
- **Use Cases**: Prompt validation, security filtering, context

---

Source: [Claudary](https://claudary.paisolsolutions.com/skills/readme-122) · https://claudary.paisolsolutions.com
