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:SessionStart - Initialization
SessionStart - Initialization
Triggered when a new Claude Code session begins.Active Hooks:
session_start.py- Initializes session state and memoryinbox_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
UserPromptSubmit - Prompt Intelligence
UserPromptSubmit - Prompt Intelligence
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)
PreToolUse - Validation Gates
PreToolUse - Validation Gates
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)
Hooks can block tool execution by returning
{"continue": false} in their JSON output.PostToolUse - Cascading Actions
PostToolUse - Cascading Actions
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
Stop - Completeness Checks
Stop - Completeness Checks
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)
SessionEnd - Cleanup & Persistence
SessionEnd - Cleanup & Persistence
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)
Key Hooks Deep Dive
skill_router.py - Auto-Routing Intelligence
The skill router is the core intelligence of the auto-routing system.skill_indexer.py(SessionStart) scans.claude/skills/and buildsSKILL-INDEX.jsonskill_router.py(UserPromptSubmit) matches keywords from user prompt- If match found, injects skill instructions into context
- 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:continuous_save.py - Session Persistence
Runs on 3 events (UserPromptSubmit, PostToolUse, Stop) with 2s timeout:Configuration
settings.json Structure
Matcher Patterns
Hooks can filter by tool name using regex matchers:| Matcher | Matches |
|---|---|
"" | All events |
"Write|Edit" | Write or Edit tools |
"Edit|Write|MultiEdit" | Any file modification |
"Bash" | Bash tool only |
Timeout Management
Writing Custom Hooks
Hook Template
Hook Response Format
Best Practices
Hook Development Guidelines
- Always return valid JSON - Even on exceptions
- Use only stdlib + PyYAML - Zero dependencies policy
- Respect timeouts - Keep hooks fast (< 5s ideal)
- Handle errors gracefully - Never crash, always continue
- Log to files, not stdout - stdout is for JSON only
- Use pathlib.Path - Cross-platform path handling
- Test in isolation - Run
python3 hooks/my_hook.py --test
Complete Hook Reference
All 20+ Active Hooks
All 20+ Active Hooks
| Hook | Event | Purpose | Timeout |
|---|---|---|---|
session_start.py | SessionStart | Initialize session | 10s |
inbox_age_alert.py | SessionStart | Check stale inbox | 5s |
skill_indexer.py | SessionStart | Build skill index | 5s |
gsd-check-update.js | SessionStart | Check updates | - |
continuous_save.py | UserPromptSubmit, PostToolUse, Stop | Auto-save | 2s |
user_prompt_submit.py | UserPromptSubmit | Process prompt | 5s |
skill_router.py | UserPromptSubmit | Route to skills | 5s |
quality_watchdog.py | UserPromptSubmit | Monitor quality | 5s |
memory_hints_injector.py | UserPromptSubmit | Inject memory | 5s |
enforce_plan_mode.py | UserPromptSubmit | Plan mode rules | 5s |
memory_updater.py | UserPromptSubmit | Update memory | 5s |
claude_md_guard.py | PreToolUse (Write/Edit) | Guard CLAUDE.md | 5s |
creation_validator.py | PreToolUse (Write/Edit) | Validate layers | 5s |
post_tool_use.py | PostToolUse | Post-processing | 5s |
post_batch_cascading.py | PostToolUse | Phase 5 cascade | 30s |
enforce_dual_location.py | PostToolUse | Dual sync | 5s |
pending_tracker.py | PostToolUse | Track pending | 5s |
agent_creation_trigger.py | PostToolUse | Create agents | 10s |
agent_index_updater.py | PostToolUse | Update index | 5s |
claude_md_agent_sync.py | PostToolUse | Sync agents | 5s |
pipeline_checkpoint.py | PostToolUse | Checkpoints | 5s |
gsd-context-monitor.js | PostToolUse | Monitor context | - |
stop_hook_completeness.py | Stop | Check complete | 10s |
ralph_wiggum.py | Stop | QA helper | 5s |
session_end.py | SessionEnd | Cleanup | 10s |
session_autosave_v2.py | SessionEnd | Save session | 10s |
agent_memory_persister.py | SessionEnd | Persist memory | 5s |
Debugging Hooks
Security & Permissions
Thepermissions block in settings.json blocks dangerous commands:
Related Documentation
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
