mcpField
H
Hooks Automation

Hooks Automation

github.com/ruvnetAgent 工作流80.0k1.1k 次安装今天更新
代码仓库

关于 Hooks Automation

Hooks Automation 是用于 Claude Code 的钩子自动化技能,可在操作前后验证、处理并记录开发工作。它还管理会话状态、协调 swarm Agent,并从执行模式中学习。

主要功能

  1. 01操作前验证与 Agent 分配
  2. 02编辑后格式化和校验
  3. 03跨会话状态恢复
  4. 04swarm 记忆同步
  5. 05Git 提交质量检查
  6. 06从模式持续训练

适用场景

  1. 01编辑前检查语法和冲突
  2. 02复杂任务自动分配 Agent
  3. 03保存并恢复开发会话
  4. 04提交时执行质量验证

MCP 相关

通过 MCP 工具协调 swarm Agent、任务、记忆和会话状态;示例中使用 claude-flow MCP 工具进行 Agent 生成与记忆持久化。

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/ruvnet/ruflo --skill hooks-automation

安装后在 Claude Code 中输入/hooks-automation确认已加载。

详细介绍

Hooks 自动化

通过与 MCP 工具集成的钩子和神经模式训练,智能自动化系统可协调、验证 Claude Code 操作并从中学习。

此技能的功能

此技能提供一套全面的钩子系统,可自动管理开发操作、协调 swarm Agent、维护会话状态,并持续学习编码模式。它支持自动分配 Agent、格式化代码、跟踪性能以及跨会话持久保存记忆。

主要功能:

  • 操作前钩子:在操作前进行验证、准备并自动分配 Agent
  • 操作后钩子:在操作后格式化、分析并训练模式
  • 会话管理:持久保存状态、恢复上下文并生成摘要
  • 记忆协调:在 swarm Agent 之间同步知识
  • Git 集成:提供带质量验证的自动化提交钩子
  • 神经训练:从成功模式中持续学习
  • MCP 集成:与 swarm 工具无缝协调

先决条件

必需:

  • 已安装 Claude Flow CLI(npm install -g claude-flow@alpha)
  • 已启用钩子的 Claude Code
  • 包含钩子配置的 .claude$settings.json

可选:

  • 已配置 MCP 服务(claude-flow、ruv-swarm、flow-nexus)
  • 用于版本控制的 Git 仓库
  • 用于质量验证的测试框架

快速入门

初始化钩子系统
# Initialize with default hooks configuration
npx claude-flow init --hooks

这将创建:

  • .claude$settings.json,其中包含预配置的钩子
  • .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

完整指南

可用钩子
操作前钩子

这些钩子会在操作执行前运行,用于准备和验证:

pre-edit - 在修改文件前验证并分配 Agent

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

功能:

  • 根据文件类型自动分配 Agent
  • 通过语法验证防止代码损坏
  • 检测并发编辑冲突
  • 自动备份文件以确保安全

pre-bash - 检查命令安全性和资源需求

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

功能:

  • 命令安全性验证
  • 资源需求估算
  • 破坏性命令确认
  • 权限检查

pre-task - 自动启动 Agent 并为复杂任务做好准备

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

功能:

  • 根据任务分析自动启动 Agent
  • 加载记忆以保持上下文连续性
  • 针对任务结构优化拓扑
  • 估算复杂度并预测耗时

pre-search - 准备并优化搜索操作

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"

功能:

  • 检查缓存以加快结果返回
  • 优化查询
  • 改进搜索模式
操作后钩子

这些钩子会在操作执行后运行,用于处理并学习:

post-edit - 自动格式化、验证并更新记忆

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

功能:

  • 按语言自动格式化(Prettier、Black、gofmt)
  • 保存编辑上下文和决策的记忆
  • 通过神经模式训练持续改进
  • 通过 lint 检查验证输出

post-bash - 记录执行情况并更新指标

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

功能:

  • 记录命令执行情况
  • 跟踪性能指标
  • 存储结果以供分析
  • 检测错误模式

post-task - 分析性能并存储决策

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

功能:

  • 测量执行时间和 token 用量
  • 记录决策和实现方案选择
  • 导出神经学习模式
  • 生成完成报告

post-search - 缓存结果并改进模式

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

功能:

  • 缓存结果以加快后续搜索
  • 改进搜索模式
  • 评估相关性
MCP 集成钩子

这些钩子会与 MCP swarm 工具协调:

mcp-initialized - 持久保存 swarm 配置

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 - 更新 Agent 名册和记忆

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 - 监控任务进度

npx claude-flow hook task-orchestrated --task-id <id>

Features:
- Track task progress through memory
- Monitor agent assignments
- Update coordination state

neural-trained - 保存模式改进

npx claude-flow hook neural-trained --pattern <name>

Features:
- Export trained neural patterns
- Update coordination models
- Share learning across agents
记忆协调钩子

memory-write - 在 Agent 写入协调记忆时触发

Features:
- Validate memory key format
- Update cross-agent indexes
- Trigger dependent hooks
- Notify subscribed agents

memory-read - 在 Agent 读取协调记忆时触发

