writing-hookify-rules
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseWriting 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 files.
.claude/hookify.{rule-name}.local.mdHookify规则是带有YAML前置元数据的Markdown文件,用于定义需要监控的模式,以及当模式匹配时显示的消息。规则存储在文件中。
.claude/hookify.{rule-name}.local.mdRule 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-rmblock-console-log - Be descriptive and action-oriented
- Start with verb: warn, prevent, block, require, check
enabled (required): Boolean to activate/deactivate
- : Rule is active
true - : Rule is disabled (won't trigger)
false - Can toggle without deleting rule
event (required): Which hook event to trigger on
- : Bash tool commands
bash - : Edit, Write, MultiEdit tools
file - : When agent wants to stop
stop - : When user submits a prompt
prompt - : All events
all
action (optional): What to do when rule matches
- : Show message but allow operation (default)
warn - : Prevent operation (PreToolUse) or stop session (Stop events)
block - 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+-rfname(必填):规则的唯一标识符
- 使用短横线命名法:、
warn-dangerous-rmblock-console-log - 描述性强且面向操作
- 以动词开头:warn(警告)、prevent(阻止)、block(拦截)、require(要求)、check(检查)
enabled(必填):用于激活/停用规则的布尔值
- :规则处于激活状态
true - :规则已禁用(不会触发)
false - 无需删除规则即可切换状态
event(必填):触发规则的钩子事件类型
- :Bash工具命令
bash - :Edit、Write、MultiEdit工具操作
file - :当Agent想要停止会话时
stop - :当用户提交提示词时
prompt - :所有事件类型
all
action(可选):规则匹配时执行的操作
- :显示消息但允许操作(默认值)
warn - :阻止操作(PreToolUse事件)或终止会话(Stop事件)
block - 若省略,默认使用
warn
pattern(简单格式):用于匹配的正则表达式
- 适用于简单的单条件规则
- 匹配目标为命令(bash事件)或新文本(file事件)
- 遵循Python正则表达式语法
示例:
yaml
event: bash
pattern: rm\s+-rfAdvanced 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:
- : Which field to check
field- For bash:
command - For file: ,
file_path,new_text,old_textcontent
- For bash:
- : How to match
operator- : Regex pattern matching
regex_match - : Substring check
contains - : Exact match
equals - : Substring must NOT be present
not_contains - : Prefix check
starts_with - : Suffix check
ends_with
- : Pattern or string to match
pattern
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_textcontent
- bash事件:
- :匹配方式
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+777chown\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+777chown\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\(,debuggerprint\( - 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\(、debuggerprint\( - 安全风险:、
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 updatedUse 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
- matches "rm"
rm - matches "console.log"
console.log
Special characters need escaping:
- (any char) →
.(literal dot)\. (→)\((literal parens)\)[→]\[(literal brackets)\]
Common metacharacters:
- - whitespace (space, tab, newline)
\s - - digit (0-9)
\d - - word character (a-z, A-Z, 0-9, _)
\w - - 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 - - 数字(0-9)
\d - - 单词字符(a-z、A-Z、0-9、_)
\w - - 任意字符
. - - 一次或多次
+ - - 零次或多次
* - - 零次或一次
? - - 或
|
示例:
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 pathBetter:
rm\s+-rfEscaping issues:
- YAML quoted strings: requires double backslashes
"pattern"\\s - YAML unquoted: works as-is
pattern: \s - 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 directory
Naming:
Gitignore: Add to
.claude/.claude/hookify.{descriptive-name}.local.md.claude/*.local.md.gitignoreGood names:
hookify.dangerous-rm.local.mdhookify.console-log.local.mdhookify.require-tests.local.mdhookify.sensitive-files.local.md
Bad names:
- (not descriptive)
hookify.rule1.local.md - (missing .local)
hookify.md - (missing hookify prefix)
danger.local.md
位置: 所有规则存储在目录下
命名:
Git忽略: 将添加到
.claude/.claude/hookify.{descriptive-name}.local.md.claude/*.local.md.gitignore规范命名示例:
hookify.dangerous-rm.local.mdhookify.console-log.local.mdhookify.require-tests.local.mdhookify.sensitive-files.local.md
不规范命名示例:
- (描述性不足)
hookify.rule1.local.md - (缺少.local后缀)
hookify.md - (缺少hookify前缀)
danger.local.md
Workflow
工作流程
Creating a Rule
创建规则
- Identify unwanted behavior
- Determine which tool is involved (Bash, Edit, etc.)
- Choose event type (bash, file, stop, etc.)
- Write regex pattern
- Create file in project root
.claude/hookify.{name}.local.md - Test immediately - rules are read dynamically on next tool use
- 识别需要监控的不良行为
- 确定涉及的工具(Bash、Edit等)
- 选择事件类型(bash、file、stop等)
- 编写正则表达式模式
- 在项目根目录创建文件
.claude/hookify.{name}.local.md - 立即测试 - 规则会在下次工具使用时动态加载
Refining a Rule
优化规则
- Edit the file
.local.md - Adjust pattern or message
- Test immediately - changes take effect on next tool use
- 编辑文件
.local.md - 调整模式或消息内容
- 立即测试 - 修改会在下次工具使用时生效
Disabling a Rule
禁用规则
Temporary: Set in frontmatter
Permanent: Delete the file
enabled: false.local.md临时禁用: 将前置元数据中的设为
永久禁用: 删除文件
enabledfalse.local.mdExamples
示例
See for complete examples:
${CLAUDE_PLUGIN_ROOT}/examples/- - Block dangerous rm commands
dangerous-rm.local.md - - Warn about console.log
console-log-warning.local.md - - Warn about editing .env files
sensitive-files-warning.local.md
可在目录下查看完整示例:
${CLAUDE_PLUGIN_ROOT}/examples/- - 拦截危险的rm命令
dangerous-rm.local.md - - 警告console.log的使用
console-log-warning.local.md - - 警告编辑.env文件的行为
sensitive-files-warning.local.md
Quick Reference
快速参考
Minimum viable rule:
markdown
---
name: my-rule
enabled: true
event: bash
pattern: dangerous_command
---
Warning message hereRule 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 messageEvent types:
- - Bash commands
bash - - File edits
file - - Completion checks
stop - - User input
prompt - - All events
all
Field options:
- Bash:
command - File: ,
file_path,new_text,old_textcontent - Prompt:
user_prompt
Operators:
- ,
regex_match,contains,equals,not_contains,starts_withends_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_textcontent - Prompt:
user_prompt
操作符:
- 、
regex_match、contains、equals、not_contains、starts_withends_with