Hooks Automation

Automate development workflows with intelligent hooks and memory coordination

✨ The solution you've been looking for

Verified
Tested and verified by our team
11981 Stars

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.

automation hooks development-workflow mcp-integration memory-coordination swarm-agents code-formatting neural-training
Repository

See It In Action

Interactive preview & real-world examples

Live Demo
Skill Demo Animation

AI Conversation Simulator

See how users interact with this skill

User Prompt

Build a user profile feature with backend API, React frontend, and comprehensive tests

Skill Processing

Analyzing request...

Agent Response

Automated agent spawning, cross-component memory coordination, consistent code formatting, and performance metrics tracking throughout the development lifecycle

Quick Start (3 Steps)

Get up and running in minutes

1

Install

claude-code skill install hooks-automation

claude-code skill install hooks-automation
2

Config

3

First Trigger

@hooks-automation help

Commands

CommandDescriptionRequired Args
@hooks-automation full-stack-feature-developmentCoordinate multiple agents across backend, frontend, and testing phases with automatic memory sharing and quality gatesNone
@hooks-automation legacy-code-refactoringMulti-agent refactoring with complexity analysis, pattern learning, and safety validationsNone
@hooks-automation debugging-with-memory-persistenceDebug complex issues with context preservation, decision tracking, and cross-session continuityNone

Typical Use Cases

Full-Stack Feature Development

Coordinate multiple agents across backend, frontend, and testing phases with automatic memory sharing and quality gates

Legacy Code Refactoring

Multi-agent refactoring with complexity analysis, pattern learning, and safety validations

Debugging with Memory Persistence

Debug complex issues with context preservation, decision tracking, and cross-session continuity

Overview

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

1# Initialize with default hooks configuration
2npx 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

1# Pre-task hook (auto-spawns agents)
2npx claude-flow hook pre-task --description "Implement authentication"
3
4# Post-edit hook (auto-formats and stores in memory)
5npx claude-flow hook post-edit --file "src/auth.js" --memory-key "auth/login"
6
7# Session end hook (saves state and metrics)
8npx 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

 1npx claude-flow hook pre-edit [options]
 2
 3Options:
 4  --file, -f <path>         File path to be edited
 5  --auto-assign-agent       Automatically assign best agent (default: true)
 6  --validate-syntax         Pre-validate syntax before edit
 7  --check-conflicts         Check for merge conflicts
 8  --backup-file             Create backup before editing
 9
10Examples:
11  npx claude-flow hook pre-edit --file "src/auth/login.js"
12  npx claude-flow hook pre-edit -f "config/db.js" --validate-syntax
13  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

 1npx claude-flow hook pre-bash --command <cmd>
 2
 3Options:
 4  --command, -c <cmd>       Command to validate
 5  --check-safety            Verify command safety (default: true)
 6  --estimate-resources      Estimate resource usage
 7  --require-confirmation    Request user confirmation for risky commands
 8
 9Examples:
10  npx claude-flow hook pre-bash -c "rm -rf /tmp/cache"
11  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

 1npx claude-flow hook pre-task [options]
 2
 3Options:
 4  --description, -d <text>  Task description for context
 5  --auto-spawn-agents       Automatically spawn required agents (default: true)
 6  --load-memory             Load relevant memory from previous sessions
 7  --optimize-topology       Select optimal swarm topology
 8  --estimate-complexity     Analyze task complexity
 9
10Examples:
11  npx claude-flow hook pre-task --description "Implement user authentication"
12  npx claude-flow hook pre-task -d "Continue API dev" --load-memory
13  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

1npx claude-flow hook pre-search --query <query>
2
3Options:
4  --query, -q <text>        Search query
5  --check-cache             Check cache first (default: true)
6  --optimize-query          Optimize search pattern
7
8Examples:
9  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

 1npx claude-flow hook post-edit [options]
 2
 3Options:
 4  --file, -f <path>         File path that was edited
 5  --auto-format             Automatically format code (default: true)
 6  --memory-key, -m <key>    Store edit context in memory
 7  --train-patterns          Train neural patterns from edit
 8  --validate-output         Validate edited file
 9
10Examples:
11  npx claude-flow hook post-edit --file "src/components/Button.jsx"
12  npx claude-flow hook post-edit -f "api/auth.js" --memory-key "auth/login"
13  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

 1npx claude-flow hook post-bash --command <cmd>
 2
 3Options:
 4  --command, -c <cmd>       Command that was executed
 5  --log-output              Log command output (default: true)
 6  --update-metrics          Update performance metrics
 7  --store-result            Store result in memory
 8
 9Examples:
