Back to Ruflo

@claude-flow/hooks

v3/@claude-flow/hooks/README.md

3.6.3012.9 KB
Original Source

@claude-flow/hooks

Event-driven lifecycle hooks with ReasoningBank learning integration for Claude Flow V3

The @claude-flow/hooks package provides a comprehensive hooks system for intercepting and extending Claude Flow operations. It enables intelligent task routing, pattern learning, background metrics collection, and real-time statusline integration.

Features

  • 🎣 Hook Registry - Priority-based hook registration with filtering and management
  • ⚑ Hook Executor - Timeout handling, error recovery, and result aggregation
  • πŸ€– Background Daemons - Metrics collection, swarm monitoring, pattern learning
  • πŸ‘· Background Workers - 12 specialized workers for analysis, optimization, and automation
  • πŸ“Š Statusline Integration - Real-time status display for Claude Code
  • 🧠 ReasoningBank Learning - Intelligent task routing based on learned patterns
  • πŸ”§ MCP Tools - 13 MCP tools for programmatic hooks access
  • πŸ”„ V2 Compatibility - Backward compatible with V2 hook commands

Installation

bash
# Using npm
npm install @claude-flow/hooks

# Using pnpm
pnpm add @claude-flow/hooks

# Using yarn
yarn add @claude-flow/hooks

Quick Start

Basic Usage

typescript
import {
  HookRegistry,
  HookExecutor,
  HookEvent,
  HookPriority,
} from '@claude-flow/hooks';

// Create registry and executor
const registry = new HookRegistry();
const executor = new HookExecutor(registry);

// Register a pre-edit hook
registry.register(
  HookEvent.PreEdit,
  async (context) => {
    console.log(`Editing file: ${context.file?.path}`);
    return { success: true };
  },
  HookPriority.Normal,
  { name: 'log-edits' }
);

// Execute hooks
const result = await executor.preEdit('src/app.ts', 'modify');
console.log(`Hooks executed: ${result.hooksExecuted}`);

Initialize with Daemons

typescript
import { initializeHooks } from '@claude-flow/hooks';

// Initialize full system with background daemons
const { registry, executor, statusline } = await initializeHooks({
  enableDaemons: true,
  enableStatusline: true,
});

// Generate statusline
console.log(statusline.generateStatusline());

Using MCP Tools

typescript
import { hooksMCPTools, getHooksTool } from '@claude-flow/hooks';

// Get specific tool
const routeTool = getHooksTool('hooks/route');

// Execute routing
const result = await routeTool.handler({
  task: 'Implement user authentication',
  includeExplanation: true,
});

console.log(`Recommended agent: ${result.recommendedAgent}`);
console.log(`Confidence: ${result.confidence}%`);

CLI Commands

Hooks Daemon

Manage background daemon processes for metrics and learning.

bash
# Start daemon with default 60s interval
hooks-daemon start

# Start with custom interval (30 seconds)
hooks-daemon start 30

# Stop daemon
hooks-daemon stop

# Check status
hooks-daemon status

# Run pattern consolidation
hooks-daemon consolidate

# Export learned patterns
hooks-daemon export json

# Rebuild HNSW index
hooks-daemon rebuild-index

# Notify activity (for hook integration)
hooks-daemon notify-activity

Statusline

Generate statusline output for Claude Code integration.

bash
# Display formatted statusline
statusline

# Output JSON data
statusline --json

# Compact JSON (single line)
statusline --compact

# Show help
statusline --help

Example Output:

β–Š Claude Flow V3 ● agentic-flow@alpha  β”‚  βŽ‡ v3
─────────────────────────────────────────────────────
πŸ—οΈ  DDD Domains    [●●●●●]  5/5    ⚑ 1.0x β†’ 2.49x-7.47x
πŸ€– Swarm Agents    β—‰ [ 5/15]      🟒 CVE 3/3    πŸ’Ύ 156 patterns
πŸ”§ Architecture    DDD ●93%  β”‚  Security ●CLEAN  β”‚  Hooks ●ACTIVE
πŸ“Š Routing         89% accuracy β”‚  Avg 4.2ms β”‚  1547 operations
─────────────────────────────────────────────────────

