writing-hookify-rules

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Writing Hookify Rules

编写Hookify规则

Overview

概述

Hookify rules are markdown files with YAML frontmatter that define patterns to watch for and messages to show when those patterns match. Rules are stored in
.claude/hookify.{rule-name}.local.md
files.
Hookify规则是带有YAML前置元数据的Markdown文件,用于定义需要监控的模式,以及当模式匹配时显示的消息。规则存储在
.claude/hookify.{rule-name}.local.md
文件中。

Rule File Format

规则文件格式

Basic Structure

基本结构

markdown
---
name: rule-identifier
enabled: true
event: bash|file|stop|prompt|all
pattern: regex-pattern-here
---

Message to show Claude when this rule triggers.
Can include markdown formatting, warnings, suggestions, etc.
markdown
---
name: rule-identifier
enabled: true
event: bash|file|stop|prompt|all
pattern: regex-pattern-here
---

当规则触发时显示给Claude的消息。
可包含Markdown格式、警告、建议等内容。

Frontmatter Fields

前置元数据字段

name (required): Unique identifier for the rule
  • Use kebab-case:
    warn-dangerous-rm
    ,
    block-console-log
  • Be descriptive and action-oriented
  • Start with verb: warn, prevent, block, require, check
enabled (required): Boolean to activate/deactivate
  • true
    : Rule is active
  • false
    : Rule is disabled (won't trigger)
  • Can toggle without deleting rule
event (required): Which hook event to trigger on
  • bash
    : Bash tool commands
  • file
    : Edit, Write, MultiEdit tools
  • stop
    : When agent wants to stop
  • prompt
    : When user submits a prompt
  • all
    : All events
action (optional): What to do when rule matches
  • warn
    : Show message but allow operation (default)
  • block
    : Prevent operation (PreToolUse) or stop session (Stop events)
  • If omitted, defaults to
    warn
pattern (simple format): Regex pattern to match
  • Used for simple single-condition rules
  • Matches against command (bash) or new_text (file)
  • Python regex syntax
Example:
yaml
event: bash
pattern: rm\s+-rf
name(必填):规则的唯一标识符
  • 使用短横线命名法:
    warn-dangerous-rm
    block-console-log
  • 描述性强且面向操作
  • 以动词开头:warn(警告)、prevent(阻止)、block(拦截)、require(要求)、check(检查)
enabled(必填):用于激活/停用规则的布尔值
  • true
    :规则处于激活状态
  • false
    :规则已禁用(不会触发)
  • 无需删除规则即可切换状态
event(必填):触发规则的钩子事件类型
  • bash
    :Bash工具命令
  • file
    :Edit、Write、MultiEdit工具操作
  • stop
    :当Agent想要停止会话时
  • prompt
    :当用户提交提示词时
  • all
    :所有事件类型
action(可选):规则匹配时执行的操作
  • warn
    :显示消息但允许操作(默认值)
  • block
    :阻止操作(PreToolUse事件)或终止会话(Stop事件)
  • 若省略,默认使用
    warn
pattern(简单格式):用于匹配的正则表达式
  • 适用于简单的单条件规则
  • 匹配目标为命令(bash事件)或新文本(file事件)
  • 遵循Python正则表达式语法
示例:
yaml
event: bash
pattern: rm\s+-rf

Advanced Format (Multiple Conditions)

高级格式(多条件)

For complex rules with multiple conditions:
markdown
---
name: warn-env-file-edits
enabled: true
event: file
conditions:
  - field: file_path
    operator: regex_match
    pattern: \.env$
  - field: new_text
    operator: contains
    pattern: API_KEY
---

You're adding an API key to a .env file. Ensure this file is in .gitignore!
Condition fields:
  • field
    : Which field to check
    • For bash:
      command
    • For file:
      file_path
      ,
      new_text
      ,
      old_text
      ,
      content
  • operator
    : How to match
    • regex_match
      : Regex pattern matching
    • contains
      : Substring check
    • equals
      : Exact match
    • not_contains
      : Substring must NOT be present
    • starts_with
      : Prefix check
    • ends_with
      : Suffix check
  • pattern
    : Pattern or string to match
All conditions must match for rule to trigger.
适用于包含多个条件的复杂规则:
markdown
---
name: warn-env-file-edits
enabled: true
event: file
conditions:
  - field: file_path
    operator: regex_match
    pattern: \.env$
  - field: new_text
    operator: contains
    pattern: API_KEY
---

你正在向.env文件中添加API密钥。请确保该文件已加入.gitignore!
条件字段说明:
  • field
    :需要检查的字段
    • bash事件:
      command
    • file事件:
      file_path
      new_text
      old_text
      content
  • operator
    :匹配方式
    • regex_match
      :正则表达式匹配
    • contains
      :子字符串检查
    • equals
      :精确匹配
    • not_contains
      :子字符串必须不存在
    • starts_with
      :前缀检查
    • ends_with
      :后缀检查
  • pattern
    :用于匹配的模式或字符串
所有条件必须同时满足,规则才会触发。

Message Body

消息主体

The markdown content after frontmatter is shown to Claude when the rule triggers.
Good messages:
  • Explain what was detected
  • Explain why it's problematic
  • Suggest alternatives or best practices
  • Use formatting for clarity (bold, lists, etc.)
Example:
markdown
⚠️ **Console.log detected!**

You're adding console.log to production code.

**Why this matters:**
- Debug logs shouldn't ship to production
- Console.log can expose sensitive data
- Impacts browser performance

**Alternatives:**
- Use a proper logging library
- Remove before committing
- Use conditional debug builds
前置元数据之后的Markdown内容会在规则触发时显示给Claude。
优质消息的特点:
  • 说明检测到的内容
  • 解释问题所在
  • 提供替代方案或最佳实践
  • 使用格式增强可读性(粗体、列表等)
示例:
markdown
⚠️ **检测到console.log!**

你正在向生产代码中添加console.log。

**问题的严重性:**
- 调试日志不应发布到生产环境
- console.log可能泄露敏感数据
- 影响浏览器性能

**替代方案:**
- 使用专业的日志库
- 提交代码前删除调试日志
- 使用条件编译的调试版本

Event Type Guide

事件类型指南

bash Events

bash事件

Match Bash command patterns:
markdown
---
event: bash
pattern: sudo\s+|rm\s+-rf|chmod\s+777
---

Dangerous command detected!
Common patterns:
  • Dangerous commands:
    rm\s+-rf
    ,
    dd\s+if=
    ,
    mkfs
  • Privilege escalation:
    sudo\s+
    ,
    su\s+
  • Permission issues:
    chmod\s+777
    ,
    chown\s+root
匹配Bash命令模式:
markdown
---
event: bash
pattern: sudo\s+|rm\s+-rf|chmod\s+777
---

检测到危险命令!
常见模式:
  • 危险命令:
    rm\s+-rf
    dd\s+if=
    mkfs
  • 权限提升:
    sudo\s+
    su\s+
  • 权限问题:
    chmod\s+777
    chown\s+root

file Events

file事件

Match Edit/Write/MultiEdit operations:
markdown
---
event: file
pattern: console\.log\(|eval\(|innerHTML\s*=
---

Potentially problematic code pattern detected!
Match on different fields:
markdown
---
event: file
conditions:
  - field: file_path
    operator: regex_match
    pattern: \.tsx?$
  - field: new_text
    operator: regex_match
    pattern: console\.log\(
---

Console.log in TypeScript file!
Common patterns:
  • Debug code:
    console\.log\(
    ,
    debugger
    ,
    print\(
  • Security risks:
    eval\(
    ,
    innerHTML\s*=
    ,
    dangerouslySetInnerHTML
  • Sensitive files:
    \.env$
    ,
    credentials
    ,
    \.pem$
  • Generated files:
    node_modules/
    ,
    dist/
    ,
    build/
匹配Edit/Write/MultiEdit操作:
markdown
---
event: file
pattern: console\.log\(|eval\(|innerHTML\s*=
---

检测到潜在的有问题代码模式!
匹配不同字段:
markdown
---
event: file
conditions:
  - field: file_path
    operator: regex_match
    pattern: \.tsx?$
  - field: new_text
    operator: regex_match
    pattern: console\.log\(
---

TypeScript文件中出现console.log!
常见模式:
  • 调试代码:
    console\.log\(
    debugger
    print\(
  • 安全风险:
    eval\(
    innerHTML\s*=
    dangerouslySetInnerHTML
  • 敏感文件:
    \.env$
    credentials
    \.pem$
  • 生成文件:
    node_modules/
    dist/
    build/

stop Events

stop事件

Match when agent wants to stop (completion checks):
markdown
---
event: stop
pattern: .*
---

Before stopping, verify:
- [ ] Tests were run
- [ ] Build succeeded
- [ ] Documentation updated
Use for:
  • Reminders about required steps
  • Completion checklists
  • Process enforcement
当Agent想要停止会话时触发(完成检查):
markdown
---
event: stop
pattern: .*
---

停止前,请确认:
- [ ] 已运行测试
- [ ] 构建成功
- [ ] 文档已更新
适用场景:
  • 提醒必要步骤
  • 完成检查清单
  • 流程强制执行

prompt Events

prompt事件

Match user prompt content (advanced):
markdown
---
event: prompt
conditions:
  - field: user_prompt
    operator: contains
    pattern: deploy to production
---

Production deployment checklist:
- [ ] Tests passing?
- [ ] Reviewed by team?
- [ ] Monitoring ready?
匹配用户提示词内容(高级用法):
markdown
---
event: prompt
conditions:
  - field: user_prompt
    operator: contains
    pattern: deploy to production
---

生产环境部署检查清单:
- [ ] 测试是否通过?
- [ ] 是否已通过团队评审?
- [ ] 监控是否准备就绪?

Pattern Writing Tips

模式编写技巧

Regex Basics

正则表达式基础

Literal characters: Most characters match themselves
  • rm
    matches "rm"
  • console.log
    matches "console.log"
Special characters need escaping:
  • .
    (any char) →
    \.
    (literal dot)
  • (
    )
    \(
    \)
    (literal parens)
  • [
    ]
    \[
    \]
    (literal brackets)
Common metacharacters:
  • \s
    - whitespace (space, tab, newline)
  • \d
    - digit (0-9)
  • \w
    - word character (a-z, A-Z, 0-9, _)
  • .
    - any character
  • +
    - one or more
  • *
    - zero or more
  • ?
    - zero or one
  • |
    - OR
Examples:
rm\s+-rf         Matches: rm -rf, rm  -rf
console\.log\(   Matches: console.log(
(eval|exec)\(    Matches: eval( or exec(
chmod\s+777      Matches: chmod 777, chmod  777
API_KEY\s*=      Matches: API_KEY=, API_KEY =
字面字符: 大多数字符匹配其本身
  • rm
    匹配 "rm"
  • console.log
    匹配 "console.log"
特殊字符需要转义:
  • .
    (任意字符)→
    \.
    (字面点)
  • (
    )
    \(
    \)
    (字面括号)
  • [
    ]
    \[
    \]
    (字面方括号)
常见元字符:
  • \s
    - 空白字符(空格、制表符、换行符)
  • \d
    - 数字(0-9)
  • \w
    - 单词字符(a-z、A-Z、0-9、_)
  • .
    - 任意字符
  • +
    - 一次或多次
  • *
    - 零次或多次
  • ?
    - 零次或一次
  • |
    - 或
示例:
rm\s+-rf         匹配:rm -rf、rm  -rf
console\.log\(   匹配:console.log(
(eval|exec)\(    匹配:eval( 或 exec(
chmod\s+777      匹配:chmod 777、chmod  777
API_KEY\s*=      匹配:API_KEY=、API_KEY =

Testing Patterns

模式测试

Test regex patterns before using:
bash
python3 -c "import re; print(re.search(r'your_pattern', 'test text'))"
Or use online regex testers (regex101.com with Python flavor).
在使用前测试正则表达式:
bash
python3 -c "import re; print(re.search(r'your_pattern', 'test text'))"
或使用在线正则表达式测试工具(如regex101.com,选择Python语法)。

Common Pitfalls

常见陷阱

Too broad:
yaml
pattern: log    # Matches "log", "login", "dialog", "catalog"
Better:
console\.log\(|logger\.
Too specific:
yaml
pattern: rm -rf /tmp  # Only matches exact path
Better:
rm\s+-rf
Escaping issues:
  • YAML quoted strings:
    "pattern"
    requires double backslashes
    \\s
  • YAML unquoted:
    pattern: \s
    works as-is
  • Recommendation: Use unquoted patterns in YAML
范围过宽:
yaml
pattern: log    # 匹配 "log"、"login"、"dialog"、"catalog"
更好的写法:
console\.log\(|logger\.
范围过窄:
yaml
pattern: rm -rf /tmp  # 仅匹配精确路径
更好的写法:
rm\s+-rf
转义问题:
  • YAML带引号字符串:
    "pattern"
    需要双反斜杠
    \\s
  • YAML无引号字符串:
    pattern: \s
    可直接使用
  • 建议:在YAML中使用无引号的模式

File Organization

文件组织

Location: All rules in
.claude/
directory Naming:
.claude/hookify.{descriptive-name}.local.md
Gitignore: Add
.claude/*.local.md
to
.gitignore
Good names:
  • hookify.dangerous-rm.local.md
  • hookify.console-log.local.md
  • hookify.require-tests.local.md
  • hookify.sensitive-files.local.md
Bad names:
  • hookify.rule1.local.md
    (not descriptive)
  • hookify.md
    (missing .local)
  • danger.local.md
    (missing hookify prefix)
位置: 所有规则存储在
.claude/
目录下 命名:
.claude/hookify.{descriptive-name}.local.md
Git忽略:
.claude/*.local.md
添加到
.gitignore
规范命名示例:
  • hookify.dangerous-rm.local.md
  • hookify.console-log.local.md
  • hookify.require-tests.local.md
  • hookify.sensitive-files.local.md
不规范命名示例:
  • hookify.rule1.local.md
    (描述性不足)
  • hookify.md
    (缺少.local后缀)
  • danger.local.md
    (缺少hookify前缀)

Workflow

工作流程

Creating a Rule

创建规则

  1. Identify unwanted behavior
  2. Determine which tool is involved (Bash, Edit, etc.)
  3. Choose event type (bash, file, stop, etc.)
  4. Write regex pattern
  5. Create
    .claude/hookify.{name}.local.md
    file in project root
  6. Test immediately - rules are read dynamically on next tool use
  1. 识别需要监控的不良行为
  2. 确定涉及的工具(Bash、Edit等)
  3. 选择事件类型(bash、file、stop等)
  4. 编写正则表达式模式
  5. 在项目根目录创建
    .claude/hookify.{name}.local.md
    文件
  6. 立即测试 - 规则会在下次工具使用时动态加载

Refining a Rule

优化规则

  1. Edit the
    .local.md
    file
  2. Adjust pattern or message
  3. Test immediately - changes take effect on next tool use
  1. 编辑
    .local.md
    文件
  2. 调整模式或消息内容
  3. 立即测试 - 修改会在下次工具使用时生效

Disabling a Rule

禁用规则

Temporary: Set
enabled: false
in frontmatter Permanent: Delete the
.local.md
file
临时禁用: 将前置元数据中的
enabled
设为
false
永久禁用: 删除
.local.md
文件

Examples

示例

See
${CLAUDE_PLUGIN_ROOT}/examples/
for complete examples:
  • dangerous-rm.local.md
    - Block dangerous rm commands
  • console-log-warning.local.md
    - Warn about console.log
  • sensitive-files-warning.local.md
    - Warn about editing .env files
可在
${CLAUDE_PLUGIN_ROOT}/examples/
目录下查看完整示例:
  • dangerous-rm.local.md
    - 拦截危险的rm命令
  • console-log-warning.local.md
    - 警告console.log的使用
  • sensitive-files-warning.local.md
    - 警告编辑.env文件的行为

Quick Reference

快速参考

Minimum viable rule:
markdown
---
name: my-rule
enabled: true
event: bash
pattern: dangerous_command
---

Warning message here
Rule with conditions:
markdown
---
name: my-rule
enabled: true
event: file
conditions:
  - field: file_path
    operator: regex_match
    pattern: \.ts$
  - field: new_text
    operator: contains
    pattern: any
---

Warning message
Event types:
  • bash
    - Bash commands
  • file
    - File edits
  • stop
    - Completion checks
  • prompt
    - User input
  • all
    - All events
Field options:
  • Bash:
    command
  • File:
    file_path
    ,
    new_text
    ,
    old_text
    ,
    content
  • Prompt:
    user_prompt
Operators:
  • regex_match
    ,
    contains
    ,
    equals
    ,
    not_contains
    ,
    starts_with
    ,
    ends_with
最简规则:
markdown
---
name: my-rule
enabled: true
event: bash
pattern: dangerous_command
---

警告消息
带多条件的规则:
markdown
---
name: my-rule
enabled: true
event: file
conditions:
  - field: file_path
    operator: regex_match
    pattern: \.ts$
  - field: new_text
    operator: contains
    pattern: any
---

警告消息
事件类型:
  • bash
    - Bash命令
  • file
    - 文件编辑
  • stop
    - 完成检查
  • prompt
    - 用户输入
  • all
    - 所有事件
字段选项:
  • Bash:
    command
  • File:
    file_path
    new_text
    old_text
    content
  • Prompt:
    user_prompt
操作符:
  • regex_match
    contains
    equals
    not_contains
    starts_with
    ends_with