hook-factory

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Hook Factory v2.0

Hook Factory v2.0

Generate production-ready Claude Code hooks with interactive Q&A, automated installation, and enhanced validation.
生成可用于生产环境的Claude Code钩子,具备交互式问答、自动化安装和增强型验证功能。

What This Skill Does

本Skill的功能

Hook Factory v2.0 is a comprehensive hook generation system with three modes:
  1. Interactive Mode (NEW!) - 7-question guided flow with smart defaults
  2. Natural Language - Describe what you want in plain English
  3. Template Mode - Direct generation from 10 production templates
Key Features:
  • Interactive Q&A - 7 questions with validation and smart defaults
  • Automated Installation - Python and Bash installers with backup/rollback
  • Enhanced Validation - Secrets detection, event-specific rules, command validation
  • 10 Templates - Covering 7 event types (PostToolUse, SubagentStop, SessionStart, PreToolUse, UserPromptSubmit, Stop, PrePush)
  • Comprehensive Safety - Tool detection, silent failure, atomic operations
  • macOS/Linux Support - Production-ready for Unix environments
Hook Factory v2.0是一套全面的钩子生成系统,包含三种模式:
  1. 交互式模式(新增!) - 包含7个问题的引导流程,提供智能默认选项
  2. 自然语言模式 - 用简单的语言描述你的需求
  3. 模板模式 - 直接从10个生产模板生成钩子
核心特性:
  • 交互式问答 - 7个带验证和智能默认选项的问题
  • 自动化安装 - 支持备份与回滚的Python和Bash安装程序
  • 增强型验证 - 密钥检测、事件专属规则、命令验证
  • 10个模板 - 覆盖7种事件类型(PostToolUse、SubagentStop、SessionStart、PreToolUse、UserPromptSubmit、Stop、PrePush)
  • 全面安全保障 - 工具检测、静默失败、原子操作
  • macOS/Linux支持 - 可用于Unix生产环境

When to Use This Skill

何时使用本Skill

Use hook-factory when you want to:
  • Auto-format code after editing
  • Automatically stage files with git
  • Run tests when agents complete
  • Load project context at session start
  • Create custom workflow automation
  • Learn how hooks work through examples
当你需要以下功能时,可使用hook-factory:
  • 编辑后自动格式化代码
  • 用git自动暂存文件
  • 代理完成时自动运行测试
  • 会话启动时加载项目上下文
  • 创建自定义工作流自动化
  • 通过示例学习钩子的工作原理

Capabilities

功能特性

Three Generation Modes

三种生成模式

1. Interactive Mode (Recommended)
bash
python3 hook_factory.py -i
  • 7-question guided flow
  • Smart defaults based on event type
  • Input validation and safety warnings
  • Optional auto-install
2. Natural Language Mode
bash
python3 hook_factory.py -r "auto-format Python files after editing"
  • Simple keyword matching
  • Quick generation for common patterns
3. Template Mode (Advanced)
bash
python3 hook_factory.py -t post_tool_use_format -l python
  • Direct template selection
  • Full customization control
1. 交互式模式(推荐)
bash
python3 hook_factory.py -i
  • 7个问题的引导流程
  • 基于事件类型的智能默认选项
  • 输入验证和安全警告
  • 可选自动安装
2. 自然语言模式
bash
python3 hook_factory.py -r "auto-format Python files after editing"
  • 简单关键词匹配
  • 快速生成常见模式的钩子
3. 模板模式(进阶)
bash
python3 hook_factory.py -t post_tool_use_format -l python
  • 直接选择模板
  • 完全自定义控制

Supported Hook Templates (10 Total)

支持的钩子模板(共10个)

Formatting & Code Quality:
  1. post_tool_use_format - Auto-format after editing (Python, JS, TS, Rust, Go)
  2. post_tool_use_git_add - Auto-stage files with git
