# Impl Hooks ## How Claude Code Uses These Patterns ```yaml Pattern Loading: On Start: Load CLAUDE.md→RULES.md (core behavioral rules) On /persona:: Check if PERSONAS.md loaded→Load if needed→Cache session On MCP ref: Check if MCP.md loaded→Load if needed→Cache session Commands: Parse .claude/commands/*.md on /user: trigger→Cache recent 5 Shared: Include shared/*.yml when referenced by active commands Severity Enforcement: CRITICAL[10]: Block op & explain why HIGH[7-9]: Warn user & require confirmation MEDIUM[4-6]: Suggest improvement & continue LOW[1-3]: Note in output & proceed Auto-Triggers: File Open: Check extension→Load PERSONAS.md if needed→Activate persona Command Start: Load command def→Check ambiguity→Clarify if needed MCP Usage: Load MCP.md if needed→Select appropriate tool Risky Op: Create checkpoint→Log audit→Validate Error: Activate analyzer→Debug workflow ``` ## Pattern Integration ```yaml Todo Management: 3+ steps → TodoWrite() with tasks Status → Update immediately on change Complete → Mark done & suggest next MCP Selection: Parse request → Check complexity → Select tool Simple → Use native | Complex → Use MCP Monitor tokens → Switch/abort if exceeded Context Management: Track % → Warn at 60% → Force compact at 90% Task complete → Auto-compact context Project switch → Clear context ``` ## Command Execution ```yaml Pre-Execution: 1. Parse command & args 2. Check thinking mode flags: - --think: Activate standard thinking mode (4K tokens) - --think-hard: Activate deep analysis mode (10K tokens) - --ultrathink: Activate critical analysis mode (32K tokens) - Default: Basic mode if no thinking flag present 3. Check MCP control flags: - --c7/--no-c7: Control Context7 documentation server - --seq/--no-seq: Control Sequential thinking server - --magic/--no-magic: Control Magic UI builder - --pup/--no-pup: Control Puppeteer browser automation - --all-mcp: Enable all MCP servers - --no-mcp: Disable all MCP servers 4. Check risk level (shared/planning-mode.yml) 5. If --plan flag → Show plan → await approval 6. Check ambiguity (shared/ambiguity-check.yml) 7. Research verification (shared/research-first.yml): - External library detected → C7 resolve + get-docs REQUIRED - New UI component needed → Magic search or WebSearch patterns - API integration found → Official docs lookup REQUIRED - Unknown pattern detected → Sequential analysis + research - Block if: No research performed for external dependencies - Cache: Store researched patterns for session reuse 8. Preemptive validation: - Dependencies: package.json vs node_modules | Required tools installed - Permissions: File write access | Command availability - State: Clean git status for risky ops | No conflicting processes - Environment: Correct versions | Required env vars set 9. Validate permissions (shared/validation.yml) 10. Create checkpoint if risky 11. Log start (shared/audit.yml) 12. Documentation directory check (shared/documentation-dirs.yml): - Report generation? → Ensure .claudedocs/[subdirs] exist - Project docs? → Ensure /docs/[category] exists - Create directories if missing with proper permissions (755) - Validate write permissions to target directories 13. UltraCompressed check (shared/ultracompressed.yml): - --uc flag? → Apply compression rules to all output - Context >70%? → Suggest --uc mode - Token budget? → Auto-enable compression - Generate legend at start of compressed docs During: - Update todo status - Show progress indicators - Handle errors gracefully - Keep user informed Post-Execution: - Log completion/failure - Update todos - If report generated → Note location in output: "📄 Report saved to: [path]" - If docs created → Update /docs/index.md with new entries - Suggest next steps - Compact context if needed ``` ## Persona Activation ```yaml File-Based: *.tsx opened → frontend persona active *.sql opened → data persona active Dockerfile → devops persona active Keyword-Based: "optimize" in request → performance persona "secure" mentioned → security persona "refactor" → refactorer persona Context-Based: Error trace → analyzer persona Architecture question → architect persona Learning request → mentor persona Multi-Persona: Complex task → Sequential activation Parallel work → Concurrent personas Handoff → Share context between ``` ## Error Handling ```yaml Pattern Detection: Match error → Error type in patterns.yml Syntax → Check syntax highlighting Runtime → Validate inputs & types Logic → Trace execution flow Recovery: Try operation → Catch error → Check pattern Known → Apply fix pattern Unknown → Activate analyzer → Debug Can't fix → Explain & suggest manual fix ``` ## Token Optimization ```yaml Real-Time: Count tokens → Apply reduction patterns Remove listed words → Use symbols YAML format → Compress output Reference > repeat → Link to existing Batch Operations: Group similar → Single operation Parallel when possible → Reduce time Cache results → Avoid re-computation ``` ## Unified Behaviors ```yaml Error Format: All commands: [COMMAND] Error: What→Why→Fix Example: [BUILD] Error: Module X failed→Missing dep Y→Run npm install Y Result Format: Success: ✓ Action (Xms) | Details Warning: ⚠ Issue | Impact | Suggestion Failure: ✗ Error | Reason | Recovery Command Memory: Store: After each command → .claude/session/[command].cache Reuse: Check cache → Use if valid → Note "using prior analysis" Clear: On file change → Invalidate related caches ## Loading Optimization ```yaml Component Loading: Core: CLAUDE.md + RULES.md loaded on startup (~3500 tokens) Personas: Load on /persona: trigger → Cache for session MCP: Load on MCP tool reference → Cache for session Commands: Load on /user: trigger → Cache recent 5 Token Savings: Simple tasks: 43% reduction (6100→3500 tokens) With personas: 33% reduction (6100→4100 tokens) With commands: 20-30% reduction (varies by usage) Cache Strategy: Session-based: Keep loaded components until session ends LRU: Evict least recently used when memory limits reached Preload: Common patterns loaded proactively ``` --- *Implementation: How patterns become actions*