Files
claude-howto/vi/06-hooks
Thiên Toán a70777e9bc Add Vietnamese (Tiếng Việt) Localization (#42)
* feat(i18n): add Vietnamese localization infrastructure

Add comprehensive infrastructure for Vietnamese translation of the
claude-howto documentation:

Features:
- Parallel vi/ directory structure for Vietnamese content
- Modified build_epub.py with --lang flag for Vietnamese EPUB
- Vietnamese-specific pre-commit hooks for quality checks
- Translation support files (glossary, style guide, queue tracker)
- sync_translations.py script to detect outdated translations

Infrastructure:
- vi/ directory with all 10 module subdirectories
- TRANSLATION_NOTES.md: comprehensive glossary and style guide
- TRANSLATION_QUEUE.md: progress tracking for 66+ files
- vi/README.md: Vietnamese landing page

EPUB Build:
- Added --lang CLI flag (en/vi) to build_epub.py
- Language-specific metadata (title, subtitle)
- Automatic root path adjustment for vi/ directory
- Dynamic output filename (claude-howto-guide-vi.epub)

Quality Assurance:
- Vietnamese markdown linting
- Vietnamese cross-reference checking
- Vietnamese Mermaid syntax validation
- Vietnamese link checking
- Vietnamese EPUB build validation

Ready for translation work to begin.

* feat(vi): translate INDEX.md to Vietnamese

Complete Vietnamese translation of INDEX.md - the comprehensive
index of all example files in the repository.

Translation follows vi/TRANSLATION_NOTES.md guidelines:
- Technical terms kept per glossary (slash command → "lệnh slash")
- File paths and code blocks preserved in English
- Table structure and formatting maintained
- All 882 lines translated

Content includes:
- Complete file tree (10 modules, 100+ files)
- Feature coverage matrix
- Quick start guides by use case
- Learning path progression
- Search by keyword sections

Progress: 1/5 core documents completed

* feat(vi): translate CATALOG.md to Vietnamese

Complete Vietnamese translation of CATALOG.md - the quick reference
guide to all Claude Code features.

Translation follows vi/TRANSLATION_NOTES.md guidelines:
- Technical terms kept per glossary (slash command → "lệnh slash")
- All command names preserved (/help, /optimize, etc.)
- Code blocks, JSON examples, and bash commands unchanged
- All tables and formatting maintained
- 517 lines translated with complete feature coverage

Content includes:
- Summary statistics (99 built-in + 43 examples = 117 total)
- Complete built-in commands reference (55+ commands)
- Custom commands examples (8 commands)
- Permission modes (6 modes)
- Subagents (6 built-in + 10 custom)
- Skills (5 bundled + 4 custom)
- Plugins (3 complete plugins)
- MCP servers (1 built-in + 8 common servers)
- Hooks (25 events + 7 example hooks)
- Memory files (7 types)
- New features (March 2026) - 17 new features
- Installation priority guide
- Complete one-command installation

Progress: 2/5 core documents completed

* docs(vi): translate learning roadmap to Vietnamese

- Add complete Vietnamese translation of LEARNING-ROADMAP.md (747 lines)
- Include self-assessment quiz for level determination
- Translate three learning levels: Beginner, Intermediate, Advanced
- Translate all milestones (1A, 1B, 2A, 2B, 3A, 3B) with hands-on exercises
- Preserve Mermaid diagram for learning path visualization
- Maintain progress tracking checklists and learning tips

* docs(vi): translate quick reference guide to Vietnamese

- Add complete Vietnamese translation of QUICK_REFERENCE.md (507 lines)
- Include installation quick commands for all features
- Translate feature cheat sheet with usage examples
- Translate common use cases (code review, documentation, DevOps, etc.)
- Preserve all code snippets, commands, and file paths in English
- Maintain file locations reference diagram
- Include learning path and new features (March 2026) sections
- Keep tips & tricks, feature matrix, and checklist intact

* docs(vi): translate module 01 - slash commands to Vietnamese

- Add complete Vietnamese translation of 01-slash-commands/README.md (553 lines)
- Translate slash commands overview and architecture
- Include 55+ built-in commands reference table with Vietnamese descriptions
- Translate bundled skills section (5 skills)
- Document custom commands (now skills) migration path
- Include frontmatter reference, arguments, and dynamic context sections
- Preserve all command names, code examples, and Mermaid diagrams
- Translate 8 available commands in folder with usage examples
- Include installation, troubleshooting, and best practices sections

* docs(vi): update translation queue progress - Module 01 README done

- Mark 01-slash-commands/README.md as completed (2026-04-02)
- Update Module 01 progress: 1/9 files (11%)
- Update overall progress: 6/66 files (9%)
- Update Priority 2 progress: 1/31 files (3%)
- Add recent completion note to queue header

* docs(vi): translate slash command - commit to Vietnamese

- Translate commit.md slash command to Vietnamese
- Keep all git commands and technical syntax intact
- Translate instructions and descriptions
- Maintain conventional commits format documentation

* docs(vi): translate slash command - doc-refactor to Vietnamese

- Translate doc-refactor.md slash command to Vietnamese
- Keep all technical terms and file paths intact
- Translate documentation refactoring instructions
- Maintain structure and numbering

* docs(vi): translate slash command - generate-api-docs to Vietnamese

- Translate generate-api-docs.md slash command to Vietnamese
- Keep all technical terms and file paths intact
- Translate API documentation generation instructions
- Maintain output format specifications

* docs(vi): translate slash command - optimize to Vietnamese

- Translate optimize.md slash command to Vietnamese
- Keep all technical terms and code concepts intact
- Translate code optimization instructions
- Maintain issue priority and response format

* docs(vi): translate slash command - pr to Vietnamese

- Translate pr.md slash command to Vietnamese
- Keep all commands and technical syntax intact
- Translate PR preparation checklist instructions
- Maintain conventional commits format documentation

* docs(vi): translate slash command - push-all to Vietnamese

- Translate push-all.md slash command to Vietnamese (153 lines)
- Keep all git commands and technical syntax intact
- Translate comprehensive workflow with safety checks
- Maintain API key validation patterns and error handling
- Preserve when to use/avoid sections and alternatives

* docs(vi): translate slash command - setup-ci-cd to Vietnamese

- Translate setup-ci-cd.md slash command to Vietnamese
- Keep all tool names and technical terms intact
- Translate CI/CD pipeline implementation instructions
- Maintain pre-commit hooks and GitHub Actions sections

* docs(vi): translate slash command - unit-test-expand to Vietnamese

- Translate unit-test-expand.md slash command to Vietnamese
- Keep all framework names and technical terms intact
- Translate test coverage expansion instructions
- Maintain testing frameworks and scenario sections

* docs(vi): update translation queue - Module 01 complete (100%)

- Mark all 9 Module 01 files as completed (2026-04-02)
- Update Module 01 progress: 9/9 files (100%) 
- Update overall progress: 14/66 files (21%)
- Update Priority 2 progress: 9/31 files (29%)
- Update header with Module 01 completion milestone

Module 01: Slash Commands - All files translated:
 README.md (overview, built-in commands, skills)
 commit.md (git commit with context)
 doc-refactor.md (documentation restructuring)
 generate-api-docs.md (API documentation generator)
 optimize.md (code optimization analysis)
 pr.md (pull request preparation)
 push-all.md (stage, commit, push with safety)
 setup-ci-cd.md (CI/CD pipeline implementation)
 unit-test-expand.md (test coverage expansion)

* docs(vi): translate module 02 - memory guide to Vietnamese

- Add complete Vietnamese translation of 02-memory/README.md (1162 lines)
- Translate memory system overview and architecture
- Include quick reference for memory commands (/init, /memory, #)
- Document complete memory hierarchy (8 levels with precedence)
- Translate auto memory section with architecture diagrams
- Include practical examples (project, directory-specific, personal memory)
- Add best practices, installation instructions, and troubleshooting
- Preserve all code examples, file paths, and technical terms
- Maintain Mermaid diagrams and tables

* docs(vi): translate example project CLAUDE.md to Vietnamese

- Translate project-CLAUDE.md example memory file
- Keep all technical terms, commands, and code style intact
- Translate descriptions and explanations
- Maintain project configuration structure

* docs(vi): translate example personal CLAUDE.md to Vietnamese

- Translate personal-CLAUDE.md example memory file
- Keep all technical terms, tools, and preferences intact
- Translate descriptions and explanations
- Maintain personal preferences structure

* docs(vi): translate example directory-specific CLAUDE.md to Vietnamese

- Translate directory-api-CLAUDE.md example memory file
- Keep all technical terms, API standards, and code examples intact
- Translate descriptions and explanations
- Maintain API module standards structure

* docs(vi): update translation queue - Module 02 complete (100%)

- Mark all 4 Module 02 files as completed (2026-04-02)
- Update Module 02 progress: 4/4 files (100%) 
- Update overall progress: 18/66 files (27%)
- Update Priority 2 progress: 13/31 files (42%)
- Update header with Module 02 completion milestone

Module 02: Memory - All files translated:
 README.md (1162 lines - comprehensive memory guide)
 project-CLAUDE.md (example project memory)
 personal-CLAUDE.md (example personal preferences)
 directory-api-CLAUDE.md (example directory-specific rules)

* docs(vi): translate module 03 - skills guide to Vietnamese

- Add complete Vietnamese translation of 03-skills/README.md (805 lines)
- Translate Agent Skills overview and architecture
- Include progressive disclosure loading mechanism (3 levels)
- Document skill types, locations, and automatic discovery
- Translate skill creation process and SKILL.md format
- Include required and optional frontmatter fields
- Document skill content types (reference vs task)
- Translate controlling skill invocation and string substitutions
- Include dynamic context injection with shell commands
- Document running skills in subagents with context: fork
- Translate 6 practical examples with directory structures
- Add supporting files, management, and best practices sections
- Preserve all code examples, YAML frontmatter, and Mermaid diagrams
- Maintain tables, troubleshooting guides, and security considerations

* docs(vi): translate skill - blog-draft to Vietnamese

- Translate blog-draft/SKILL.md to Vietnamese (275 lines)
- Keep all workflow steps and technical structure intact
- Translate instructions and descriptions
- Maintain version tracking and file structure
- Preserve all markdown formatting and code examples

* docs(vi): translate skill - brand-voice to Vietnamese

- Translate brand-voice/SKILL.md to Vietnamese (73 lines)
- Keep brand identity, tone, and vocabulary intact
- Translate writing guidelines and examples
- Maintain preferred/avoided terms sections
- Preserve good/bad examples with explanations

* docs(vi): translate skill - claude-md to Vietnamese

- Translate claude-md/SKILL.md to Vietnamese (213 lines)
- Keep all golden rules and core principles intact
- Translate execution flow and content strategy
- Maintain WHAT/WHY/HOW structure
- Preserve quality constraints and validation checklist
- Keep anti-patterns and output format sections

* docs(vi): translate skill - code-review to Vietnamese

- Translate code-review/SKILL.md to Vietnamese (71 lines)
- Keep all review categories and template intact
- Translate security, performance, quality, maintainability sections
- Maintain review template structure
- Preserve version history

* docs(vi): translate skill - refactor to Vietnamese

- Translate refactor/SKILL.md to Vietnamese (427 lines)
- Keep all Martin Fowler refactoring methodology intact
- Translate 6-phase workflow with detailed steps
- Maintain core principles and safety rules
- Preserve code smell catalog and refactoring techniques
- Keep quick start example with before/after code
- Maintain version history and references sections

* docs(vi): update translation queue - Module 03 complete (100%)

- Mark all 6 Module 03 files as completed (2026-04-02)
- Update Module 03 progress: 6/6 files (100%) 
- Update overall progress: 24/66 files (36%)
- Update Priority 2 progress: 19/31 files (61%)
- Update header with Module 03 completion milestone

Module 03: Skills - All files translated:
 README.md (805 lines - comprehensive skills guide)
 blog-draft/SKILL.md (275 lines - blog post creation workflow)
 brand-voice/SKILL.md (73 lines - brand voice consistency)
 claude-md/SKILL.md (213 lines - CLAUDE.md best practices)
 code-review/SKILL.md (71 lines - comprehensive code review)
 refactor/SKILL.md (427 lines - Fowler refactoring methodology)

* docs(vi): translate Module 04 Subagents README

Complete Vietnamese translation of subagents reference guide:
- Configuration and built-in subagents (general-purpose, Plan, Explore, Bash, statusline-setup, Claude Code Guide)
- Agent management with /agents command
- Automatic delegation vs explicit invocation
- Resumable agents and chaining
- Persistent memory across agent sessions
- Background subagents for parallel work
- Worktree isolation for safe experimentation
- Agent Teams (experimental feature)
- Best practices and usage patterns

* docs(vi): complete Module 04 Subagents translation

Translate all 6 subagent example definitions:
- code-reviewer.md: Expert code review specialist
- debugger.md: Root cause analysis and debugging
- documentation-writer.md: Technical documentation creation
- implementation-agent.md: Full-stack feature implementation
- secure-reviewer.md: Security-focused code review
- test-engineer.md: Comprehensive test coverage

Update translation queue progress:
- Module 04: 7/7 files (100%) 
- Overall: 31/66 files (47%)
- Next: Module 05 (MCP)

* docs(vi): complete Module 05 MCP translation

Translate comprehensive MCP (Model Context Protocol) guide:
- Overview and architecture diagrams
- Installation methods (HTTP, Stdio, SSE, WebSocket)
- OAuth 2.0 authentication support
- MCP tool search and dynamic updates
- Elicitation and prompt slash commands
- Configuration management (local, project, user scopes)
- Practical examples (GitHub, Database, Filesystem, Slack MCPs)
- MCP vs Memory decision matrix
- Code execution approach for solving context bloat
- MCPorter runtime reference
- Security best practices and troubleshooting

Translate 4 MCP configuration JSON examples:
- filesystem-mcp.json: File operations
- github-mcp.json: GitHub integration
- database-mcp.json: SQL queries
- multi-mcp.json: Multiple servers configuration

Update translation queue progress:
- Module 05: 5/5 files (100%) 
- Overall: 36/66 files (55%)
- Next: Module 06 (Hooks)

* docs(vi): complete Module 06 Hooks translation

Translate comprehensive Hooks guide:
- Overview and architecture
- Configuration structure (user, project, local scopes)
- Four hook types: command, HTTP, prompt, agent
- 25 hook events with matcher patterns
- Component-scoped hooks and subagent frontmatter
- JSON input/output format and exit codes
- Environment variables and best practices
- Security considerations and debugging
- Installation instructions

Copy 9 hook example files (code, no translation needed):
- format-code.sh: Auto-format code after write/edit
- log-bash.sh: Bash command logging
- notify-team.sh: Team notifications
- pre-commit.sh: Pre-commit validation
- security-scan.sh: Security scanning
- validate-prompt.sh: Prompt validation
- context-tracker.py: Token usage tracking
- context-tracker-tiktoken.py: Accurate token counting

Update translation queue progress:
- Module 06: 9/9 files (100%) 
- Overall: 45/67 files (67%)
- Next: Module 07 (Plugins)

* docs(vi): complete Module 07 Plugins translation

Translate comprehensive Plugins guide:
- Overview and architecture diagrams
- Plugin loading process and lifecycle
- Plugin types (Official, Community, Organization, Personal)
- Plugin definition structure and manifest
- Plugin structure example with all directories
- LSP server configuration and examples
- Plugin options (v2.1.83+) with userConfig
- Persistent plugin data via CLAUDE_PLUGIN_DATA
- Inline plugins via settings (v2.1.80+)
- Standalone vs Plugin approach comparison
- Practical examples (PR Review, DevOps, Documentation plugins)
- Plugin marketplace and distribution
- Marketplace configuration and definition schema
- Plugin source types and distribution methods
- Plugin CLI commands and installation methods
- Plugin features comparison table
- Testing, hot-reload, and managed settings
- Plugin security restrictions
- Publishing workflow and best practices
- Complete troubleshooting guide

Copy all plugin subdirectories (code, no translation needed):
- devops-automation/: Deployment workflows, incident management
- documentation/: API docs, README generation, templates
- pr-review/: Pull request review automation

Update translation queue progress:
- Module 07: 10+/10+ files (100%) 
- Overall: 55+/67 files (82%)
- Next: Module 08-10 (Checkpoints, Advanced Features, CLI)

* docs(vi): complete Modules 08-10 translation

Module 08: Checkpoints and Rewind (2 files)
- Overview and architecture
- Access methods (keyboard shortcut, slash command)
- Five rewind options (restore code+conversation, conversation, code, summarize, cancel)
- Automatic checkpoints and retention policies
- Use cases and practical examples
- Integration with git and best practices

Module 09: Advanced Features (3 files)
- Planning Mode: Two-phase implementation approach
- Extended Thinking: Deep reasoning for complex problems
- Auto Mode: Background safety classifier
- Background Tasks, Scheduled Tasks
- Permission Modes (default, acceptEdits, plan, auto, dontAsk, bypassPermissions)
- Print Mode, Session Management
- Voice Dictation, Channels, Remote Control
- Web Sessions, Desktop App, Task List
- Git Worktrees, Sandboxing, Managed Settings

Module 10: CLI Reference (1 file)
- CLI commands reference
- Core flags and options
- Interactive vs Print Mode
- Model selection and configuration
- System prompt customization
- Tool & permission management
- Output formats and scripting

Update translation queue progress:
- Modules 08-10: 6/6 files (100%) 
- All Modules 01-10: 61+/61+ files (100%) 
- Overall: 61+/67 files (91%)
- Remaining: Supporting docs (6 files)

* docs(vi): complete supporting documentation translation

Translate all 5 supporting documents:
- CONTRIBUTING.md: Contribution guidelines
- SECURITY.md: Security policy and vulnerability reporting
- CODE_OF_CONDUCT.md: Community standards and harassment policy
- STYLE_GUIDE.md: Documentation formatting conventions
- CHANGELOG.md: Version history (v2.2.0, v2.1.1, v2.1.0, v2.0.0)

Update translation queue to 100% completion:
- All Modules 01-10: 61+ files (100%) 
- Supporting Docs: 5/5 files (100%) 
- Overall: 67+/67 files (100%) 
- Status: HOÀN THÀNH 

* fix(vi): fix mermaid syntax and broken cross-references in Vietnamese translation

Fix invalid `#` comment in mermaid block (use `%%` instead) and update
cross-reference script to support Unicode/Vietnamese diacritics in anchor
generation. Fix broken anchor links across vi/ documentation files.

* fix(vi): remove inline mermaid comment causing parse error

Inline %% comments on node definition lines are not supported by the
mermaid parser. The surrounding HTML comment already explains this is
an incorrect example.
2026-04-06 21:34:18 +02:00
..

Claude How To

Hooks / Hooks

Hooks là các script tự động thực thi để phản hồi các sự kiện cụ thể trong các phiên Claude Code. Chúng cho phép tự động hóa, xác thực, quản lý quyền, và workflows tùy chỉnh.

Tổng Quan / Overview

Hooks là các hành động tự động (lệnh shell, HTTP webhooks, prompts LLM, hoặc đánh giá subagent) thực thi tự động khi các sự kiện cụ thể xảy ra trong Claude Code. Chúng nhận đầu vào JSON và giao tiếp kết quả qua exit codes và đầu ra JSON.

Tính năng chính:

  • Tự động hóa dựa trên sự kiện
  • Đầu vào/ra dựa trên JSON
  • Hỗ trợ cho các loại hook command, prompt, HTTP, và agent
  • Khớp mẫu cho các hooks cụ thể theo công cụ

Cấu Hình / Configuration

Hooks được cấu hình trong các file settings với cấu trúc cụ thể:

  • ~/.claude/settings.json - Cài đặt người dùng (tất cả projects)
  • .claude/settings.json - Cài đặt project (có thể chia sẻ, được commit)
  • .claude/settings.local.json - Cài đặt project local (không được commit)
  • Managed policy - Cài đặt toàn tổ chức
  • Plugin hooks/hooks.json - Hooks scoped plugin
  • Skill/Agent frontmatter - Hooks vòng đời component

Cấu Trúc Cấu Hình Cơ Bản / Basic Configuration Structure

{
  "hooks": {
    "EventName": [
      {
        "matcher": "ToolPattern",
        "hooks": [
          {
            "type": "command",
            "command": "your-command-here",
            "timeout": 60
          }
        ]
      }
    ]
  }
}

Các trường chính:

Trường Mô Tả Ví Dụ
matcher Mẫu để khớp tên công cụ (phân biệt hoa/thường) "Write", "Edit|Write", "*"
hooks Mảng định nghĩa hook [{ "type": "command", ... }]
type Loại hook: "command" (bash), "prompt" (LLM), "http" (webhook), hoặc "agent" (subagent) "command"
command Lệnh shell để thực thi "$CLAUDE_PROJECT_DIR/.claude/hooks/format.sh"
timeout Timeout tùy chọn tính bằng giây (mặc định 60) 30
once Nếu true, chạy hook chỉ một lần mỗi phiên true

Các Mẫu Matcher / Matcher Patterns

Mẫu Mô Tả Ví Dụ
Chuỗi chính xác Khớp công cụ cụ thể "Write"
Mẫu regex Khớp nhiều công cụ "Edit|Write"
Wildcard Khớp tất cả công cụ "*" hoặc ""
Công cụ MCP Mẫu server và công cụ "mcp__memory__.*"

Các Loại Hook / Hook Types

Claude Code hỗ trợ bốn loại hook:

Command Hooks / Hooks Lệnh

Loại hook mặc định. Thực thi một lệnh shell và giao tiếp qua JSON stdin/stdout và exit codes.

{
  "type": "command",
  "command": "python3 \"$CLAUDE_PROJECT_DIR/.claude/hooks/validate.py\"",
  "timeout": 60
}

HTTP Hooks / Hooks HTTP

Thêm vào v2.1.63.

Các endpoints webhook từ xa nhận cùng đầu vào JSON như command hooks. HTTP hooks POST JSON đến URL và nhận phản hồi JSON. HTTP hooks được định tuyến qua sandbox khi sandboxing được bật. Nội suy biến môi trường trong URLs yêu cầu danh sách allowedEnvVars rõ ràng để bảo mật.

{
  "hooks": {
    "PostToolUse": [{
      "type": "http",
      "url": "https://my-webhook.example.com/hook",
      "matcher": "Write"
    }]
  }
}

Các thuộc tính chính:

  • "type": "http" -- xác định đây là một HTTP hook
  • "url" -- URL endpoint webhook
  • Được định tuyến qua sandbox khi sandbox được bật
  • Yêu cầu danh sách allowedEnvVars rõ ràng cho bất kỳ nội suy biến môi trường nào trong URL

Prompt Hooks / Hooks Prompt

Prompts được đánh giá bởi LLM nơi nội dung hook là một prompt mà Claude đánh giá. Chủ yếu được sử dụng với các sự kiện StopSubagentStop để kiểm tra hoàn thành tác vụ thông minh.

{
  "type": "prompt",
  "prompt": "Evaluate if Claude completed all requested tasks.",
  "timeout": 30
}

LLM đánh giá prompt và trả về một quyết định có cấu trúc (xem Prompt-Based Hooks để biết chi tiết).

Agent Hooks / Hooks Agent

Hooks xác thực dựa trên subagent mà spawn một agent chuyên dụng để đánh giá điều kiện hoặc thực hiện các kiểm tra phức tạp. Khác với prompt hooks (đánh giá LLM một turn), agent hooks có thể sử dụng các công cụ và thực hiện suy luận đa bước.

{
  "type": "agent",
  "prompt": "Verify the code changes follow our architecture guidelines. Check the relevant design docs and compare.",
  "timeout": 120
}

Các thuộc tính chính:

  • "type": "agent" -- xác định đây là một agent hook
  • "prompt" -- mô tả nhiệm vụ cho subagent
  • Agent có thể sử dụng các công cụ (Read, Grep, Bash, v.v.) để thực hiện đánh giá của nó
  • Trả về một quyết định có cấu trúc tương tự như prompt hooks

Các Sự Kiện Hook / Hook Events

Claude Code hỗ trợ 25 sự kiện hook:

Sự Kiện Khi Được Kích Hoạt Matcher Input Có Chặn Sử Dụng Phổ Biến
SessionStart Phiên bắt đầu/tiếp tục/xóa/dồn startup/resume/clear/compact Không Thiết lập môi trường
InstructionsLoaded Sau khi CLAUDE.md hoặc file rules được tải (none) Không Sửa đổi/bộ lọc hướng dẫn
UserPromptSubmit Người dùng gửi prompt (none) Xác thực prompts
PreToolUse Trước khi thực thi công cụ Tên công cụ Có (allow/deny/ask) Xác thực, sửa đổi đầu vào
PermissionRequest Hộp thoại quyền được hiển thị Tên công cụ Tự động phê duyệt/từ chối
PostToolUse Sau khi công cụ thành công Tên công cụ Không Thêm ngữ cảnh, feedback
PostToolUseFailure Thực thi công cụ thất bại Tên công cụ Không Xử lý lỗi, logging
Notification Thông báo được gửi Loại thông báo Không Thông báo tùy chỉnh
SubagentStart Subagent được spawn Tên loại agent Không Thiết lập subagent
SubagentStop Subagent hoàn thành Tên loại agent Xác thực subagent
Stop Claude hoàn thành phản hồi (none) Kiểm tra hoàn thành tác vụ
StopFailure Lỗi API kết thúc turn (none) Không Phục hồi lỗi, logging
TeammateIdle Đồng nghiệp nhóm agent rảnh (none) Phối hợp đồng nghiệp
TaskCompleted Nhiệm vụ được đánh dấu hoàn thành (none) Hành động sau tác vụ
TaskCreated Nhiệm vụ được tạo qua TaskCreate (none) Không Theo dõi nhiệm vụ, logging
ConfigChange File config thay đổi (none) Có (trừ policy) Phản hồi cập nhật config
CwdChanged Thư mục làm việc thay đổi (none) Không Thiết lập cụ thể thư mục
FileChanged File được watch thay đổi (none) Không Giám sát file, rebuild
PreCompact Trước khi dồn ngữ cảnh manual/auto Không Hành động pre-dồn
PostCompact Sau khi dồn hoàn thành (none) Không Hành động post-dồn
WorktreeCreate Worktree đang được tạo (none) Có (trả về path) Khởi tạo worktree
WorktreeRemove Worktree đang được xóa (none) Không Dọn dẹp worktree
Elicitation MCP server yêu cầu đầu vào người dùng (none) Xác thực đầu vào
ElicitationResult Người dùng phản hồi elicitation (none) Xử lý phản hồi
SessionEnd Phiên kết thúc (none) Không Dọn dẹp, logging cuối

PreToolUse

Chạy sau khi Claude tạo tham số công cụ và trước khi xử lý. Sử dụng điều này để xác thực hoặc sửa đổi đầu vào công cụ.

Cấu Hình:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/validate-bash.py"
          }
        ]
      }
    ]
  }
}