Testing & Validation: 3. subagent_stop_test_runner - Run tests when agent completes 4. pre_tool_use_validation - Validate before tool execution 5. pre_push_validation - Check before git push
Session Management: 6. session_start_load_context - Load context at session start 7. stop_session_cleanup - Cleanup at session end
User Interaction: 8. user_prompt_submit_preprocessor - Pre-process user prompts 9. notify_user_desktop - Desktop notifications (macOS/Linux)
Security: 10. security_scan_code - Security scanning with semgrep/bandit
格式化与代码质量:
  1. post_tool_use_format - 编辑后自动格式化(Python、JS、TS、Rust、Go)
  2. post_tool_use_git_add - 用git自动暂存文件
测试与验证: 3. subagent_stop_test_runner - 代理完成时运行测试 4. pre_tool_use_validation - 工具执行前进行验证 5. pre_push_validation - git推送前进行检查
会话管理: 6. session_start_load_context - 会话启动时加载上下文 7. stop_session_cleanup - 会话结束时清理
用户交互: 8. user_prompt_submit_preprocessor - 预处理用户提示 9. notify_user_desktop - 桌面通知(macOS/Linux)
安全: 10. security_scan_code - 用semgrep/bandit进行安全扫描

Languages Supported

支持的语言

  • Python (black formatter, pytest)
  • JavaScript (prettier, jest)
  • TypeScript (prettier, jest)
  • Rust (rustfmt, cargo test)
  • Go (gofmt, go test)
  • Python(black格式化工具、pytest)
  • JavaScript(prettier、jest)
  • TypeScript(prettier、jest)
  • Rust(rustfmt、cargo test)
  • Go(gofmt、go test)

Enhanced Validation (v2.0)

增强型验证(v2.0)

4-Layer Validation System:
  1. Structure Validation - JSON syntax, required fields, types
  2. Safety Validation - No destructive ops, tool detection, silent failure
  3. Matcher Validation - Valid glob patterns, tool names, file paths
  4. Event-Specific Validation - Rules per event type (PreToolUse, SessionStart, etc.)
NEW in v2.0:
  • Secrets Detection - AWS keys, JWT tokens, API keys, private keys (20+ patterns)
  • Event-Specific Rules - PreToolUse must have tool matcher, SessionStart read-only, etc.
  • Command Validation - Bash syntax, Unix commands, path validation, dangerous operations
  • macOS/Linux Validation - Platform-specific command checks
四层验证系统:
  1. 结构验证 - JSON语法、必填字段、类型检查
  2. 安全验证 - 无破坏性操作、工具检测、静默失败
  3. 匹配器验证 - 有效的glob模式、工具名称、文件路径
  4. 事件专属验证 - 针对每种事件类型的规则(PreToolUse、SessionStart等)
v2.0新增:
  • 密钥检测 - AWS密钥、JWT令牌、API密钥、私钥(20+种模式)
  • 事件专属规则 - PreToolUse必须包含工具匹配器、SessionStart为只读等
  • 命令验证 - Bash语法、Unix命令、路径验证、危险操作检查
  • macOS/Linux验证 - 针对特定平台的命令检查

Safety Features

安全特性

Every generated hook includes:
  • ✅ Tool detection (checks if required tools are installed)
  • ✅ Silent failure mode (never interrupts your workflow)
  • ✅ Appropriate timeout settings (5s-120s based on event type)
  • ✅ No destructive operations
  • ✅ Comprehensive validation before generation
  • ✅ Clear documentation and troubleshooting guides
  • ✅ Automatic backup during installation
每个生成的钩子都包含:
  • ✅ 工具检测(检查所需工具是否已安装)
  • ✅ 静默失败模式(绝不中断你的工作流)
  • ✅ 合适的超时设置(基于事件类型设置5秒-120秒)
  • ✅ 无破坏性操作
  • ✅ 生成前的全面验证
  • ✅ 清晰的文档和故障排除指南
  • ✅ 安装时自动备份

