@claude-flow/hooks

中文文档
3.0.3发布于 2026/11/09MITTypeScriptES Module近 30 天下载 6325

V3 Hooks System - Event-driven lifecycle hooks with ReasoningBank learning integration

原始使用文档
文档目录27 节
  1. Quickstart
  2. Features
  3. Installation
  4. Quick Start
  5. Basic Usage
  6. Initialize with Daemons
  7. Using MCP Tools
  8. CLI Commands
  9. Hooks Daemon
  10. Statusline
  11. Hook Events
  12. Hook Priorities
  13. Background Workers
  14. Available Workers
  15. Worker CLI Commands
  16. Performance Targets
  17. UserPromptSubmit Integration
  18. MCP Tools
  19. API Reference
  20. HookRegistry
  21. HookExecutor
  22. DaemonManager
  23. StatuslineGenerator
  24. Environment Variables
  25. Integration with Claude Code
  26. Related Packages
  27. License

@claude-flow/hooks

Animated diagram: a lifecycle event reaches the HookRegistry, the HookExecutor runs hooks in priority order, and ReasoningBank learns from the outcome

@claude-flow/hooks — Registers and runs lifecycle hooks (PreEdit, PostTask, session start and end, and more) in priority order, and feeds their outcomes to ReasoningBank pattern learning.

Supported environments: Node.js 20+ · ESM

Quickstart

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

const registry = new HookRegistry();
registry.register(HookEvent.PreEdit, async () => ({ success: true }), HookPriority.Normal, { name: 'log-edit' });
console.log(registry.getForEvent(HookEvent.PreEdit).map((h) => h.name));

Expected output:

[ 'log-edit' ]

Built on @claude-flow/shared; used by @claude-flow/plugins.

npm version npm downloads License: MIT TypeScript Node.js

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

# 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

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

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

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.

# 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.

# 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

# 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:

{
  "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

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

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

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

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):

{
  "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


Built by rUv · ruv.io · Source

版本与发布记录

@claude-flow/hooks 共发布 7 个版本,首次发布于 2026/01/07;过去 12 个月发布了 7 个版本。

版本发布日期距今
3.0.3latest2026/11/09今天
3.0.22026/10/2317 天前
3.0.12026/10/2218 天前
3.0.0v3alphaalpha2026/09/291 个月前
3.0.0-alpha.72026/01/0810 个月前
3.0.0-alpha.22026/01/0710 个月前

关于 @claude-flow/hooks 的常见问题

@claude-flow/hooks 是什么?

V3 Hooks System - Event-driven lifecycle hooks with ReasoningBank learning integration

如何安装 @claude-flow/hooks?

在项目目录运行 npm install @claude-flow/hooks,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@claude-flow/shared(^3.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。它还提供命令行工具 guidance、statusline、hooks-daemon、claude-flow-hooks,可以用 npx guidance 直接运行。

@claude-flow/hooks 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@claude-flow/hooks 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@claude-flow/hooks 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=20.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@claude-flow/hooks 可以商用吗?

@claude-flow/hooks 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@claude-flow/hooks 的下载量有多少?

根据 npm 官方下载统计,@claude-flow/hooks 在 2026/10/10 – 2026/11/08 这 30 天内被下载 6,325 次,日均约 211 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@claude-flow/hooks 还在维护吗?

最新版本 3.0.3 发布于 2026/11/09(今天);至今共发布 7 个版本,其中过去 12 个月发布了 7 个;首次发布于 2026/01/07。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。