AI Automation

Claude Code Hooks: tự động format, chặn lệnh nguy hiểm, ép chạy test — không cần nhắc

Tóm tắt

Hook là lệnh shell (hoặc HTTP, prompt…) chạy tại các sự kiện như PreToolUse, PostToolUse, Stop. Exit code 2 ở PreToolUse chặn tool call và gửi lý do cho Claude; ở Stop thì buộc Claude làm tiếp. Cấu hình trong .claude/settings.json, xem bằng /hooks.

Ví dụ 1: tự format sau khi sửa file

{
  "hooks": {
    "PostToolUse": [{
      "matcher": "Edit|Write",
      "hooks": [{ "type": "command", "command": "npx prettier --write \"$(jq -r .tool_input.file_path)\"" }]
    }]
  }
}

Ví dụ 2: chặn rm -rf

{
  "hooks": {
    "PreToolUse": [{
      "matcher": "Bash",
      "hooks": [{ "type": "command", "if": "Bash(rm *)",
                   "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/block-rm.sh" }]
    }]
  }
}

# block-rm.sh
echo "Không được xoá file bằng rm. Hãy hỏi người dùng." >&2
exit 2

Exit code quan trọng

Sự kiệnExit 2 nghĩa là
PreToolUseChặn tool, stderr thành lý do cho Claude
PostToolUseKhông chặn (tool đã chạy), stderr gửi cho Claude
StopKhông cho Claude dừng — ví dụ khi test còn đỏ
  • Exit 1 không chặn — dùng exit 2 cho luật bắt buộc.
  • Hook ở .claude/settings.json commit cùng repo để cả team dùng chung.
  • Tạm tắt tất cả: "disableAllHooks": true.