AgentSkillsCN

hook-templates

全面的Claude代码钩子模式,用于自动化、状态管理和外部集成。在实现验证钩子、工作流门控、MCP集成或状态机时使用。

SKILL.md
--- frontmatter
name: hook-templates
description: Comprehensive Claude Code hook patterns for automation, state management, and external integration. Use when implementing hooks for validation, workflow gates, MCP integration, or state machines.
allowed-tools: ["Read", "Write", "Bash", "Grep", "Glob"]

Hook Patterns

Production-tested patterns for Claude Code hooks (1.0.40+).

Hook Roles (Beyond Just Validation)

RoleHook EventExample
GatePreToolUseBlock dangerous commands, require prerequisites
Side EffectPostToolUseAuto-format, auto-commit, lint
State ManagerPostToolUseCreate/delete state files, track workflow phase
External IntegratorAnyMCP calls, HTTP APIs, WebSocket
Context InjectorSessionStartLoad project context, activate services

Event Reference

EventTriggerCan BlockUse For
SessionStartSession beginsNoContext loading, service activation
UserPromptSubmitUser sends messageYesPrompt validation, skill suggestion
PreToolUseBefore toolYesValidation, workflow gates
PostToolUseAfter toolNoState updates, side effects
StopClaude stopsYesQuality gates, cleanup
SubagentStopSubagent stopsYesSubagent quality gates

Exit Codes

CodePreToolUse/StopOthers
0AllowContinue
2Block (stderr→Claude)Logged
1, 3+BlockLogged

JSON Response (Advanced)

json
{
  "decision": "approve|block",
  "reason": "Shown to user/Claude",
  "continue": true,
  "suppressOutput": false
}

Quick Registration

json
{
  "hooks": {
    "PreToolUse": [{
      "matcher": "Edit|Write",
      "hooks": [{ "type": "command", "command": "script.sh", "timeout": 5 }]
    }]
  }
}

Pattern Selection

NeedPatternReference
Force skill/agent activationOrchestrationorchestration-templates.md
Block dangerous actionsGate Patterngate-patterns.md
Auto-format/lint/commitSide Effect Patternside-effect-patterns.md
Full working examplesExamplesfull-examples.md

Orchestration Patterns (NEW)

Hook-based skill/agent activation with reliability stats:

PatternSuccessUse Case
Forced Evaluation84%Force Claude to evaluate and use skills
Agent Router100%Route to plugin agents via Task tool
Context Injection100%Load project context at session start

See orchestration-templates.md for templates.

Debugging

Common issues and solutions in debugging-guide.md.

Quick checklist:

  • Hook executable? (chmod +x)
  • Using INPUT=$(cat) to read stdin?
  • Using exit 2 for blocking (not exit 1)?
  • Debug to stderr (>&2), output to stdout?
  • New session after settings.json change?

Common Mistakes

  • Missing nested hooks array
  • Missing "type": "command"
  • Using exit 1 instead of exit 2 for blocking
  • Object matcher (not supported) - use script parsing instead