Hook Events

EventDescription
PreToolUseBefore any tool execution
PostToolUseAfter tool execution completes
PreEditBefore file modification
PostEditAfter file modification
PreReadBefore file read
PostReadAfter file read
PreCommandBefore shell command execution
PostCommandAfter shell command completes
PreTaskBefore task starts
PostTaskAfter task completes
TaskProgressDuring task execution
SessionStartWhen session begins
SessionEndWhen session ends
SessionRestoreWhen restoring previous session
AgentSpawnWhen agent is spawned
AgentTerminateWhen agent terminates
PreRouteBefore task routing
PostRouteAfter routing decision
PatternLearnedWhen new pattern is learned
PatternConsolidatedWhen patterns are consolidated

Hook Priorities

PriorityValueUse Case
Critical1000Security validation, must run first
High100Pre-processing, preparation
Normal50Standard hooks
Low10Logging, metrics
Background1Async operations, runs last

Background Workers

The hooks system includes 12 specialized background workers that can be triggered automatically or manually dispatched.

Available Workers

WorkerPriorityEst. TimeDescription
ultralearnnormal60sDeep knowledge acquisition and learning
optimizehigh30sPerformance optimization and tuning
consolidatelow20sMemory consolidation and cleanup
predictnormal15sPredictive preloading and anticipation
auditcritical45sSecurity analysis and vulnerability scanning
mapnormal30sCodebase mapping and architecture analysis
preloadlow10sResource preloading and cache warming
deepdivenormal60sDeep code analysis and examination
documentnormal45sAuto-documentation generation
refactornormal30sCode refactoring suggestions
benchmarknormal60sPerformance benchmarking
testgapsnormal30sTest coverage analysis

Worker CLI Commands

bash
# List all available workers
claude-flow hooks worker list

# Detect triggers from prompt text
claude-flow hooks worker detect --prompt "optimize performance"

# Auto-dispatch when triggers match (confidence β‰₯0.6)
claude-flow hooks worker detect --prompt "deep dive into auth" --auto-dispatch --min-confidence 0.6

# Manually dispatch a worker
claude-flow hooks worker dispatch --trigger refactor --context "auth module"

# Check worker status
claude-flow hooks worker status

# Cancel a running worker
claude-flow hooks worker cancel --id worker_refactor_1_abc123

Performance Targets

MetricTarget
Trigger detection<5ms
Worker spawn<50ms
Max concurrent10

UserPromptSubmit Integration

Workers are automatically triggered via the UserPromptSubmit hook when prompt patterns match worker triggers with confidence β‰₯0.6. Add this to your Claude settings:

json
{
  "hooks": {
    "UserPromptSubmit": [{
      "matcher": ".*",
      "hooks": [{
        "type": "command",
        "timeout": 6000,
        "command": "claude-flow hooks worker detect --prompt \"$USER_PROMPT\" --auto-dispatch --min-confidence 0.6"
      }]
    }]
  }
}

MCP Tools

ToolDescription
hooks/pre-editGet context and suggestions before file edit
hooks/post-editRecord edit outcome for learning
hooks/routeRoute task to optimal agent
hooks/metricsQuery learning metrics
hooks/pre-commandAssess command risk
hooks/post-commandRecord command outcome
hooks/daemon-statusGet daemon status
hooks/statuslineGet statusline data
hooks/worker-listList all 12 background workers
hooks/worker-dispatchDispatch a worker by trigger type
hooks/worker-statusGet status of running workers
hooks/worker-detectDetect worker triggers from prompt text
hooks/worker-cancelCancel a running worker

API Reference

HookRegistry

typescript
class HookRegistry {
  // Register a hook
  register(
    event: HookEvent,
    handler: HookHandler,
    priority: HookPriority,
    options?: HookRegistrationOptions
  ): string;

  // Unregister a hook
  unregister(hookId: string): boolean;

