πͺ Hooks, Event Hooks, Workers & Pattern Intelligence
/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.
| Concept | Plain English | Technical Details |
|---|---|---|
| Hook | Code that runs before/after an action | Event listener with pre/post lifecycle |
| Pattern | A learned strategy that worked | Vector embedding stored in ReasoningBank |
| Trajectory | Recording of actions β outcomes | RL episode for SONA training |
| Routing | Picking the best agent for a task | MoE-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 lockHook Signals (ADR-026 Model Routing)
When hooks run, they emit signals that guide routing decisions. Watch for these in hook output:
| Signal | Meaning | Action |
|---|---|---|
[AGENT_BOOSTER_AVAILABLE] | Simple transform detected, skip LLM | Use Edit tool directly (instant (regex-based, no LLM call), $0) |
[TASK_MODEL_RECOMMENDATION] Use model="haiku" | Low complexity task | Pass model: "haiku" to Task tool |
[TASK_MODEL_RECOMMENDATION] Use model="sonnet" | Medium complexity task | Pass model: "sonnet" to Task tool |
[TASK_MODEL_RECOMMENDATION] Use model="opus" | High complexity task | Pass model: "opus" to Task tool |
Agent Booster Intents (handled without LLM):
var-to-const- Convert var/let to constadd-types- Add TypeScript type annotationsadd-error-handling- Wrap in try/catchasync-await- Convert promises to async/awaitadd-logging- Add console.log statementsremove-console- Strip console.* calls
Example Hook Output:
$ 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: $0Intelligence 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 trackingMeasuring improvement:
node .claude/helpers/hook-handler.cjs stats
node .claude/helpers/hook-handler.cjs stats --json
node .claude/helpers/intelligence.cjs statsThe stats command shows:
| Section | What It Tells You |
|---|---|
| Graph | Node/edge count, density % |
| Confidence | Min/max/mean/median across all patterns |
| Access | Total accesses, patterns used vs never accessed |
| PageRank | Sum (~1.0), highest-ranked node |
| Top Patterns | Top 10 by composite score with access counts |
| Last Delta | Changes since previous session (confidence shift, access delta) |
| Trend | Over 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)
| Hook | When It Fires | What It Does | Learning Benefit |
|---|---|---|---|
pre-edit | Before file edit | Gathers context, checks security | Learns which files need extra validation |
post-edit | After file edit | Records outcome, extracts patterns | Learns successful edit strategies |
pre-command | Before shell command | Assesses risk, validates input | Learns which commands are safe |
post-command | After shell command | Tracks success/failure | Learns command reliability patterns |
pre-task | Before task starts | Routes to optimal agent | Learns taskβagent mappings |
post-task | After task completes | Records quality score | Learns what makes tasks succeed |
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)
| Hook | Purpose | What You Get |
|---|---|---|
route | Pick best agent for task | Agent recommendation with confidence score |
explain | Understand routing decision | Full transparency on why agent was chosen |
pretrain | Bootstrap from codebase | Learns your project's patterns before you start |
build-agents | Generate optimized configs | Agent YAML files tuned for your codebase |
transfer | Import patterns from another project | Cross-project learning |
init | Initialize hooks system | Sets up .claude/settings.json |
metrics | View learning dashboard | Success rates, pattern counts, routing accuracy |
list | List all registered hooks | See what's active |
npx ruflo@latest hooks route "refactor authentication to use JWT" --include-explanation
npx ruflo@latest hooks pretrain --depth deep --model-type moeπ Session Management Hooks (4 hooks)
| Hook | Purpose | Key Options |
|---|---|---|
session-start | Begin session, load context | --session-id, --load-context, --start-daemon |
session-end | End session, persist state | --export-metrics, --persist-patterns, --stop-daemon |
session-restore | Resume previous session | --session-id or latest |
notify | Send cross-agent notification | --message, --priority, --target |
npx ruflo@latest hooks session-start --session-id "feature-auth" --start-daemon
npx ruflo@latest hooks session-end --export-metrics --persist-patternsπ€ Intelligence System Hooks (9 hooks)
| Hook | Category | What It Does |
|---|---|---|
intelligence | Status | Shows SONA, MoE, HNSW, EWC++ status |
intelligence-reset | Admin | Clears learned patterns (use carefully!) |
trajectory-start | RL | Begin recording actions for learning |
trajectory-step | RL | Record an action with reward signal |
trajectory-end | RL | Finish recording, trigger learning |
pattern-store | Memory | Store a pattern with HNSW indexing |
pattern-search | Memory | Find similar patterns (150x faster) |
stats | Analytics | Intelligence diagnostics, confidence trends, improvement tracking |
attention | Focus | Compute attention-weighted similarity |
npx ruflo@latest hooks intelligence trajectory-start --task "implement OAuth2"
npx ruflo@latest hooks intelligence trajectory-step --action "created token service" --quality 0.9
npx ruflo@latest hooks intelligence trajectory-end --success true
node .claude/helpers/hook-handler.cjs stats
node .claude/helpers/intelligence.cjs stats --json12 Background Workers (Auto-Triggered)
Workers run automatically based on context, or dispatch manually.
| Worker | Trigger | Auto-Fires When | What It Does |
|---|---|---|---|
ultralearn | New project | First session in new codebase | Deep knowledge acquisition |
optimize | Slow ops | Operation takes >2s | Performance suggestions |
consolidate | Session end | Every 30 min or session-end | Memory consolidation |
predict | Pattern match | Similar task seen before | Preloads likely resources |
audit | Security file | Changes to auth/crypto files | Security vulnerability scan |
map | New dirs | New directories created | Codebase structure mapping |
preload | Cache miss | Frequently accessed patterns | Resource preloading |
deepdive | Complex edit | File >500 lines edited | Deep code analysis |
document | New code | New functions/classes | Auto-documentation |
refactor | Code smell | Duplicate code detected | Refactoring suggestions |
benchmark | Perf code | Performance-critical changes | Performance benchmarking |
testgaps | No tests | Code changes without tests | Test coverage analysis |
npx ruflo@latest hooks worker list
npx ruflo@latest hooks worker dispatch --trigger audit --context "./src/auth"
npx ruflo@latest hooks worker statusModel Routing Hooks (3 hooks)
Automatically selects haiku/sonnet/opus based on task complexity.
| Hook | Purpose | Saves Money By |
|---|---|---|
model-route | Route to optimal model | Using haiku for simple tasks |
model-outcome | Record result | Learning which model works for what |
model-stats | View routing stats | Showing cost savings |
npx ruflo@latest hooks model-route --task "fix typo in README"
npx ruflo@latest hooks model-route --task "design distributed consensus system"Progress Tracking
| Command | Output |
|---|---|
hooks progress | Current V3 implementation % |
hooks progress --detailed | Breakdown by category |
hooks progress --sync | Sync and persist to file |
hooks progress --json | JSON for scripting |
Quick Reference
npx ruflo@latest hooks route "<task>" --include-explanation
npx ruflo@latest hooks session-start --start-daemon
npx ruflo@latest hooks session-end --persist-patterns
npx ruflo@latest hooks metrics
npx ruflo@latest hooks intelligence stats
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
npx ruflo@latest hooks pretrain --depth deep
npx ruflo@latest hooks worker dispatch --trigger audit