Hooks Automation について
Hooks Automationは、Claude Codeのフックを設定し、開発操作の検証と調整、セッション管理、学習内容の記録を行います。編集・タスク・検索・セッションのイベントをエージェント連携やメモリに結び付けたいClaude Flowユーザー向けです。
主な機能
- 01操作前・操作後のフック
- 02エージェントの自動割り当てと起動
- 03セッション状態の保存と復元
- 04エージェント間のメモリ連携
- 05フォーマット・検証・Git品質チェック
- 06メトリクス追跡とニューラルパターン学習
活用シーン
- 01実行前のコマンドや編集内容の検証
- 02編集後のファイル整形と検証
- 03コンテキストを復元してセッションを再開
- 04swarmエージェント間でのタスク状態の共有
MCP 対応
フックはClaude FlowのMCPツールを呼び出し、エージェントの起動、メモリ保存、セッション永続化、swarm連携を行えます。任意で設定できるMCPサーバーとして、claude-flow、ruv-swarm、flow-nexusが挙げられています。
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ proffesor-for-testing/ agentic-qe --skill hooks-automationインストール後、Claude Code で/hooks-automationを入力して読み込まれたか確認します。
詳細
フックの自動化
MCP ツールと統合されたフックおよびニューラルパターンのトレーニングを通じて、Claude Code の操作を調整、検証し、そこから学習するインテリジェントな自動化システムです。
このスキルでできること
このスキルは、開発操作を自動的に管理し、スウォームエージェントを調整し、セッション状態を維持し、コーディングパターンから継続的に学習する包括的なフックシステムを提供します。エージェントの自動割り当て、コードのフォーマット、パフォーマンスの追跡、セッションをまたいだメモリの永続化を実現します。
主な機能:
- 操作前フック:操作の前に検証と準備を行い、エージェントを自動割り当てします
- 操作後フック:操作の後にフォーマット、分析、パターンのトレーニングを行います
- セッション管理:状態を永続化し、コンテキストを復元し、要約を生成します
- メモリ調整:スウォームエージェント間でナレッジを同期します
- Git 統合:品質検証を備えたコミットフックを自動化します
- ニューラルトレーニング:成功したパターンから継続的に学習します
- MCP 統合:スウォームツールとシームレスに連携します
前提条件
必須:
- 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 - ファイルを変更する前に検証し、エージェントを割り当てます
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
機能:
- ファイルの種類に基づいてエージェントを自動割り当て
- 構文を検証してコードの破損を防止
- 同時編集における競合を検出
- 安全のためファイルを自動バックアップ
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 - エージェントを自動起動し、複雑なタスクに備えます
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
機能:
- タスクの分析に基づいてエージェントを自動起動
- コンテキストを継続するためにメモリを読み込み
- タスクの構造に合わせてトポロジーを最適化
- 複雑さを推定し、所要時間を予測
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)
- 編集のコンテキストと判断をメモリに保存
- 継続的な改善に向けてニューラルパターンをトレーニング
- リントによる出力の検証
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
機能:
- 実行時間とトークン使用量を測定
- 判断と実装の選択を記録
- ニューラル学習パターンをエクスポート
- 完了レポートを生成
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 スウォームツールと連携するフックです。
mcp-initialized - スウォーム設定を永続化します
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 - エージェント一覧とメモリを更新します
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 - エージェントが調整メモリに書き込むときにトリガーされます
Features:
- Validate memory key format
- Update cross-agent indexes
- Trigger dependent hooks
- Notify subscribed agents
memory-read - エージェントが調整メモリから読み取るときにトリガーされます
Features:
- Log access patterns
- Update popularity metrics
- Preload related data
- Track usage statistics
memory-sync - スウォームエージェント間でメモリを同期します
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
機能:
- 前回のセッションコンテキストを読み込む
- メモリ状態と決定事項を復元する
- エージェントを以前の状態に再構成する
- 進行中のタスクを再開する
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
機能:
- 調整システムに通知を送信する
- スウォームステータスとメトリクスを含める
- すべてのエージェントにブロードキャストする
- 重要なイベントをログに記録する
設定
基本設定
フックを設定するには .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 ツールと自動的に連携します:
エージェント生成を伴うタスク前フック
// 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
メモリ調整プロトコル
すべてのフックは標準化されたメモリ調整パターンに従います:
3 フェーズメモリプロトコル
フェーズ 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 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: マルチエージェントリファクタリング
# 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
パフォーマンスのヒント
- フックを軽量に保つ - 実行時間 100ms 未満を目標にする
- 重い操作には非同期を使用する - メインフローをブロックしない
- 積極的にキャッシュする - 頻繁にアクセスされるデータを保存する
- 関連する操作をバッチ処理する - 複数のアクションを組み合わせる
- メモリを賢く使用する - 適切な TTL を設定する
- フックのパフォーマンスを監視する - 実行時間を追跡する
- 可能な場合は並列化する - 独立したフックを同時に実行する
フックのデバッグ
トラブルシューティングのためにデバッグモードを有効にします:
# 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
メリット
- 自動エージェント割り当て: ファイルタイプごとに適切なエージェント
- 一貫したコードフォーマット: 言語固有のフォーマッター
- 継続的な学習: ニューラルパターンが時間とともに改善される
- セッション間メモリ: コンテキストがセッション間で保持される
- パフォーマンス追跡: 包括的なメトリクスと分析
- 自動調整: エージェントがメモリを介して同期する
- スマートなエージェント生成: タスクベースのエージェント選択
- 品質ゲート: コミット前の検証と確認
- エラー防止: 編集前の構文検証
- 知識共有: 決定事項が保存され共有される
- 手動作業の削減: 反復タスクの自動化
- より良いコラボレーション: シームレスなマルチエージェント調整
ベストプラクティス
- 早期にフックを設定する - プロジェクトの初期化時に設定します
- メモリーキーを戦略的に使用する - 明確な名前空間で整理します
- 自動フォーマットを有効にする - コードの一貫性を維持します
- パターンを継続的に学習する - 成功した操作から学習します
- パフォーマンスを監視する - フックの実行時間を追跡します
- 設定を検証する - 本番環境で使用する前にフックをテストします
- カスタムフックを文書化する - フックのドキュメントを維持します
- 適切なタイムアウトを設定する - 操作のハングを防ぎます
- エラーを適切に処理する - 適切な場合は continueOnError を使用します
- メトリクスを定期的に確認する - 使用パターンに基づいて最適化します
トラブルシューティング
フックが実行されない
.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- エージェントを起動しますnpx claude-flow swarm init- スウォームを初期化します
他のスキルとの統合
このスキルは次のスキルとシームレスに連携します:
- SPARC Methodology - フックによって SPARC ワークフローが強化されます
- Pair Programming - ペアプログラミングセッションで品質を自動化します
- Verification Quality - フックで真偽スコアを検証します
- GitHub Workflows - コミット/PR の Git 統合
- Performance Analysis - フックでメトリクスを収集します
- Swarm Advanced - フックによるマルチエージェントの連携