Các matcher phổ biến: Task, Bash, Glob, Grep, Read, Edit, Write, WebFetch, WebSearch

Điều khiển đầu ra:

  • permissionDecision: "allow", "deny", hoặc "ask"
  • permissionDecisionReason: Giải thích cho quyết định
  • updatedInput: Các tham số đầu vào công cụ đã sửa đổi

PostToolUse

Chạy ngay sau khi công cụ hoàn thành. Sử dụng để xác minh, logging, hoặc cung cấp ngữ cảnh trở lại Claude.

Cấu Hình:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/security-scan.py"
          }
        ]
      }
    ]
  }
}

Điều khiển đầu ra:

  • Quyết định "block" nhắc Claude với feedback
  • additionalContext: Ngữ cảnh được thêm vào cho Claude

UserPromptSubmit

Chạy khi người dùng gửi prompt, trước khi Claude xử lý nó.

Cấu Hình:

{
  "hooks": {
    "UserPromptSubmit": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/validate-prompt.py"
          }
        ]
      }
    ]
  }
}

Điều khiển đầu ra:

  • decision: "block" để ngăn chặn xử lý
  • reason: Giải thích nếu bị chặn
  • additionalContext: Ngữ cảnh được thêm vào prompt

Stop và SubagentStop / Stop and SubagentStop