10  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

 1npx claude-flow hook post-task [options]
 2
 3Options:
 4  --task-id, -t <id>        Task identifier for tracking
 5  --analyze-performance     Generate performance metrics (default: true)
 6  --store-decisions         Save task decisions to memory
 7  --export-learnings        Export neural pattern learnings
 8  --generate-report         Create task completion report
 9
10Examples:
11  npx claude-flow hook post-task --task-id "auth-implementation"
12  npx claude-flow hook post-task -t "api-refactor" --analyze-performance
13  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

 1npx claude-flow hook post-search --query <query> --results <path>
 2
 3Options:
 4  --query, -q <text>        Original search query
 5  --results, -r <path>      Results file path
 6  --cache-results           Cache for future use (default: true)
 7  --train-patterns          Improve search patterns
 8
 9Examples:
10  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

1npx claude-flow hook mcp-initialized --swarm-id <id>
2
3Features:
4- Save swarm topology and configuration
5- Store agent roster in memory
6- Initialize coordination namespace

agent-spawned - Update agent roster and memory

1npx claude-flow hook agent-spawned --agent-id <id> --type <type>
2
3Features:
4- Register agent in coordination memory
5- Update agent roster
6- Initialize agent-specific memory namespace

task-orchestrated - Monitor task progress

1npx claude-flow hook task-orchestrated --task-id <id>
2
3Features:
4- Track task progress through memory
5- Monitor agent assignments
6- Update coordination state

neural-trained - Save pattern improvements

1npx claude-flow hook neural-trained --pattern <name>
2
3Features:
4- Export trained neural patterns
5- Update coordination models
6- Share learning across agents

Memory Coordination Hooks

memory-write - Triggered when agents write to coordination memory

1Features:
2- Validate memory key format
3- Update cross-agent indexes
4- Trigger dependent hooks
5- Notify subscribed agents

memory-read - Triggered when agents read from coordination memory

1Features:
2- Log access patterns
3- Update popularity metrics
4- Preload related data
5- Track usage statistics

memory-sync - Synchronize memory across swarm agents

1npx claude-flow hook memory-sync --namespace <ns>
2
3Features:
4- Sync memory state across agents
5- Resolve conflicts
6- Propagate updates
7- Maintain consistency

Session Hooks

session-start - Initialize new session

 1npx claude-flow hook session-start --session-id <id>
 2
 3Options:
 4  --session-id, -s <id>     Session identifier
 5  --load-context            Load context from previous session
 6  --init-agents             Initialize required agents
 7
 8Features:
 9- Create session directory
10- Initialize metrics tracking
11- Load previous context
12- Set up coordination namespace

session-restore - Load previous session state

 1npx claude-flow hook session-restore --session-id <id>
 2
 3Options:
 4  --session-id, -s <id>     Session to restore
 5  --restore-memory          Restore memory state (default: true)
 6  --restore-agents          Restore agent configurations
 7
 8Examples:
 9  npx claude-flow hook session-restore --session-id "swarm-20241019"
10  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

 1npx claude-flow hook session-end [options]
 2
 3Options:
 4  --session-id, -s <id>     Session identifier to end
 5  --save-state              Save current session state (default: true)
 6  --export-metrics          Export session metrics
 7  --generate-summary        Create session summary
 8  --cleanup-temp            Remove temporary files
 9
10Examples:
11  npx claude-flow hook session-end --session-id "dev-session-2024"
12  npx claude-flow hook session-end -s "feature-auth" --export-metrics --generate-summary
13  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

 1npx claude-flow hook notify --message <msg>
 2
 3Options:
 4  --message, -m <text>      Notification message
 5  --level <level>           Notification level (info|warning|error)
 6  --swarm-status            Include swarm status (default: true)
 7  --broadcast               Send to all agents
 8
 9Examples:
