Claude Code Stop Hook¶
概念概覽
觸發時機(最重要的誤解來源)¶
核心知識¶
觸發時機(最重要的誤解來源)¶
Stop hook 不是 session 完全關閉才觸發,而是**每次 Claude 停止輸出**(即每次問答結束)就觸發。
- 一個長 session 會觸發多次,且每次 hash 不同(對話內容在增長)
- 純 hash-based 去重機制無法防止同 session 重複觸發
- 實際案例:一個 session 觸發 14 次,產生 14 篇重複文檔
Windows vs WSL 環境差異¶
兩套環境的設定**完全獨立**,互不影響:
- WSL 內:
~/.claude/settings.json,hook command 用 bash 語法 - Windows 端:
%USERPROFILE%\.claude\settings.json,hook command 用 PowerShell/cmd 語法
Windows Claude Code 執行的是 Windows 原生 shell,**不能**呼叫 /c/Windows/system32/wsl.exe 或任何 Linux binary,會報 cannot execute binary file。
Bash Background 執行限制¶
# 失敗:source 進來的函數不會帶入 subshell
nohup bash -c 'source utils.sh && ensure_spool_exists && ...' &
# 正確:獨立 script,不依賴 source
nohup bash /path/to/process-and-publish.sh &
背景執行時,所有需要的邏輯必須抽成獨立 script,避免依賴 source 載入的函數。
經驗教訓¶
-
Stop hook 設計必須假設「同一 session 會多次觸發」,而非「每個 session 只觸發一次」
-
Windows 與 WSL 各自有獨立的 Claude Code 設定,修改一個不影響另一個
-
Hook 的 bash background 執行(nohup &)不繼承 sourced functions,須用獨立 script
常見陷阱¶
-
誤以為 Stop hook 在 session 關閉時才觸發 → 導致重複文檔
-
在 Windows Claude Code 中呼叫 wsl.exe → cannot execute binary file
-
nohup bash -c 'source ...' 中使用 sourced functions → command not found
-
tee -a 搭配 >> 雙重導向 → 每行 log 寫兩次
最佳實踐¶
-
Stop hook command 應為獨立可執行 script,不依賴外部 source
-
Windows 端與 WSL 端分別維護各自的 settings.json
-
Hook 系統設計需以 session_id 而非 hash 作為去重主鍵,因為同 session hash 會變動
相關概念¶
- claude-code-hooks-configuration----dangling-------dangling---
- Semi-Brain Knowledge Management System
- Semi-Brain Session Deduplication
來源 Sessions¶
| 日期 | Session | 貢獻摘要 |
|---|---|---|
| 2026-03-18 | b0b2a293-9dc3-4b1b-a41f-7ab423a8fd45 | 釐清 Stop Hook 的實際觸發時機(每次問答結束,非 session 關閉),並完整記錄 Windows/WSL 雙環境的配置差異與除錯實錄 |