Chạy khi Claude hoàn thành phản hồi (Stop) hoặc một subagent hoàn thành (SubagentStop). Hỗ trợ đánh giá dựa trên prompt để kiểm tra hoàn thành tác vụ thông minh.

Trường đầu vào thêm: Cả hai hooks StopSubagentStop nhận một trường last_assistant_message trong đầu vào JSON của chúng, chứa thông báo cuối cùng từ Claude hoặc subagent trước khi dừng. Điều này hữu ích để đánh giá hoàn thành tác vụ.

Cấu Hình:

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "prompt",
            "prompt": "Evaluate if Claude completed all requested tasks.",
            "timeout": 30
          }
        ]
      }
    ]
  }
}

SubagentStart

Chạy khi một subagent bắt đầu thực thi. Matcher input là tên loại agent, cho phép hooks nhắm đến các loại subagent cụ thể.

Cấu Hình:

{
  "hooks": {
    "SubagentStart": [
      {
        "matcher": "code-review",
        "hooks": [
          {
            "type": "command",
            "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/subagent-init.sh"
          }
        ]
      }
    ]
  }
}

SessionStart

Chạy khi phiên bắt đầu hoặc tiếp tục. Có thể persist các biến môi trường.

Matchers: startup, resume, clear, compact

Tính năng đặc biệt: Sử dụng CLAUDE_ENV_FILE để persist các biến môi trường (cũng có sẵn trong các hooks CwdChangedFileChanged):