How to Invoke

调用方式

Natural Language Requests

自然语言请求

Simply describe what you want the hook to do:
"I want to auto-format Python files after editing"
"Create a hook that runs tests when agents complete"
"Auto-add files to git after editing"
"Load my TODO.md at session start"
只需描述你希望钩子实现的功能:
"我需要一个钩子在编辑后自动格式化Python代码"
"创建一个在代理完成时运行测试的钩子"
"编辑后自动将文件添加到git"
"会话启动时加载我的TODO.md"

Explicit Template Selection

明确选择模板

If you know which template you want:
"Generate a hook using the post_tool_use_format template for JavaScript"
"Create a test runner hook for Rust"
如果你知道想要使用的模板:
"使用post_tool_use_format模板为JavaScript生成钩子"
"为Rust创建测试运行器钩子"

List Available Templates

列出可用模板

"Show me all available hook templates"
"List hook templates"
"显示所有可用的钩子模板"
"列出钩子模板"

Example Interactions

交互示例

Example 1: Auto-Format Python

示例1:自动格式化Python代码

You: "I need a hook to auto-format my Python code after editing"
Hook Factory:
  • Detects template:
    post_tool_use_format
  • Detects language: Python
  • Generates hook with black formatter
  • Validates configuration
  • Saves to
    generated-hooks/auto-format-code-after-editing-python/
  • Creates
    hook.json
    and
    README.md
你: "我需要一个钩子在编辑后自动格式化我的Python代码"
Hook Factory:
  • 检测到模板:
    post_tool_use_format
  • 检测到语言:Python
  • 生成使用black格式化工具的钩子
  • 验证配置
  • 保存到
    generated-hooks/auto-format-code-after-editing-python/
  • 创建
    hook.json
    README.md

Example 2: Git Auto-Add

示例2:Git自动暂存

You: "Automatically stage files with git when I edit them"
Hook Factory:
  • Detects template:
    post_tool_use_git_add
  • Generates git auto-add hook
  • Validates git commands
  • Saves to
    generated-hooks/auto-add-files-to-git-after-editing/
你: "编辑文件后自动用git暂存"
Hook Factory:
  • 检测到模板:
    post_tool_use_git_add
  • 生成git自动暂存钩子
  • 验证git命令
  • 保存到
    generated-hooks/auto-add-files-to-git-after-editing/

Example 3: Test Runner

示例3:测试运行器

You: "Run my JavaScript tests after the agent finishes coding"
Hook Factory:
  • Detects template:
    subagent_stop_test_runner
  • Detects language: JavaScript
  • Configures jest/npm test
  • Saves to
    generated-hooks/run-tests-when-agent-completes-javascript/
你: "代理完成编码后运行我的JavaScript测试"
Hook Factory:
  • 检测到模板:
    subagent_stop_test_runner
  • 检测到语言:JavaScript
  • 配置jest/npm测试
  • 保存到
    generated-hooks/run-tests-when-agent-completes-javascript/

Output Structure

输出结构

For each hook, Hook Factory creates:
generated-hooks/
└── [hook-name]/
    ├── hook.json        # Complete hook configuration (validated)
    └── README.md        # Installation guide, usage, troubleshooting
每个钩子生成后,Hook Factory会创建以下结构:
generated-hooks/
└── [hook-name]/
    ├── hook.json        # 已验证的完整钩子配置
    └── README.md        # 安装指南、使用方法、故障排除

hook.json

hook.json

