npx skills add https://github.com/chrislemke/stoffy --skill 'Hooks Automation'通过集成 MCP 工具和神经模式训练的钩子,协调、验证并学习 Claude Code 操作的智能自动化系统。
此技能提供了一个全面的钩子系统,可自动管理开发操作、协调集群代理、维护会话状态,并持续从编码模式中学习。它支持自动代理分配、代码格式化、性能跟踪和跨会话内存持久化。
核心能力:
必需:
npm install -g claude-flow@alpha).claude/settings.json可选:
# 使用默认钩子配置进行初始化
npx claude-flow init --hooks
这将创建:
.claude/settings.json.claude/commands/hooks/ 中的钩子命令文档# 任务前钩子(自动生成代理)
npx claude-flow hook pre-task --description "实现身份验证"
# 编辑后钩子(自动格式化并存储到内存)
npx claude-flow hook post-edit --file "src/auth.js" --memory-key "auth/login"
# 会话结束钩子(保存状态和指标)
npx claude-flow hook session-end --session-id "dev-session" --export-metrics
在操作之前执行以准备和验证的钩子:
pre-edit - 在文件修改前验证并分配代理
npx claude-flow hook pre-edit [options]
Options:
--file, -f <path> 要编辑的文件路径
--auto-assign-agent 自动分配最佳代理 (默认: true)
--validate-syntax 编辑前预验证语法
--check-conflicts 检查合并冲突
--backup-file 编辑前创建备份
Examples:
npx claude-flow hook pre-edit --file "src/auth/login.js"
npx claude-flow hook pre-edit -f "config/db.js" --validate-syntax
npx claude-flow hook pre-edit -f "production.env" --backup-file --check-conflicts
特性:
pre-bash - 检查命令安全性和资源需求
npx claude-flow hook pre-bash --command <cmd>
Options:
--command, -c <cmd> 要验证的命令
--check-safety 验证命令安全性 (默认: true)
--estimate-resources 估算资源使用情况
--require-confirmation 对危险命令请求用户确认
Examples:
npx claude-flow hook pre-bash -c "rm -rf /tmp/cache"
npx claude-flow hook pre-bash --command "docker build ." --estimate-resources
特性:
pre-task - 自动生成代理并为复杂任务做准备
npx claude-flow hook pre-task [options]
Options:
--description, -d <text> 用于上下文的描述
--auto-spawn-agents 自动生成所需代理 (默认: true)
--load-memory 从之前的会话加载相关内存
--optimize-topology 选择最优集群拓扑
--estimate-complexity 分析任务复杂度
Examples:
npx claude-flow hook pre-task --description "实现用户身份验证"
npx claude-flow hook pre-task -d "继续 API 开发" --load-memory
npx claude-flow hook pre-task -d "重构代码库" --optimize-topology
特性:
pre-search - 准备和优化搜索操作
npx claude-flow hook pre-search --query <query>
Options:
--query, -q <text> 搜索查询
--check-cache 首先检查缓存 (默认: true)
--optimize-query 优化搜索模式
Examples:
npx claude-flow hook pre-search -q "身份验证中间件"
特性:
在操作之后执行以处理和学习:
post-edit - 自动格式化、验证和更新内存
npx claude-flow hook post-edit [options]
Options:
--file, -f <path> 已编辑的文件路径
--auto-format 自动格式化代码 (默认: true)
--memory-key, -m <key> 将编辑上下文存储到内存
--train-patterns 从编辑中训练神经模式
--validate-output 验证已编辑的文件
Examples:
npx claude-flow hook post-edit --file "src/components/Button.jsx"
npx claude-flow hook post-edit -f "api/auth.js" --memory-key "auth/login"
npx claude-flow hook post-edit -f "utils/helpers.ts" --train-patterns
特性:
post-bash - 记录执行并更新指标
npx claude-flow hook post-bash --command <cmd>
Options:
--command, -c <cmd> 已执行的命令
--log-output 记录命令输出 (默认: true)
--update-metrics 更新性能指标
--store-result 将结果存储到内存
Examples:
npx claude-flow hook post-bash -c "npm test" --update-metrics
特性:
post-task - 性能分析和决策存储
npx claude-flow hook post-task [options]
Options:
--task-id, -t <id> 用于跟踪的任务标识符
--analyze-performance 生成性能指标 (默认: true)
--store-decisions 将任务决策保存到内存
--export-learnings 导出神经模式学习成果
--generate-report 创建任务完成报告
Examples:
npx claude-flow hook post-task --task-id "auth-implementation"
npx claude-flow hook post-task -t "api-refactor" --analyze-performance
npx claude-flow hook post-task -t "bug-fix-123" --store-decisions
特性:
post-search - 缓存结果并改进模式
npx claude-flow hook post-search --query <query> --results <path>
Options:
--query, -q <text> 原始搜索查询
--results, -r <path> 结果文件路径
--cache-results 缓存以供将来使用 (默认: true)
--train-patterns 改进搜索模式
Examples:
npx claude-flow hook post-search -q "auth" -r "results.json" --train-patterns
特性:
与 MCP 集群工具协调的钩子:
mcp-initialized - 持久化集群配置
npx claude-flow hook mcp-initialized --swarm-id <id>
Features:
- 保存集群拓扑和配置
- 将代理名册存储到内存
- 初始化协调命名空间
agent-spawned - 更新代理名册和内存
npx claude-flow hook agent-spawned --agent-id <id> --type <type>
Features:
- 在协调内存中注册代理
- 更新代理名册
- 初始化代理特定的内存命名空间
task-orchestrated - 监控任务进度
npx claude-flow hook task-orchestrated --task-id <id>
Features:
- 通过内存跟踪任务进度
- 监控代理分配
- 更新协调状态
neural-trained - 保存模式改进
npx claude-flow hook neural-trained --pattern <name>
Features:
- 导出已训练的神经模式
- 更新协调模型
- 跨代理共享学习成果
memory-write - 当代理写入协调内存时触发
Features:
- 验证内存键格式
- 更新跨代理索引
- 触发依赖钩子
- 通知订阅的代理
memory-read - 当代理从协调内存读取时触发
Features:
- 记录访问模式
- 更新流行度指标
- 预加载相关数据
- 跟踪使用统计
memory-sync - 跨集群代理同步内存
npx claude-flow hook memory-sync --namespace <ns>
Features:
- 跨代理同步内存状态
- 解决冲突
- 传播更新
- 维护一致性
session-start - 初始化新会话
npx claude-flow hook session-start --session-id <id>
Options:
--session-id, -s <id> 会话标识符
--load-context 从之前的会话加载上下文
--init-agents 初始化所需代理
Features:
- 创建会话目录
- 初始化指标跟踪
- 加载之前的上下文
- 设置协调命名空间
session-restore - 加载之前的会话状态
npx claude-flow hook session-restore --session-id <id>
Options:
--session-id, -s <id> 要恢复的会话
--restore-memory 恢复内存状态 (默认: true)
--restore-agents 恢复代理配置
Examples:
npx claude-flow hook session-restore --session-id "swarm-20241019"
npx claude-flow hook session-restore -s "feature-auth" --restore-memory
特性:
session-end - 清理并持久化会话状态
npx claude-flow hook session-end [options]
Options:
--session-id, -s <id> 要结束的会话标识符
--save-state 保存当前会话状态 (默认: true)
--export-metrics 导出会话指标
--generate-summary 创建会话摘要
--cleanup-temp 删除临时文件
Examples:
npx claude-flow hook session-end --session-id "dev-session-2024"
npx claude-flow hook session-end -s "feature-auth" --export-metrics --generate-summary
npx claude-flow hook session-end -s "quick-fix" --cleanup-temp
特性:
notify - 带集群状态的自定义通知
npx claude-flow hook notify --message <msg>
Options:
--message, -m <text> 通知消息
--level <level> 通知级别 (info|warning|error)
--swarm-status 包含集群状态 (默认: true)
--broadcast 发送给所有代理
Examples:
npx claude-flow hook notify -m "任务完成" --level info
npx claude-flow hook notify -m "严重错误" --level error --broadcast
特性:
编辑 .claude/settings.json 以配置钩子:
{
"hooks": {
"PreToolUse": [
{
"matcher": "^(Write|Edit|MultiEdit)$",
"hooks": [{
"type": "command",
"command": "npx claude-flow hook pre-edit --file '${tool.params.file_path}' --memory-key 'swarm/editor/current'"
}]
},
{
"matcher": "^Bash$",
"hooks": [{
"type": "command",
"command": "npx claude-flow hook pre-bash --command '${tool.params.command}'"
}]
}
],
"PostToolUse": [
{
"matcher": "^(Write|Edit|MultiEdit)$",
"hooks": [{
"type": "command",
"command": "npx claude-flow hook post-edit --file '${tool.params.file_path}' --memory-key 'swarm/editor/complete' --auto-format --train-patterns"
}]
},
{
"matcher": "^Bash$",
"hooks": [{
"type": "command",
"command": "npx claude-flow hook post-bash --command '${tool.params.command}' --update-metrics"
}]
}
]
}
}
包含所有功能的完整钩子配置:
{
"hooks": {
"enabled": true,
"debug": false,
"timeout": 5000,
"PreToolUse": [
{
"matcher": "^(Write|Edit|MultiEdit)$",
"hooks": [
{
"type": "command",
"command": "npx claude-flow hook pre-edit --file '${tool.params.file_path}' --auto-assign-agent --validate-syntax",
"timeout": 3000,
"continueOnError": true
}
]
},
{
"matcher": "^Task$",
"hooks": [
{
"type": "command",
"command": "npx claude-flow hook pre-task --description '${tool.params.task}' --auto-spawn-agents --load-memory",
"async": true
}
]
},
{
"matcher": "^Grep$",
"hooks": [
{
"type": "command",
"command": "npx claude-flow hook pre-search --query '${tool.params.pattern}' --check-cache"
}
]
}
],
"PostToolUse": [
{
"matcher": "^(Write|Edit|MultiEdit)$",
"hooks": [
{
"type": "command",
"command": "npx claude-flow hook post-edit --file '${tool.params.file_path}' --memory-key 'edits/${tool.params.file_path}' --auto-format --train-patterns",
"async": true
}
]
},
{
"matcher": "^Task$",
"hooks": [
{
"type": "command",
"command": "npx claude-flow hook post-task --task-id '${result.task_id}' --analyze-performance --store-decisions --export-learnings",
"async": true
}
]
},
{
"matcher": "^Grep$",
"hooks": [
{
"type": "command",
"command": "npx claude-flow hook post-search --query '${tool.params.pattern}' --cache-results --train-patterns"
}
]
}
],
"SessionStart": [
{
"hooks": [
{
"type": "command",
"command": "npx claude-flow hook session-start --session-id '${session.id}' --load-context"
}
]
}
],
"SessionEnd": [
{
"hooks": [
{
"type": "command",
"command": "npx claude-flow hook session-end --session-id '${session.id}' --export-metrics --generate-summary --cleanup-temp"
}
]
}
]
}
}
为敏感文件添加保护:
{
"hooks": {
"PreToolUse": [
{
"matcher": "^(Write|Edit|MultiEdit)$",
"hooks": [
{
"type": "command",
"command": "npx claude-flow hook check-protected --file '${tool.params.file_path}'"
}
]
}
]
}
}
文件修改后运行测试:
{
"hooks": {
"PostToolUse": [
{
"matcher": "^Write$",
"hooks": [
{
"type": "command",
"command": "test -f '${tool.params.file_path%.js}.test.js' && npm test '${tool.params.file_path%.js}.test.js'",
"continueOnError": true
}
]
}
]
}
}
钩子自动与 MCP 工具集成以进行协调:
// 钩子命令
npx claude-flow hook pre-task --description "构建 REST API"
// 内部调用 MCP 工具:
mcp__claude-flow__agent_spawn {
type: "backend-dev",
capabilities: ["api", "database", "testing"]
}
mcp__claude-flow__memory_usage {
action: "store",
key: "swarm/task/api-build/context",
namespace: "coordination",
value: JSON.stringify({
description: "Build REST API",
agents: ["backend-dev"],
started: Date.now()
})
}
// 钩子命令
npx claude-flow hook post-edit --file "api/auth.js"
// 内部调用 MCP 工具:
mcp__claude-flow__memory_usage {
action: "store",
key: "swarm/edits/api/auth.js",
namespace: "coordination",
value: JSON.stringify({
file: "api/auth.js",
timestamp: Date.now(),
changes: { added: 45, removed: 12 },
formatted: true,
linted: true
})
}
mcp__claude-flow__neural_train {
pattern_type: "coordination",
training_data: { /* edit patterns */ }
}
// 钩子命令
npx claude-flow hook session-end --session-id "dev-2024"
// 内部调用 MCP 工具:
mcp__claude-flow__memory_persist {
sessionId: "dev-2024"
}
mcp__claude-flow__swarm_status {
swarmId: "current"
}
// 生成指标和摘要
所有钩子都遵循标准化的内存协调模式:
阶段 1: STATUS - 钩子开始
mcp__claude-flow__memory_usage {
action: "store",
key: "swarm/hooks/pre-edit/status",
namespace: "coordination",
value: JSON.stringify({
status: "running",
hook: "pre-edit",
file: "src/auth.js",
timestamp: Date.now()
})
}
阶段 2: PROGRESS - 钩子处理
mcp__claude-flow__memory_usage {
action: "store",
key: "swarm/hooks/pre-edit/progress",
namespace: "coordination",
value: JSON.stringify({
progress: 50,
action: "validating syntax",
file: "src/auth.js"
})
}
阶段 3: COMPLETE - 钩子完成
mcp__claude-flow__memory_usage {
action: "store",
key: "swarm/hooks/pre-edit/complete",
namespace: "coordination",
value: JSON.stringify({
status: "complete",
result: "success",
agent_assigned: "backend-dev",
syntax_valid: true,
backup_created: true
})
}
钩子返回 JSON 响应以控制操作流程:
{
"continue": true,
"reason": "所有验证通过",
"metadata": {
"agent_assigned": "backend-dev",
"syntax_valid": true,
"file": "src/auth.js"
}
}
{
"continue": false,
"reason": "受保护文件 - 需要手动审核",
"metadata": {
"file": ".env.production",
"protection_level": "high",
"requires": "manual_approval"
}
}
{
"continue": true,
"reason": "语法有效但复杂度高",
"warnings": [
"圈复杂度: 15 (阈值: 10)",
"考虑重构以提高可维护性"
],
"metadata": {
"complexity": 15,
"threshold": 10
}
}
钩子可以与 Git 操作集成以进行质量控制:
# 添加到 .git/hooks/pre-commit 或使用 husky
#!/bin/bash
# 提交前运行质量检查
# 获取暂存文件
FILES=$(git diff --cached --name-only --diff-filter=ACM)
for FILE in $FILES; do
# 运行 pre-edit 钩子进行验证
npx claude-flow hook pre-edit --file "$FILE" --validate-syntax
if [ $? -ne 0 ]; then
echo "验证失败: $FILE"
exit 1
fi
# 运行 post-edit 钩子进行格式化
npx claude-flow hook post-edit --file "$FILE" --auto-format
done
# 运行测试
npm test
exit $?
# 添加到 .git/hooks/post-commit
#!/bin/bash
# 跟踪提交指标
COMMIT_HASH=$(git rev-parse HEAD)
COMMIT_MSG=$(git log -1 --pretty=%B)
npx claude-flow hook notify \
--message "提交完成: $COMMIT_MSG" \
--level info \
--swarm-status
# 添加到 .git/hooks/pre-push
#!/bin/bash
# 推送前的质量门控
# 运行完整测试套件
npm run test:all
# 运行质量检查
npx claude-flow hook session-end \
--generate-report \
--export-metrics
# 验证质量阈值
TRUTH_SCORE=$(npx claude-flow metrics score --format json | jq -r '.truth_score')
if (( $(echo "$TRUTH_SCORE < 0.95" | bc -l) )); then
echo "真实度分数低于阈值: $TRUTH_SCORE < 0.95"
exit 1
fi
exit 0
代理如何使用钩子进行协调:
# 代理 1: 后端开发人员
# 步骤 1: 任务前准备
npx claude-flow hook pre-task \
--description "实现用户身份验证 API" \
--auto-spawn-agents \
--load-memory
# 步骤 2: 工作开始 - 编辑前验证
npx claude-flow hook pre-edit \
--file "api/auth.js" \
--auto-assign-agent \
--validate-syntax
# 步骤 3: 编辑文件 (通过 Claude Code Edit 工具)
# ... 代码更改 ...
# 步骤 4: 编辑后处理
npx claude-flow hook post-edit \
--file "api/auth.js" \
--memory-key "swarm/backend/auth-api" \
--auto-format \
--train-patterns
# 步骤 5: 通知协调系统
npx claude-flow hook notify \
--message "身份验证 API 实现完成" \
--swarm-status \
--broadcast
# 步骤 6: 任务完成
npx claude-flow hook post-task \
--task-id "auth-api" \
--analyze-performance \
--store-decisions \
--export-learnings
# 代理 2: 测试工程师 (接收通知)
# 步骤 1: 检查内存中的 API 详情
npx claude-flow hook session-restore \
--session-id "swarm-current" \
--restore-memory
# 内存包含: swarm/backend/auth-api 及实现详情
# 步骤 2: 生成测试
npx claude-flow hook pre-task \
--description "为身份验证 API 编写测试" \
--load-memory
# 步骤 3: 创建测试文件
npx claude-flow hook post-edit \
--file "api/auth.test.js" \
--memory-key "swarm/testing/auth-api-tests" \
--train-patterns
# 步骤 4: 分享测试结果
npx claude-flow hook notify \
--message "身份验证 API 测试完成 - 100% 覆盖率" \
--broadcast
为特定工作流创建自定义钩子:
// .claude/hooks/custom-quality-check.js
module.exports = {
name: 'custom-quality-check',
type: 'pre',
matcher: /\.(ts|js)$/,
async execute(context) {
const { file, content } = context;
// 自定义验证逻辑
const complexity = await analyzeComplexity(content);
const securityIssues = await scanSecurity(content);
// 存储到内存
await storeInMemory({
key: `quality/${file}`,
value: { complexity, securityIssues }
});
// 返回决策
if (complexity > 15 || securityIssues.length > 0) {
return {
continue: false,
reason: '质量检查失败',
warnings: [
`复杂度: ${complexity} (最大值: 15)`,
`安全问题: ${securityIssues.length}`
]
};
}
return {
continue: true,
reason: '质量检查通过',
metadata: { complexity, securityIssues: 0 }
};
}
};
{
"hooks": {
"PreToolUse": [
{
"matcher": "^(Write|Edit)$",
"hooks": [
{
"type": "script",
"script": ".claude/hooks/custom-quality-check.js"
}
]
}
]
}
}
# 会话开始 - 初始化协调
npx claude-flow hook session-start --session-id "fullstack-feature"
# 任务前规划
npx claude-flow hook pre-task \
--description "构建用户个人资料功能 - 前端 + 后端 + 测试" \
--auto-spawn-agents \
--optimize-topology
# 后端工作
npx claude-flow hook pre-edit --file "api/profile.js"
# ... 实现后端 ...
npx claude-flow hook post-edit \
--file "api/profile.js" \
--memory-key "profile/backend" \
--train-patterns
# 前端工作 (从内存读取后端详情)
npx claude-flow hook pre-edit --file "components/Profile.jsx"
# ... 实现前端 ...
npx claude-flow hook post-edit \
--file "components/Profile.jsx" \
--memory-key "profile/frontend" \
--train-patterns
# 测试 (从内存读取后端和前端)
npx claude-flow hook pre-task \
--description "测试个人资料功能" \
--load-memory
# 会话结束 - 导出所有内容
npx claude-flow hook session-end \
--session-id "fullstack-feature" \
--export-metrics \
--generate-summary
# 开始调试会话
npx claude-flow hook session-start --session-id "debug-memory-leak"
# 任务前: 分析问题
npx claude-flow hook pre-task \
--description "调试事件处理器中的内存泄漏" \
--load-memory \
--estimate-complexity
# 搜索事件发射器
npx claude-flow hook pre-search --query "EventEmitter"
# ... 执行搜索 ...
npx claude-flow hook post-search \
--query "EventEmitter" \
--cache-results
# 修复问题
npx claude-flow hook pre-edit \
--file "services/events.js" \
--backup-file
# ... 修复代码 ...
npx claude-flow hook post-edit \
--file "services/events.js" \
--memory-key "debug/memory-leak-fix" \
--validate-output
# 验证修复
npx claude-flow hook post-task \
--task-id "memory-leak-fix" \
--analyze-performance \
--generate-report
# 结束会话
npx claude-flow hook session-end \
--session-id "debug-memory-leak" \
--export-metrics
# 为重构初始化集群
npx claude-flow hook pre-task \
--description "将遗留代码库重构为现代模式" \
--auto-spawn-agents \
--optimize-topology
# 代理 1: 代码分析器
npx claude-flow hook pre-task --description "分析代码复杂度"
# ... 分析 ...
npx claude-flow hook post-task \
--task-id "analysis" \
--store-decisions
# 代理 2: 重构 (从内存读取分析结果)
npx claude-flow hook session-restore \
--session-id "swarm-refactor" \
--restore-memory
for file in src/**/*.js; do
npx claude-flow hook pre-edit --file "$file" --backup-file
# ... 重构 ...
npx claude-flow hook post-edit \
--file "$file" \
--memory-key "refactor/$file" \
--auto-format \
--train-patterns
done
# 代理 3: 测试 (从内存读取重构后的代码)
npx claude-flow hook pre-task \
--description "为重构后的代码生成测试" \
--load-memory
# 广播完成
npx claude-flow hook notify \
--message "重构完成 - 所有测试通过" \
--broadcast
启用调试模式进行故障排除:
# 启用调试输出
export CLAUDE_FLOW_DEBUG=true
# 使用详细输出测试特定钩子
npx claude-flow hook pre-edit --file "test.js" --debug
# 检查钩子执行日志
cat .claude-flow/logs/hooks-$(date +%Y-%m-%d).log
# 验证配置
npx claude-flow hook validate-config
.claude/settings.json 语法Intelligent automation system that coordinates, validates, and learns from Claude Code operations through hooks integrated with MCP tools and neural pattern training.
This skill provides a comprehensive hook system that automatically manages development operations, coordinates swarm agents, maintains session state, and continuously learns from coding patterns. It enables automated agent assignment, code formatting, performance tracking, and cross-session memory persistence.
Key Capabilities:
Required:
npm install -g claude-flow@alpha).claude/settings.json with hook configurations广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
Optional:
# Initialize with default hooks configuration
npx claude-flow init --hooks
This creates:
.claude/settings.json with pre-configured hooks.claude/commands/hooks/# Pre-task hook (auto-spawns agents)
npx claude-flow hook pre-task --description "Implement authentication"
# Post-edit hook (auto-formats and stores in memory)
npx claude-flow hook post-edit --file "src/auth.js" --memory-key "auth/login"
# Session end hook (saves state and metrics)
npx claude-flow hook session-end --session-id "dev-session" --export-metrics
Hooks that execute BEFORE operations to prepare and validate:
pre-edit - Validate and assign agents before file modifications
npx claude-flow hook pre-edit [options]
Options:
--file, -f <path> File path to be edited
--auto-assign-agent Automatically assign best agent (default: true)
--validate-syntax Pre-validate syntax before edit
--check-conflicts Check for merge conflicts
--backup-file Create backup before editing
Examples:
npx claude-flow hook pre-edit --file "src/auth/login.js"
npx claude-flow hook pre-edit -f "config/db.js" --validate-syntax
npx claude-flow hook pre-edit -f "production.env" --backup-file --check-conflicts
Features:
pre-bash - Check command safety and resource requirements
npx claude-flow hook pre-bash --command <cmd>
Options:
--command, -c <cmd> Command to validate
--check-safety Verify command safety (default: true)
--estimate-resources Estimate resource usage
--require-confirmation Request user confirmation for risky commands
Examples:
npx claude-flow hook pre-bash -c "rm -rf /tmp/cache"
npx claude-flow hook pre-bash --command "docker build ." --estimate-resources
Features:
pre-task - Auto-spawn agents and prepare for complex tasks
npx claude-flow hook pre-task [options]
Options:
--description, -d <text> Task description for context
--auto-spawn-agents Automatically spawn required agents (default: true)
--load-memory Load relevant memory from previous sessions
--optimize-topology Select optimal swarm topology
--estimate-complexity Analyze task complexity
Examples:
npx claude-flow hook pre-task --description "Implement user authentication"
npx claude-flow hook pre-task -d "Continue API dev" --load-memory
npx claude-flow hook pre-task -d "Refactor codebase" --optimize-topology
Features:
pre-search - Prepare and optimize search operations
npx claude-flow hook pre-search --query <query>
Options:
--query, -q <text> Search query
--check-cache Check cache first (default: true)
--optimize-query Optimize search pattern
Examples:
npx claude-flow hook pre-search -q "authentication middleware"
Features:
Hooks that execute AFTER operations to process and learn:
post-edit - Auto-format, validate, and update memory
npx claude-flow hook post-edit [options]
Options:
--file, -f <path> File path that was edited
--auto-format Automatically format code (default: true)
--memory-key, -m <key> Store edit context in memory
--train-patterns Train neural patterns from edit
--validate-output Validate edited file
Examples:
npx claude-flow hook post-edit --file "src/components/Button.jsx"
npx claude-flow hook post-edit -f "api/auth.js" --memory-key "auth/login"
npx claude-flow hook post-edit -f "utils/helpers.ts" --train-patterns
Features:
post-bash - Log execution and update metrics
npx claude-flow hook post-bash --command <cmd>
Options:
--command, -c <cmd> Command that was executed
--log-output Log command output (default: true)
--update-metrics Update performance metrics
--store-result Store result in memory
Examples:
npx claude-flow hook post-bash -c "npm test" --update-metrics
Features:
post-task - Performance analysis and decision storage
npx claude-flow hook post-task [options]
Options:
--task-id, -t <id> Task identifier for tracking
--analyze-performance Generate performance metrics (default: true)
--store-decisions Save task decisions to memory
--export-learnings Export neural pattern learnings
--generate-report Create task completion report
Examples:
npx claude-flow hook post-task --task-id "auth-implementation"
npx claude-flow hook post-task -t "api-refactor" --analyze-performance
npx claude-flow hook post-task -t "bug-fix-123" --store-decisions
Features:
post-search - Cache results and improve patterns
npx claude-flow hook post-search --query <query> --results <path>
Options:
--query, -q <text> Original search query
--results, -r <path> Results file path
--cache-results Cache for future use (default: true)
--train-patterns Improve search patterns
Examples:
npx claude-flow hook post-search -q "auth" -r "results.json" --train-patterns
Features:
Hooks that coordinate with MCP swarm tools:
mcp-initialized - Persist swarm configuration
npx claude-flow hook mcp-initialized --swarm-id <id>
Features:
- Save swarm topology and configuration
- Store agent roster in memory
- Initialize coordination namespace
agent-spawned - Update agent roster and memory
npx claude-flow hook agent-spawned --agent-id <id> --type <type>
Features:
- Register agent in coordination memory
- Update agent roster
- Initialize agent-specific memory namespace
task-orchestrated - Monitor task progress
npx claude-flow hook task-orchestrated --task-id <id>
Features:
- Track task progress through memory
- Monitor agent assignments
- Update coordination state
neural-trained - Save pattern improvements
npx claude-flow hook neural-trained --pattern <name>
Features:
- Export trained neural patterns
- Update coordination models
- Share learning across agents
memory-write - Triggered when agents write to coordination memory
Features:
- Validate memory key format
- Update cross-agent indexes
- Trigger dependent hooks
- Notify subscribed agents
memory-read - Triggered when agents read from coordination memory
Features:
- Log access patterns
- Update popularity metrics
- Preload related data
- Track usage statistics
memory-sync - Synchronize memory across swarm agents
npx claude-flow hook memory-sync --namespace <ns>
Features:
- Sync memory state across agents
- Resolve conflicts
- Propagate updates
- Maintain consistency
session-start - Initialize new session
npx claude-flow hook session-start --session-id <id>
Options:
--session-id, -s <id> Session identifier
--load-context Load context from previous session
--init-agents Initialize required agents
Features:
- Create session directory
- Initialize metrics tracking
- Load previous context
- Set up coordination namespace
session-restore - Load previous session state
npx claude-flow hook session-restore --session-id <id>
Options:
--session-id, -s <id> Session to restore
--restore-memory Restore memory state (default: true)
--restore-agents Restore agent configurations
Examples:
npx claude-flow hook session-restore --session-id "swarm-20241019"
npx claude-flow hook session-restore -s "feature-auth" --restore-memory
Features:
session-end - Cleanup and persist session state
npx claude-flow hook session-end [options]
Options:
--session-id, -s <id> Session identifier to end
--save-state Save current session state (default: true)
--export-metrics Export session metrics
--generate-summary Create session summary
--cleanup-temp Remove temporary files
Examples:
npx claude-flow hook session-end --session-id "dev-session-2024"
npx claude-flow hook session-end -s "feature-auth" --export-metrics --generate-summary
npx claude-flow hook session-end -s "quick-fix" --cleanup-temp
Features:
notify - Custom notifications with swarm status
npx claude-flow hook notify --message <msg>
Options:
--message, -m <text> Notification message
--level <level> Notification level (info|warning|error)
--swarm-status Include swarm status (default: true)
--broadcast Send to all agents
Examples:
npx claude-flow hook notify -m "Task completed" --level info
npx claude-flow hook notify -m "Critical error" --level error --broadcast
Features:
Edit .claude/settings.json to configure hooks:
{
"hooks": {
"PreToolUse": [
{
"matcher": "^(Write|Edit|MultiEdit)$",
"hooks": [{
"type": "command",
"command": "npx claude-flow hook pre-edit --file '${tool.params.file_path}' --memory-key 'swarm/editor/current'"
}]
},
{
"matcher": "^Bash$",
"hooks": [{
"type": "command",
"command": "npx claude-flow hook pre-bash --command '${tool.params.command}'"
}]
}
],
"PostToolUse": [
{
"matcher": "^(Write|Edit|MultiEdit)$",
"hooks": [{
"type": "command",
"command": "npx claude-flow hook post-edit --file '${tool.params.file_path}' --memory-key 'swarm/editor/complete' --auto-format --train-patterns"
}]
},
{
"matcher": "^Bash$",
"hooks": [{
"type": "command",
"command": "npx claude-flow hook post-bash --command '${tool.params.command}' --update-metrics"
}]
}
]
}
}
Complete hook configuration with all features:
{
"hooks": {
"enabled": true,
"debug": false,
"timeout": 5000,
"PreToolUse": [
{
"matcher": "^(Write|Edit|MultiEdit)$",
"hooks": [
{
"type": "command",
"command": "npx claude-flow hook pre-edit --file '${tool.params.file_path}' --auto-assign-agent --validate-syntax",
"timeout": 3000,
"continueOnError": true
}
]
},
{
"matcher": "^Task$",
"hooks": [
{
"type": "command",
"command": "npx claude-flow hook pre-task --description '${tool.params.task}' --auto-spawn-agents --load-memory",
"async": true
}
]
},
{
"matcher": "^Grep$",
"hooks": [
{
"type": "command",
"command": "npx claude-flow hook pre-search --query '${tool.params.pattern}' --check-cache"
}
]
}
],
"PostToolUse": [
{
"matcher": "^(Write|Edit|MultiEdit)$",
"hooks": [
{
"type": "command",
"command": "npx claude-flow hook post-edit --file '${tool.params.file_path}' --memory-key 'edits/${tool.params.file_path}' --auto-format --train-patterns",
"async": true
}
]
},
{
"matcher": "^Task$",
"hooks": [
{
"type": "command",
"command": "npx claude-flow hook post-task --task-id '${result.task_id}' --analyze-performance --store-decisions --export-learnings",
"async": true
}
]
},
{
"matcher": "^Grep$",
"hooks": [
{
"type": "command",
"command": "npx claude-flow hook post-search --query '${tool.params.pattern}' --cache-results --train-patterns"
}
]
}
],
"SessionStart": [
{
"hooks": [
{
"type": "command",
"command": "npx claude-flow hook session-start --session-id '${session.id}' --load-context"
}
]
}
],
"SessionEnd": [
{
"hooks": [
{
"type": "command",
"command": "npx claude-flow hook session-end --session-id '${session.id}' --export-metrics --generate-summary --cleanup-temp"
}
]
}
]
}
}
Add protection for sensitive files:
{
"hooks": {
"PreToolUse": [
{
"matcher": "^(Write|Edit|MultiEdit)$",
"hooks": [
{
"type": "command",
"command": "npx claude-flow hook check-protected --file '${tool.params.file_path}'"
}
]
}
]
}
}
Run tests after file modifications:
{
"hooks": {
"PostToolUse": [
{
"matcher": "^Write$",
"hooks": [
{
"type": "command",
"command": "test -f '${tool.params.file_path%.js}.test.js' && npm test '${tool.params.file_path%.js}.test.js'",
"continueOnError": true
}
]
}
]
}
}
Hooks automatically integrate with MCP tools for coordination:
// Hook command
npx claude-flow hook pre-task --description "Build REST API"
// Internally calls MCP tools:
mcp__claude-flow__agent_spawn {
type: "backend-dev",
capabilities: ["api", "database", "testing"]
}
mcp__claude-flow__memory_usage {
action: "store",
key: "swarm/task/api-build/context",
namespace: "coordination",
value: JSON.stringify({
description: "Build REST API",
agents: ["backend-dev"],
started: Date.now()
})
}
// Hook command
npx claude-flow hook post-edit --file "api/auth.js"
// Internally calls MCP tools:
mcp__claude-flow__memory_usage {
action: "store",
key: "swarm/edits/api/auth.js",
namespace: "coordination",
value: JSON.stringify({
file: "api/auth.js",
timestamp: Date.now(),
changes: { added: 45, removed: 12 },
formatted: true,
linted: true
})
}
mcp__claude-flow__neural_train {
pattern_type: "coordination",
training_data: { /* edit patterns */ }
}
// Hook command
npx claude-flow hook session-end --session-id "dev-2024"
// Internally calls MCP tools:
mcp__claude-flow__memory_persist {
sessionId: "dev-2024"
}
mcp__claude-flow__swarm_status {
swarmId: "current"
}
// Generates metrics and summary
All hooks follow a standardized memory coordination pattern:
Phase 1: STATUS - Hook starts
mcp__claude-flow__memory_usage {
action: "store",
key: "swarm/hooks/pre-edit/status",
namespace: "coordination",
value: JSON.stringify({
status: "running",
hook: "pre-edit",
file: "src/auth.js",
timestamp: Date.now()
})
}
Phase 2: PROGRESS - Hook processes
mcp__claude-flow__memory_usage {
action: "store",
key: "swarm/hooks/pre-edit/progress",
namespace: "coordination",
value: JSON.stringify({
progress: 50,
action: "validating syntax",
file: "src/auth.js"
})
}
Phase 3: COMPLETE - Hook finishes
mcp__claude-flow__memory_usage {
action: "store",
key: "swarm/hooks/pre-edit/complete",
namespace: "coordination",
value: JSON.stringify({
status: "complete",
result: "success",
agent_assigned: "backend-dev",
syntax_valid: true,
backup_created: true
})
}
Hooks return JSON responses to control operation flow:
{
"continue": true,
"reason": "All validations passed",
"metadata": {
"agent_assigned": "backend-dev",
"syntax_valid": true,
"file": "src/auth.js"
}
}
{
"continue": false,
"reason": "Protected file - manual review required",
"metadata": {
"file": ".env.production",
"protection_level": "high",
"requires": "manual_approval"
}
}
{
"continue": true,
"reason": "Syntax valid but complexity high",
"warnings": [
"Cyclomatic complexity: 15 (threshold: 10)",
"Consider refactoring for better maintainability"
],
"metadata": {
"complexity": 15,
"threshold": 10
}
}
Hooks can integrate with Git operations for quality control:
# Add to .git/hooks/pre-commit or use husky
#!/bin/bash
# Run quality checks before commit
# Get staged files
FILES=$(git diff --cached --name-only --diff-filter=ACM)
for FILE in $FILES; do
# Run pre-edit hook for validation
npx claude-flow hook pre-edit --file "$FILE" --validate-syntax
if [ $? -ne 0 ]; then
echo "Validation failed for $FILE"
exit 1
fi
# Run post-edit hook for formatting
npx claude-flow hook post-edit --file "$FILE" --auto-format
done
# Run tests
npm test
exit $?
# Add to .git/hooks/post-commit
#!/bin/bash
# Track commit metrics
COMMIT_HASH=$(git rev-parse HEAD)
COMMIT_MSG=$(git log -1 --pretty=%B)
npx claude-flow hook notify \
--message "Commit completed: $COMMIT_MSG" \
--level info \
--swarm-status
# Add to .git/hooks/pre-push
#!/bin/bash
# Quality gate before push
# Run full test suite
npm run test:all
# Run quality checks
npx claude-flow hook session-end \
--generate-report \
--export-metrics
# Verify quality thresholds
TRUTH_SCORE=$(npx claude-flow metrics score --format json | jq -r '.truth_score')
if (( $(echo "$TRUTH_SCORE < 0.95" | bc -l) )); then
echo "Truth score below threshold: $TRUTH_SCORE < 0.95"
exit 1
fi
exit 0
How agents use hooks for coordination:
# Agent 1: Backend Developer
# STEP 1: Pre-task preparation
npx claude-flow hook pre-task \
--description "Implement user authentication API" \
--auto-spawn-agents \
--load-memory
# STEP 2: Work begins - pre-edit validation
npx claude-flow hook pre-edit \
--file "api/auth.js" \
--auto-assign-agent \
--validate-syntax
# STEP 3: Edit file (via Claude Code Edit tool)
# ... code changes ...
# STEP 4: Post-edit processing
npx claude-flow hook post-edit \
--file "api/auth.js" \
--memory-key "swarm/backend/auth-api" \
--auto-format \
--train-patterns
# STEP 5: Notify coordination system
npx claude-flow hook notify \
--message "Auth API implementation complete" \
--swarm-status \
--broadcast
# STEP 6: Task completion
npx claude-flow hook post-task \
--task-id "auth-api" \
--analyze-performance \
--store-decisions \
--export-learnings
# Agent 2: Test Engineer (receives notification)
# STEP 1: Check memory for API details
npx claude-flow hook session-restore \
--session-id "swarm-current" \
--restore-memory
# Memory contains: swarm/backend/auth-api with implementation details
# STEP 2: Generate tests
npx claude-flow hook pre-task \
--description "Write tests for auth API" \
--load-memory
# STEP 3: Create test file
npx claude-flow hook post-edit \
--file "api/auth.test.js" \
--memory-key "swarm/testing/auth-api-tests" \
--train-patterns
# STEP 4: Share test results
npx claude-flow hook notify \
--message "Auth API tests complete - 100% coverage" \
--broadcast
Create custom hooks for specific workflows:
// .claude/hooks/custom-quality-check.js
module.exports = {
name: 'custom-quality-check',
type: 'pre',
matcher: /\.(ts|js)$/,
async execute(context) {
const { file, content } = context;
// Custom validation logic
const complexity = await analyzeComplexity(content);
const securityIssues = await scanSecurity(content);
// Store in memory
await storeInMemory({
key: `quality/${file}`,
value: { complexity, securityIssues }
});
// Return decision
if (complexity > 15 || securityIssues.length > 0) {
return {
continue: false,
reason: 'Quality checks failed',
warnings: [
`Complexity: ${complexity} (max: 15)`,
`Security issues: ${securityIssues.length}`
]
};
}
return {
continue: true,
reason: 'Quality checks passed',
metadata: { complexity, securityIssues: 0 }
};
}
};
{
"hooks": {
"PreToolUse": [
{
"matcher": "^(Write|Edit)$",
"hooks": [
{
"type": "script",
"script": ".claude/hooks/custom-quality-check.js"
}
]
}
]
}
}
# Session start - initialize coordination
npx claude-flow hook session-start --session-id "fullstack-feature"
# Pre-task planning
npx claude-flow hook pre-task \
--description "Build user profile feature - frontend + backend + tests" \
--auto-spawn-agents \
--optimize-topology
# Backend work
npx claude-flow hook pre-edit --file "api/profile.js"
# ... implement backend ...
npx claude-flow hook post-edit \
--file "api/profile.js" \
--memory-key "profile/backend" \
--train-patterns
# Frontend work (reads backend details from memory)
npx claude-flow hook pre-edit --file "components/Profile.jsx"
# ... implement frontend ...
npx claude-flow hook post-edit \
--file "components/Profile.jsx" \
--memory-key "profile/frontend" \
--train-patterns
# Testing (reads both backend and frontend from memory)
npx claude-flow hook pre-task \
--description "Test profile feature" \
--load-memory
# Session end - export everything
npx claude-flow hook session-end \
--session-id "fullstack-feature" \
--export-metrics \
--generate-summary
# Start debugging session
npx claude-flow hook session-start --session-id "debug-memory-leak"
# Pre-task: analyze issue
npx claude-flow hook pre-task \
--description "Debug memory leak in event handlers" \
--load-memory \
--estimate-complexity
# Search for event emitters
npx claude-flow hook pre-search --query "EventEmitter"
# ... search executes ...
npx claude-flow hook post-search \
--query "EventEmitter" \
--cache-results
# Fix the issue
npx claude-flow hook pre-edit \
--file "services/events.js" \
--backup-file
# ... fix code ...
npx claude-flow hook post-edit \
--file "services/events.js" \
--memory-key "debug/memory-leak-fix" \
--validate-output
# Verify fix
npx claude-flow hook post-task \
--task-id "memory-leak-fix" \
--analyze-performance \
--generate-report
# End session
npx claude-flow hook session-end \
--session-id "debug-memory-leak" \
--export-metrics
# Initialize swarm for refactoring
npx claude-flow hook pre-task \
--description "Refactor legacy codebase to modern patterns" \
--auto-spawn-agents \
--optimize-topology
# Agent 1: Code Analyzer
npx claude-flow hook pre-task --description "Analyze code complexity"
# ... analysis ...
npx claude-flow hook post-task \
--task-id "analysis" \
--store-decisions
# Agent 2: Refactoring (reads analysis from memory)
npx claude-flow hook session-restore \
--session-id "swarm-refactor" \
--restore-memory
for file in src/**/*.js; do
npx claude-flow hook pre-edit --file "$file" --backup-file
# ... refactor ...
npx claude-flow hook post-edit \
--file "$file" \
--memory-key "refactor/$file" \
--auto-format \
--train-patterns
done
# Agent 3: Testing (reads refactored code from memory)
npx claude-flow hook pre-task \
--description "Generate tests for refactored code" \
--load-memory
# Broadcast completion
npx claude-flow hook notify \
--message "Refactoring complete - all tests passing" \
--broadcast
Enable debug mode for troubleshooting:
# Enable debug output
export CLAUDE_FLOW_DEBUG=true
# Test specific hook with verbose output
npx claude-flow hook pre-edit --file "test.js" --debug
# Check hook execution logs
cat .claude-flow/logs/hooks-$(date +%Y-%m-%d).log
# Validate configuration
npx claude-flow hook validate-config
.claude/settings.json syntaxnpx claude-flow init --hooks - Initialize hooks systemnpx claude-flow hook --list - List available hooksnpx claude-flow hook --test <hook> - Test specific hooknpx claude-flow memory usage - Manage memorynpx claude-flow agent spawn - Spawn agentsnpx claude-flow swarm init - Initialize swarmThis skill works seamlessly with:
Weekly Installs
0
Repository
First Seen
Jan 1, 1970
Security Audits
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
103,800 周安装
智能体技能查找与安装指南 - 使用Skills CLI快速扩展AI助手能力
599 周安装
MarkItDown - 微软开源文件转Markdown工具,支持PDF/Word/PPT/图像OCR/音频转录
600 周安装
Stable Diffusion图像生成指南:使用HuggingFace Diffusers库进行AI绘图与图像转换
601 周安装
Claude Code技能改进工具:自动化技能质量审查与修复方法指南
601 周安装
Claude技能创建器 - 官方技能开发工具,AI技能制作与迭代指南
602 周安装
OpenAI图像生成技能:AI绘图、图片编辑与批量生成,支持网站素材、UI设计、产品模型
602 周安装