10  npx claude-flow hook notify -m "Task completed" --level info
11  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:

 1{
 2  "hooks": {
 3    "PreToolUse": [
 4      {
 5        "matcher": "^(Write|Edit|MultiEdit)$",
 6        "hooks": [{
 7          "type": "command",
 8          "command": "npx claude-flow hook pre-edit --file '${tool.params.file_path}' --memory-key 'swarm/editor/current'"
 9        }]
10      },
11      {
12        "matcher": "^Bash$",
13        "hooks": [{
14          "type": "command",
15          "command": "npx claude-flow hook pre-bash --command '${tool.params.command}'"
16        }]
17      }
18    ],
19    "PostToolUse": [
20      {
21        "matcher": "^(Write|Edit|MultiEdit)$",
22        "hooks": [{
23          "type": "command",
24          "command": "npx claude-flow hook post-edit --file '${tool.params.file_path}' --memory-key 'swarm/editor/complete' --auto-format --train-patterns"
25        }]
26      },
27      {
28        "matcher": "^Bash$",
29        "hooks": [{
30          "type": "command",
31          "command": "npx claude-flow hook post-bash --command '${tool.params.command}' --update-metrics"
32        }]
33      }
34    ]
35  }
36}

Advanced Configuration

Complete hook configuration with all features:

 1{
 2  "hooks": {
 3    "enabled": true,
 4    "debug": false,
 5    "timeout": 5000,
 6
 7    "PreToolUse": [
 8      {
 9        "matcher": "^(Write|Edit|MultiEdit)$",
10        "hooks": [
11          {
12            "type": "command",
13            "command": "npx claude-flow hook pre-edit --file '${tool.params.file_path}' --auto-assign-agent --validate-syntax",
14            "timeout": 3000,
15            "continueOnError": true
16          }
17        ]
18      },
19      {
20        "matcher": "^Task$",
21        "hooks": [
22          {
23            "type": "command",
24            "command": "npx claude-flow hook pre-task --description '${tool.params.task}' --auto-spawn-agents --load-memory",
25            "async": true
26          }
27        ]
28      },
29      {
30        "matcher": "^Grep$",
31        "hooks": [
32          {
33            "type": "command",
34            "command": "npx claude-flow hook pre-search --query '${tool.params.pattern}' --check-cache"
35          }
36        ]
37      }
38    ],
39
40    "PostToolUse": [
41      {
42        "matcher": "^(Write|Edit|MultiEdit)$",
43        "hooks": [
44          {
45            "type": "command",
46            "command": "npx claude-flow hook post-edit --file '${tool.params.file_path}' --memory-key 'edits/${tool.params.file_path}' --auto-format --train-patterns",
47            "async": true
48          }
49        ]
50      },
51      {
52        "matcher": "^Task$",
53        "hooks": [
54          {
55            "type": "command",
56            "command": "npx claude-flow hook post-task --task-id '${result.task_id}' --analyze-performance --store-decisions --export-learnings",
57            "async": true
58          }
59        ]
60      },
61      {
62        "matcher": "^Grep$",
63        "hooks": [
64          {
65            "type": "command",
66            "command": "npx claude-flow hook post-search --query '${tool.params.pattern}' --cache-results --train-patterns"
67          }
68        ]
69      }
70    ],
71
72    "SessionStart": [
73      {
74        "hooks": [
75          {
76            "type": "command",
77            "command": "npx claude-flow hook session-start --session-id '${session.id}' --load-context"
78          }
79        ]
80      }
81    ],
82
83    "SessionEnd": [
84      {
85        "hooks": [
86          {
87            "type": "command",
88            "command": "npx claude-flow hook session-end --session-id '${session.id}' --export-metrics --generate-summary --cleanup-temp"
89          }
90        ]
91      }
92    ]
93  }
94}

Protected File Patterns

Add protection for sensitive files:

 1{
 2  "hooks": {
 3    "PreToolUse": [
 4      {
 5        "matcher": "^(Write|Edit|MultiEdit)$",
 6        "hooks": [
 7          {
 8            "type": "command",
 9            "command": "npx claude-flow hook check-protected --file '${tool.params.file_path}'"
10          }
11        ]
12      }
13    ]
14  }
15}

Automatic Testing

Run tests after file modifications:

 1{
 2  "hooks": {
 3    "PostToolUse": [
 4      {
 5        "matcher": "^Write$",
 6        "hooks": [
 7          {
 8            "type": "command",
 9            "command": "test -f '${tool.params.file_path%.js}.test.js' && npm test '${tool.params.file_path%.js}.test.js'",
10            "continueOnError": true
11          }
12        ]
13      }
14    ]
15  }
16}

MCP Tool Integration

Hooks automatically integrate with MCP tools for coordination:

Pre-Task Hook with Agent Spawning

 1// Hook command
 2npx claude-flow hook pre-task --description "Build REST API"
 3
 4// Internally calls MCP tools:
 5mcp__claude-flow__agent_spawn {
 6  type: "backend-dev",
 7  capabilities: ["api", "database", "testing"]
 8}
 9
