Hooks automation skill

Automated coordination, formatting, and learning from Claude Code operations using intelligent hooks with MCP integration.

by ruvnet·MIT license·★ 94,702 Stars on the repo·GitHub ↗

Use now

Files of Hooks automation

ruvnet/main1 file shown
SKILL.md
Show the full text1202 lines

Hooks Automation

Intelligent automation system that coordinates, validates, and learns from Claude Code operations through hooks integrated with MCP tools and neural pattern training.

What This Skill Does

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:

  • Pre-Operation Hooks: Validate, prepare, and auto-assign agents before operations
  • Post-Operation Hooks: Format, analyze, and train patterns after operations
  • Session Management: Persist state, restore context, generate summaries
  • Memory Coordination: Synchronize knowledge across swarm agents
  • Git Integration: Automated commit hooks with quality verification
  • Neural Training: Continuous learning from successful patterns
  • MCP Integration: Seamless coordination with swarm tools

Prerequisites

Required:

  • Claude Flow CLI installed (npm install -g claude-flow@alpha)
  • Claude Code with hooks enabled
  • .claude/settings.json with hook configurations

Optional:

  • MCP servers configured (claude-flow, ruv-swarm, flow-nexus)
  • Git repository for version control
  • Testing framework for quality verification

Quick Start

Initialize Hooks System
# Initialize with default hooks configuration
npx claude-flow init --hooks

This creates:

  • .claude/settings.json with pre-configured hooks
  • Hook command documentation in .claude/commands/hooks/
  • Default hook handlers for common operations
Basic Hook Usage
# 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

Complete Guide

Available Hooks
Pre-Operation Hooks

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:

  • Auto agent assignment based on file type
  • Syntax validation to prevent broken code
  • Conflict detection for concurrent edits
  • Automatic file backups for safety

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:

  • Command safety validation
  • Resource requirement estimation
  • Destructive command confirmation
  • Permission checks

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:

  • Automatic agent spawning based on task analysis
  • Memory loading for context continuity
  • Topology optimization for task structure
  • Complexity estimation and time prediction

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:

  • Cache checking for faster results
  • Query optimization
  • Search pattern improvement
Post-Operation Hooks

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:

  • Language-specific auto-formatting (Prettier, Black, gofmt)
  • Memory storage for edit context and decisions
  • Neural pattern training for continuous improvement
  • Output validation with linting

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:

  • Command execution logging
  • Performance metric tracking
  • Result storage for analysis
  • Error pattern detection

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:

  • Execution time and token usage measurement
  • Decision and implementation choice recording
  • Neural learning pattern export
  • Completion report generation

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:

  • Result caching for faster subsequent searches
  • Search pattern improvement
  • Relevance scoring
MCP Integration Hooks

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 Coordination Hooks

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 Hooks

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:

  • Load previous session context
  • Restore memory state and decisions
  • Reconfigure agents to previous state
  • Resume in-progress tasks

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:

  • Save current context and progress
  • Export session metrics (duration, commands, tokens, files)
  • Generate work summary with decisions and next steps
  • Cleanup temporary files and optimize storage

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:

  • Send notifications to coordination system
  • Include swarm status and metrics
  • Broadcast to all agents
  • Log important events
Configuration
Basic Configuration

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"
        }]
      }
    ]
  }
}
Advanced Configuration

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"
          }
        ]
      }
    ]
  }
}
Protected File Patterns

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}'"
          }
        ]
      }
    ]
  }
}
Automatic Testing

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
          }
        ]
      }
    ]
  }
}
MCP Tool Integration

Hooks automatically integrate with MCP tools for coordination:

Pre-Task Hook with Agent Spawning
// 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()
  })
}
Post-Edit Hook with Memory Storage
// 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 */ }
}
Session End Hook with State Persistence
// 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
Memory Coordination Protocol

All hooks follow a standardized memory coordination pattern:

Three-Phase Memory Protocol

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
  })
}
Hook Response Format

Hooks return JSON responses to control operation flow:

Continue Response
{
  "continue": true,
  "reason": "All validations passed",
  "metadata": {
    "agent_assigned": "backend-dev",
    "syntax_valid": true,
    "file": "src/auth.js"
  }
}
Block Response
{
  "continue": false,
  "reason": "Protected file - manual review required",
  "metadata": {
    "file": ".env.production",
    "protection_level": "high",
    "requires": "manual_approval"
  }
}
Warning Response
{
  "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 Integration

Hooks can integrate with Git operations for quality control:

Pre-Commit Hook
# 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 $?
Post-Commit Hook
# 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
Pre-Push Hook
# 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 Coordination Workflow

How agents use hooks for coordination:

Agent Workflow Example
# 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
Custom Hook Creation

Create custom hooks for specific workflows:

Custom Hook Template
// .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 }
    };
  }
};
Register Custom Hook
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "^(Write|Edit)$",
        "hooks": [
          {
            "type": "script",
            "script": ".claude/hooks/custom-quality-check.js"
          }
        ]
      }
    ]
  }
}
Real-World Examples
Example 1: Full-Stack Development Workflow
# 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
Example 2: Debugging with Hooks
# 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
Example 3: Multi-Agent Refactoring
# 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
Performance Tips
  1. Keep Hooks Lightweight - Target < 100ms execution time
  2. Use Async for Heavy Operations - Don't block the main flow
  3. Cache Aggressively - Store frequently accessed data
  4. Batch Related Operations - Combine multiple actions
  5. Use Memory Wisely - Set appropriate TTLs
  6. Monitor Hook Performance - Track execution times
  7. Parallelize When Possible - Run independent hooks concurrently
