Skip to main content

Hooks System

Mega Brain’s hooks system provides event-driven automation through 20+ Python hooks that execute at key lifecycle events. All hooks are written in Python 3 using only stdlib + PyYAML for zero-dependency operation.

Architecture

Hooks are configured in .claude/settings.json and execute automatically at specific lifecycle events:

Hook Events

Mega Brain supports 6 primary hook events:
Triggered when a new Claude Code session begins.Active Hooks:
  • session_start.py - Initializes session state and memory
  • inbox_age_alert.py - Checks for stale inbox content (10s timeout)
  • skill_indexer.py - Builds SKILL-INDEX.json from skills/ (5s timeout)
  • gsd-check-update.js - Checks for GSD system updates
Configuration:
Triggered when the user submits a prompt, before Claude processes it.Active Hooks:
  • continuous_save.py - Auto-saves session state (2s timeout)
  • user_prompt_submit.py - Processes user input (5s timeout)
  • skill_router.py - Auto-routes to skills based on keywords (5s timeout)
  • quality_watchdog.py - Monitors quality metrics (5s timeout)
  • memory_hints_injector.py - Injects relevant memory context (5s timeout)
  • enforce_plan_mode.py - Enforces plan mode rules (5s timeout)
  • memory_updater.py - Updates agent memory (5s timeout)
Key Feature - Skill Routing:
Triggered before a tool executes, allowing validation and blocking.Active Hooks:
  • claude_md_guard.py - Prevents CLAUDE.md creation in invalid locations (5s)
  • creation_validator.py - Validates new file creation against layer rules (5s)
Matcher Pattern:
Hooks can block tool execution by returning {"continue": false} in their JSON output.
Triggered after a tool completes, enabling cascading automation.Active Hooks (9 total):
  • continuous_save.py - Auto-saves after edits (2s)
  • post_tool_use.py - Generic post-processing (5s)
  • post_batch_cascading.py - Phase 5 cascade system (30s timeout)
  • enforce_dual_location.py - Syncs files to dual locations (5s)
  • pending_tracker.py - Tracks pending tasks (5s)
  • agent_creation_trigger.py - Auto-creates agents from templates (10s)
  • agent_index_updater.py - Updates AGENT-INDEX.yaml (5s)
  • claude_md_agent_sync.py - Syncs agent CLAUDE.md files (5s)
  • pipeline_checkpoint.py - Pipeline checkpoint management (5s)
  • gsd-context-monitor.js - Context monitoring
Cascading Architecture:
Triggered when the user stops Claude’s generation.Active Hooks:
  • continuous_save.py - Final save (2s)
  • stop_hook_completeness.py - Checks for incomplete tasks (10s)
  • ralph_wiggum.py - Quality assurance helper (5s)
The stop_hook_completeness.py detects unfinished work and reminds Claude to complete tasks.
Triggered when the session ends (clean exit).Active Hooks:
  • session_end.py - Session cleanup and finalization (10s)
  • session_autosave_v2.py - Saves session to logs/ (10s)
  • agent_memory_persister.py - Persists agent memory to disk (5s)
Persistence Flow:

Key Hooks Deep Dive

skill_router.py - Auto-Routing Intelligence

The skill router is the core intelligence of the auto-routing system.
How it works:
  1. skill_indexer.py (SessionStart) scans .claude/skills/ and builds SKILL-INDEX.json
  2. skill_router.py (UserPromptSubmit) matches keywords from user prompt
  3. If match found, injects skill instructions into context
  4. Claude automatically follows skill instructions
See Skills Routing for complete skill system documentation.

post_batch_cascading.py - Phase 5 Orchestration

The largest hook (56KB) orchestrates the Phase 5 cascade system:
1

Detect Phase Completion

Monitors for Phase 1-4 completion markers in batch logs.
2

Activate Phase 5

Triggers agent activation, dossier creation, and knowledge extraction.
3

Cascade Updates

Updates AGENT-INDEX.yaml, DNA, and knowledge base in sequence.

continuous_save.py - Session Persistence

Runs on 3 events (UserPromptSubmit, PostToolUse, Stop) with 2s timeout:

Configuration

settings.json Structure

settings.local.json is gitignored and merges with settings.json. Use for local-only hooks.

Matcher Patterns

Hooks can filter by tool name using regex matchers:

Timeout Management

  • Fast hooks (< 2s): continuous_save, guards
  • Medium hooks (5s): skill_router, validators
  • Slow hooks (10-30s): session_start, post_batch_cascading

Writing Custom Hooks

Hook Template

Hook Response Format

Best Practices

Hook Development Guidelines

  1. Always return valid JSON - Even on exceptions
  2. Use only stdlib + PyYAML - Zero dependencies policy
  3. Respect timeouts - Keep hooks fast (< 5s ideal)
  4. Handle errors gracefully - Never crash, always continue
  5. Log to files, not stdout - stdout is for JSON only
  6. Use pathlib.Path - Cross-platform path handling
  7. Test in isolation - Run python3 hooks/my_hook.py --test

Complete Hook Reference

Debugging Hooks

1

Enable Debug Output

Set CLAUDE_DEBUG=1 environment variable:
2

Test Hook Directly

Run hooks with test data:
3

Check Hook Logs

Hooks should log to .claude/logs/hooks/:
4

Validate JSON Output

Ensure hooks always return valid JSON:

Security & Permissions

The permissions block in settings.json blocks dangerous commands:
These blocks are enforced before execution. Claude cannot run these commands even if instructed.

Skills Routing

Learn how skill auto-routing works with keyword detection

Agent Creation

Understand agent lifecycle and hook triggers

Validation

Layer validation and quality gates

Layer Management

L1/L2/L3 classification system