ruflo

πŸͺ Hooks, Event Hooks, Workers & Pattern Intelligence

/docs/intelligence--learning/hooks-event-hooks-workers--pattern-intelligence

What Are Hooks?

Hooks intercept operations (file edits, commands, tasks) and learn from outcomes. Unlike static automation, hooks improve over time by tracking what works and applying those patterns to future tasks.

ConceptPlain EnglishTechnical Details
HookCode that runs before/after an actionEvent listener with pre/post lifecycle
PatternA learned strategy that workedVector embedding stored in ReasoningBank
TrajectoryRecording of actions β†’ outcomesRL episode for SONA training
RoutingPicking the best agent for a taskMoE-based classifier with learned weights

How Hooks Learn (4-Step Pipeline)

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  RETRIEVE   │───▢│    JUDGE    │───▢│   DISTILL   │───▢│ CONSOLIDATE β”‚
β”‚             β”‚    β”‚             β”‚    β”‚             β”‚    β”‚             β”‚
β”‚ Find similarβ”‚    β”‚ Was it      β”‚    β”‚ Extract key β”‚    β”‚ Prevent     β”‚
β”‚ past patternsβ”‚   β”‚ successful? β”‚    β”‚ learnings   β”‚    β”‚ forgetting  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
     HNSW              Verdict            LoRA              EWC++
   150x faster        success/fail      compression       memory lock

Hook Signals (ADR-026 Model Routing)

When hooks run, they emit signals that guide routing decisions. Watch for these in hook output:

SignalMeaningAction
[AGENT_BOOSTER_AVAILABLE]Simple transform detected, skip LLMUse Edit tool directly (instant (regex-based, no LLM call), $0)
[TASK_MODEL_RECOMMENDATION] Use model="haiku"Low complexity taskPass model: "haiku" to Task tool
[TASK_MODEL_RECOMMENDATION] Use model="sonnet"Medium complexity taskPass model: "sonnet" to Task tool
[TASK_MODEL_RECOMMENDATION] Use model="opus"High complexity taskPass model: "opus" to Task tool

Agent Booster Intents (handled without LLM):

  • var-to-const - Convert var/let to const
  • add-types - Add TypeScript type annotations
  • add-error-handling - Wrap in try/catch
  • async-await - Convert promises to async/await
  • add-logging - Add console.log statements
  • remove-console - Strip console.* calls

Example Hook Output:

bash
$ npx ruflo@latest hooks pre-task --description "convert var to const in utils.ts"

[AGENT_BOOSTER_AVAILABLE] Intent: var-to-const
Recommendation: Use Edit tool directly
Performance: <1ms (instant (regex-based, no LLM call) than LLM)
Cost: $0

Intelligence Loop (ADR-050)

The intelligence loop wires PageRank-ranked memory into the hook system. Every session builds a knowledge graph that improves over time:

SessionStart:
  session-restore  β†’ intelligence.init()
    β†’ Read MEMORY.md / auto-memory-store.json
    β†’ Build graph (nodes + similarity/temporal edges)
    β†’ Compute PageRank
    β†’ "[INTELLIGENCE] Loaded 13 patterns, 12 edges"

