編寫 Hookify 規則
概述
Hookify 規則是以 YAML 前置元資料 (frontmatter) 為基礎的 Markdown 檔案,用於定義要監控的模式以及模式匹配時要顯示的訊息。規則儲存在 .claude/hookify.{規則名稱}.local.md 檔案中。
規則檔案格式
基本結構
---
name: rule-identifier
enabled: true
event: bash|file|stop|prompt|all
pattern: regex-pattern-here
---
當此規則觸發時要顯示給 Claude 的訊息。
可以包含 Markdown 格式、警告、建議等。
前置元資料欄位
| 欄位 | 必填 | 值 | 說明 |
|---|---|---|---|
| name | 是 | kebab-case 字串 | 唯一識別碼 (動詞優先:warn-, block-, require-*) |
| enabled | 是 | true/false | 在不刪除的情況下切換開關 |
| event | 是 | bash/file/stop/prompt/all | 觸發此規則的掛鉤事件 |
| action | 否 | warn/block | warn (預設) 顯示訊息;block 阻止操作 |
| pattern | 是* | regex 字串 | 要匹配的模式 (*或使用 conditions 進行複雜規則) |
進階格式 (多個條件)
---
name: warn-env-api-keys
enabled: true
event: file
conditions:
- field: file_path
operator: regex_match
pattern: \.env$
- field: new_text
operator: contains
pattern: API_KEY
---
你正在將 API 金鑰新增到 .env 檔案中。請確保此檔案已加入 .gitignore!
依事件分類的條件欄位:
- bash:
command - file:
file_path、new_text、old_text、content - prompt:
user_prompt
運算子: regex_match、contains、equals、not_contains、starts_with、ends_with
所有條件必須都符合才能觸發規則。
事件類型指南
bash 事件
匹配 Bash 指令模式:
- 危險指令:
rm\s+-rf、dd\s+if=、mkfs - 權限提升:
sudo\s+、su\s+ - 權限問題:
chmod\s+777
file 事件
匹配編輯/寫入/多重編輯操作:
- 除錯代碼:
console\.log\(、debugger - 安全風險:
eval\(、innerHTML\s*= - 敏感檔案:
\.env$、credentials、\.pem$
stop 事件
完成檢查與提醒。模式 .* 永遠匹配。
prompt 事件
匹配使用者提示內容以強制執行工作流程。
模式編寫技巧
正規表示式基礎
- 跳脫特殊字元:
.變\.、(變\( \s空白字元、\d數字、\w字詞字元+一個或多個、*零個或多個、?可選|OR 運算子
常見陷阱
- 過於寬泛:
log會匹配