← 回到學習日誌 Back to Journal

讓規則真的發生:Claude Code 與 Codex HooksMaking Rules Happen: Claude Code and Codex Hooks

真正有用的,不是把規則寫得越長越好,而是把規則放在對的時機。The useful lesson is not to write longer rules. It is to put a small rule at the right moment.

筆記本工作流、Hook 四個元件與安全實作情境的三段視覺
01 把規則放在正確時機Put the rule at the right moment 02 Event、Matcher、Handler、Stop ruleFour parts of a Hook 03 從窄範圍開始驗證Start narrow and verify
中文版 Chinese version

提醒不一定可靠

Agent 可能忘記先讀專案規則,也可能在改完檔案後忘記驗證;遇到危險的 Git 指令,單靠對話提醒也不一定可靠。Hook 的價值,就是把這些提醒變成固定時機、固定範圍、固定回應的工作規則。

一個 Hook 先回答四個問題

  1. Event:什麼時候觸發?例如 SessionStart、PreToolUse、PostToolUse 或 Stop。
  2. Matcher:哪些情況才執行?例如只匹配 Bash,或只在 Edit/Write 後處理。
  3. Handler:要檢查什麼,或補充什麼上下文?
  4. Stop rule:什麼時候放行、拒絕,或交給人判斷?

這四個元件讓自動化變得比較可預測。規則被觸發時就執行,不必期待模型剛好記得;Matcher 把範圍縮小,避免每個動作都被慢檢查拖住;Stop rule 則防止自動化變成無限循環。

從安全的窄範圍開始

我整理了 15 個可實作的情境,從啟動時的專案範圍校正、隱私提醒,到工具使用前的危險 Git 指令攔截,再到改檔後的最小驗證與公開內容品質檢查。最先值得嘗試的通常不是複雜的自動修復,而是兩種窄範圍 Hook:

Hook 不是讓 Agent 自動做更多事,而是讓它在不該忘記的地方更穩定地停下來、檢查,或把決定交還給人。

Claude Code 與 Codex 不能照抄設定

兩者的概念相近,但設定方式與支援能力不能直接照抄。實作時,我會先查各自的官方文件,再以本機、無外部網路的 command handler 開始;既有設定保留,新的 Hook 先用模擬輸入驗證,再由人審閱與信任。

從一個窄 Matcher 開始,通常比一次建立一整套規則更容易看出價值。

English version

Reminders Are Not Always Reliable

An agent may forget to read project instructions, skip a check after editing a file, or run a risky command even after a reminder. A Hook turns that reminder into a rule with a fixed event, scope, response, and stop condition.

Four Questions for Every Hook

  1. Event: What triggers it, such as SessionStart, PreToolUse, PostToolUse, or Stop?
  2. Matcher: Which cases should run, such as Bash or Edit/Write?
  3. Handler: What should it check or add to the context?
  4. Stop rule: When should it allow, deny, or return the decision to a person?

These four parts make automation more predictable. The rule runs when the event happens instead of relying on the model to remember. A narrow matcher prevents slow checks from running everywhere. A stop rule keeps automation from turning into an endless loop.

Start with a Safe, Narrow Boundary

I organized 15 practical situations, from startup context checks and privacy reminders to risky Git command blocking, post-edit verification, and a human gate before public changes. I would start with one narrow Hook, such as blocking destructive Bash commands or checking public content at the end of a task.

Claude Code and Codex Are Not Interchangeable

They share the same idea, but their settings and supported handlers are different. Read the current official documentation for each tool, keep the handler local, test it with sample input, and have a person review and trust the change.

Hooks are not mainly about making agents do more. They make agents stop, verify, and return important decisions to people at the right time.

Claude CodeCodexHooksAgent WorkflowSafety