Debugging Hooks

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
Benefits
  • Automatic Agent Assignment: Right agent for every file type
  • Consistent Code Formatting: Language-specific formatters
  • Continuous Learning: Neural patterns improve over time
  • Cross-Session Memory: Context persists between sessions
  • Performance Tracking: Comprehensive metrics and analytics
  • Automatic Coordination: Agents sync via memory
  • Smart Agent Spawning: Task-based agent selection
  • Quality Gates: Pre-commit validation and verification
  • Error Prevention: Syntax validation before edits
  • Knowledge Sharing: Decisions stored and shared
  • Reduced Manual Work: Automation of repetitive tasks
  • Better Collaboration: Seamless multi-agent coordination
Best Practices
  1. Configure Hooks Early - Set up during project initialization
  2. Use Memory Keys Strategically - Organize with clear namespaces
  3. Enable Auto-Formatting - Maintain code consistency
  4. Train Patterns Continuously - Learn from successful operations
  5. Monitor Performance - Track hook execution times
  6. Validate Configuration - Test hooks before production use
  7. Document Custom Hooks - Maintain hook documentation
  8. Set Appropriate Timeouts - Prevent hanging operations
  9. Handle Errors Gracefully - Use continueOnError when appropriate
  10. Review Metrics Regularly - Optimize based on usage patterns
Troubleshooting
Hooks Not Executing
  • Verify .claude/settings.json syntax
  • Check hook matcher patterns
  • Enable debug mode
  • Review permission settings
  • Ensure claude-flow CLI is in PATH
Hook Timeouts
  • Increase timeout values in configuration
  • Make hooks asynchronous for heavy operations
  • Optimize hook logic
  • Check network connectivity for MCP tools
Memory Issues
  • Set appropriate TTLs for memory keys
  • Clean up old memory entries
  • Use memory namespaces effectively
  • Monitor memory usage
Performance Problems
  • Profile hook execution times
  • Use caching for repeated operations
  • Batch operations when possible
  • Reduce hook complexity
  • npx claude-flow init --hooks - Initialize hooks system
  • npx claude-flow hook --list - List available hooks
  • npx claude-flow hook --test <hook> - Test specific hook
  • npx claude-flow memory usage - Manage memory
  • npx claude-flow agent spawn - Spawn agents
  • npx claude-flow swarm init - Initialize swarm
Integration with Other Skills

This skill works seamlessly with:

  • SPARC Methodology - Hooks enhance SPARC workflows
  • Pair Programming - Automated quality in pairing sessions
  • Verification Quality - Truth-score validation in hooks
  • GitHub Workflows - Git integration for commits/PRs
  • Performance Analysis - Metrics collection in hooks
  • Swarm Advanced - Multi-agent coordination via hooks