Valid JSON configuration ready to copy into your Claude Code settings:
json
{
  "matcher": {
    "tool_names": ["Write", "Edit"]
  },
  "hooks": [
    {
      "type": "command",
      "command": "if ! command -v black &> /dev/null; then\n    exit 0\nfi\n\nif [[ \"$CLAUDE_TOOL_FILE_PATH\" == *.py ]]; then\n    black \"$CLAUDE_TOOL_FILE_PATH\" || exit 0\nfi",
      "timeout": 60
    }
  ]
}
可直接复制到Claude Code设置中的有效JSON配置:
json
{
  "matcher": {
    "tool_names": ["Write", "Edit"]
  },
  "hooks": [
    {
      "type": "command",
      "command": "if ! command -v black &> /dev/null; then\n    exit 0\nfi\n\nif [[ \"$CLAUDE_TOOL_FILE_PATH\" == *.py ]]; then\n    black \"$CLAUDE_TOOL_FILE_PATH\" || exit 0\nfi",
      "timeout": 60
    }
  ]
}

README.md

README.md

Comprehensive documentation including:
  • Overview and how it works
  • Prerequisites
  • Installation instructions (manual)
  • Configuration options
  • Safety notes
  • Troubleshooting guide
  • Advanced customization tips
全面的文档包含:
  • 概述和工作原理
  • 前置条件
  • 手动安装说明
  • 配置选项
  • 安全注意事项
  • 故障排除指南
  • 进阶自定义技巧

Installation of Generated Hooks

生成钩子的安装

Automated Installation (NEW in v2.0!)

自动化安装(v2.0新增!)

Using Python Installer:
bash
cd generated-skills/hook-factory
使用Python安装程序:
bash
cd generated-skills/hook-factory

Install to user level (~/.claude/settings.json)

安装到用户级别 (~/.claude/settings.json)

python3 installer.py install generated-hooks/[hook-name] user
python3 installer.py install generated-hooks/[hook-name] user

Install to project level (.claude/settings.json)

安装到项目级别 (.claude/settings.json)

python3 installer.py install generated-hooks/[hook-name] project
python3 installer.py install generated-hooks/[hook-name] project

Uninstall

卸载

python3 installer.py uninstall [hook-name] user
python3 installer.py uninstall [hook-name] user

List installed hooks

列出已安装的钩子

python3 installer.py list user

**Using Bash Script (macOS/Linux):**
```bash
cd generated-skills/hook-factory
python3 installer.py list user

**使用Bash脚本(macOS/Linux):**
```bash
cd generated-skills/hook-factory

Install

安装

./install-hook.sh generated-hooks/[hook-name] user
./install-hook.sh generated-hooks/[hook-name] user

Features:

特性:

- Automatic backup with timestamp

- 带时间戳的自动备份

- JSON validation before/after

- 前后JSON验证

- Atomic write operations

- 原子写入操作

- Rollback on failure

- 失败时回滚

- Keeps last 5 backups

- 保留最近5个备份


**Auto-Install from Interactive Mode:**
- Answer 'y' to Q7 (Auto-Install)
- Hook is automatically installed
- No manual steps required

**从交互式模式自动安装:**
- 回答第7个问题(自动安装)时选择'y'
- 钩子会自动安装
- 无需手动步骤

Manual Installation (Legacy)

手动安装(传统方式)

  1. Review Generated Files
    bash
    cd generated-hooks/[hook-name]
    cat README.md
    cat hook.json
  2. Manual Installation
    • Open
      .claude/settings.json
      (project) or
      ~/.claude/settings.json
      (user)
    • Copy the hook configuration from
      hook.json
    • Add to the appropriate event type array
    • Save and restart Claude Code
  3. Verify
    • Check Claude Code logs:
      ~/.claude/logs/
    • Test the hook by performing the trigger action
  1. 查看生成的文件
    bash
    cd generated-hooks/[hook-name]
    cat README.md
    cat hook.json
  2. 手动安装
    • 打开
      .claude/settings.json
      (项目级别)或
      ~/.claude/settings.json
      (用户级别)
    • 复制
      hook.json
      中的钩子配置
    • 添加到对应的事件类型数组中
    • 保存并重启Claude Code
  3. 验证
    • 查看Claude Code日志:
      ~/.claude/logs/
    • 执行触发操作测试钩子