10mcp__claude-flow__memory_usage {
11  action: "store",
12  key: "swarm/task/api-build/context",
13  namespace: "coordination",
14  value: JSON.stringify({
15    description: "Build REST API",
16    agents: ["backend-dev"],
17    started: Date.now()
18  })
19}

Post-Edit Hook with Memory Storage

 1// Hook command
 2npx claude-flow hook post-edit --file "api/auth.js"
 3
 4// Internally calls MCP tools:
 5mcp__claude-flow__memory_usage {
 6  action: "store",
 7  key: "swarm/edits/api/auth.js",
 8  namespace: "coordination",
 9  value: JSON.stringify({
10    file: "api/auth.js",
11    timestamp: Date.now(),
12    changes: { added: 45, removed: 12 },
13    formatted: true,
14    linted: true
15  })
16}
17
18mcp__claude-flow__neural_train {
19  pattern_type: "coordination",
20  training_data: { /* edit patterns */ }
21}

Session End Hook with State Persistence

 1// Hook command
 2npx claude-flow hook session-end --session-id "dev-2024"
 3
 4// Internally calls MCP tools:
 5mcp__claude-flow__memory_persist {
 6  sessionId: "dev-2024"
 7}
 8
 9mcp__claude-flow__swarm_status {
10  swarmId: "current"
11}
12
13// Generates metrics and summary

Memory Coordination Protocol

All hooks follow a standardized memory coordination pattern:

Three-Phase Memory Protocol

Phase 1: STATUS - Hook starts

 1mcp__claude-flow__memory_usage {
 2  action: "store",
 3  key: "swarm/hooks/pre-edit/status",
 4  namespace: "coordination",
 5  value: JSON.stringify({
 6    status: "running",
 7    hook: "pre-edit",
 8    file: "src/auth.js",
 9    timestamp: Date.now()
10  })
11}

Phase 2: PROGRESS - Hook processes

 1mcp__claude-flow__memory_usage {
 2  action: "store",
 3  key: "swarm/hooks/pre-edit/progress",
 4  namespace: "coordination",
 5  value: JSON.stringify({
 6    progress: 50,
 7    action: "validating syntax",
 8    file: "src/auth.js"
 9  })
10}

Phase 3: COMPLETE - Hook finishes

 1mcp__claude-flow__memory_usage {
 2  action: "store",
 3  key: "swarm/hooks/pre-edit/complete",
 4  namespace: "coordination",
 5  value: JSON.stringify({
 6    status: "complete",
 7    result: "success",
 8    agent_assigned: "backend-dev",
 9    syntax_valid: true,
10    backup_created: true
11  })
12}

Hook Response Format

Hooks return JSON responses to control operation flow:

Continue Response

1{
2  "continue": true,
3  "reason": "All validations passed",
4  "metadata": {
5    "agent_assigned": "backend-dev",
6    "syntax_valid": true,
7    "file": "src/auth.js"
8  }
9}

Block Response

1{
2  "continue": false,
3  "reason": "Protected file - manual review required",
4  "metadata": {
5    "file": ".env.production",
6    "protection_level": "high",
7    "requires": "manual_approval"
8  }
9}

Warning Response

 1{
 2  "continue": true,
 3  "reason": "Syntax valid but complexity high",
 4  "warnings": [
 5    "Cyclomatic complexity: 15 (threshold: 10)",
 6    "Consider refactoring for better maintainability"
 7  ],
 8  "metadata": {
 9    "complexity": 15,
10    "threshold": 10
11  }
12}

Git Integration

Hooks can integrate with Git operations for quality control:

Pre-Commit Hook

 1# Add to .git/hooks/pre-commit or use husky
 2
 3#!/bin/bash
 4# Run quality checks before commit
 5
 6# Get staged files
 7FILES=$(git diff --cached --name-only --diff-filter=ACM)
 8
 9for FILE in $FILES; do
10  # Run pre-edit hook for validation
11  npx claude-flow hook pre-edit --file "$FILE" --validate-syntax
12
13  if [ $? -ne 0 ]; then
14    echo "Validation failed for $FILE"
15    exit 1
16  fi
17
18  # Run post-edit hook for formatting
19  npx claude-flow hook post-edit --file "$FILE" --auto-format
20done
21
22# Run tests
23npm test
24
25exit $?

Post-Commit Hook

 1# Add to .git/hooks/post-commit
 2
 3#!/bin/bash
 4# Track commit metrics
 5
 6COMMIT_HASH=$(git rev-parse HEAD)
 7COMMIT_MSG=$(git log -1 --pretty=%B)
 8
 9npx claude-flow hook notify \