1---
2name: Hooks Automation
3description: Automated coordination, formatting, and learning from Claude Code operations using intelligent hooks with MCP integration. Includes pre/post task hooks, session management, Git integration, memory coordination, and neural pattern training for enhanced development workflows.
4---
5 
6# Hooks Automation
7 
8Intelligent automation system that coordinates, validates, and learns from Claude Code operations through hooks integrated with MCP tools and neural pattern training.
9 
10## What This Skill Does
11 
12This 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.
13 
14**Key Capabilities:**
15- **Pre-Operation Hooks**: Validate, prepare, and auto-assign agents before operations
16- **Post-Operation Hooks**: Format, analyze, and train patterns after operations
17- **Session Management**: Persist state, restore context, generate summaries
18- **Memory Coordination**: Synchronize knowledge across swarm agents
19- **Git Integration**: Automated commit hooks with quality verification
20- **Neural Training**: Continuous learning from successful patterns
21- **MCP Integration**: Seamless coordination with swarm tools
22 
23## Prerequisites
24 
25**Required:**
26- Claude Flow CLI installed (`npm install -g claude-flow@alpha`)
27- Claude Code with hooks enabled
28- `.claude/settings.json` with hook configurations
29 
30**Optional:**
31- MCP servers configured (claude-flow, ruv-swarm, flow-nexus)
32- Git repository for version control
33- Testing framework for quality verification
34 
35## Quick Start
36 
37### Initialize Hooks System
38 
39```bash
40# Initialize with default hooks configuration
41npx claude-flow init --hooks
42```
43 
44This creates:
45- `.claude/settings.json` with pre-configured hooks
46- Hook command documentation in `.claude/commands/hooks/`
47- Default hook handlers for common operations
48 
49### Basic Hook Usage
50 
51```bash
52# Pre-task hook (auto-spawns agents)
53npx claude-flow hook pre-task --description "Implement authentication"
54 
55# Post-edit hook (auto-formats and stores in memory)
56npx claude-flow hook post-edit --file "src/auth.js" --memory-key "auth/login"
57 
58# Session end hook (saves state and metrics)
59npx claude-flow hook session-end --session-id "dev-session" --export-metrics
60```
61 
62---
63 
64## Complete Guide
65 
66### Available Hooks
67 
68#### Pre-Operation Hooks
69 
70Hooks that execute BEFORE operations to prepare and validate:
71 
72**pre-edit** - Validate and assign agents before file modifications
73```bash
74npx claude-flow hook pre-edit [options]
75 
76Options:
77 --file, -f <path> File path to be edited
78 --auto-assign-agent Automatically assign best agent (default: true)
79 --validate-syntax Pre-validate syntax before edit
80 --check-conflicts Check for merge conflicts
81 --backup-file Create backup before editing
82 
83Examples:
84 npx claude-flow hook pre-edit --file "src/auth/login.js"
85 npx claude-flow hook pre-edit -f "config/db.js" --validate-syntax
86 npx claude-flow hook pre-edit -f "production.env" --backup-file --check-conflicts
87```
88 
89**Features:**
90- Auto agent assignment based on file type
91- Syntax validation to prevent broken code
92- Conflict detection for concurrent edits
93- Automatic file backups for safety
94 
95**pre-bash** - Check command safety and resource requirements
96```bash
97npx claude-flow hook pre-bash --command <cmd>
98 
99Options:
100 --command, -c <cmd> Command to validate
101 --check-safety Verify command safety (default: true)
102 --estimate-resources Estimate resource usage
103 --require-confirmation Request user confirmation for risky commands
104 
105Examples:
106 npx claude-flow hook pre-bash -c "rm -rf /tmp/cache"
107 npx claude-flow hook pre-bash --command "docker build ." --estimate-resources
108```
109 
110**Features:**
111- Command safety validation
112- Resource requirement estimation
113- Destructive command confirmation
114- Permission checks
115 
116**pre-task** - Auto-spawn agents and prepare for complex tasks
117```bash
118npx claude-flow hook pre-task [options]
119 
120Options:
121 --description, -d <text> Task description for context
122 --auto-spawn-agents Automatically spawn required agents (default: true)
123 --load-memory Load relevant memory from previous sessions
124 --optimize-topology Select optimal swarm topology
125 --estimate-complexity Analyze task complexity
126 
127Examples:
128 npx claude-flow hook pre-task --description "Implement user authentication"
129 npx claude-flow hook pre-task -d "Continue API dev" --load-memory
130 npx claude-flow hook pre-task -d "Refactor codebase" --optimize-topology
131```
132 
133**Features:**
134- Automatic agent spawning based on task analysis
135- Memory loading for context continuity
136- Topology optimization for task structure
137- Complexity estimation and time prediction
138 
139**pre-search** - Prepare and optimize search operations
140```bash
141npx claude-flow hook pre-search --query <query>
142 
143Options:
144 --query, -q <text> Search query
145 --check-cache Check cache first (default: true)
146 --optimize-query Optimize search pattern
147 
148Examples:
149 npx claude-flow hook pre-search -q "authentication middleware"
150```
151 
152**Features:**
153- Cache checking for faster results
154- Query optimization
155- Search pattern improvement
156 
157#### Post-Operation Hooks
158 
159Hooks that execute AFTER operations to process and learn:
160 
161**post-edit** - Auto-format, validate, and update memory
162```bash
163npx claude-flow hook post-edit [options]
164 
165Options:
166 --file, -f <path> File path that was edited
167 --auto-format Automatically format code (default: true)
168 --memory-key, -m <key> Store edit context in memory
169 --train-patterns Train neural patterns from edit
170 --validate-output Validate edited file
171 
172Examples:
173 npx claude-flow hook post-edit --file "src/components/Button.jsx"
174 npx claude-flow hook post-edit -f "api/auth.js" --memory-key "auth/login"
175 npx claude-flow hook post-edit -f "utils/helpers.ts" --train-patterns
176```
177 
178**Features:**
179- Language-specific auto-formatting (Prettier, Black, gofmt)
180- Memory storage for edit context and decisions
181- Neural pattern training for continuous improvement
182- Output validation with linting
183 
184**post-bash** - Log execution and update metrics
185```bash
186npx claude-flow hook post-bash --command <cmd>
187 
188Options:
189 --command, -c <cmd> Command that was executed
190 --log-output Log command output (default: true)
191 --update-metrics Update performance metrics
192 --store-result Store result in memory
193 
194Examples:
195 npx claude-flow hook post-bash -c "npm test" --update-metrics
196```
197 
198**Features:**
199- Command execution logging
200- Performance metric tracking
201- Result storage for analysis
202- Error pattern detection
203 
204**post-task** - Performance analysis and decision storage
205```bash
206npx claude-flow hook post-task [options]
207 
208Options:
209 --task-id, -t <id> Task identifier for tracking
210 --analyze-performance Generate performance metrics (default: true)
211 --store-decisions Save task decisions to memory
212 --export-learnings Export neural pattern learnings
213 --generate-report Create task completion report
214 
215Examples:
216 npx claude-flow hook post-task --task-id "auth-implementation"
217 npx claude-flow hook post-task -t "api-refactor" --analyze-performance
218 npx claude-flow hook post-task -t "bug-fix-123" --store-decisions
219```
220 
221**Features:**
222- Execution time and token usage measurement
223- Decision and implementation choice recording
224- Neural learning pattern export
225- Completion report generation
226 
227**post-search** - Cache results and improve patterns
228```bash
229npx claude-flow hook post-search --query <query> --results <path>
230 
231Options:
232 --query, -q <text> Original search query
233 --results, -r <path> Results file path
234 --cache-results Cache for future use (default: true)
235 --train-patterns Improve search patterns
236 
237Examples:
238 npx claude-flow hook post-search -q "auth" -r "results.json" --train-patterns
239```
240 
241**Features:**
242- Result caching for faster subsequent searches
243- Search pattern improvement
244- Relevance scoring
245 
246#### MCP Integration Hooks
247 
248Hooks that coordinate with MCP swarm tools:
249 
250**mcp-initialized** - Persist swarm configuration
251```bash
252npx claude-flow hook mcp-initialized --swarm-id <id>
253 
254Features:
255- Save swarm topology and configuration
256- Store agent roster in memory
257- Initialize coordination namespace
258```
259 
260**agent-spawned** - Update agent roster and memory
261```bash
262npx claude-flow hook agent-spawned --agent-id <id> --type <type>
263 
264Features:
265- Register agent in coordination memory
266- Update agent roster
267- Initialize agent-specific memory namespace
268```
269 
270**task-orchestrated** - Monitor task progress
271```bash
272npx claude-flow hook task-orchestrated --task-id <id>
273 
274Features:
275- Track task progress through memory
276- Monitor agent assignments
277- Update coordination state
278```
279 
280**neural-trained** - Save pattern improvements
281```bash
282npx claude-flow hook neural-trained --pattern <name>
283 
284Features:
285- Export trained neural patterns
286- Update coordination models
287- Share learning across agents
288```
289 
290#### Memory Coordination Hooks
291 
292**memory-write** - Triggered when agents write to coordination memory
293```bash
294Features:
295- Validate memory key format
296- Update cross-agent indexes
297- Trigger dependent hooks
298- Notify subscribed agents
299```
300 
301**memory-read** - Triggered when agents read from coordination memory
302```bash
303Features:
304- Log access patterns
305- Update popularity metrics
306- Preload related data
307- Track usage statistics
308```
309 
310**memory-sync** - Synchronize memory across swarm agents
311```bash
312npx claude-flow hook memory-sync --namespace <ns>
313 
314Features:
315- Sync memory state across agents
316- Resolve conflicts
317- Propagate updates
318- Maintain consistency
319```
320 
321#### Session Hooks
322 
323**session-start** - Initialize new session
324```bash
325npx claude-flow hook session-start --session-id <id>
326 
327Options:
328 --session-id, -s <id> Session identifier
329 --load-context Load context from previous session
330 --init-agents Initialize required agents
331 
332Features:
333- Create session directory
334- Initialize metrics tracking
335- Load previous context
336- Set up coordination namespace
337```
338 
339**session-restore** - Load previous session state
340```bash
341npx claude-flow hook session-restore --session-id <id>
342 
343Options:
344 --session-id, -s <id> Session to restore
345 --restore-memory Restore memory state (default: true)
346 --restore-agents Restore agent configurations
347 
348Examples:
349 npx claude-flow hook session-restore --session-id "swarm-20241019"
350 npx claude-flow hook session-restore -s "feature-auth" --restore-memory
351```
352 
353**Features:**
354- Load previous session context
355- Restore memory state and decisions
356- Reconfigure agents to previous state
357- Resume in-progress tasks
358 
359**session-end** - Cleanup and persist session state
360```bash
361npx claude-flow hook session-end [options]
362 
363Options:
364 --session-id, -s <id> Session identifier to end
365 --save-state Save current session state (default: true)
366 --export-metrics Export session metrics
367 --generate-summary Create session summary
368 --cleanup-temp Remove temporary files
369 
370Examples:
371 npx claude-flow hook session-end --session-id "dev-session-2024"
372 npx claude-flow hook session-end -s "feature-auth" --export-metrics --generate-summary
373 npx claude-flow hook session-end -s "quick-fix" --cleanup-temp
374```
375 
376**Features:**
377- Save current context and progress
378- Export session metrics (duration, commands, tokens, files)
379- Generate work summary with decisions and next steps
380- Cleanup temporary files and optimize storage
381 
382**notify** - Custom notifications with swarm status
383```bash
384npx claude-flow hook notify --message <msg>
385 
386Options:
387 --message, -m <text> Notification message
388 --level <level> Notification level (info|warning|error)
389 --swarm-status Include swarm status (default: true)
390 --broadcast Send to all agents
391 
392Examples:
393 npx claude-flow hook notify -m "Task completed" --level info
394 npx claude-flow hook notify -m "Critical error" --level error --broadcast
395```
396 
397**Features:**
398- Send notifications to coordination system
399- Include swarm status and metrics
400- Broadcast to all agents
401- Log important events
402 
403### Configuration
404 
405#### Basic Configuration
406 
407Edit `.claude/settings.json` to configure hooks:
408 
409```json
410{
411 "hooks": {
412 "PreToolUse": [
413 {
414 "matcher": "^(Write|Edit|MultiEdit)$",
415 "hooks": [{
416 "type": "command",
417 "command": "npx claude-flow hook pre-edit --file '${tool.params.file_path}' --memory-key 'swarm/editor/current'"
418 }]
419 },
420 {
421 "matcher": "^Bash$",
422 "hooks": [{
423 "type": "command",
424 "command": "npx claude-flow hook pre-bash --command '${tool.params.command}'"
425 }]
426 }
427 ],
428 "PostToolUse": [
429 {
430 "matcher": "^(Write|Edit|MultiEdit)$",
431 "hooks": [{
432 "type": "command",
433 "command": "npx claude-flow hook post-edit --file '${tool.params.file_path}' --memory-key 'swarm/editor/complete' --auto-format --train-patterns"
434 }]
435 },
436 {
437 "matcher": "^Bash$",
438 "hooks": [{
439 "type": "command",
440 "command": "npx claude-flow hook post-bash --command '${tool.params.command}' --update-metrics"
441 }]
442 }
443 ]
444 }
445}
446```
447 
448#### Advanced Configuration
449 
450Complete hook configuration with all features:
451 
452```json
453{
454 "hooks": {
455 "enabled": true,
456 "debug": false,
457 "timeout": 5000,
458 
459 "PreToolUse": [
460 {
461 "matcher": "^(Write|Edit|MultiEdit)$",
462 "hooks": [
463 {
464 "type": "command",
465 "command": "npx claude-flow hook pre-edit --file '${tool.params.file_path}' --auto-assign-agent --validate-syntax",
466 "timeout": 3000,
467 "continueOnError": true
468 }
469 ]
470 },
471 {
472 "matcher": "^Task$",
473 "hooks": [
474 {
475 "type": "command",
476 "command": "npx claude-flow hook pre-task --description '${tool.params.task}' --auto-spawn-agents --load-memory",
477 "async": true
478 }
479 ]
480 },
481 {
482 "matcher": "^Grep$",
483 "hooks": [
484 {
485 "type": "command",
486 "command": "npx claude-flow hook pre-search --query '${tool.params.pattern}' --check-cache"
487 }
488 ]
489 }
490 ],
491 
492 "PostToolUse": [
493 {
494 "matcher": "^(Write|Edit|MultiEdit)$",
495 "hooks": [
496 {
497 "type": "command",
498 "command": "npx claude-flow hook post-edit --file '${tool.params.file_path}' --memory-key 'edits/${tool.params.file_path}' --auto-format --train-patterns",
499 "async": true
500 }
501 ]
502 },
503 {
504 "matcher": "^Task$",
505 "hooks": [
506 {
507 "type": "command",
508 "command": "npx claude-flow hook post-task --task-id '${result.task_id}' --analyze-performance --store-decisions --export-learnings",
509 "async": true
510 }
511 ]
512 },
513 {
514 "matcher": "^Grep$",
515 "hooks": [
516 {
517 "type": "command",
518 "command": "npx claude-flow hook post-search --query '${tool.params.pattern}' --cache-results --train-patterns"
519 }
520 ]
521 }
522 ],
523 
524 "SessionStart": [
525 {
526 "hooks": [
527 {
528 "type": "command",
529 "command": "npx claude-flow hook session-start --session-id '${session.id}' --load-context"
530 }
531 ]
532 }
533 ],
534 
535 "SessionEnd": [
536 {
537 "hooks": [
538 {
539 "type": "command",
540 "command": "npx claude-flow hook session-end --session-id '${session.id}' --export-metrics --generate-summary --cleanup-temp"
541 }
542 ]
543 }
544 ]
545 }
546}
547```
548 
549#### Protected File Patterns
550 
551Add protection for sensitive files:
552 
553```json
554{
555 "hooks": {
556 "PreToolUse": [
557 {
558 "matcher": "^(Write|Edit|MultiEdit)$",
559 "hooks": [
560 {
561 "type": "command",
562 "command": "npx claude-flow hook check-protected --file '${tool.params.file_path}'"
563 }
564 ]
565 }
566 ]
567 }
568}
569```
570 
571#### Automatic Testing
572 
573Run tests after file modifications:
574 
575```json
576{
577 "hooks": {
578 "PostToolUse": [
579 {
580 "matcher": "^Write$",
581 "hooks": [
582 {
583 "type": "command",
584 "command": "test -f '${tool.params.file_path%.js}.test.js' && npm test '${tool.params.file_path%.js}.test.js'",
585 "continueOnError": true
586 }
587 ]
588 }
589 ]
590 }
591}
592```
593 
594### MCP Tool Integration
595 
596Hooks automatically integrate with MCP tools for coordination:
597 
598#### Pre-Task Hook with Agent Spawning
599 
600```javascript
601// Hook command
602npx claude-flow hook pre-task --description "Build REST API"
603 
604// Internally calls MCP tools:
605mcp__claude-flow__agent_spawn {
606 type: "backend-dev",
607 capabilities: ["api", "database", "testing"]
608}
609 
610mcp__claude-flow__memory_usage {
611 action: "store",
612 key: "swarm/task/api-build/context",
613 namespace: "coordination",
614 value: JSON.stringify({
615 description: "Build REST API",
616 agents: ["backend-dev"],
617 started: Date.now()
618 })
619}
620```
621 
622#### Post-Edit Hook with Memory Storage
623 
624```javascript
625// Hook command
626npx claude-flow hook post-edit --file "api/auth.js"
627 
628// Internally calls MCP tools:
629mcp__claude-flow__memory_usage {
630 action: "store",
631 key: "swarm/edits/api/auth.js",
632 namespace: "coordination",
633 value: JSON.stringify({
634 file: "api/auth.js",
635 timestamp: Date.now(),
636 changes: { added: 45, removed: 12 },
637 formatted: true,
638 linted: true
639 })
640}
641 
642mcp__claude-flow__neural_train {
643 pattern_type: "coordination",
644 training_data: { /* edit patterns */ }
645}
646```
647 
648#### Session End Hook with State Persistence
649 
650```javascript
651// Hook command
652npx claude-flow hook session-end --session-id "dev-2024"
653 
654// Internally calls MCP tools:
655mcp__claude-flow__memory_persist {
656 sessionId: "dev-2024"
657}
658 
659mcp__claude-flow__swarm_status {
660 swarmId: "current"
661}
662 
663// Generates metrics and summary
664```
665 
666### Memory Coordination Protocol
667 
668All hooks follow a standardized memory coordination pattern:
669 
670#### Three-Phase Memory Protocol
671 
672**Phase 1: STATUS** - Hook starts
673```javascript
674mcp__claude-flow__memory_usage {
675 action: "store",
676 key: "swarm/hooks/pre-edit/status",
677 namespace: "coordination",
678 value: JSON.stringify({
679 status: "running",
680 hook: "pre-edit",
681 file: "src/auth.js",
682 timestamp: Date.now()
683 })
684}
685```
686 
687**Phase 2: PROGRESS** - Hook processes
688```javascript
689mcp__claude-flow__memory_usage {
690 action: "store",
691 key: "swarm/hooks/pre-edit/progress",
692 namespace: "coordination",
693 value: JSON.stringify({
694 progress: 50,
695 action: "validating syntax",
696 file: "src/auth.js"
697 })
698}
699```
700 
701**Phase 3: COMPLETE** - Hook finishes
702```javascript
703mcp__claude-flow__memory_usage {
704 action: "store",
705 key: "swarm/hooks/pre-edit/complete",
706 namespace: "coordination",
707 value: JSON.stringify({
708 status: "complete",
709 result: "success",
710 agent_assigned: "backend-dev",
711 syntax_valid: true,
712 backup_created: true
713 })
714}
715```
716 
717### Hook Response Format
718 
719Hooks return JSON responses to control operation flow:
720 
721#### Continue Response
722```json
723{
724 "continue": true,
725 "reason": "All validations passed",
726 "metadata": {
727 "agent_assigned": "backend-dev",
728 "syntax_valid": true,
729 "file": "src/auth.js"
730 }
731}
732```
733 
734#### Block Response
735```json
736{
737 "continue": false,
738 "reason": "Protected file - manual review required",
739 "metadata": {
740 "file": ".env.production",
741 "protection_level": "high",
742 "requires": "manual_approval"
743 }
744}
745```
746 
747#### Warning Response
748```json
749{
750 "continue": true,
751 "reason": "Syntax valid but complexity high",
752 "warnings": [
753 "Cyclomatic complexity: 15 (threshold: 10)",
754 "Consider refactoring for better maintainability"
755 ],
756 "metadata": {
757 "complexity": 15,
758 "threshold": 10
759 }
760}
761```
762 
763### Git Integration
764 
765Hooks can integrate with Git operations for quality control:
766 
767#### Pre-Commit Hook
768```bash
769# Add to .git/hooks/pre-commit or use husky
770 
771#!/bin/bash
772# Run quality checks before commit
773 
774# Get staged files
775FILES=$(git diff --cached --name-only --diff-filter=ACM)
776 
777for FILE in $FILES; do
778 # Run pre-edit hook for validation
779 npx claude-flow hook pre-edit --file "$FILE" --validate-syntax
780 
781 if [ $? -ne 0 ]; then
782 echo "Validation failed for $FILE"
783 exit 1
784 fi
785 
786 # Run post-edit hook for formatting
787 npx claude-flow hook post-edit --file "$FILE" --auto-format
788done
789 
790# Run tests
791npm test
792 
793exit $?
794```
795 
796#### Post-Commit Hook
797```bash
798# Add to .git/hooks/post-commit
799 
800#!/bin/bash
801# Track commit metrics
802 
803COMMIT_HASH=$(git rev-parse HEAD)
804COMMIT_MSG=$(git log -1 --pretty=%B)
805 
806npx claude-flow hook notify \
807 --message "Commit completed: $COMMIT_MSG" \
808 --level info \
809 --swarm-status
810```
811 
812#### Pre-Push Hook
813```bash
814# Add to .git/hooks/pre-push
815 
816#!/bin/bash
817# Quality gate before push
818 
819# Run full test suite
820npm run test:all
821 
822# Run quality checks
823npx claude-flow hook session-end \
824 --generate-report \
825 --export-metrics
826 
827# Verify quality thresholds
828TRUTH_SCORE=$(npx claude-flow metrics score --format json | jq -r '.truth_score')
829 
830if (( $(echo "$TRUTH_SCORE < 0.95" | bc -l) )); then
831 echo "Truth score below threshold: $TRUTH_SCORE < 0.95"
832 exit 1
833fi
834 
835exit 0
836```
837 
838### Agent Coordination Workflow
839 
840How agents use hooks for coordination:
841 
842#### Agent Workflow Example
843 
844```bash
845# Agent 1: Backend Developer
846# STEP 1: Pre-task preparation
847npx claude-flow hook pre-task \
848 --description "Implement user authentication API" \
849 --auto-spawn-agents \
850 --load-memory
851 
852# STEP 2: Work begins - pre-edit validation
853npx claude-flow hook pre-edit \
854 --file "api/auth.js" \
855 --auto-assign-agent \
856 --validate-syntax
857 
858# STEP 3: Edit file (via Claude Code Edit tool)
859# ... code changes ...
860 
861# STEP 4: Post-edit processing
862npx claude-flow hook post-edit \
863 --file "api/auth.js" \
864 --memory-key "swarm/backend/auth-api" \
865 --auto-format \
866 --train-patterns
867 
868# STEP 5: Notify coordination system
869npx claude-flow hook notify \
870 --message "Auth API implementation complete" \
871 --swarm-status \
872 --broadcast
873 
874# STEP 6: Task completion
875npx claude-flow hook post-task \
876 --task-id "auth-api" \
877 --analyze-performance \
878 --store-decisions \
879 --export-learnings
880```
881 
882```bash
883# Agent 2: Test Engineer (receives notification)
884# STEP 1: Check memory for API details
885npx claude-flow hook session-restore \
886 --session-id "swarm-current" \
887 --restore-memory
888 
889# Memory contains: swarm/backend/auth-api with implementation details
890 
891# STEP 2: Generate tests
892npx claude-flow hook pre-task \
893 --description "Write tests for auth API" \
894 --load-memory
895 
896# STEP 3: Create test file
897npx claude-flow hook post-edit \
898 --file "api/auth.test.js" \
899 --memory-key "swarm/testing/auth-api-tests" \
900 --train-patterns
901 
902# STEP 4: Share test results
903npx claude-flow hook notify \
904 --message "Auth API tests complete - 100% coverage" \
905 --broadcast
906```
907 
908### Custom Hook Creation
909 
910Create custom hooks for specific workflows:
911 
912#### Custom Hook Template
913 
914```javascript
915// .claude/hooks/custom-quality-check.js
916 
917module.exports = {
918 name: 'custom-quality-check',
919 type: 'pre',
920 matcher: /\.(ts|js)$/,
921 
922 async execute(context) {
923 const { file, content } = context;
924 
925 // Custom validation logic
926 const complexity = await analyzeComplexity(content);
927 const securityIssues = await scanSecurity(content);
928 
929 // Store in memory
930 await storeInMemory({
931 key: `quality/${file}`,
932 value: { complexity, securityIssues }
933 });
934 
935 // Return decision
936 if (complexity > 15 || securityIssues.length > 0) {
937 return {
938 continue: false,
939 reason: 'Quality checks failed',
940 warnings: [
941 `Complexity: ${complexity} (max: 15)`,
942 `Security issues: ${securityIssues.length}`
943 ]
944 };
945 }
946 
947 return {
948 continue: true,
949 reason: 'Quality checks passed',
950 metadata: { complexity, securityIssues: 0 }
951 };
952 }
953};
954```
955 
956#### Register Custom Hook
957 
958```json
959{
960 "hooks": {
961 "PreToolUse": [
962 {
963 "matcher": "^(Write|Edit)$",
964 "hooks": [
965 {
966 "type": "script",
967 "script": ".claude/hooks/custom-quality-check.js"
968 }
969 ]
970 }
971 ]
972 }
973}
974```
975 
976### Real-World Examples
977 
978#### Example 1: Full-Stack Development Workflow
979 
980```bash
981# Session start - initialize coordination
982npx claude-flow hook session-start --session-id "fullstack-feature"
983 
984# Pre-task planning
985npx claude-flow hook pre-task \
986 --description "Build user profile feature - frontend + backend + tests" \
987 --auto-spawn-agents \
988 --optimize-topology
989 
990# Backend work
991npx claude-flow hook pre-edit --file "api/profile.js"
992# ... implement backend ...
993npx claude-flow hook post-edit \
994 --file "api/profile.js" \
995 --memory-key "profile/backend" \
996 --train-patterns
997 
998# Frontend work (reads backend details from memory)
999npx claude-flow hook pre-edit --file "components/Profile.jsx"
1000# ... implement frontend ...
1001npx claude-flow hook post-edit \
1002 --file "components/Profile.jsx" \
1003 --memory-key "profile/frontend" \
1004 --train-patterns
1005 
1006# Testing (reads both backend and frontend from memory)
1007npx claude-flow hook pre-task \
1008 --description "Test profile feature" \
1009 --load-memory
1010 
1011# Session end - export everything
1012npx claude-flow hook session-end \
1013 --session-id "fullstack-feature" \
1014 --export-metrics \
1015 --generate-summary
1016```
1017 
1018#### Example 2: Debugging with Hooks
1019 
1020```bash
1021# Start debugging session
1022npx claude-flow hook session-start --session-id "debug-memory-leak"
1023 
1024# Pre-task: analyze issue
1025npx claude-flow hook pre-task \
1026 --description "Debug memory leak in event handlers" \
1027 --load-memory \
1028 --estimate-complexity
1029 
1030# Search for event emitters
1031npx claude-flow hook pre-search --query "EventEmitter"
1032# ... search executes ...
1033npx claude-flow hook post-search \
1034 --query "EventEmitter" \
1035 --cache-results
1036 
1037# Fix the issue
1038npx claude-flow hook pre-edit \
1039 --file "services/events.js" \
1040 --backup-file
1041# ... fix code ...
1042npx claude-flow hook post-edit \
1043 --file "services/events.js" \
1044 --memory-key "debug/memory-leak-fix" \
1045 --validate-output
1046 
1047# Verify fix
1048npx claude-flow hook post-task \
1049 --task-id "memory-leak-fix" \
1050 --analyze-performance \
1051 --generate-report
1052 
1053# End session
1054npx claude-flow hook session-end \
1055 --session-id "debug-memory-leak" \
1056 --export-metrics
1057```
1058 
1059#### Example 3: Multi-Agent Refactoring
1060 
1061```bash
1062# Initialize swarm for refactoring
1063npx claude-flow hook pre-task \
1064 --description "Refactor legacy codebase to modern patterns" \
1065 --auto-spawn-agents \
1066 --optimize-topology
1067 
1068# Agent 1: Code Analyzer
1069npx claude-flow hook pre-task --description "Analyze code complexity"
1070# ... analysis ...
1071npx claude-flow hook post-task \
1072 --task-id "analysis" \
1073 --store-decisions
1074 
1075# Agent 2: Refactoring (reads analysis from memory)
1076npx claude-flow hook session-restore \
1077 --session-id "swarm-refactor" \
1078 --restore-memory
1079 
1080for file in src/**/*.js; do
1081 npx claude-flow hook pre-edit --file "$file" --backup-file
1082 # ... refactor ...
1083 npx claude-flow hook post-edit \
1084 --file "$file" \
1085 --memory-key "refactor/$file" \
1086 --auto-format \
1087 --train-patterns
1088done
1089 
1090# Agent 3: Testing (reads refactored code from memory)
1091npx claude-flow hook pre-task \
1092 --description "Generate tests for refactored code" \
1093 --load-memory
1094 
1095# Broadcast completion
1096npx claude-flow hook notify \
1097 --message "Refactoring complete - all tests passing" \
1098 --broadcast
1099```
1100 
1101### Performance Tips
1102 
11031. **Keep Hooks Lightweight** - Target < 100ms execution time
11042. **Use Async for Heavy Operations** - Don't block the main flow
11053. **Cache Aggressively** - Store frequently accessed data
11064. **Batch Related Operations** - Combine multiple actions
11075. **Use Memory Wisely** - Set appropriate TTLs
11086. **Monitor Hook Performance** - Track execution times
11097. **Parallelize When Possible** - Run independent hooks concurrently
1110 
1111### Debugging Hooks
1112 
1113Enable debug mode for troubleshooting:
1114 
1115```bash
1116# Enable debug output
1117export CLAUDE_FLOW_DEBUG=true
1118 
1119# Test specific hook with verbose output
1120npx claude-flow hook pre-edit --file "test.js" --debug
1121 
1122# Check hook execution logs
1123cat .claude-flow/logs/hooks-$(date +%Y-%m-%d).log
1124 
1125# Validate configuration
1126npx claude-flow hook validate-config
1127```
1128 
1129### Benefits
1130 
1131- **Automatic Agent Assignment**: Right agent for every file type
1132- **Consistent Code Formatting**: Language-specific formatters
1133- **Continuous Learning**: Neural patterns improve over time
1134- **Cross-Session Memory**: Context persists between sessions
1135- **Performance Tracking**: Comprehensive metrics and analytics
1136- **Automatic Coordination**: Agents sync via memory
1137- **Smart Agent Spawning**: Task-based agent selection
1138- **Quality Gates**: Pre-commit validation and verification
1139- **Error Prevention**: Syntax validation before edits
1140- **Knowledge Sharing**: Decisions stored and shared
1141- **Reduced Manual Work**: Automation of repetitive tasks
1142- **Better Collaboration**: Seamless multi-agent coordination
1143 
1144### Best Practices
1145 
11461. **Configure Hooks Early** - Set up during project initialization
11472. **Use Memory Keys Strategically** - Organize with clear namespaces
11483. **Enable Auto-Formatting** - Maintain code consistency
11494. **Train Patterns Continuously** - Learn from successful operations
11505. **Monitor Performance** - Track hook execution times
11516. **Validate Configuration** - Test hooks before production use
11527. **Document Custom Hooks** - Maintain hook documentation
11538. **Set Appropriate Timeouts** - Prevent hanging operations
11549. **Handle Errors Gracefully** - Use continueOnError when appropriate
115510. **Review Metrics Regularly** - Optimize based on usage patterns
1156 
1157### Troubleshooting
1158 
1159#### Hooks Not Executing
1160- Verify `.claude/settings.json` syntax
1161- Check hook matcher patterns
1162- Enable debug mode
1163- Review permission settings
1164- Ensure claude-flow CLI is in PATH
1165 
1166#### Hook Timeouts
1167- Increase timeout values in configuration
1168- Make hooks asynchronous for heavy operations
1169- Optimize hook logic
1170- Check network connectivity for MCP tools
1171 
1172#### Memory Issues
1173- Set appropriate TTLs for memory keys
1174- Clean up old memory entries
1175- Use memory namespaces effectively
1176- Monitor memory usage
1177 
1178#### Performance Problems
1179- Profile hook execution times
1180- Use caching for repeated operations
1181- Batch operations when possible
1182- Reduce hook complexity
1183 
1184### Related Commands
1185 
1186- `npx claude-flow init --hooks` - Initialize hooks system
1187- `npx claude-flow hook --list` - List available hooks
1188- `npx claude-flow hook --test <hook>` - Test specific hook
1189- `npx claude-flow memory usage` - Manage memory
1190- `npx claude-flow agent spawn` - Spawn agents
1191- `npx claude-flow swarm init` - Initialize swarm
1192 
1193### Integration with Other Skills
1194 
1195This skill works seamlessly with:
1196- **SPARC Methodology** - Hooks enhance SPARC workflows
1197- **Pair Programming** - Automated quality in pairing sessions
1198- **Verification Quality** - Truth-score validation in hooks
1199- **GitHub Workflows** - Git integration for commits/PRs
1200- **Performance Analysis** - Metrics collection in hooks
1201- **Swarm Advanced** - Multi-agent coordination via hooks
1202 