UserPrompt:
  route            β†’ intelligence.getContext(prompt)
    β†’ Jaccard-match prompt against pre-ranked entries
    β†’ Inject top-5 patterns into Claude's context:

    [INTELLIGENCE] Relevant patterns for this task:
      * (0.95) HNSW gives HNSW-indexed search [rank #1, 12x accessed]
      * (0.88) London School TDD preferred [rank #3, 8x accessed]

PostEdit:
  post-edit        β†’ intelligence.recordEdit(file)
    β†’ Append to pending-insights.jsonl (<2ms)

SessionEnd:
  session-end      β†’ intelligence.consolidate()
    β†’ Process pending insights (3+ edits β†’ new entry)
    β†’ Confidence boost for accessed patterns (+0.03)
    β†’ Confidence decay for unused patterns (-0.005/day)
    β†’ Recompute PageRank, rebuild edges
    β†’ Save snapshot for trend tracking

Measuring improvement:

bash
# Human-readable diagnostics
node .claude/helpers/hook-handler.cjs stats

# JSON output for scripting
node .claude/helpers/hook-handler.cjs stats --json

# Or via intelligence.cjs directly
node .claude/helpers/intelligence.cjs stats

The stats command shows:

SectionWhat It Tells You
GraphNode/edge count, density %
ConfidenceMin/max/mean/median across all patterns
AccessTotal accesses, patterns used vs never accessed
PageRankSum (~1.0), highest-ranked node
Top PatternsTop 10 by composite score with access counts
Last DeltaChanges since previous session (confidence shift, access delta)
TrendOver all sessions: IMPROVING / DECLINING / STABLE

Example output:

+--------------------------------------------------------------+
|  Intelligence Diagnostics (ADR-050)                          |
+--------------------------------------------------------------+

  Graph
    Nodes:    9
    Edges:    8 (7 temporal, 1 similar)
    Density:  22.2%

  Confidence
    Min:      0.490    Max:  0.600
    Mean:     0.556    Median: 0.580

  Access
    Total accesses:     11
    Patterns used:      6/9
    Never accessed:     3

  Top Patterns (by composite score)
    #1  HNSW gives HNSW-indexed search
         conf=0.600  pr=0.2099  score=0.3659  accessed=2x
    #2  London School TDD preferred
         conf=0.600  pr=0.1995  score=0.3597  accessed=2x

  Last Delta (5m ago)
    Confidence: +0.0300
    Accesses:   +6

  Trend (3 snapshots)
    Confidence drift:  +0.0422
    Direction:         IMPROVING
+--------------------------------------------------------------+

All 27 Hooks by Category

πŸ”§ Tool Lifecycle Hooks (6 hooks)

HookWhen It FiresWhat It DoesLearning Benefit
pre-editBefore file editGathers context, checks securityLearns which files need extra validation
post-editAfter file editRecords outcome, extracts patternsLearns successful edit strategies
pre-commandBefore shell commandAssesses risk, validates inputLearns which commands are safe
post-commandAfter shell commandTracks success/failureLearns command reliability patterns
pre-taskBefore task startsRoutes to optimal agentLearns task→agent mappings
post-taskAfter task completesRecords quality scoreLearns what makes tasks succeed
bash
# Example: Edit with pattern learning
npx ruflo@latest hooks pre-edit ./src/auth.ts
npx ruflo@latest hooks post-edit ./src/auth.ts --success true --train-patterns

🧠 Intelligence & Routing Hooks (8 hooks)

HookPurposeWhat You Get
routePick best agent for taskAgent recommendation with confidence score
explainUnderstand routing decisionFull transparency on why agent was chosen
pretrainBootstrap from codebaseLearns your project's patterns before you start
build-agentsGenerate optimized configsAgent YAML files tuned for your codebase
transferImport patterns from another projectCross-project learning
initInitialize hooks systemSets up .claude/settings.json
metricsView learning dashboardSuccess rates, pattern counts, routing accuracy
listList all registered hooksSee what's active
bash
# Route a task with explanation
npx ruflo@latest hooks route "refactor authentication to use JWT" --include-explanation

# Bootstrap intelligence from your codebase
npx ruflo@latest hooks pretrain --depth deep --model-type moe

πŸ“… Session Management Hooks (4 hooks)

HookPurposeKey Options
session-startBegin session, load context--session-id, --load-context, --start-daemon
session-endEnd session, persist state--export-metrics, --persist-patterns, --stop-daemon
session-restoreResume previous session--session-id or latest
notifySend cross-agent notification--message, --priority, --target
bash
# Start session with auto-daemon
npx ruflo@latest hooks session-start --session-id "feature-auth" --start-daemon

# End session and export learnings
npx ruflo@latest hooks session-end --export-metrics --persist-patterns

πŸ€– Intelligence System Hooks (9 hooks)

HookCategoryWhat It Does
intelligenceStatusShows SONA, MoE, HNSW, EWC++ status
intelligence-resetAdminClears learned patterns (use carefully!)
trajectory-startRLBegin recording actions for learning
trajectory-stepRLRecord an action with reward signal
trajectory-endRLFinish recording, trigger learning
pattern-storeMemoryStore a pattern with HNSW indexing
pattern-searchMemoryFind similar patterns (150x faster)
statsAnalyticsIntelligence diagnostics, confidence trends, improvement tracking
attentionFocusCompute attention-weighted similarity
bash
# Start trajectory for complex task
npx ruflo@latest hooks intelligence trajectory-start --task "implement OAuth2"

# Record successful action
npx ruflo@latest hooks intelligence trajectory-step --action "created token service" --quality 0.9

# End trajectory and trigger learning
npx ruflo@latest hooks intelligence trajectory-end --success true

# View intelligence diagnostics and improvement trends (ADR-050)
node .claude/helpers/hook-handler.cjs stats
node .claude/helpers/intelligence.cjs stats --json

12 Background Workers (Auto-Triggered)

Workers run automatically based on context, or dispatch manually.

WorkerTriggerAuto-Fires WhenWhat It Does
ultralearnNew projectFirst session in new codebaseDeep knowledge acquisition
optimizeSlow opsOperation takes >2sPerformance suggestions
consolidateSession endEvery 30 min or session-endMemory consolidation
predictPattern matchSimilar task seen beforePreloads likely resources
auditSecurity fileChanges to auth/crypto filesSecurity vulnerability scan
mapNew dirsNew directories createdCodebase structure mapping
preloadCache missFrequently accessed patternsResource preloading
deepdiveComplex editFile >500 lines editedDeep code analysis
documentNew codeNew functions/classesAuto-documentation
refactorCode smellDuplicate code detectedRefactoring suggestions
benchmarkPerf codePerformance-critical changesPerformance benchmarking
testgapsNo testsCode changes without testsTest coverage analysis
bash
# List all workers
npx ruflo@latest hooks worker list

# Manually dispatch security audit
npx ruflo@latest hooks worker dispatch --trigger audit --context "./src/auth"

# Check worker status
npx ruflo@latest hooks worker status

Model Routing Hooks (3 hooks)

Automatically selects haiku/sonnet/opus based on task complexity.

HookPurposeSaves Money By
model-routeRoute to optimal modelUsing haiku for simple tasks
model-outcomeRecord resultLearning which model works for what
model-statsView routing statsShowing cost savings
bash
# Get model recommendation
npx ruflo@latest hooks model-route --task "fix typo in README"
# β†’ Recommends: haiku (simple task, low complexity)

npx ruflo@latest hooks model-route --task "design distributed consensus system"
# β†’ Recommends: opus (complex architecture, high reasoning)

Progress Tracking

CommandOutput
hooks progressCurrent V3 implementation %
hooks progress --detailedBreakdown by category
hooks progress --syncSync and persist to file
hooks progress --jsonJSON for scripting

Quick Reference

bash
# ══════════════════════════════════════════════════════════════════
# MOST COMMON HOOKS
# ══════════════════════════════════════════════════════════════════

# Route task to best agent (with intelligence context injection)
npx ruflo@latest hooks route "<task>" --include-explanation

# Start/end session with learning
npx ruflo@latest hooks session-start --start-daemon
npx ruflo@latest hooks session-end --persist-patterns

# View what the system has learned
npx ruflo@latest hooks metrics
npx ruflo@latest hooks intelligence stats

# Intelligence diagnostics β€” see if intelligence is improving
node .claude/helpers/hook-handler.cjs stats          # Human-readable
node .claude/helpers/hook-handler.cjs stats --json   # JSON for scripting
node .claude/helpers/intelligence.cjs stats           # Direct access

# Bootstrap on new project
npx ruflo@latest hooks pretrain --depth deep

# Dispatch background worker
npx ruflo@latest hooks worker dispatch --trigger audit