10  --message "Commit completed: $COMMIT_MSG" \
11  --level info \
12  --swarm-status

Pre-Push Hook

 1# Add to .git/hooks/pre-push
 2
 3#!/bin/bash
 4# Quality gate before push
 5
 6# Run full test suite
 7npm run test:all
 8
 9# Run quality checks
10npx claude-flow hook session-end \
11  --generate-report \
12  --export-metrics
13
14# Verify quality thresholds
15TRUTH_SCORE=$(npx claude-flow metrics score --format json | jq -r '.truth_score')
16
17if (( $(echo "$TRUTH_SCORE < 0.95" | bc -l) )); then
18  echo "Truth score below threshold: $TRUTH_SCORE < 0.95"
19  exit 1
20fi
21
22exit 0

Agent Coordination Workflow

How agents use hooks for coordination:

Agent Workflow Example

 1# Agent 1: Backend Developer
 2# STEP 1: Pre-task preparation
 3npx claude-flow hook pre-task \
 4  --description "Implement user authentication API" \
 5  --auto-spawn-agents \
 6  --load-memory
 7
 8# STEP 2: Work begins - pre-edit validation
 9npx claude-flow hook pre-edit \
10  --file "api/auth.js" \
11  --auto-assign-agent \
12  --validate-syntax
13
14# STEP 3: Edit file (via Claude Code Edit tool)
15# ... code changes ...
16
17# STEP 4: Post-edit processing
18npx claude-flow hook post-edit \
19  --file "api/auth.js" \
20  --memory-key "swarm/backend/auth-api" \
21  --auto-format \
22  --train-patterns
23
24# STEP 5: Notify coordination system
25npx claude-flow hook notify \
26  --message "Auth API implementation complete" \
27  --swarm-status \
28  --broadcast
29
30# STEP 6: Task completion
31npx claude-flow hook post-task \
32  --task-id "auth-api" \
33  --analyze-performance \
34  --store-decisions \
35  --export-learnings
 1# Agent 2: Test Engineer (receives notification)
 2# STEP 1: Check memory for API details
 3npx claude-flow hook session-restore \
 4  --session-id "swarm-current" \
 5  --restore-memory
 6
 7# Memory contains: swarm/backend/auth-api with implementation details
 8
 9# STEP 2: Generate tests
10npx claude-flow hook pre-task \
11  --description "Write tests for auth API" \
12  --load-memory
13
14# STEP 3: Create test file
15npx claude-flow hook post-edit \
16  --file "api/auth.test.js" \
17  --memory-key "swarm/testing/auth-api-tests" \
18  --train-patterns
19
20# STEP 4: Share test results
21npx claude-flow hook notify \
22  --message "Auth API tests complete - 100% coverage" \
23  --broadcast

Custom Hook Creation

Create custom hooks for specific workflows:

Custom Hook Template

 1// .claude/hooks/custom-quality-check.js
 2
 3module.exports = {
 4  name: 'custom-quality-check',
 5  type: 'pre',
 6  matcher: /\.(ts|js)$/,
 7
 8  async execute(context) {
 9    const { file, content } = context;
10
11    // Custom validation logic
12    const complexity = await analyzeComplexity(content);
13    const securityIssues = await scanSecurity(content);
14
15    // Store in memory
16    await storeInMemory({
17      key: `quality/${file}`,
18      value: { complexity, securityIssues }
19    });
20
21    // Return decision
22    if (complexity > 15 || securityIssues.length > 0) {
23      return {
24        continue: false,
25        reason: 'Quality checks failed',
26        warnings: [
27          `Complexity: ${complexity} (max: 15)`,
28          `Security issues: ${securityIssues.length}`
29        ]
30      };
31    }
32
33    return {
34      continue: true,
35      reason: 'Quality checks passed',
36      metadata: { complexity, securityIssues: 0 }
37    };
38  }
39};

Register Custom Hook

 1{
 2  "hooks": {
 3    "PreToolUse": [
 4      {
 5        "matcher": "^(Write|Edit)$",
 6        "hooks": [
 7          {
 8            "type": "script",
 9            "script": ".claude/hooks/custom-quality-check.js"
10          }
11        ]
12      }
13    ]
14  }
15}

Real-World Examples

