Skip to content

Hookify 钩子创建工具插件

Hookify 让你无需编辑复杂的 hooks.json 文件,通过简单的 Markdown 配置文件就能创建自定义钩子,防止不需要的行为模式。

概述

Hookify 是一个强大的钩子管理插件,它将复杂的 hooks.json 配置简化为直观的 Markdown 文件。通过分析对话模式或显式指令,你可以快速创建规则来警告或阻止特定行为。

核心特性

特性说明
Markdown 配置使用 .local.md 文件定义规则,无需编辑 JSON
多种事件支持 Bash、文件操作、停止、用户提示等事件
灵活匹配支持正则表达式和多条件匹配
即时生效规则保存后立即生效,无需重启
Fail-safe钩子错误时不会阻止操作

设计理念

mermaid
graph LR
    A[传统方式<br/>编辑 hooks.json] --> B[复杂的 JSON 语法]
    B --> C[容易出错]

    D[Hookify 方式<br/>创建 .local.md] --> E[简单的 Markdown]
    E --> F[直观易懂]

    style A fill:#ffcdd2
    style D fill:#c8e6c9

安装与配置

插件安装

bash
# 安装 hookify 插件
/plugin install hookify@claude-plugins-official

目录结构

plugins/hookify/
├── .claude-plugin/
│   └── plugin.json
├── README.md
├── commands/
│   ├── hookify.md              # 创建规则命令
│   ├── list.md                 # 列出规则命令
│   ├── configure.md            # 配置规则命令
│   └── help.md                 # 帮助命令
├── hooks/
│   ├── hooks.json              # 钩子配置
│   ├── pretooluse.py           # PreToolUse 钩子
│   ├── posttooluse.py          # PostToolUse 钩子
│   ├── stop.py                 # Stop 钩子
│   └── userpromptsubmit.py     # UserPromptSubmit 钩子
├── core/
│   ├── config_loader.py        # 配置加载器
│   └── rule_engine.py          # 规则引擎
├── examples/                    # 示例规则
└── ...

配置文件 (plugin.json)

json
{
  "name": "hookify",
  "version": "0.1.0",
  "description": "Easily create hooks to prevent unwanted behaviors by analyzing conversation patterns",
  "author": {
    "name": "Daisy Hollman",
    "email": "daisy@anthropic.com"
  }
}

核心命令

/hookify

创建新的规则来防止特定行为。

语法

bash
# 基于对话分析创建规则
/hookify

# 指定要处理的行为
/hookify "阻止 rm -rf 命令"

工作流程

mermaid
sequenceDiagram
    participant U as 用户
    participant C as Claude
    participant F as 文件系统

    U->>C: /hookify "阻止危险命令"
    C->>C: 分析需求
    C->>F: 创建 .claude/hookify.*.local.md
    C->>U: 规则已创建

/hookify:list

列出所有已配置的规则。

语法

bash
/hookify:list

输出示例

📋 Hookify Rules