#!/bin/bash
if [ -n "$CLAUDE_ENV_FILE" ]; then
  echo 'export NODE_ENV=development' >> "$CLAUDE_ENV_FILE"
fi
exit 0

SessionEnd

Chạy khi phiên kết thúc để thực hiện dọn dẹp hoặc logging cuối cùng. Không thể chấm dứt sự kết thúc.

Các giá trị trường reason:

  • clear - Người dùng xóa phiên
  • logout - Người dùng đăng xuất
  • prompt_input_exit - Người dùng thoát qua đầu vào prompt
  • other - Lý do khác

Cấu Hình:

{
  "hooks": {
    "SessionEnd": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/session-cleanup.sh\""
          }
        ]
      }
    ]
  }
}

Sự Kiện Notification / Notification Event

Các matcher được cập nhật cho các sự kiện thông báo:

  • permission_prompt - Thông báo yêu cầu quyền
  • idle_prompt - Thông báo trạng thái rảnh
  • auth_success - Xác thực thành công
  • elicitation_dialog - Hộp thoại được hiển thị cho người dùng

Hooks Scoped Component / Component-Scoped Hooks

Hooks có thể được gắn vào các component cụ thể (skills, agents, commands) trong frontmatter của chúng:

Trong SKILL.md, agent.md, hoặc command.md:

---
name: secure-operations
description: Perform operations with security checks
hooks:
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: "./scripts/check.sh"
          once: true  # Chỉ chạy một lần mỗi phiên
---

Các sự kiện được hỗ trợ cho component hooks: PreToolUse, PostToolUse, Stop

Điều này cho phép định nghĩa hooks trực tiếp trong component sử dụng chúng, giữ code liên quan cùng nhau.

Hooks trong Frontmatter Subagent / Hooks in Subagent Frontmatter

Khi một hook Stop được định nghĩa trong frontmatter của một subagent, nó tự động được chuyển đổi thành một hook SubagentStop scoped cho subagent đó. Điều này đảm bảo rằng hook stop chỉ kích hoạt khi subagent cụ thể đó hoàn thành, thay vì khi phiên chính dừng.

---
name: code-review-agent
description: Automated code review subagent
hooks:
  Stop:
    - hooks:
        - type: prompt
          prompt: "Verify the code review is thorough and complete."
  # Hook Stop ở trên tự chuyển thành SubagentStop cho subagent này
---

Sự Kiện PermissionRequest / PermissionRequest Event

Xử lý các yêu cầu quyền với định dạng đầu ra tùy chỉnh:

{
  "hookSpecificOutput": {
    "hookEventName": "PermissionRequest",
    "decision": {
      "behavior": "allow|deny",
      "updatedInput": {},
      "message": "Custom message",
      "interrupt": false
    }
  }
}

