Files
ruflo/v3/@claude-flow/hooks
rUv 402b701a9d fix(security): ADR-165 Phase 1 — close 5 critical CVEs + refresh registry + audit CI gate (#2508)
* fix(security): ADR-165 Phase 1 — close all critical CVEs, refresh registry, add CI gate

Closes ADR-165 Phase 1. Both workspaces pass `npm audit --audit-level=critical`.

## Before (2026-06-29)

| Workspace | Critical | High | Moderate | Total |
|-----------|----------|------|----------|-------|
| Root      | **1**    | 6    | 31       | 38    |
| v3        | **4**    | 33   | 57       | 97    |

## After

| Workspace | Critical | High | Moderate | Total |
|-----------|----------|------|----------|-------|
| Root      | **0**    | 0    | 31       | 31    |
| v3        | **0**    | 27   | 58       | 88    |

All 5 critical advisories closed (vitest GHSA-5xrq, handlebars prototype-pollution,
protobufjs constructor-pollution, plus 2 more in v3). 12 of 39 high advisories
closed via overrides; the remaining 27 v3 highs are deeper transitive chains
that would require breaking-change major bumps — flagged for ADR-165 Phase 2.

## Changes

### Root workspace overrides (package.json)

- `vitest`: `^1.0.0` → `^3.2.6` (closes critical GHSA-5xrq CVSS 9.8)
- `hono`: `>=4.11.4` → `>=4.12.25` (closes 6 hono advisories)
- `undici`: `>=7.18.0` → `>=8.5.0` (closes 7 undici advisories — bumps the
  stale pin that ADR-165 flagged as still-in-vulnerable-range)
- `vite`: `>=6.4.6` → `>=8.0.16` (closes 2 vite advisories)
- NEW `@grpc/grpc-js`: `>=1.14.4`
- NEW `form-data`: `>=4.0.6`
- NEW `http-proxy-middleware`: `>=3.0.7`
- `@hono/node-server`: `>=1.19.10` → `>=1.19.14`

### v3 workspace overrides (v3/package.json + pnpm.overrides)

- `vitest`: `^4.0.16` → `^4.1.0` (and `@vitest/coverage-v8` matched)
- Top-level + pnpm overrides: `handlebars: >=4.7.9`, `protobufjs: >=8.6.0`
- 27 sub-package `package.json` updated to `vitest ^4.1.0`

### CVE registry refresh (v3/@claude-flow/security/src/CVE-REMEDIATION.ts)

Rewritten from 5 stale Jan-2026 entries to 16 total: 15 fixed, 1 open
(ADR165-OPEN-01 — PII pipeline wiring per ADR-164 §6.1 not yet on
dispatch-layer). `SECURITY_SUMMARY` is now computed dynamically from the
registry; `validateRemediation()` correctly returns `allFixed: false`
with 1 issue. ADR-165 §5 flagged this as THE Phase 2 priority — now closed.

### New CI gate

`.github/workflows/cve-audit.yml`:
- `audit-root` — `npm audit --audit-level=critical` in root, blocking
- `audit-v3` — same in v3, blocking
- `audit-high-report` — warn-only summary on high-severity drift
- Triggers: PR, push to main, daily cron

### ADR-165 §9 evidence ledger addendum

Captures AFTER-remediation `npm audit --json` metadata for both workspaces.
The diff between BEFORE (already in §9) and AFTER makes Phase 1 verifiable.

Also CORRECTED one prior surprise in §9: the `validate-input.ts` in
`mcp-tools/` is NOT a 9-line shim. It's 269 lines of real implementation.
(That was an inaccurate findings note from the initial audit.)

### §7.3 research items resolved

- `protobufjs` v3 chain confirmed gone after override pins
- `handlebars` v3 chain confirmed not user-reachable on the workflow path
  (toolchain-only; override sufficient)
- `validate-input.ts` confirmed real implementation, not a shim (registry
  entry corrected)
- CORS surface check: no `cors()` / `app.use(cors` call sites — the hono
  CORS-wildcard advisory is not exploitable on the current server
- ADR-164 §6.1 PII pipeline NOT wired in current agentbbs dispatch —
  recorded as ADR165-OPEN-01 (Phase 3 work)

## Gates (all PASS)

- `npm audit --audit-level=critical` root: exit 0 (was non-zero)
- `npm audit --audit-level=critical` v3:   exit 0 (was non-zero)
- vitest suites: 105/109 pass (4 skip-conditional — same as before)
- ADR-112 audit: 352/352 tools with guidance
- business-pods smoke: 11/11 PASS
- agentbbs smoke: 8/8 PASS
- agenticow smoke: 8/8 PASS
- cli build: clean (tsc)

## Phase 2+ deferred

The 27 v3 high-severity advisories that remain are transitive chains with
no patched-in-range version. ADR-165 §6 Phase 2 picks these up after the
`cve-watch.yml` automation in §6 lands (NEW PR — not in scope here).

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01WbBa4nccx5aGhXphoHxcni

* chore(lock): regen v3/pnpm-lock.yaml after override updates (PR #2508 CI fix)

PR #2508 added handlebars + protobufjs to v3 overrides + bumped vitest pin,
but v3/pnpm-lock.yaml wasn't regenerated. CI surfaced
ERR_PNPM_LOCKFILE_CONFIG_MISMATCH on every install step.

Same pattern as the previous lockfile-drift fixes on PR #2500 and #2503.

* fix(ci): cve-audit.yml jq-only + regen witness manifests for #1609 marker drift

Two PR #2508 CI failures fixed:

1. Static-regression-guard tripped on cve-audit.yml line 52: the static
   YAML strict-parser sees `if high > 0:` inside the `run: |` block as
   a YAML block-mapping key indicator. Refactored all 3 inline-python
   blocks to use jq (preinstalled on ubuntu-latest) — no embedded
   `if x > 0:` lines, so the YAML guard passes.

2. Witness marker drift smoke flagged fix-marker #1609 — the Phase 1
   vitest bump (4.0.16 → 4.1.0) drifted the cited marker string in
   v3/@claude-flow/aidefence/package.json. Updated `marker` field in
   all 3 platform manifests + `desc` to reference ADR-165 Phase 1, then
   re-signed via plugins/ruflo-core/scripts/witness/regen.mjs.

Co-Authored-By: RuFlo <ruv@ruv.net>
2026-06-29 22:41:24 -04:00
..

@claude-flow/hooks

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

Event Description
PreToolUse Before any tool execution
PostToolUse After tool execution completes
PreEdit Before file modification
PostEdit After file modification
PreRead Before file read
PostRead After file read
PreCommand Before shell command execution
PostCommand After shell command completes
PreTask Before task starts
PostTask After task completes
TaskProgress During task execution
SessionStart When session begins
SessionEnd When session ends
SessionRestore When restoring previous session
AgentSpawn When agent is spawned
AgentTerminate When agent terminates
PreRoute Before task routing
PostRoute After routing decision
PatternLearned When new pattern is learned
PatternConsolidated When patterns are consolidated

Hook Priorities

Priority Value Use Case
Critical 1000 Security validation, must run first
High 100 Pre-processing, preparation
Normal 50 Standard hooks
Low 10 Logging, metrics
Background 1 Async operations, runs last

Background Workers

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

Available Workers

Worker Priority Est. Time Description
ultralearn normal 60s Deep knowledge acquisition and learning
optimize high 30s Performance optimization and tuning
consolidate low 20s Memory consolidation and cleanup
predict normal 15s Predictive preloading and anticipation
audit critical 45s Security analysis and vulnerability scanning
map normal 30s Codebase mapping and architecture analysis
preload low 10s Resource preloading and cache warming
deepdive normal 60s Deep code analysis and examination
document normal 45s Auto-documentation generation
refactor normal 30s Code refactoring suggestions
benchmark normal 60s Performance benchmarking
testgaps normal 30s Test 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

Metric Target
Trigger detection <5ms
Worker spawn <50ms
Max concurrent 10

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

Tool Description
hooks/pre-edit Get context and suggestions before file edit
hooks/post-edit Record edit outcome for learning
hooks/route Route task to optimal agent
hooks/metrics Query learning metrics
hooks/pre-command Assess command risk
hooks/post-command Record command outcome
hooks/daemon-status Get daemon status
hooks/statusline Get statusline data
hooks/worker-list List all 12 background workers
hooks/worker-dispatch Dispatch a worker by trigger type
hooks/worker-status Get status of running workers
hooks/worker-detect Detect worker triggers from prompt text
hooks/worker-cancel Cancel 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

Variable Description Default
CLAUDE_FLOW_HOOK_TIMEOUT Hook execution timeout (ms) 5000
CLAUDE_FLOW_REASONINGBANK_ENABLED Enable ReasoningBank true
CLAUDE_FLOW_HOOKS_NAMESPACE Learning namespace hooks-learning
CLAUDE_FLOW_HOOKS_LOG_LEVEL Logging level info
CLAUDE_FLOW_SHOW_HOOKS_METRICS Show hooks in statusline true
CLAUDE_FLOW_SHOW_SWARM_ACTIVITY Show swarm in statusline true
CLAUDE_FLOW_SHOW_PERFORMANCE Show performance targets true

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