1. warn-console-log (enabled)
   Event: file
   Action: warn
   Pattern: console\.log\(

2. block-dangerous-rm (enabled)
   Event: bash
   Action: block
   Pattern: rm\s+-rf

3. warn-sensitive-files (enabled)
   Event: file
   Action: warn
   Conditions: 2 conditions

/hookify:configure

交互式配置现有规则。

语法

bash
/hookify:configure

功能

  • 启用/禁用规则
  • 修改规则参数
  • 删除规则

/hookify:help

显示 Hookify 帮助文档。

语法

bash
/hookify:help

规则配置格式

规则文件位置

规则存储在 .claude/hookify.*.local.md 文件中:

.claude/
├── hookify.warn-console-log.local.md
├── hookify.block-dangerous-rm.local.md
└── hookify.warn-sensitive-files.local.md

基本规则结构

markdown
---
name: rule-name
enabled: true
event: file
pattern: 正则表达式
action: warn
---

规则触发时显示的消息

可以使用 **Markdown** 格式

YAML 字段说明

字段类型必需说明
namestring规则唯一标识符
enabledboolean是否启用规则
eventstring触发事件类型
patternstring条件简单规则的匹配模式
actionstring动作类型 (warn/block)
conditionsarray条件复杂规则的多条件

事件类型

事件说明触发时机
bashBash 命令执行 Bash 工具时
file文件操作Edit、Write、MultiEdit 时
stop停止事件Claude 想要停止时
prompt用户提示用户提交提示时
all所有事件任何事件

动作类型

动作说明
warn显示警告消息,但允许操作继续(默认)
block阻止操作执行

简单规则示例

警告 console.log

markdown
---
name: warn-console-log
enabled: true
event: file
pattern: console\.log\(
action: warn
---

🔍 **Console.log detected**

You're adding a console.log statement. Please consider:
- Is this for debugging or should it be proper logging?
- Will this ship to production?
- Should this use a logging library instead?

阻止危险的 rm 命令

markdown
---
name: block-dangerous-rm
enabled: true
event: bash
pattern: rm\s+-rf
action: block
---

⚠️ **Dangerous rm command detected!**

This command could delete important files. Please:
- Verify the path is correct
- Consider using a safer approach
- Make sure you have backups

警告 TODO 注释

markdown
---
name: warn-todo-comments
enabled: true
event: file
pattern: //\s*TODO|#\s*TODO
action: warn
---

📝 **TODO comment detected**

You're adding a TODO comment. Consider:
- Is this something that should be tracked in an issue?
- Should this be addressed before merging?
- Add a ticket number for tracking: `// TODO(TICKET-123): description`

复杂规则(多条件)

语法结构

markdown
---
name: rule-name
enabled: true
event: file
action: warn
conditions:
  - field: file_path
    operator: regex_match
    pattern: 模式1
  - field: content
    operator: contains
    pattern: 模式2
---

消息内容

条件字段

字段说明可用事件
file_path文件路径file
content文件/命令内容file, bash
commandBash 命令bash
transcript对话记录stop
prompt用户提示prompt

条件操作符

操作符说明
regex_match正则表达式匹配
contains包含字符串
equals完全相等
not_contains不包含字符串
starts_with以...开头
ends_with以...结尾

示例:敏感文件警告

markdown
---
name: warn-sensitive-files
enabled: true
event: file
action: warn
conditions:
  - field: file_path
    operator: regex_match
    pattern: \.env$|\.env\.|credentials|secrets
---

🔐 **Sensitive file detected**

You're editing a file that may contain sensitive data:
- Ensure credentials are not hardcoded
- Use environment variables for secrets
- Verify this file is in .gitignore

示例:要求运行测试才能停止

markdown
---
name: require-tests-run
enabled: false
event: stop
action: block
conditions:
  - field: transcript
    operator: not_contains
    pattern: npm test|pytest|cargo test
---

🧪 **Tests not detected in transcript!**

Before stopping, please run tests to verify your changes work correctly.

Run one of these commands:
- `npm test`
- `pytest`
- `cargo test`

示例:阻止直接修改 node_modules

markdown
---
name: block-node-modules-edit
enabled: true
event: file
action: block
conditions:
  - field: file_path
    operator: contains
    pattern: node_modules/
---

**Cannot edit node_modules**

Editing files in node_modules is not allowed:
- Changes will be lost on next `npm install`
- Modify the source package instead
- Or create a patch using patch-package

技术架构

规则引擎

mermaid
graph TD
    A[钩子触发] --> B[加载规则文件]
    B --> C[rule_engine.py]
    C --> D{遍历规则}

    D --> E{规则启用?}
    E -->|否| D
    E -->|是| F{事件匹配?}

    F -->|否| D
    F -->|是| G{条件满足?}

    G -->|否| D
    G -->|是| H{动作类型}

    H -->|warn| I[显示警告<br/>允许操作]
    H -->|block| J[显示消息<br/>阻止操作]

    style I fill:#fff3e0
    style J fill:#ffcdd2

核心组件

config_loader.py

  • 加载 .local.md 规则文件
  • 解析 YAML frontmatter
  • 构建规则数据结构

rule_engine.py

  • 编译正则表达式(带缓存)
  • 评估规则条件
  • 返回匹配结果

Fail-safe 设计

python
try:
    # 执行规则检查
    result = rule_engine.evaluate(rules, input_data)
except Exception as e:
    # 发生错误时,允许操作继续
    # 不会因为钩子错误阻止用户工作
    return {"decision": "allow"}

实战示例

场景 1:团队代码规范

创建一组规则来强制团队代码规范:

bash
# 警告 any 类型使用
/hookify "警告 TypeScript 中使用 any 类型"

生成的规则:

markdown
---
name: warn-any-type
enabled: true
event: file
pattern: :\s*any\b|\<any\>|as\s+any
action: warn
---

⚠️ **TypeScript `any` type detected**

Using `any` defeats the purpose of TypeScript. Consider:
- Using a specific type
- Using `unknown` for truly unknown types
- Using generics for flexible typing

场景 2:安全审查

创建安全相关的规则:

bash
/hookify "阻止在代码中硬编码 API 密钥"

生成的规则:

markdown
---
name: block-hardcoded-secrets
enabled: true
event: file
action: block
conditions:
  - field: content
    operator: regex_match
    pattern: (api[_-]?key|secret|password|token)\s*[:=]\s*["'][^"']{10,}["']
---

🔒 **Hardcoded secret detected!**

Never hardcode secrets in source code:
- Use environment variables
- Use a secrets manager
- Add the file to .gitignore if it must contain secrets

场景 3:开发流程

创建流程相关的规则:

bash
/hookify "确保提交前运行 lint"

生成的规则:

markdown
---
name: require-lint-before-commit
enabled: true
event: bash
action: warn
conditions:
  - field: command
    operator: regex_match
    pattern: git\s+commit
---

🔍 **Committing without lint check?**

Before committing, please run:
```bash
npm run lint

This ensures code quality and consistency.


---

## 最佳实践

### 规则设计原则

| 原则 | 说明 |
|------|------|
| **明确目的** | 每个规则解决一个具体问题 |
| **友好消息** | 提供有帮助的说明和建议 |
| **谨慎阻止** | 优先使用 warn,block 仅用于真正危险的操作 |
| **定期审查** | 检查规则是否仍然需要 |

### 规则命名

hookify.<action>-<target>.local.md

示例:

  • hookify.warn-console-log.local.md
  • hookify.block-dangerous-rm.local.md
  • hookify.warn-todo-comments.local.md

### 团队共享

规则文件可以通过 Git 共享:

```bash
# 将规则移到项目目录
mv ~/.claude/hookify.*.local.md .claude/

# 提交到仓库
git add .claude/hookify.*.local.md
git commit -m "Add team hookify rules"

常见问题

Q: 规则不生效怎么办?

A: 检查以下几点:

  1. enabled: true 是否设置
  2. event 类型是否正确
  3. pattern 正则表达式是否有效
  4. 文件是否在 .claude/ 目录

Q: 如何测试规则?

A:

  1. 创建规则后立即触发相应操作
  2. 检查是否显示预期的消息
  3. 使用 /hookify:list 确认规则已加载

Q: 正则表达式语法是什么?

A: 使用 Python 正则表达式语法。常用模式:

  • \. - 匹配点号
  • \s+ - 一个或多个空白
  • \b - 单词边界
  • | - 或

Q: 如何临时禁用规则?

A: 两种方式:

  1. 编辑规则文件,设置 enabled: false
  2. 使用 /hookify:configure 交互式禁用

总结

Hookify 插件让钩子创建变得简单:

  1. Markdown 配置 - 无需编辑复杂的 JSON
  2. 多种事件 - 覆盖 Bash、文件、停止等场景
  3. 灵活匹配 - 支持正则和多条件
  4. 即时生效 - 保存后立即可用
  5. Fail-safe - 错误不会阻止正常工作

通过 Hookify,你可以轻松创建团队规范、安全检查和开发流程规则。


参考资源


本文档基于 hookify 插件 v0.1.0 编写

基于 MIT 许可证发布。内容版权归作者所有。