Đầu Vào Và Đầu Ra Hook / Hook Input and Output

Đầu Vào JSON (qua stdin) / JSON Input (via stdin)

Tất cả hooks nhận đầu vào JSON qua stdin:

{
  "session_id": "abc123",
  "transcript_path": "/path/to/transcript.jsonl",
  "cwd": "/current/working/directory",
  "permission_mode": "default",
  "hook_event_name": "PreToolUse",
  "tool_name": "Write",
  "tool_input": {
    "file_path": "/path/to/file.js",
    "content": "..."
  },
  "tool_use_id": "toolu_01ABC123...",
  "agent_id": "agent-abc123",
  "agent_type": "main",
  "worktree": "/path/to/worktree"
}

Các trường phổ biến:

Trường Mô Tả
session_id Định danh phiên duy nhất
transcript_path Đường dẫn đến file transcript hội thoại
cwd Thư mục làm việc hiện tại
hook_event_name Tên của sự kiện kích hoạt hook
agent_id Định danh của agent chạy hook này
agent_type Loại agent ("main", tên loại subagent, v.v.)
worktree Đường dẫn đến git worktree, nếu agent chạy trong một

Exit Codes

Exit Code Ý Nghĩa Hành Vi
0 Thành công Tiếp tục, phân tích cú pháp JSON stdout
2 Lỗi chặn Chặn thao tác, stderr được hiển thị như lỗi
Khác Lỗi không chặn Tiếp tục, stderr được hiển thị trong chế độ verbose