Example 1: Full-Stack Development Workflow

 1# Session start - initialize coordination
 2npx claude-flow hook session-start --session-id "fullstack-feature"
 3
 4# Pre-task planning
 5npx claude-flow hook pre-task \
 6  --description "Build user profile feature - frontend + backend + tests" \
 7  --auto-spawn-agents \
 8  --optimize-topology
 9
10# Backend work
11npx claude-flow hook pre-edit --file "api/profile.js"
12# ... implement backend ...
13npx claude-flow hook post-edit \
14  --file "api/profile.js" \
15  --memory-key "profile/backend" \
16  --train-patterns
17
18# Frontend work (reads backend details from memory)
19npx claude-flow hook pre-edit --file "components/Profile.jsx"
20# ... implement frontend ...
21npx claude-flow hook post-edit \
22  --file "components/Profile.jsx" \
23  --memory-key "profile/frontend" \
24  --train-patterns
25
26# Testing (reads both backend and frontend from memory)
27npx claude-flow hook pre-task \
28  --description "Test profile feature" \
29  --load-memory
30
31# Session end - export everything
32npx claude-flow hook session-end \
33  --session-id "fullstack-feature" \
34  --export-metrics \
35  --generate-summary

Example 2: Debugging with Hooks

 1# Start debugging session
 2npx claude-flow hook session-start --session-id "debug-memory-leak"
 3
 4# Pre-task: analyze issue
 5npx claude-flow hook pre-task \
 6  --description "Debug memory leak in event handlers" \
 7  --load-memory \
 8  --estimate-complexity
 9
10# Search for event emitters
11npx claude-flow hook pre-search --query "EventEmitter"
12# ... search executes ...
13npx claude-flow hook post-search \
14  --query "EventEmitter" \
15  --cache-results
16
17# Fix the issue
18npx claude-flow hook pre-edit \
19  --file "services/events.js" \
20  --backup-file
21# ... fix code ...
22npx claude-flow hook post-edit \
23  --file "services/events.js" \
24  --memory-key "debug/memory-leak-fix" \
25  --validate-output
26
27# Verify fix
28npx claude-flow hook post-task \
29  --task-id "memory-leak-fix" \
30  --analyze-performance \
31  --generate-report
32
33# End session
34npx claude-flow hook session-end \
35  --session-id "debug-memory-leak" \
36  --export-metrics

Example 3: Multi-Agent Refactoring

 1# Initialize swarm for refactoring
 2npx claude-flow hook pre-task \
 3  --description "Refactor legacy codebase to modern patterns" \
 4  --auto-spawn-agents \
 5  --optimize-topology
 6
 7# Agent 1: Code Analyzer
 8npx claude-flow hook pre-task --description "Analyze code complexity"
 9# ... analysis ...
10npx claude-flow hook post-task \
11  --task-id "analysis" \
12  --store-decisions
13
14# Agent 2: Refactoring (reads analysis from memory)
15npx claude-flow hook session-restore \
16  --session-id "swarm-refactor" \
17  --restore-memory
18
19for file in src/**/*.js; do
20  npx claude-flow hook pre-edit --file "$file" --backup-file
21  # ... refactor ...
22  npx claude-flow hook post-edit \
23    --file "$file" \
24    --memory-key "refactor/$file" \
25    --auto-format \
26    --train-patterns
27done
28
29# Agent 3: Testing (reads refactored code from memory)
30npx claude-flow hook pre-task \
31  --description "Generate tests for refactored code" \
32  --load-memory
33
34# Broadcast completion
35npx claude-flow hook notify \
36  --message "Refactoring complete - all tests passing" \
37  --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:

 1# Enable debug output
 2export CLAUDE_FLOW_DEBUG=true
 3
 4# Test specific hook with verbose output
 5npx claude-flow hook pre-edit --file "test.js" --debug
 6
 7# Check hook execution logs
 8cat .claude-flow/logs/hooks-$(date +%Y-%m-%d).log
 9
10# Validate configuration
11npx 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

What Users Are Saying

Real feedback from the community

Environment Matrix

Dependencies

Claude Flow CLI (npm install -g claude-flow@alpha)
Node.js 16+
Claude Code with hooks enabled

Framework Support

MCP Servers ✓ (claude-flow, ruv-swarm, flow-nexus) Git ✓ (recommended for version control) Testing frameworks ✓ (Jest, Mocha, pytest) Code formatters ✓ (Prettier, Black, gofmt)

Context Window

Token Usage ~5K-15K tokens for complex multi-agent operations with memory coordination

Security & Privacy

Information

Author
ruvnet
Updated
2026-01-30
Category
productivity-tools