### Sub-Agent Configuration Example Source: https://context7.com/disler/claude-code-hooks-mastery/llms.txt Example of a sub-agent configuration file using YAML frontmatter to define its name, description, model, color, and hooks. ```yaml # .claude/agents/team/builder.md --- name: builder description: > Generic engineering agent that executes ONE task at a time. Use when work needs to be done — writing code, creating files, implementing features. model: opus color: cyan hooks: PostToolUse: - matcher: "Write|Edit" hooks: - type: command command: uv run $CLAUDE_PROJECT_DIR/.claude/hooks/validators/ruff_validator.py - type: command command: uv run $CLAUDE_PROJECT_DIR/.claude/hooks/validators/ty_validator.py --- # Body is the system prompt for this agent You are a focused engineering agent responsible for executing ONE task at a time... ``` -------------------------------- ### Setup Hook: Add Additional Context Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_hooks_docs.md Use the 'Setup' hook to add custom context during repository initialization. Multiple 'additionalContext' values are concatenated. ```json { "hookSpecificOutput": { "hookEventName": "Setup", "additionalContext": "Repository initialized with custom configuration" } } ``` -------------------------------- ### Example Logged Bash Command Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_hooks_getting_started.md This is an example of an entry that would appear in the `bash-command-log.txt` file after a command like `ls` is executed. ```text ls - Lists files and directories ``` -------------------------------- ### Example Hook in a Skill Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_hooks_docs.md This example shows how to define a 'PreToolUse' hook directly within a skill's frontmatter. It uses a bash command to perform a security check before a 'Bash' tool is used. ```yaml --- name: secure-operations description: Perform operations with security checks hooks: PreToolUse: - matcher: "Bash" hooks: - type: command command: "./scripts/security-check.sh" --- ``` -------------------------------- ### Setup Hook: Initialize Project Context Source: https://context7.com/disler/claude-code-hooks-mastery/llms.txt Fires during repository initialization or maintenance. Gathers project info, checks tools, and provides context. ```python # Invocation: # uv run .claude/hooks/setup.py # uv run .claude/hooks/setup.py --install-deps --verbose # Stdin payload: payload = { "session_id": "550e8400...", "trigger": "init", # "init" | "maintenance" "cwd": "/home/user/myproject", "permission_mode": "default" } # Output (always printed to stdout for Claude to consume): output = { "hookSpecificOutput": { "hookEventName": "Setup", "additionalContext": ( "Setup triggered: init\n" "Session: 550e8400...\n" "Working directory: /home/user/myproject\n" "\n--- Project Information ---\n" "Git branch: main\n" "Detected: Node.js project\n" "Claude Code configuration directory present\n" "\n--- Available Tools ---\n" "node: v20.11.0\n" "python: Python 3.12.1\n" "uv: uv 0.4.0\n" "git: git version 2.43.0\n" "\n--- Repository Initialization ---\n" "Repository initialized with custom configuration\n" ) } } # With --install-deps: detects and installs package.json / requirements.txt / pyproject.toml # PROJECT_ROOT env var is persisted via CLAUDE_ENV_FILE for subsequent hooks ``` -------------------------------- ### Setup Input Schema Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_hooks_docs.md Schema for Setup hook, triggered during initialization or maintenance. The `trigger` field specifies whether it's an initial setup ('init') or maintenance ('maintenance'). ```json { "session_id": "abc123", "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", "cwd": "/Users/...", "permission_mode": "default", "hook_event_name": "Setup", "trigger": "init" } ``` -------------------------------- ### SessionStart Hook: Add Additional Context Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_hooks_docs.md Inject context at the beginning of a session using the 'SessionStart' hook. Similar to 'Setup', 'additionalContext' values are concatenated. ```json { "hookSpecificOutput": { "hookEventName": "SessionStart", "additionalContext": "My additional context here" } } ``` -------------------------------- ### User Prompt Submit Hook - Audit Logging Example Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/README.md Example JSON structure for logging user prompts, including timestamp, session ID, and the prompt content itself. This is useful for compliance and debugging. ```json { "timestamp": "2024-01-20T15:30:45.123Z", "session_id": "550e8400-e29b-41d4-a716", "prompt": "Delete all test files in the project" } ``` -------------------------------- ### Debug Output Example for Hooks Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_hooks_docs.md Use `claude --debug` to view detailed hook execution logs. This example shows the typical output when hooks are triggered for a PostToolUse event. ```bash [DEBUG] Executing hooks for PostToolUse:Write [DEBUG] Getting matching hook commands for PostToolUse with query: Write [DEBUG] Found 1 hook matchers in settings [DEBUG] Matched 1 hooks for query "Write" [DEBUG] Found 1 hook commands to execute [DEBUG] Executing hook command: with timeout 60000ms [DEBUG] Hook command completed with status 0: ``` -------------------------------- ### Workflow Example: Executing a Plan with Claude Code Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/README.md This bash script demonstrates the typical workflow for using Claude Code, from creating a plan with team orchestration to executing the plan and observing agent actions. ```bash # 1. Create a plan with team orchestration /plan_w_team # User prompt: "Update the hooks documentation and add missing status lines" # Orchestration prompt: "Create groups of agents for each hook, one builder and one validator" # 2. Plan is generated with: # - Team members (session_end_builder, session_end_validator, etc.) # - Step-by-step tasks with dependencies # - Validation commands # 3. Execute the plan /build # 4. Watch agents work in parallel: # - Builders implement features # - Validators verify completion # - Task system coordinates everything ``` -------------------------------- ### SessionEnd Hook Input Example Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_hooks_docs.md This is an example of the input payload received by a SessionEnd hook. It includes session details, transcript path, current working directory, permission mode, hook event name, and the reason for the session end. ```json { "session_id": "abc123", "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", "cwd": "/Users/...", "permission_mode": "default", "hook_event_name": "SessionEnd", "reason": "exit" } ``` -------------------------------- ### Configure Project-Level Hooks for Subagent Events Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_subagents_docs.md Define 'settings.json' hooks to trigger commands when specific subagents start or stop. Use the 'matcher' field to target agents by name. ```json { "hooks": { "SubagentStart": [ { "matcher": "db-agent", "hooks": [ { "type": "command", "command": "./scripts/setup-db-connection.sh" } ] } ], "SubagentStop": [ { "matcher": "db-agent", "hooks": [ { "type": "command", "command": "./scripts/cleanup-db-connection.sh" } ] } ] } } ``` -------------------------------- ### Bash Command Validation Example Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_hooks_docs.md This example demonstrates how to validate a bash command within a hook. Ensure the command is safe and meets requirements before execution. ```bash if [[ "$command" == "ls -l" ]]; then echo "Valid command" else echo "Invalid command" exit 1 fi ``` -------------------------------- ### Example Hook in an Agent Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_hooks_docs.md This configuration demonstrates defining a 'PostToolUse' hook within an agent's frontmatter. It executes a linter script after 'Edit' or 'Write' tool uses. ```yaml --- name: code-reviewer description: Review code changes hooks: PostToolUse: - matcher: "Edit|Write" hooks: - type: command command: "./scripts/run-linter.sh" --- ``` -------------------------------- ### Create a New User-Level Agent Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_subagents_docs.md Use the `/agents` command to initiate the creation of a new user-level subagent. This process guides you through defining the agent's purpose, selecting tools, and choosing a model. ```bash /agents ``` -------------------------------- ### User Prompt Submit Hook - Security Validation Example Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/README.md Illustrates how a UserPromptSubmit hook can block dangerous commands. The example shows a user prompt and the hook's response indicating a blocked system deletion command. ```bash User: "rm -rf / --no-preserve-root" Hook: BLOCKED: Dangerous system deletion command detected ``` -------------------------------- ### Example Plugin Hook Configuration Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_hooks_docs.md This configuration defines a plugin hook that automatically formats code after a 'Write' or 'Edit' tool use. It specifies a bash script to execute and a timeout. ```json { "description": "Automatic code formatting", "hooks": { "PostToolUse": [ { "matcher": "Write|Edit", "hooks": [ { "type": "command", "command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh", "timeout": 30 } ] } ] } } ``` -------------------------------- ### PreToolUse Hook Configuration Example Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_hooks_getting_started.md This JSON configuration sets up a `PreToolUse` hook that specifically targets 'Bash' tool calls. It defines a command to log the executed Bash command and its description. ```json { "hooks": { "PreToolUse": [ { "matcher": "Bash", "hooks": [ { "type": "command", "command": "jq -r '\"\(.tool_input.command) - \(.tool_input.description // \"No description\")\"' >> ~/.claude/bash-command-log.txt" } ] } ] } } ``` -------------------------------- ### TTS Provider Selection and Queueing Source: https://context7.com/disler/claude-code-hooks-mastery/llms.txt This Python code demonstrates how to select a Text-to-Speech (TTS) provider based on environment variables and how to use a queue to manage concurrent TTS requests. It includes setup for ElevenLabs, OpenAI, and a local fallback. ```python # Provider selection (used by stop.py, notification.py, subagent_stop.py): # Priority: ElevenLabs (ELEVENLABS_API_KEY) > OpenAI (OPENAI_API_KEY) > pyttsx3 (no key) import os, subprocess from pathlib import Path def get_tts_script_path(): tts_dir = Path(".claude/hooks/utils/tts") if os.getenv("ELEVENLABS_API_KEY"): return str(tts_dir / "elevenlabs_tts.py") if os.getenv("OPENAI_API_KEY"): return str(tts_dir / "openai_tts.py") return str(tts_dir / "pyttsx3_tts.py") # Speak a message: tts_script = get_tts_script_path() subprocess.run(["uv", "run", tts_script, "Task complete"], timeout=10) # Queue-based locking (prevents overlap from parallel agents): from utils.tts.tts_queue import acquire_tts_lock, release_tts_lock, cleanup_stale_locks cleanup_stale_locks(max_age_seconds=60) if acquire_tts_lock("agent-id-42", timeout=30): try: subprocess.run(["uv", "run", tts_script, "Auth endpoints complete"], timeout=10) finally: release_tts_lock("agent-id-42") # .env variables: # ELEVENLABS_API_KEY=... → highest quality cloud TTS # OPENAI_API_KEY=... → cloud TTS fallback # (pyttsx3 runs locally with no API key — always available) # ENGINEER_NAME=Alex → personalized notifications ("Alex, your agent needs your input") ``` -------------------------------- ### Status Line Configuration Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/README.md Configure the preferred status line type and command in settings.json. This example sets the status line to use a Python script. ```json { "statusLine": { "type": "command", "command": "uv run $CLAUDE_PROJECT_DIR/.claude/status_lines/status_line_v3.py" } } ``` -------------------------------- ### Describe a Code Improvement Agent Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_subagents_docs.md When prompted to generate a subagent, describe its functionality. This example outlines a code improvement agent that scans files and suggests enhancements for readability, performance, and best practices, including explanations and code examples. ```bash A code improvement agent that scans files and suggests improvements for readability, performance, and best practices. It should explain each issue, show the current code, and provide an improved version. ``` -------------------------------- ### Create Subagent File Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_subagents_docs.md Define a subagent using YAML frontmatter for configuration and a Markdown body for the system prompt. Subagent files are loaded at session start. ```yaml --- name: code-reviewer description: Reviews code for quality and best practices tools: Read, Glob, Grep model: sonnet --- You are a code reviewer. When invoked, analyze the code and provide specific, actionable feedback on quality, security, and best practices. ``` -------------------------------- ### Preload Skills into Sub-Agent Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_subagents_docs.md The `skills` field injects skill content into a sub-agent's context at startup, providing domain knowledge. This example configures an 'api-developer' sub-agent with 'api-conventions' and 'error-handling-patterns' skills. ```yaml --- name: api-developer description: Implement API endpoints following team conventions skills: - api-conventions - error-handling-patterns --- Implement API endpoints. Follow the conventions and patterns from the preloaded skills. ``` -------------------------------- ### User Prompt Submit Hook - Context Injection Example Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/README.md Demonstrates how a UserPromptSubmit hook can inject additional context before Claude processes the user's prompt. The hook adds project details and standards, which Claude will see along with the original prompt. ```bash User: "Write a new API endpoint" Hook adds: "Project: E-commerce API Standards: Follow REST conventions and OpenAPI 3.0 Generated at: 2024-01-20T15:30:45" Claude sees: [Context above] + "Write a new API endpoint" ``` -------------------------------- ### Status Line v6 Context Window Visualization Source: https://context7.com/disler/claude-code-hooks-mastery/llms.txt Configuration for a status line script that displays context window usage as a progress bar. Includes stdin payload and output example. ```json # .claude/settings.json: # "statusLine": {"type": "command", "command": "uv run .../status_line_v6.py"} # Stdin payload (sent by Claude Code on every message): payload = { "model": {"display_name": "claude-opus-4-5"}, "session_id": "550e8400-e29b-41d4-a716-446655440000", "context_window": { "used_percentage": 42.5, "context_window_size": 200000 } } ``` ```text # Output rendered in terminal: # [claude-opus-4-5] # [######---------] 42.5% used | ~115.0k left | 550e8400-... ``` ```text # Color thresholds: # < 50% → GREEN # < 75% → YELLOW # < 90% → RED # >= 90% → BRIGHT RED (critical) ``` ```text # v9 (powerline style) output example: # claude-opus-4-5 main ~/myproject 42% # (uses Unicode powerline glyphs: \ue0b0 separators, background color segments) ``` ```text # All 9 status line variants: # v1 status_line.py — git branch, directory, model # v2 status_line_v2.py — last prompt (250 chars), color by task type # v3 status_line_v3.py — agent name, model, last 3 prompts # v4 status_line_v4.py — agent name, model, prompt, custom key-value extras # v5 status_line_v5.py — cost ($), line changes (+/-), session duration # v6 status_line_v6.py — visual context bar, percentage, tokens remaining # v7 status_line_v7.py — session duration timer, start/end time # v8 status_line_v8.py — input/output tokens, cache creation/read stats # v9 status_line_v9.py — minimal powerline segments with Unicode separators ``` -------------------------------- ### Project-Specific Hook Script with CLAUDE_PROJECT_DIR Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_hooks_docs.md This example demonstrates using the CLAUDE_PROJECT_DIR environment variable to reference a project-specific hook script. This ensures the script runs correctly regardless of the current working directory. ```json { "hooks": { "PostToolUse": [ { "matcher": "Write|Edit", "hooks": [ { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-style.sh" } ] } ] } } ``` -------------------------------- ### SessionStart Input Schema Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_hooks_docs.md Schema for SessionStart hook, providing details about how the session began. Includes `source` (e.g., 'startup', 'resume') and the `model` identifier. An `agent_type` field is present if started with `claude --agent`. ```json { "session_id": "abc123", "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", "cwd": "/Users/...", "permission_mode": "default", "hook_event_name": "SessionStart", "source": "startup", "model": "claude-sonnet-4-20250514" } ``` -------------------------------- ### Subagent Auto-Compaction Log Entry Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_subagents_docs.md Compaction events in subagents are logged in transcript files. This example shows a system log entry indicating an auto-compaction event and the number of tokens used before compaction. ```json { "type": "system", "subtype": "compact_boundary", "compactMetadata": { "trigger": "auto", "preTokens": 167189 } } ``` -------------------------------- ### Configure Sub-Agent Tools Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_subagents_docs.md Use the `tools` and `disallowedTools` fields in the YAML frontmatter to specify which tools a sub-agent can access. This example restricts the 'safe-researcher' agent to read-only tools while disallowing write operations. ```yaml --- name: safe-researcher description: Research agent with restricted capabilities tools: Read, Grep, Glob, Bash disallowedTools: Write, Edit --- ``` -------------------------------- ### Simple Bash Script for Status Line Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_status_lines_docs.md This bash script reads JSON input from stdin, extracts the model's display name and the current directory's base name using 'jq', and then echoes a formatted string to be displayed as the status line. Ensure 'jq' is installed. ```bash #!/bin/bash # Read JSON input from stdin input=$(cat) # Extract values using jq MODEL_DISPLAY=$(echo "$input" | jq -r '.model.display_name') CURRENT_DIR=$(echo "$input" | jq -r '.workspace.current_dir') echo "[$MODEL_DISPLAY] 📁 ${CURRENT_DIR##*/}" ``` -------------------------------- ### Use a Custom Code Improvement Agent Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_subagents_docs.md After creating a custom subagent, you can invoke it using the `Use the [agent-name] agent to...` command. This example shows how to use a 'code-improver' agent to suggest improvements within the current project. ```bash Use the code-improver agent to suggest improvements in this project ``` -------------------------------- ### Log Bash Commands with PreToolUse Hook Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_hooks_getting_started.md This hook logs the command and description of Bash tool calls to a file. It uses `jq` to parse the tool input and appends the formatted string to `~/.claude/bash-command-log.txt`. Ensure `jq` is installed. ```bash jq -r '"\(.tool_input.command) - \(.tool_input.description // "No description")"' >> ~/.claude/bash-command-log.txt ``` -------------------------------- ### Using the Meta-Agent to Build New Agents Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/README.md Describe the desired sub-agent functionality. Claude Code automatically delegates to the meta-agent to create the agent file. ```bash # Simply describe what you want "Build a new sub-agent that runs tests and fixes failures" # Claude Code will automatically delegate to meta-agent # which will create a properly formatted agent file ``` -------------------------------- ### PreCompact Hook: Backup Transcript Source: https://context7.com/disler/claude-code-hooks-mastery/llms.txt Fires before context window compaction. Can create timestamped transcript backups. ```python # Invocation: # uv run .claude/hooks/pre_compact.py --backup --verbose # Stdin payload: payload = { "session_id": "550e8400...", "transcript_path": "/path/to/session.jsonl", "trigger": "auto", # "manual" | "auto" "custom_instructions": "" # populated for manual compaction } # Backup file created at: # logs/transcript_backups/_pre_compact_auto_20240120_153045.jsonl # Verbose stdout (visible in transcript mode Ctrl-R): # "Auto-compaction triggered due to full context window (session: 550e8400...)" # "Transcript backed up to: logs/transcript_backups/abc123_pre_compact_auto_20240120_153045.jsonl" ``` -------------------------------- ### Configure hooks for MCP tools Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_hooks_docs.md This configuration demonstrates how to set up hooks for MCP tools. It includes a hook to log memory operations and another to validate MCP write operations. ```json { "hooks": { "PreToolUse": [ { "matcher": "mcp__memory__.*", "hooks": [ { "type": "command", "command": "echo 'Memory operation initiated' >> ~/mcp-operations.log" } ] }, { "matcher": "mcp__.*__write.*", "hooks": [ { "type": "command", "command": "/home/user/scripts/validate-mcp-write.py" } ] } ] } } ``` -------------------------------- ### Stop/SubagentStop: Block Claude from Stopping Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_hooks_docs.md Use this hook to prevent Claude from stopping its current task. A reason must be provided to guide Claude on how to proceed. ```json { "decision": "block", "reason": "Must be provided when Claude is blocked from stopping" } ``` -------------------------------- ### Configure Command Hook with Tool Matcher Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_hooks_docs.md This configuration sets up a command hook that triggers for 'Write' or 'Edit' tools. It executes a bash command when the specified tool pattern matches. ```json { "hooks": { "EventName": [ { "matcher": "ToolPattern", "hooks": [ { "type": "command", "command": "your-command-here" } ] } ] } } ``` -------------------------------- ### Manually Calculate Context Window Usage Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_status_lines_docs.md This script calculates the context window usage percentage manually by summing input tokens, cache creation input tokens, and cache read input tokens, then dividing by the total context window size. It handles cases where current usage data might be null. ```bash #!/bin/bash input=$(cat) MODEL=$(echo "$input" | jq -r '.model.display_name') CONTEXT_SIZE=$(echo "$input" | jq -r '.context_window.context_window_size') USAGE=$(echo "$input" | jq '.context_window.current_usage') if [ "$USAGE" != "null" ]; then # Calculate current context from current_usage fields CURRENT_TOKENS=$(echo "$USAGE" | jq '.input_tokens + .cache_creation_input_tokens + .cache_read_input_tokens') PERCENT_USED=$((CURRENT_TOKENS * 100 / CONTEXT_SIZE)) echo "[$MODEL] Context: ${PERCENT_USED}%" else echo "[$MODEL] Context: 0%" fi ``` -------------------------------- ### Persist All Environment Changes in SessionStart Hook Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_hooks_docs.md Capture and persist all environment changes made within a SessionStart hook by diffing the environment before and after modifications. ```bash #!/bin/bash ENV_BEFORE=$(export -p | sort) ``` -------------------------------- ### Disable Specific Sub-agents via CLI Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_subagents_docs.md This command-line interface example shows how to disable specific sub-agents using the --disallowedTools flag. Replace 'Task(Explore)' with the name of the sub-agent you wish to disable. ```bash claude --disallowedTools "Task(Explore)" ``` -------------------------------- ### Intelligent Stop Hook Example Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_hooks_docs.md Configure a prompt-based hook to intelligently decide if Claude should stop working. This hook analyzes the conversation context to determine if tasks are complete, errors need addressing, or follow-up is required. ```json { "hooks": { "Stop": [ { "hooks": [ { "type": "prompt", "prompt": "You are evaluating whether Claude should stop working. Context: $ARGUMENTS\n\nAnalyze the conversation and determine if:\n1. All user-requested tasks are complete\n2. Any errors need to be addressed\n3. Follow-up work is needed\n\nRespond with JSON: {\"ok\": true} to allow stopping, or {\"ok\": false, \"reason\": \"your explanation\"} to continue working.", "timeout": 30 } ] } ] } } ``` -------------------------------- ### Resume Subagent Work Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_subagents_docs.md To continue an existing subagent's work instead of starting over, ask Claude to resume it. Resumed subagents retain their full conversation history, including all previous tool calls, results, and reasoning. ```text Use the code-reviewer subagent to review the authentication module [Agent completes] Continue that code review and now analyze the authorization logic [Claude resumes the subagent with full context from previous conversation] ``` -------------------------------- ### Configure UserPromptSubmit Hook Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/README.md Configure the UserPromptSubmit hook in `.claude/settings.json` to execute a Python script for prompt processing. Use `$CLAUDE_PROJECT_DIR` for reliable path resolution. Options include `--log-only`, `--validate`, and `--context`. ```json "UserPromptSubmit": [ { "hooks": [ { "type": "command", "command": "uv run $CLAUDE_PROJECT_DIR/.claude/hooks/user_prompt_submit.py --log-only" } ] } ] ``` -------------------------------- ### Verify Hook Configuration Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_hooks_getting_started.md This command displays the current hook configuration stored in `~/.claude/settings.json`. It's useful for verifying that your hooks have been saved correctly. ```bash cat ~/.claude/settings.json ``` -------------------------------- ### Configure Notification Hooks Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_hooks_docs.md Configure different hooks to run based on specific notification types using matchers. Omit the matcher to run hooks for all notifications. ```json { "hooks": { "Notification": [ { "matcher": "permission_prompt", "hooks": [ { "type": "command", "command": "/path/to/permission-alert.sh" } ] }, { "matcher": "idle_prompt", "hooks": [ { "type": "command", "command": "/path/to/idle-notification.sh" } ] } ] } } ``` -------------------------------- ### Display Context Window Usage Percentage Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_status_lines_docs.md Use this script to display the percentage of the context window used by Claude. It parses the model display name and the pre-calculated used percentage from the input JSON. ```bash #!/bin/bash input=$(cat) MODEL=$(echo "$input" | jq -r '.model.display_name') PERCENT_USED=$(echo "$input" | jq -r '.context_window.used_percentage // 0') echo "[$MODEL] Context: ${PERCENT_USED}%" ``` -------------------------------- ### Pre-Tool Use Hook for Validation Source: https://context7.com/disler/claude-code-hooks-mastery/llms.txt Fires before tool execution to block dangerous commands like `rm -rf` and access to `.env` files. Logs all tool calls. Returns exit code 2 on blocking. ```python # Stdin payload from Claude Code: payload = { "tool_name": "Bash", "tool_input": {"command": "rm -rf ./node_modules"}, "session_id": "...", "cwd": "/home/user/myproject" } # is_dangerous_rm_command() detects all rm -rf variants: from pre_tool_use import is_dangerous_rm_command assert is_dangerous_rm_command("rm -rf /tmp/test") == True assert is_dangerous_rm_command("rm --recursive --force /home") == True assert is_dangerous_rm_command("rm -fr ./dist") == True assert is_dangerous_rm_command("rm -f ./single_file.txt") == False # not recursive # is_env_file_access() blocks reads/writes to .env (but not .env.sample): from pre_tool_use import is_env_file_access # Blocked: assert is_env_file_access("Read", {"file_path": ".env"}) == True assert is_env_file_access("Bash", {"command": "cat .env"}) == True assert is_env_file_access("Write", {"file_path": "/project/.env"}) == True # Allowed: assert is_env_file_access("Read", {"file_path": ".env.sample"}) == False assert is_env_file_access("Bash", {"command": "cat .env.sample"}) == False # Log entry written on each call (even if not blocked): # logs/pre_tool_use.json: # [ # {"tool_name": "Bash", "tool_input": {"command": "ls -la"}, "session_id": "...", ...}, # ... # ] ``` -------------------------------- ### Auto-approve documentation file reads Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_hooks_docs.md This hook automatically approves 'Read' tool calls for documentation files (.md, .mdx, .txt, .json) by setting 'decision' to 'approve' and suppressing output. ```python if tool_name == "Read": file_path = tool_input.get("file_path", "") if file_path.endswith((".md", ".mdx", ".txt", ".json")): # Use JSON output to auto-approve the tool call output = { "decision": "approve", "reason": "Documentation file auto-approved", "suppressOutput": True # Don't show in verbose mode } print(json.dumps(output)) sys.exit(0) # For other cases, let the normal permission flow proceed sys.exit(0) ``` -------------------------------- ### Set Up Environment Variables for Claude Code Session Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_hooks_docs.md Use this bash script in a SessionStart hook to set environment variables. Variables written to CLAUDE_ENV_FILE are available in subsequent bash commands. CLAUDE_ENV_FILE is only accessible in SessionStart hooks. ```bash source ~/.nvm/nvm.sh nvm use 20 if [ -n "$CLAUDE_ENV_FILE" ]; then ENV_AFTER=$(export -p | sort) comm -13 <(echo "$ENV_BEFORE") <(echo "$ENV_AFTER") >> "$CLAUDE_ENV_FILE" fi exit 0 ``` -------------------------------- ### Chain Subagents for Multi-Step Workflows Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_subagents_docs.md Ask Claude to use subagents in sequence for multi-step workflows. Each subagent completes its task and returns results to Claude, which then passes relevant context to the next subagent. ```text Use the code-reviewer subagent to find performance issues, then use the optimizer subagent to fix them ``` -------------------------------- ### Checking Audit Logs - Bash Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/README.md Command to view the user prompt submit audit logs using `cat` and `jq` for pretty-printing the JSON output. ```bash cat logs/user_prompt_submit.json | jq '.' ``` -------------------------------- ### SubagentStart Input Schema Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_hooks_docs.md Schema for SubagentStart hook, triggered when a subagent is spawned. Contains the subagent's unique `agent_id` and its `agent_type` (e.g., 'Explore', 'Bash'). ```json { "session_id": "abc123", "transcript_path": "~/.claude/projects/.../00893aaf-19fa-41d2-8238-13269b9b3ca0.jsonl", "cwd": "/Users/...", "permission_mode": "default", "hook_event_name": "SubagentStart", "agent_id": "agent-abc123", "agent_type": "Explore" } ``` -------------------------------- ### Prompt-Based Stop Hook Configuration Source: https://github.com/disler/claude-code-hooks-mastery/blob/main/ai_docs/claude_code_hooks_docs.md This configuration sets up a prompt-based hook for the 'Stop' event. It uses an LLM to evaluate whether Claude should stop based on the provided prompt and arguments. ```json { "hooks": { "Stop": [ { "hooks": [ { "type": "prompt", "prompt": "Evaluate if Claude should stop: $ARGUMENTS. Check if all tasks are complete." } ] } ] } } ``` -------------------------------- ### Approve Permission Request with JSON Source: https://context7.com/disler/claude-code-hooks-mastery/llms.txt Use structured JSON output in a PermissionRequest hook to automatically approve a permission request. ```python # PreToolUse: approve a permission request, bypassing the dialog output = { "decision": "approve", "reason": "Read-only operation auto-approved" } print(json.dumps(output)) sys.exit(0) ```