Features:
- Log access patterns
- Update popularity metrics
- Preload related data
- Track usage statistics

memory-sync - 在群组 Agent 之间同步记忆

npx claude-flow hook memory-sync --namespace <ns>

Features:
- Sync memory state across agents
- Resolve conflicts
- Propagate updates
- Maintain consistency
会话钩子

session-start - 初始化新会话

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 - 加载之前的会话状态

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

功能:

  • 加载之前的会话上下文
  • 恢复记忆状态和决策
  • 将 Agent 重新配置为之前的状态
  • 恢复进行中的任务

session-end - 清理并持久化会话状态

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

功能:

  • 保存当前上下文和进度
  • 导出会话指标(时长、命令、令牌、文件)
  • 生成包含决策和后续步骤的工作摘要
  • 清理临时文件并优化存储

notify - 发送包含群组状态的自定义通知

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

功能:

  • 向协调系统发送通知
  • 包含群组状态和指标
  • 向所有 Agent 广播
  • 记录重要事件
配置
基本配置

编辑 .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 工具集成

钩子会自动与 MCP 工具集成以进行协调:

带有 Agent 派生的任务前钩子
// 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
记忆协调协议

所有钩子都遵循标准化的记忆协调模式:

三阶段记忆协议

阶段 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": "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
  }
}
Git 集成

钩子可以与 Git 操作集成以进行质量控制:

提交前钩子
# 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
Agent 协调工作流

Agent 如何使用钩子进行协调:

Agent 工作流示例
# 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
创建自定义钩子

为特定工作流创建自定义钩子:

自定义钩子模板
// .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"
          }
        ]
      }
    ]
  }
}
实际示例
示例 1:全栈开发工作流
# 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
示例 2:使用钩子进行调试
# 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
示例 3:多 Agent 重构
# 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
性能提示
  1. 保持钩子轻量 - 目标执行时间 < 100ms
  2. 对繁重操作使用异步处理 - 不要阻塞主流程
  3. 积极使用缓存 - 存储经常访问的数据
  4. 批量处理相关操作 - 合并多个操作
  5. 合理使用记忆 - 设置适当的 TTL
  6. 监控钩子性能 - 跟踪执行时间
  7. 尽可能并行执行 - 并发运行互不依赖的钩子
调试钩子

启用调试模式以排查问题:

# 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
优势
  • 自动分配 Agent:为每种文件类型分配合适的 Agent
  • 统一代码格式:使用针对特定语言的格式化工具
  • 持续学习:神经模式会随时间不断改进
  • 跨会话记忆:会话之间保留上下文
  • 性能跟踪:全面的指标和分析
  • 自动协调:Agent 通过记忆进行同步
  • 智能派生 Agent:根据任务选择 Agent
  • 质量门禁:提交前验证和检查
  • 预防错误:编辑前验证语法
  • 知识共享:存储并共享决策
  • 减少手动工作:自动执行重复性任务
  • 提升协作:多 Agent 无缝协调
最佳实践
  1. 尽早配置钩子 - 在项目初始化期间进行设置
  2. 策略性地使用内存键 - 使用清晰的命名空间进行组织
  3. 启用自动格式化 - 保持代码一致性
  4. 持续训练模式 - 从成功的操作中学习
  5. 监控性能 - 跟踪钩子执行时间
  6. 验证配置 - 在投入生产使用前测试钩子
  7. 记录自定义钩子 - 维护钩子文档
  8. 设置适当的超时时间 - 防止操作挂起
  9. 妥善处理错误 - 适当时使用 continueOnError
  10. 定期查看指标 - 根据使用模式进行优化
故障排除
钩子未执行
  • 验证 .claude$settings.json 语法
  • 检查钩子匹配模式
  • 启用调试模式
  • 查看权限设置
  • 确保 claude-flow CLI 位于 PATH 中
钩子超时
  • 在配置中增加超时时间
  • 对繁重操作使用异步钩子
  • 优化钩子逻辑
  • 检查 MCP 工具的网络连接
内存问题
  • 为内存键设置适当的 TTL
  • 清理旧的内存条目
  • 有效使用内存命名空间
  • 监控内存使用情况
性能问题
  • 分析钩子执行时间
  • 对重复操作使用缓存
  • 尽可能批量处理操作
  • 降低钩子的复杂度
相关命令
  • npx claude-flow init --hooks - 初始化钩子系统
  • npx claude-flow hook --list - 列出可用钩子
  • npx claude-flow hook --test <hook> - 测试指定钩子
  • npx claude-flow memory usage - 管理内存
  • npx claude-flow agent spawn - 生成 Agent
  • npx claude-flow swarm init - 初始化群体
与其他技能集成

此技能可与以下内容无缝协作:

  • SPARC Methodology - 钩子可增强 SPARC 工作流
  • Pair Programming - 在结对编程过程中自动保障质量
  • Verification Quality - 在钩子中验证真值评分
  • GitHub Workflows - 为提交/PR 提供 Git 集成
  • Performance Analysis - 在钩子中收集指标
  • Swarm Advanced - 通过钩子实现多 Agent 协调

评论

支持 Markdown