[ PROMPT_NODE_24890 ]
常见钩子模式
[ SKILL_DOCUMENTATION ]
# 常见钩子模式
本参考指南提供了实现 Claude Code 钩子的常用、经过验证的模式。请将这些模式作为典型钩子用例的起点。
## 模式 1:安全验证
使用基于提示词的钩子拦截危险的文件写入:
{
"PreToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "prompt",
"prompt": "File path: $TOOL_INPUT.file_path. Verify: 1) Not in /etc or system directories 2) Not .env or credentials 3) Path doesn't contain '..' traversal. Return 'approve' or 'deny'."
}
]
}
]
}
**适用场景:** 防止写入敏感文件或系统目录。
## 模式 2:测试强制执行
确保在停止前运行测试:
{
"Stop": [
{
"matcher": "*",
"hooks": [
{
"type": "prompt",
"prompt": "Review transcript. If code was modified (Write/Edit tools used), verify tests were executed. If no tests were run, block with reason 'Tests must be run after code changes'."
}
]
}
]
}
**适用场景:** 强制执行质量标准并防止工作未完成。
## 模式 3:上下文加载
在会话开始时加载项目特定上下文:
{
"SessionStart": [
{
"matcher": "*",
"hooks": [
{
"type": "command",
"command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/load-context.sh"
}
]
}
]
}
**示例脚本 (load-context.sh):**
bash
#!/bin/bash
cd "$CLAUDE_PROJECT_DIR" || exit 1
# Detect project type
if [ -f "package.json" ]; then
echo "📦 Node.js project detected"
echo "export PROJECT_TYPE=nodejs" >> "$CLAUDE_ENV_FILE"
elif [ -f "Cargo.toml" ]; then
echo "🦀 Rust project detected"
echo "export PROJECT_TYPE=rust" >> "$CLAUDE_ENV_FILE"
fi
**适用场景:** 自动检测并配置项目特定设置。