Token导航 LogoToken导航TokenDH.com
AI 工具敏感数据github未标认证来源可访问clear审计通过

hooks-builder钩子生成器

Agent Skill

hooks-builder 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

744

周安装

31

GitHub Stars

16

下载量

248
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:hooks-builder(钩子生成器)
来源仓库:https://github.com/mike-coulbourn/claude-vibes
仓库路径:skills/hooks-builder
安装命令:
npx skills add https://github.com/mike-coulbourn/claude-vibes --skill hooks-builder
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/mike-coulbourn/claude-vibes --skill hooks-builder

简介

hooks-builder 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息。

  • 适合在 Codex、Claude、Cursor、Gemini CLI 中围绕仓库状态、代码变更或协作事项进行整理。
  • 通过 npx skills add 命令从指定仓库安装并使用该技能。
  • 安装前需确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。
  • 适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

SKILL.md

Hooks Builder

A comprehensive guide for creating Claude Code hooks — event-driven automation that monitors and controls Claude's actions.

Quick Reference

The 10 Hook Events

EventWhen It FiresCan Block?Supports Matchers?
PreToolUseBefore tool executesYESYES (tool names)
PermissionRequestPermission dialog shownYESYES (tool names)
PostToolUseAfter tool succeedsNoYES (tool names)
NotificationClaude sends notificationNoYES
UserPromptSubmitUser submits promptYESNo
StopClaude finishes respondingCan force continueNo
SubagentStopSubagent finishesCan force continueNo
PreCompactBefore context compactionNoYES (manual/auto)
SessionStartSession beginsNoYES (startup/resume/clear/compact)
SessionEndSession endsNoNo

Exit Code Semantics

Exit CodeMeaningEffect
0Successstdout parsed as JSON for control
2Blocking errorVETO — stderr shown to Claude
OtherNon-blocking errorstderr logged in debug mode

Configuration Locations

~/.claude/settings.json          → Personal hooks (all projects)
.claude/settings.json            → Project hooks (team, committed)
.claude/settings.local.json      → Local overrides (not committed)

Essential Environment Variables

VariableDescription
$CLAUDE_PROJECT_DIRProject root directory
$CLAUDE_CODE_REMOTERemote/local indicator
$CLAUDE_ENV_FILEEnvironment persistence path (SessionStart)
$CLAUDE_PLUGIN_ROOTPlugin directory (plugin hooks)

Key Commands

/hooks              # View active hooks
claude --debug      # Enable debug logging
chmod +x script.sh  # Make script executable

6-Phase Workflow

Phase 1: Requirements Gathering

Use AskUserQuestion to clarify:

  1. What event should trigger this hook?

- Tool execution (Pre/Post/Permission) → PreToolUse, PostToolUse, PermissionRequest - User input → UserPromptSubmit - Response completion → Stop, SubagentStop - Session lifecycle → SessionStart, SessionEnd - Context management → PreCompact - Notifications → Notification

  1. What should happen when triggered?

- Observe only (logging, metrics) - Block/allow based on conditions - Modify inputs before execution - Add context to prompts - Force continuation

  1. Should it block, modify, or just observe?