Discussion

Alternatives

shadcn/uiManages shadcn components and projects — adding, searching, fixing, debugging, styling, and composing UI, including chat interfaces. Provides project context, component docs, and usage examples. Applies when working with shadcn/ui, component registries, presets, --preset codes, or any project with a components.json file. Also triggers for "shadcn init", "create an app with --preset", or "switch to --preset".Coding · MITADK Code ReferenceThis skill should be used when the user wants to "write agent code", build an agent with ADK", "add a tool", "create a callback", "define an agent", use state management" — in a project that needs ADK (Agent Development Kit) API patterns and code examples. It provides a quick reference for agent types, tool definitions, orchestration patterns, callbacks, state management, the graph Workflow API, and reference recipes to study. Do NOT use for scaffolding (use google-agents-cli-scaffold) or deployment (use google-agents-cli-deploy).Coding · Apache-2.0Visual editOpen and collaboratively edit a running local app in Design, with shared fallback previews and source handoff. Use when the user asks to inspect, share, or edit a real local app in Design.Coding · MITModsmithPatterns, cost review and ready templates for Claude Mods (Claude Code plugins whose behaviour is a function-hooks module). Adds what the built-in mod authoring does not: proven designs (fork-check-draw, tool + ledger, mode registry, artifact-backed state), prompt-cache and token-cost review, a vetting pass for someone else's mod, and rules for mods that compose. USE WHEN: build a mod, make a claude mod, mod templates, quiz me after each turn, assumptions tool / register_assumption, supervisor that checks the turn, next-steps check, mode selector / mode registry, effort by domain, model router that keeps the cache, prompt cache cost of a mod, what does this mod cost per turn, review or vet someone's mod before installing, mods that work together, Kanban artifact as shared project state. NOT FOR: classic shell-command hooks in settings.json (PreToolUse etc.), a plain skill or slash command, MCP server authoring, or looking up the hooks API itself (use the engine's plugin-authoring guidance and generated types).Coding · MIT