  // Get hooks for event
  getForEvent(event: HookEvent, enabledOnly?: boolean): HookEntry[];

  // Enable/disable hooks
  enable(hookId: string): boolean;
  disable(hookId: string): boolean;

  // List hooks with filtering
  list(filter?: HookListFilter): HookEntry[];

  // Get statistics
  getStats(): HookRegistryStats;
}

HookExecutor

typescript
class HookExecutor {
  // Execute hooks for any event
  execute<T>(
    event: HookEvent,
    context: Partial<HookContext<T>>,
    options?: HookExecutionOptions
  ): Promise<HookExecutionResult>;

  // Convenience methods
  preToolUse(toolName: string, parameters: Record<string, unknown>): Promise<HookExecutionResult>;
  postToolUse(toolName: string, parameters: Record<string, unknown>, duration: number): Promise<HookExecutionResult>;
  preEdit(filePath: string, operation: 'create' | 'modify' | 'delete'): Promise<HookExecutionResult>;
  postEdit(filePath: string, operation: 'create' | 'modify' | 'delete', duration: number): Promise<HookExecutionResult>;
  preCommand(command: string, workingDirectory?: string): Promise<HookExecutionResult>;
  postCommand(command: string, exitCode: number, output?: string, error?: string): Promise<HookExecutionResult>;
  sessionStart(sessionId: string): Promise<HookExecutionResult>;
  sessionEnd(sessionId: string): Promise<HookExecutionResult>;
  agentSpawn(agentId: string, agentType: string): Promise<HookExecutionResult>;
  agentTerminate(agentId: string, agentType: string, status: string): Promise<HookExecutionResult>;
}

DaemonManager

typescript
class DaemonManager {
  // Register and manage daemons
  register(config: DaemonConfig, task: () => Promise<void>): void;
  start(name: string): Promise<void>;
  stop(name: string): Promise<void>;
  restart(name: string): Promise<void>;

  // Bulk operations
  startAll(): Promise<void>;
  stopAll(): Promise<void>;

  // Status
  getState(name: string): DaemonState | undefined;
  getAllStates(): DaemonState[];
  isRunning(name: string): boolean;
}

StatuslineGenerator

typescript
class StatuslineGenerator {
  // Register data sources
  registerDataSources(sources: StatuslineDataSources): void;

  // Generate output
  generateData(): StatuslineData;
  generateStatusline(): string;
  generateJSON(): string;
  generateCompactJSON(): string;

  // Configuration
  updateConfig(config: Partial<StatuslineConfig>): void;
  invalidateCache(): void;
}

Environment Variables

VariableDescriptionDefault
CLAUDE_FLOW_HOOK_TIMEOUTHook execution timeout (ms)5000
CLAUDE_FLOW_REASONINGBANK_ENABLEDEnable ReasoningBanktrue
CLAUDE_FLOW_HOOKS_NAMESPACELearning namespacehooks-learning
CLAUDE_FLOW_HOOKS_LOG_LEVELLogging levelinfo
CLAUDE_FLOW_SHOW_HOOKS_METRICSShow hooks in statuslinetrue
CLAUDE_FLOW_SHOW_SWARM_ACTIVITYShow swarm in statuslinetrue
CLAUDE_FLOW_SHOW_PERFORMANCEShow performance targetstrue

Integration with Claude Code

Add to your Claude settings (~/.claude/settings.json):

json
{
  "hooks": {
    "SessionStart": [{
      "hooks": [{
        "type": "command",
        "timeout": 5000,
        "command": "hooks-daemon start"
      }]
    }],
    "SessionEnd": [{
      "hooks": [{
        "type": "command",
        "timeout": 3000,
        "command": "hooks-daemon stop"
      }]
    }],
    "PreToolUse": [{
      "hooks": [{
        "type": "command",
        "timeout": 100,
        "command": "hooks-daemon notify-activity"
      }]
    }]
  },
  "statusLine": {
    "type": "command",
    "command": "statusline"
  }
}

License

MIT Β© Claude Flow Team