Validation

验证

Every hook is validated for:
  • JSON Syntax: Valid, parseable JSON
  • Structure: Required fields present and correct types
  • Safety: No destructive operations (rm -rf, etc.)
  • Tool Detection: External tools have detection checks
  • Silent Failure: Commands won't interrupt workflow
  • Timeouts: Appropriate for event type
  • Matchers: Valid glob patterns and tool names
每个钩子都会经过以下验证:
  • JSON语法:有效的可解析JSON
  • 结构:必填字段存在且类型正确
  • 安全:无破坏性操作(如rm -rf等)
  • 工具检测:外部工具包含检测检查
  • 静默失败:命令不会中断工作流
  • 超时:适合事件类型的超时设置
  • 匹配器:有效的glob模式和工具名称

Best Practices

最佳实践

  1. Start Simple: Use natural language requests for common patterns
  2. Review Before Installing: Always read the generated README.md
  3. Test in Isolation: Try hooks in a test project first
  4. Customize Gradually: Start with defaults, customize later
  5. Monitor Logs: Check
    ~/.claude/logs/
    if hooks aren't working
  1. 从简单开始:对常见模式使用自然语言请求
  2. 安装前检查:务必阅读生成的README.md
  3. 隔离测试:先在测试项目中试用钩子
  4. 逐步自定义:先使用默认值,之后再自定义
  5. 监控日志:如果钩子不工作,查看
    ~/.claude/logs/

Limitations

限制

Platform Support:
  • ✅ macOS and Linux fully supported
  • ❌ Windows not supported (Unix commands, bash-specific syntax)
Customization:
  • Interactive mode provides smart defaults but limited deep customization
  • Advanced users should use template mode + manual editing
  • No GUI - CLI only
Template System:
  • 10 templates cover common patterns
  • Custom templates require manual addition to templates.json
  • No template composition yet (combining multiple patterns)
平台支持:
  • ✅ 完全支持macOS和Linux
  • ❌ 不支持Windows(Unix命令、bash专属语法)
自定义:
  • 交互式模式提供智能默认选项,但深度自定义有限
  • 进阶用户应使用模板模式+手动编辑
  • 无图形界面 - 仅支持CLI
模板系统:
  • 10个模板覆盖常见模式
  • 自定义模板需手动添加到templates.json
  • 暂不支持模板组合(合并多种模式)

Technical Details

技术细节

Files in This Skill

本Skill包含的文件

Core Files:
  • SKILL.md
    - This manifest file
  • hook_factory.py
    - Main orchestrator with CLI interface (687 lines)
  • generator.py
    - Template substitution and hook generation
  • validator.py
    - Enhanced validation engine (700+ lines)
  • templates.json
    - 10 production hook templates
  • README.md
    - Skill usage guide and examples
NEW in v2.0:
  • installer.py
    - Automated installation system (536 lines)
  • install-hook.sh
    - Bash installation script (148 lines)
  • examples/
    - 10 reference examples (10 folders × 2 files)
核心文件:
  • SKILL.md
    - 本清单文件
  • hook_factory.py
    - 带CLI界面的主协调器(687行)
  • generator.py
    - 模板替换和钩子生成器
  • validator.py
    - 增强型验证引擎(700+行)
  • templates.json
    - 10个生产钩子模板
  • README.md
    - Skill使用指南和示例
v2.0新增:
  • installer.py
    - 自动化安装系统(536行)
  • install-hook.sh
    - Bash安装脚本(148行)
  • examples/
    - 10个参考示例(10个文件夹 × 2个文件)

Dependencies

依赖

  • Python 3.7+
  • Standard library only (no external dependencies)
  • Python 3.7+
  • 仅使用标准库(无外部依赖)

Architecture (v2.0)

架构(v2.0)