- Observer: PostToolUse, Notification, SessionEnd (can't block) - Gatekeeper: PreToolUse, PermissionRequest, UserPromptSubmit (can block) - Transformer: PreToolUse with updatedInput (can modify) - Controller: Stop, SubagentStop (can force continue)

  1. What are the security implications?

- Will it handle untrusted input? - Could it expose sensitive data? - Does it need to access external systems?

Phase 2: Event Selection

Match event to use case:

Use CaseBest Event
Block dangerous operationsPreToolUse
Auto-format code after writesPostToolUse
Validate user promptsUserPromptSubmit
Setup environmentSessionStart
Ensure task completionStop
Log all tool usagePostToolUse with "*" matcher
Protect sensitive filesPreToolUse for Write/Edit
Add project contextUserPromptSubmit

Determine if matchers are needed:

  • Specific tools? → Use matcher: "Write|Edit"
  • All tools? → Use "*" or omit matcher
  • MCP tools? → Use mcp__server__tool pattern
  • Bash commands? → Use Bash(git:*) pattern

Phase 3: Matcher Design

Matcher Pattern Syntax:

// Exact match (case-sensitive!)
"matcher": "Write"

// OR pattern
"matcher": "Write|Edit"

// Prefix match
"matcher": "Notebook.*"

// Contains match
"matcher": ".*Read.*"

// All tools
"matcher": "*"

// MCP tools
"matcher": "mcp__memory__.*"

// Bash sub-patterns
"matcher": "Bash(git:*)"

Common Matcher Patterns:

PatternMatches
"Write"Only Write tool
`"Write\Edit"`Write OR Edit
"Bash"All Bash commands
"Bash(git:*)"Only git commands
"Bash(npm:*)"Only npm commands
"mcp__.*__.*"All MCP tools
".*" or "*"Everything

Phase 4: Implementation

Choose implementation approach:

  1. Inline command (simple, no external file): {"type": "command", "command": "echo \"$(date) | $tool_name\" >> ~/.claude/audit.log"}
  2. External script (complex logic, reusable): {"type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/validate.sh"}
  3. Prompt-based (LLM evaluation, intelligent decisions): {"type": "prompt", "prompt": "Analyze if all tasks are complete: $ARGUMENTS", "timeout": 30}

Script Template (Bash):

#!/bin/bash
set -euo pipefail

# Read JSON input from stdin
input=$(cat)

# Parse fields with jq
tool_name=$(echo "$input" | jq -r '.tool_name // empty')
file_path=$(echo "$input" | jq -r '.tool_input.file_path // empty')

# Your logic here
if [[ "$file_path" == *".env"* ]]; then
    echo "BLOCKED: Cannot modify .env files" >&2
    exit 2
fi

# Success - output decision
echo '{"decision": "approve"}'
exit 0

Script Template (Python):

#!/usr/bin/env python3
import sys
import json

# Read JSON input from stdin
data = json.load(sys.stdin)

# Extract fields
tool_name = data.get('tool_name', '')
tool_input = data.get('tool_input', {})
file_path = tool_input.get('file_path', '')

# Your logic here
if '.env' in file_path:
    print("BLOCKED: Cannot modify .env files", file=sys.stderr)
    sys.exit(2)

# Success - output decision
output = {"decision": "approve"}
print(json.dumps(output))
sys.exit(0)

Phase 5: Security Hardening

CRITICAL: Hooks execute shell commands with YOUR permissions.

Security Checklist:

  • All variables quoted: "$VAR" not $VAR
  • JSON parsed with jq or json.load (not grep/sed)
  • Paths validated (no .., normalized)
  • No sensitive data in logs/output
  • No sudo or privilege escalation
  • Script tested manually first
  • Project hooks audited before running
  • Timeout set appropriately
  • Error handling for all failure modes

Secure Patterns:

# UNSAFE - injection risk
rm $file_path

# SAFE - quoted, prevents flag injection
rm -- "$file_path"

# UNSAFE - parsing risk
cat "$input" | grep "field"

# SAFE - proper JSON parsing
echo "$input" | jq -r '.field'

Defense in Depth:

  1. Input validation (parse JSON properly)
  2. Path sanitization (normalize, check boundaries)
  3. Output sanitization (no sensitive data)
  4. Fail-safe defaults (block on error, not allow)
  5. Timeout protection (prevent infinite loops)

Phase 6: Testing

Step 1: Manual Script Testing

# Create mock input
cat > /tmp/mock-input.json << 'EOF'
{
  "session_id": "test-123",
  "hook_event_name": "PreToolUse",
  "tool_name": "Write",
  "tool_input": {
    "file_path": "/path/to/file.txt",
    "content": "test content"
  }
}
EOF

# Test script
cat /tmp/mock-input.json | ./my-hook.sh
echo "Exit code: $?"

Step 2: Edge Case Testing

  • Empty inputs: {}
  • Missing fields: {"tool_name": "Write"}
  • Malicious inputs: {"tool_input": {"file_path": "; rm -rf /"}}
  • Large inputs: 10KB+ content
  • Unicode: paths with special characters

Step 3: Integration Testing

# Start Claude with debug mode
claude --debug

# Trigger the tool your hook targets
# Watch debug output for hook execution

Step 4: Verification

# Check hooks are registered
/hooks

# Watch hook execution
claude --debug 2>&1 | grep -i hook

Hook Patterns

Observer Pattern

Log without blocking — use PostToolUse or Notification.

{
  "hooks": {
    "PostToolUse": [{
      "matcher": "*",
      "hooks": [{
        "type": "command",
        "command": "echo \"$(date) | $tool_name\" >> ~/.claude/audit.log"
      }]
    }]
  }
}

Gatekeeper Pattern

Block dangerous actions — use PreToolUse or PermissionRequest.

{
  "hooks": {
    "PreToolUse": [{
      "matcher": "Write|Edit",
      "hooks": [{
        "type": "command",
        "command": "python3 ~/.claude/hooks/file-protector.py"
      }]
    }]
  }
}

Transformer Pattern

Modify inputs before execution — use PreToolUse with updatedInput.

# In script, output:
output = {
    "hookSpecificOutput": {
        "hookEventName": "PreToolUse",
        "permissionDecision": "allow",
        "updatedInput": {
            "content": add_license_header(original_content)
        }
    }
}
print(json.dumps(output))

Orchestrator Pattern

Coordinate multiple events — combine SessionStart + PreToolUse + PostToolUse.

{
  "hooks": {
    "SessionStart": [{
      "matcher": "startup",
      "hooks": [{"type": "command", "command": "~/.claude/hooks/setup-env.sh"}]
    }],
    "PreToolUse": [{
      "matcher": "Write|Edit",
      "hooks": [{"type": "command", "command": "~/.claude/hooks/validate.sh"}]
    }],
    "PostToolUse": [{
      "matcher": "Write|Edit",
      "hooks": [{"type": "command", "command": "~/.claude/hooks/format.sh"}]
    }]
  }
}

Common Pitfalls

1. Forgetting Exit Code 2 for Blocking

# WRONG - exit 1 doesn't block
echo "Error" >&2
exit 1

# RIGHT - exit 2 blocks Claude
echo "BLOCKED: reason" >&2
exit 2

2. Case Sensitivity in Matchers

// WRONG - won't match "Write" tool
"matcher": "write"

// RIGHT - case-sensitive match
"matcher": "Write"

3. Unquoted Variables (Injection Risk)

# WRONG - command injection vulnerability
rm $file_path

# RIGHT - properly quoted
rm -- "$file_path"

4. Missing Shebang in Scripts

# WRONG - no shebang, may fail
set -euo pipefail

# RIGHT - explicit interpreter
#!/bin/bash
set -euo pipefail

5. Not Making Scripts Executable

# Don't forget!
chmod +x ~/.claude/hooks/my-hook.sh

6. Forgetting to Quote Paths in JSON

// WRONG - spaces in path will break
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/script.sh"

// RIGHT - quoted path
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/script.sh"

7. No Error Handling

# WRONG - silent failures
input=$(cat)
tool=$(echo "$input" | jq -r '.tool_name')

# RIGHT - handle errors
input=$(cat) || { echo "Failed to read input" >&2; exit 1; }
tool=$(echo "$input" | jq -r '.tool_name') || { echo "Failed to parse JSON" >&2; exit 1; }

8. Logging Sensitive Data

# WRONG - may log secrets
echo "Processing: $input" >> /tmp/debug.log

# RIGHT - sanitize before logging
echo "Processing tool: $tool_name" >> /tmp/debug.log

When to Use Hooks

USE hooks for:

  • Security enforcement (block dangerous operations)
  • Code quality automation (format, lint on save)
  • Compliance and auditing (log all actions)
  • Environment setup (consistent configuration)
  • Workflow automation (notifications, integrations)
  • Input validation (prompt checking)
  • Task completion verification

DON'T use hooks for:

  • Adding new capabilities (use Skills)
  • Delegating complex work (use Agents)
  • User-invoked prompts (use Commands)
  • Simple one-off tasks (just ask Claude)

Files in This Skill

Templates (Progressive Complexity)

  • templates/basic-hook.md — Single event, inline command
  • templates/with-scripts.md — External shell scripts
  • templates/with-decisions.md — Permission control, input modification
  • templates/with-prompts.md — LLM-based evaluation
  • templates/production-hooks.md — Complete multi-event system

Examples (18 Complete Hooks)

  • examples/security-hooks.md — Protection, validation, auditing
  • examples/quality-hooks.md — Formatting, linting, testing
  • examples/workflow-hooks.md — Setup, context, notifications

Reference

  • reference/syntax-guide.md — Complete JSON schemas, all events
  • reference/best-practices.md — Security, design, team deployment
  • reference/troubleshooting.md — 10 common issues, testing methodology

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Claude Code

26.73%
按下载量换算66

OpenCode

22.11%
按下载量换算55

Gemini CLI

18.43%
按下载量换算46

Antigravity

10.8%
按下载量换算27

Codex

8.02%
按下载量换算20

windsurf

3.35%
按下载量换算8

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。

来源信息

继续浏览同类 Skills