Đầu Ra JSON (stdout, exit code 0) / JSON Output (stdout, exit code 0)

{
  "continue": true,
  "stopReason": "Optional message if stopping",
  "suppressOutput": false,
  "systemMessage": "Optional warning message",
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "allow",
    "permissionDecisionReason": "File is in allowed directory",
    "updatedInput": {
      "file_path": "/modified/path.js"
    }
  }
}

Các Biến Môi Trường / Environment Variables

Biến Khả Dụng Mô Tả
CLAUDE_PROJECT_DIR Tất cả hooks Đường dẫn tuyệt đối đến thư mục gốc project
CLAUDE_ENV_FILE SessionStart, CwdChanged, FileChanged Đường dẫn file để persist env vars
CLAUDE_CODE_REMOTE Tất cả hooks "true" nếu chạy trong môi trường từ xa
${CLAUDE_PLUGIN_ROOT} Hooks plugin Đường dẫn đến thư mục plugin
${CLAUDE_PLUGIN_DATA} Hooks plugin Đường dẫn đến thư mục dữ liệu plugin
CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS Hooks SessionEnd Timeout có thể cấu hình tính bằng mili giây cho hooks SessionEnd (ghi đè mặc định)

Hooks Dựa Trên Prompt / Prompt-Based Hooks

Đối với các sự kiện StopSubagentStop, bạn có thể sử dụng đánh giá dựa trên LLM:

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "prompt",
            "prompt": "Review if all tasks are complete. Return your decision.",
            "timeout": 30
          }
        ]
      }
    ]
  }
}

Schema Phản Hồi LLM:

{
  "decision": "approve",
  "reason": "All tasks completed successfully",
  "continue": false,
  "stopReason": "Task complete"
}

Ví Dụ / Examples

Ví Dụ 1: Trình Xác Thực Lệnh Bash (PreToolUse) / Example 1: Bash Command Validator

File: .claude/hooks/validate-bash.py

#!/usr/bin/env python3
import json
import sys
import re

BLOCKED_PATTERNS = [
    (r"\brm\s+-rf\s+/", "Blocking dangerous rm -rf / command"),
    (r"\bsudo\s+rm", "Blocking sudo rm command"),
]

def main():
    input_data = json.load(sys.stdin)

    tool_name = input_data.get("tool_name", "")
    if tool_name != "Bash":
        sys.exit(0)

    command = input_data.get("tool_input", {}).get("command", "")

    for pattern, message in BLOCKED_PATTERNS:
        if re.search(pattern, command):
            print(message, file=sys.stderr)
            sys.exit(2)  # Exit 2 = blocking error

    sys.exit(0)

if __name__ == "__main__":
    main()

Ví Dụ 2: Bộ Quét Bảo Mật (PostToolUse) / Example 2: Security Scanner

File: .claude/hooks/security-scan.py

#!/usr/bin/env python3
import json
import sys
import re

SECRET_PATTERNS = [
    (r"password\s*=\s*['\"][^'\"]+['\"]", "Potential hardcoded password"),
    (r"api[_-]?key\s*=\s*['\"][^'\"]+['\"]", "Potential hardcoded API key"),
]

def main():
    input_data = json.load(sys.stdin)

    tool_name = input_data.get("tool_name", "")
    if tool_name not in ["Write", "Edit"]:
        sys.exit(0)

    tool_input = input_data.get("tool_input", {})
    content = tool_input.get("content", "") or tool_input.get("new_string", "")
    file_path = tool_input.get("file_path", "")

    warnings = []
    for pattern, message in SECRET_PATTERNS:
        if re.search(pattern, content, re.IGNORECASE):
            warnings.append(message)

    if warnings:
        output = {
            "hookSpecificOutput": {
                "hookEventName": "PostToolUse",
                "additionalContext": f"Security warnings for {file_path}: " + "; ".join(warnings)
            }
        }
        print(json.dumps(output))

    sys.exit(0)

if __name__ == "__main__":
    main()

Ví Dụ 3: Tự Động Format Code (PostToolUse) / Example 3: Auto-Format Code

File: .claude/hooks/format-code.sh

#!/bin/bash

# Đọc JSON từ stdin
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | python3 -c "import sys, json; print(json.load(sys.stdin).get('tool_name', ''))")
FILE_PATH=$(echo "$INPUT" | python3 -c "import sys, json; print(json.load(sys.stdin).get('tool_input', {}).get('file_path', ''))")

if [ "$TOOL_NAME" != "Write" ] && [ "$TOOL_NAME" != "Edit" ]; then
    exit 0
fi

# Format dựa trên phần mở rộng file
case "$FILE_PATH" in
    *.js|*.jsx|*.ts|*.tsx|*.json)
        command -v prettier &>/dev/null && prettier --write "$FILE_PATH" 2>/dev/null
        ;;
    *.py)
        command -v black &>/dev/null && black "$FILE_PATH" 2>/dev/null
        ;;
    *.go)
        command -v gofmt &>/dev/null && gofmt -w "$FILE_PATH" 2>/dev/null
        ;;