Interactive Mode Flow:
User: python3 hook_factory.py -i
[7-Question Flow with Smart Defaults]
[Template Selection]
[Variable Substitution]
[4-Layer Validation]
[File Generation]
[Optional: Auto-Install via installer.py]
Generated Hook in generated-hooks/ + Installed
Natural Language Flow:
User Request
[Keyword Matching]
[Template Selection]
[Variable Substitution]
[4-Layer Validation]
[File Generation]
Generated Hook in generated-hooks/
Installation Flow:
Hook Folder
[installer.py or install-hook.sh]
[Backup settings.json]
[Load + Validate JSON]
[Merge Hook]
[Atomic Write (temp → rename)]
[Validate Result]
✅ Installed (or ❌ Rollback)
交互式模式流程:
用户: python3 hook_factory.py -i
[带智能默认选项的7问题流程]
[模板选择]
[变量替换]
[四层验证]
[文件生成]
[可选:通过installer.py自动安装]
生成的钩子保存到generated-hooks/ + 已安装
自然语言流程:
用户请求
[关键词匹配]
[模板选择]
[变量替换]
[四层验证]
[文件生成]
生成的钩子保存到generated-hooks/
安装流程:
钩子文件夹
[installer.py或install-hook.sh]
[备份settings.json]
[加载 + 验证JSON]
[合并钩子]
[原子写入(临时文件 → 重命名)]
[验证结果]
✅ 安装完成(或 ❌ 回滚)

Troubleshooting

故障排除

"Could not determine hook type from request"

"无法从请求中确定钩子类型"

  • Use more specific keywords (format, test, git add, load)
  • Or use explicit template selection
  • Or list templates to see what's available
  • 使用更具体的关键词(format、test、git add、load)
  • 或明确选择模板
  • 或列出所有可用模板

Generated hook not working

生成的钩子不工作

  • Check Claude Code logs
  • Verify required tools are installed
  • Test command manually in terminal
  • Review README.md troubleshooting section
  • 查看Claude Code日志
  • 验证所需工具是否已安装
  • 在终端手动测试命令
  • 查看README.md的故障排除部分

Validation errors

验证错误

  • Review error messages and fix suggestions
  • Common issues: missing tool detection, destructive commands
  • Modify template if needed
  • 查看错误消息和修复建议
  • 常见问题:缺少工具检测、破坏性命令
  • 如有需要,修改模板

Examples Directory

示例目录

The
examples/
directory contains reference implementations:
examples/
├── auto-format-python/      # PostToolUse format example
├── git-auto-add/            # PostToolUse git example
├── test-runner/             # SubagentStop test example
└── load-context/            # SessionStart context example
Each example includes working
hook.json
and
README.md
files you can copy directly.
examples/
目录包含参考实现:
examples/
├── auto-format-python/      # PostToolUse格式化示例
├── git-auto-add/            # PostToolUse git示例
├── test-runner/             # SubagentStop测试示例
└── load-context/            # SessionStart上下文示例
每个示例都包含可直接复制使用的
hook.json
README.md
文件。

Contributing

贡献

To add new hook patterns:
  1. Add template to
    templates.json
  2. Update keyword matching in
    generator.py
  3. Add example to
    examples/
  4. Update this SKILL.md
如需添加新的钩子模式:
  1. 将模板添加到
    templates.json
  2. 更新
    generator.py
    中的关键词匹配
  3. 将示例添加到
    examples/
  4. 更新本SKILL.md

Version History

版本历史

  • 1.0.0 (2025-10-30): Initial release
    • 4 core hook patterns
    • Natural language generation
    • Comprehensive validation
    • Simple keyword matching
  • 1.0.0 (2025-10-30): 初始版本
    • 4个核心钩子模式
    • 自然语言生成
    • 全面验证
    • 简单关键词匹配

Support

支持


Generated by Claude Code Skills Factory Last Updated: 2025-10-30

Generated by Claude Code Skills Factory Last Updated: 2025-10-30