esac

exit 0

Ví Dụ 4: Trình Xác Thực Prompt (UserPromptSubmit) / Example 4: Prompt Validator

File: .claude/hooks/validate-prompt.py

#!/usr/bin/env python3
import json
import sys
import re

BLOCKED_PATTERNS = [
    (r"delete\s+(all\s+)?database", "Dangerous: database deletion"),
    (r"rm\s+-rf\s+/", "Dangerous: root deletion"),
]

def main():
    input_data = json.load(sys.stdin)
    prompt = input_data.get("user_prompt", "") or input_data.get("prompt", "")

    for pattern, message in BLOCKED_PATTERNS:
        if re.search(pattern, prompt, re.IGNORECASE):
            output = {
                "decision": "block",
                "reason": f"Blocked: {message}"
            }
            print(json.dumps(output))
            sys.exit(0)

    sys.exit(0)

if __name__ == "__main__":
    main()

Ví Dụ 5: Stop Hook Thông Minh (Dựa Trên Prompt) / Example 5: Intelligent Stop Hook

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "prompt",
            "prompt": "Review if Claude completed all requested tasks. Check: 1) Were all files created/modified? 2) Were there unresolved errors? If incomplete, explain what's missing.",
            "timeout": 30
          }
        ]
      }
    ]
  }
}

Hooks Plugin / Plugin Hooks

Plugins có thể bao gồm hooks trong file hooks/hooks.json của chúng:

File: plugins/hooks/hooks.json

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh"
          }
        ]
      }
    ]
  }
}

Các Biến Môi Trường Trong Hooks Plugin:

  • ${CLAUDE_PLUGIN_ROOT} - Đường dẫn đến thư mục plugin
  • ${CLAUDE_PLUGIN_DATA} - Đường dẫn đến thư mục dữ liệu plugin

Điều này cho phép các plugins bao gồm các hook xác thực và tự động hóa tùy chỉnh.

Hooks Công Cụ MCP / MCP Tool Hooks

Các công cụ MCP theo mẫu mcp__<server>__<tool>:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "mcp__memory__.*",
        "hooks": [
          {
            "type": "command",
            "command": "echo '{\"systemMessage\": \"Memory operation logged\"}'"
          }
        ]
      }
    ]
  }
}

Cân Nhắc Bảo Mật / Security Considerations

Tuyên Bố Từ Chối Trách Nhiệm / Disclaimer

SỬ DỤNG VỚI RỦI RO RIÊNG CỦA BẠN: Hooks thực thi các lệnh shell tùy ý. Bạn chịu trách nhiệm duy nhất cho:

  • Các lệnh bạn cấu hình
  • Quyền truy cập/sửa đổi file
  • Mất dữ liệu hoặc hư hại hệ thống tiềm ẩn
  • Testing hooks trong môi trường an toàn trước khi sử dụng production

Ghi Chú Bảo Mật / Security Notes

  • Cần tin cậy workspace: Các output commands hook statusLinefileSuggestion bây giờ yêu cầu chấp nhận tin cậy workspace trước khi chúng có hiệu lực.
  • HTTP hooks và biến môi trường: HTTP hooks yêu cầu danh sách allowedEnvVars rõ ràng để sử dụng nội suy biến môi trường trong URLs. Điều này ngăn chặn lộ vô ý các biến môi trường nhạy cảm đến các endpoints từ xa.
  • Phân cấp settings được quản lý: Cài đặt disableAllHooks bây giờ tôn trọng phân cấp settings được quản lý, nghĩa là settings cấp tổ chức có thể thực thi vô hiệu hóa hook mà người dùng cá nhân không thể ghi đè.

Thực Hành Tốt Nhất / Best Practices

Nên Không Nên
Xác thực và vệ sinh tất cả đầu vào Tin tưởng dữ liệu đầu vào mù quáng
Trích dẫn biến shell: "$VAR" Sử dụng không trích dẫn: $VAR
Chặn đường dẫn path traversal (..) Cho phép các đường dẫn tùy ý
Sử dụng đường dẫn tuyệt đối với $CLAUDE_PROJECT_DIR Hardcode các đường dẫn
Bỏ qua các file nhạy cảm (.env, .git/, keys) Xử lý tất cả các files
Test hooks trong cô lập trước Triển khai hooks chưa được test
Sử dụng allowedEnvVars rõ ràng cho HTTP hooks Lộ tất cả env vars cho webhooks

Gỡ Lỗi / Debugging

Kích Hoạt Chế Độ Debug / Enable Debug Mode

Chạy Claude với cờ debug để xem logs chi tiết hook:

claude --debug

Chế Độ Verbose / Verbose Mode

Sử dụng Ctrl+O trong Claude Code để kích hoạt chế độ verbose và xem tiến độ thực thi hook.

Test Hooks Độc Lập / Test Hooks Independently

# Test với đầu vào JSON mẫu
echo '{"tool_name": "Bash", "tool_input": {"command": "ls -la"}}' | python3 .claude/hooks/validate-bash.py

# Kiểm tra exit code
echo $?

Cài Đặt / Installation

Bước 1: Tạo Thư Mục Hooks

mkdir -p ~/.claude/hooks

Bước 2: Sao Chép Hooks Ví Dụ

cp 06-hooks/*.sh ~/.claude/hooks/
chmod +x ~/.claude/hooks/*.sh

Bước 3: Cấu Hình Trong Settings

Chỉnh sửa ~/.claude/settings.json hoặc .claude/settings.json với cấu hình hook được hiển thị ở trên.

Tài Nguyên Thêm / Additional Resources