docs: Complete Framework-Hooks documentation overhaul

Major documentation update focused on technical accuracy and developer clarity:

Documentation Changes:
- Rewrote README.md with focus on hooks system architecture
- Updated all core docs (Overview, Integration, Performance) to match implementation
- Created 6 missing configuration docs for undocumented YAML files
- Updated all 7 hook docs to reflect actual Python implementations
- Created docs for 2 missing shared modules (intelligence_engine, validate_system)
- Updated all 5 pattern docs with real YAML examples
- Added 4 essential operational docs (INSTALLATION, TROUBLESHOOTING, CONFIGURATION, QUICK_REFERENCE)

Key Improvements:
- Removed all marketing language in favor of humble technical documentation
- Fixed critical configuration discrepancies (logging defaults, performance targets)
- Used actual code examples and configuration from implementation
- Complete coverage: 15 configs, 10 modules, 7 hooks, 3 pattern tiers
- Based all documentation on actual file review and code analysis

Technical Accuracy:
- Corrected performance targets to match performance.yaml
- Fixed timeout values from settings.json (10-15 seconds)
- Updated module count and descriptions to match actual shared/ directory
- Aligned all examples with actual YAML and Python implementations

The documentation now provides accurate, practical information for developers
working with the Framework-Hooks system, focusing on what it actually does
rather than aspirational features.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
NomenAK
2025-08-06 15:13:07 +02:00
parent ff7eda0e8a
commit 9edf3f8802
52 changed files with 4990 additions and 10202 deletions

View File

@@ -1,53 +1,26 @@
# Notification Hook Documentation
## Overview
The notification hook implements just-in-time capability loading and pattern updates for the SuperClaude-Lite framework. This hook runs on notification events in Claude Code and provides intelligent, on-demand resource loading instead of upfront documentation loading, enabling a pattern-driven approach that reduces context usage by 90%.
## Purpose
**Just-in-Time Capability Loading and Pattern Updates**
The `notification` hook processes notification events from Claude Code and provides just-in-time capability loading and pattern updates. It handles various notification types to trigger appropriate SuperClaude framework responses.
The notification hook transforms the SuperClaude framework from a static documentation loader into a dynamic, intelligent system that loads capabilities precisely when needed. Key purposes include:
- **On-Demand Resource Loading**: Load MCP server documentation and patterns only when specific capabilities are required
- **Dynamic Pattern Updates**: Update framework patterns in real-time based on operation context and usage effectiveness
- **Intelligence Caching**: Implement performance-optimized caching strategies to minimize repeated loading overhead
- **Real-Time Learning**: Adapt framework behavior based on notification patterns and operational effectiveness
- **Context Optimization**: Reduce framework context overhead by 90% through selective, just-in-time loading
**Core Implementation**: Responds to Claude Code notifications (errors, performance issues, tool requests, context changes) with intelligent resource loading and pattern updates to minimize context overhead.
## Execution Context
### When This Hook Runs
The notification hook runs on notification events from Claude Code. According to `settings.json`, it has a 10-second timeout and executes via: `python3 ~/.claude/hooks/notification.py`
The notification hook executes on **notification events** from Claude Code, specifically:
**Notification Types Handled:**
- **High Priority**: error, failure, security_alert, performance_issue, validation_failure
- **Medium Priority**: tool_request, context_change, resource_constraint
- **Low Priority**: info, debug, status_update
#### Primary Triggers
- **Tool Request Notifications**: When Claude Code requests specific tools or capabilities
- **Context Change Notifications**: When the operational context shifts (project type, complexity, domain)
- **Performance Issue Notifications**: When resource constraints or performance issues are detected
- **Error/Failure Notifications**: When operations fail and recovery intelligence is needed
- **Operation Start/Complete Notifications**: When major operations begin or conclude
#### Notification Types Processed
```yaml
high_priority:
- error # System errors requiring immediate intelligence loading
- failure # Operation failures needing recovery patterns
- security_alert # Security issues requiring specialized documentation
- performance_issue # Performance problems needing optimization patterns
- validation_failure # Validation errors requiring compliance patterns
medium_priority:
- tool_request # Tool usage requiring MCP documentation
- context_change # Context shifts requiring pattern updates
- resource_constraint # Resource limitations requiring optimization
low_priority:
- info # Informational notifications
- debug # Debug notifications
- status_update # Status change notifications
```
**Actual Processing:**
1. Receives notification event via stdin (JSON)
2. Determines notification priority and type
3. Loads appropriate capabilities or patterns on-demand
4. Updates framework intelligence based on notification context
5. Outputs response configuration via stdout (JSON)
#### Integration Points
- **Pre-Tool Use Hook**: Coordinates with tool selection intelligence

View File

@@ -2,37 +2,32 @@
## Purpose
The **post_tool_use hook** implements comprehensive validation and learning after every tool execution in Claude Code. It serves as the primary quality assurance and continuous improvement mechanism for the SuperClaude framework, ensuring operations comply with RULES.md and PRINCIPLES.md while learning from each execution to enhance future performance.
The `post_tool_use` hook analyzes tool execution results and provides validation, quality assessment, and learning feedback after every tool execution in Claude Code. It implements validation against SuperClaude principles and records learning events for continuous improvement.
**Core Functions:**
- **Quality Validation**: Verifies tool execution against SuperClaude framework standards
- **Rules Compliance**: Enforces RULES.md operational requirements and safety protocols
- **Principles Alignment**: Validates adherence to PRINCIPLES.md development philosophy
- **Effectiveness Measurement**: Quantifies operation success and learning value
- **Error Pattern Detection**: Identifies and learns from recurring issues and failures
- **Learning Integration**: Records insights for continuous framework improvement
**Core Implementation**: A 794-line Python implementation that validates tool results against RULES.md and PRINCIPLES.md, measures effectiveness, detects error patterns, and records learning events with a target execution time of <100ms.
## Execution Context
The post_tool_use hook **runs after every tool use** in Claude Code, providing universal validation coverage across all operations.
The post_tool_use hook runs after every tool execution in Claude Code. According to `settings.json`, it has a 10-second timeout and executes via: `python3 ~/.claude/hooks/post_tool_use.py`
**Execution Trigger Points:**
- **Universal Coverage**: Activated after every tool execution (Read, Write, Edit, Bash, etc.)
- **Automatic Activation**: No manual intervention required - built into Claude Code's execution pipeline
- **Real-Time Processing**: Immediate validation and feedback on tool results
- **Session Integration**: Maintains context across multiple tool executions within a session
**Actual Execution Flow:**
1. Receives tool execution result from Claude Code via stdin (JSON)
2. Initializes PostToolUseHook class with shared module components
3. Processes tool result through `process_tool_result()` method
4. Validates results against SuperClaude principles and measures effectiveness
5. Outputs comprehensive validation report via stdout (JSON)
6. Falls back gracefully on errors with basic validation report
**Input Processing:**
- Receives complete tool execution result via stdin as JSON
- Extracts execution context including parameters, results, errors, and performance data
- Analyzes operation characteristics and quality indicators
- Enriches context with framework-specific metadata
**Input Analysis:**
- Extracts execution context (tool name, status, timing, parameters, results, errors)
- Analyzes operation outcome (success, performance, quality indicators)
- Evaluates quality indicators (code quality, security compliance, performance efficiency)
**Output Generation:**
- Comprehensive validation report with quality scores and compliance status
- Actionable recommendations for improvement and optimization
- Learning insights and pattern detection results
- Performance metrics and effectiveness measurements
**Output Reporting:**
- Validation results (quality score, issues, warnings, suggestions)
- Effectiveness metrics (overall effectiveness, quality/performance/satisfaction scores)
- Learning analysis (patterns detected, success/failure factors, optimization opportunities)
- Compliance assessment (rules compliance, principles alignment, SuperClaude score)
## Performance Target

View File

@@ -1,39 +1,22 @@
# pre_compact Hook Technical Documentation
## Overview
The `pre_compact` hook implements SuperClaude's intelligent token optimization system, executing before context compaction in Claude Code to achieve 30-50% token reduction while maintaining ≥95% information preservation. This hook serves as the core implementation of `MODE_Token_Efficiency.md` compression algorithms.
## Purpose
**Token efficiency and compression before context compaction** - The pre_compact hook provides intelligent context optimization through adaptive compression strategies, symbol systems, and evidence-based validation. It operates as a preprocessing layer that optimizes content for efficient token usage while preserving semantic accuracy and technical correctness.
The `pre_compact` hook implements token optimization before context compaction in Claude Code. It analyzes content for compression opportunities, applies selective compression strategies, and maintains quality preservation targets while reducing token usage.
### Core Objectives
- **Resource Management**: Optimize token usage during large-scale operations and high resource utilization
- **Quality Preservation**: Maintain ≥95% information retention through selective compression strategies
- **Framework Protection**: Complete exclusion of SuperClaude framework content from compression
- **Adaptive Intelligence**: Context-aware compression based on content type, user expertise, and resource constraints
- **Performance Optimization**: Sub-150ms execution time for real-time compression decisions
**Core Implementation**: Implements MODE_Token_Efficiency.md compression algorithms with selective content classification, symbol systems, and quality-gated compression with a target execution time of <150ms.
## Execution Context
The pre_compact hook executes **before context compaction** in the Claude Code session lifecycle, triggered by:
The pre_compact hook runs before context compaction in Claude Code. According to `settings.json`, it has a 15-second timeout and executes via: `python3 ~/.claude/hooks/pre_compact.py`
### Automatic Activation Triggers
- **Resource Constraints**: Context usage >75%, memory pressure, conversation length thresholds
- **Performance Optimization**: Multi-MCP server coordination, extended sessions, complex analysis workflows
- **Content Characteristics**: Large content blocks, repetitive patterns, technical documentation
- **Framework Integration**: Wave coordination, task management operations, quality gate validation
### Execution Sequence
```
Claude Code Session → Context Analysis → pre_compact Hook → Compression Applied → Context Compaction → Response Generation
```
### Integration Points
- **Before**: Context analysis and resource state evaluation
- **During**: Selective compression with real-time quality validation
- **After**: Optimized content delivery to Claude Code context system
**Actual Execution Flow:**
1. Receives compaction request from Claude Code via stdin (JSON)
2. Initializes PreCompactHook class with compression engine and shared modules
3. Processes request through `process_pre_compact()` method
4. Analyzes content characteristics and determines compression strategy
5. Outputs compression configuration via stdout (JSON)
6. Falls back gracefully on errors with no compression applied
## Performance Target

View File

@@ -1,67 +1,35 @@
# Pre-Tool-Use Hook Technical Documentation
**Intelligent Tool Routing and MCP Server Selection Hook**
---
## Purpose
The `pre_tool_use` hook implements intelligent tool routing and MCP server selection for the SuperClaude framework. It runs before every tool execution in Claude Code, providing optimal tool configuration, MCP server coordination, and performance optimization within a strict 200ms execution target.
The `pre_tool_use` hook analyzes tool requests and provides intelligent routing decisions before tool execution in Claude Code. It determines optimal MCP server coordination, performance optimizations, and execution strategies based on tool characteristics and context.
**Core Value Proposition**:
- **Intelligent Routing**: Matches tool requests to optimal execution strategies using pattern detection
- **MCP Server Orchestration**: Coordinates multiple specialized servers (Context7, Sequential, Magic, Playwright, Morphllm, Serena)
- **Performance Optimization**: Parallel execution planning, caching strategies, and resource management
- **Adaptive Intelligence**: Learning-based routing improvements over time
- **Fallback Resilience**: Graceful degradation when preferred tools are unavailable
**Core Implementation**: A 648-line Python implementation that processes tool requests, analyzes operation characteristics, routes to appropriate MCP servers, and provides enhanced tool configurations with a target execution time of <200ms.
---
## Execution Context
### Trigger Event
The hook executes **before every tool use** in Claude Code, intercepting tool requests to enhance them with SuperClaude intelligence.
The pre_tool_use hook runs before every tool execution in Claude Code. According to `settings.json`, it has a 15-second timeout and executes via: `python3 ~/.claude/hooks/pre_tool_use.py`
### Execution Flow
```
Tool Request → pre_tool_use Hook → Enhanced Tool Configuration → Tool Execution
```
**Actual Execution Flow:**
1. Receives tool request from Claude Code via stdin (JSON)
2. Initializes PreToolUseHook class with shared module components
3. Processes tool request through `process_tool_use()` method
4. Analyzes operation characteristics and routing patterns
5. Outputs enhanced tool configuration via stdout (JSON)
6. Falls back gracefully on errors with basic tool configuration
### Input Context
```json
{
"tool_name": "Read|Write|Edit|Analyze|Build|Test|...",
"parameters": {...},
"user_intent": "natural language description",
"session_context": {...},
"previous_tools": [...],
"operation_sequence": [...],
"resource_state": {...}
}
```
**Input Processing:**
- Extracts tool context including tool name, parameters, user intent
- Analyzes operation characteristics (file count, complexity, parallelizability)
- Identifies tool chain patterns (read-edit, multi-file, analysis chains)
### Output Enhancement
```json
{
"tool_name": "original_tool",
"enhanced_mode": true,
"mcp_integration": {
"enabled": true,
"servers": ["serena", "sequential"],
"coordination_strategy": "collaborative"
},
"performance_optimization": {
"parallel_execution": true,
"caching_enabled": true,
"optimizations": ["parallel_file_processing"]
},
"execution_metadata": {
"estimated_time_ms": 1200,
"complexity_score": 0.65,
"intelligence_level": "medium"
}
}
```
**Output Configuration:**
- Enhanced mode flag and MCP server coordination
- Performance optimization settings (parallel execution, caching)
- Quality enhancement settings (validation, error recovery)
- Execution metadata (estimated time, complexity score, intelligence level)
---

View File

@@ -2,25 +2,22 @@
## Purpose
The session_start hook is the foundational intelligence layer of the SuperClaude-Lite framework that initializes every Claude Code session with intelligent, context-aware configuration. This hook transforms basic Claude Code sessions into SuperClaude-powered experiences by implementing comprehensive project analysis, intelligent mode detection, and optimized MCP server routing.
The session_start hook initializes Claude Code sessions with SuperClaude framework intelligence. It analyzes project context, detects patterns, and configures appropriate modes and MCP servers based on the actual session requirements.
The hook serves as the entry point for SuperClaude's session lifecycle pattern, establishing the groundwork for all subsequent intelligent behaviors including adaptive learning, performance optimization, and context preservation across sessions.
**Core Implementation**: A 704-line Python implementation that performs lazy loading, pattern detection, MCP intelligence routing, compression configuration, and learning adaptations with a target execution time of <50ms.
## Execution Context
The session_start hook executes at the very beginning of every Claude Code session, before any user interactions or tool executions occur. It sits at the critical initialization phase where session context is established and intelligence systems are activated.
The session_start hook runs automatically at the beginning of every Claude Code session. According to `settings.json`, it has a 10-second timeout and executes via: `python3 ~/.claude/hooks/session_start.py`
**Execution Flow Position:**
```
Claude Code Session Start → session_start Hook → Enhanced Session Configuration → User Interaction
```
**Actual Execution Flow:**
1. Receives session data from Claude Code via stdin (JSON)
2. Initializes SessionStartHook class with lazy loading of components
3. Processes session initialization with project analysis and pattern detection
4. Outputs enhanced session configuration via stdout (JSON)
5. Falls back gracefully on errors with basic session configuration
**Lifecycle Integration:**
- **Trigger**: Every new Claude Code session initialization
- **Duration**: Target <50ms execution time
- **Dependencies**: Session context data from Claude Code
- **Output**: Enhanced session configuration with SuperClaude intelligence
- **Next Phase**: Active session with intelligent routing and optimization
**Performance**: Target <50ms execution time (configurable via superclaude-config.json)
## Performance Target
@@ -42,105 +39,78 @@ This aggressive performance target is critical for maintaining seamless user exp
## Core Features
### 1. Smart Project Context Loading with Framework Exclusion
### 1. Project Structure Analysis
**Implementation**: The hook performs intelligent project structure analysis while implementing selective content loading to optimize performance and focus.
**Implementation**: The `_analyze_project_structure()` method performs quick project analysis by examining key files and directories.
**Technical Details:**
- **Rapid Project Scanning**: Limited file enumeration (max 100 files) for performance
- **Technology Stack Detection**: Identifies Node.js, Python, Rust, Go projects via manifest files
- **Framework Recognition**: Detects React, Vue, Angular, Express through dependency analysis
- **Production Environment Detection**: Identifies deployment configurations and CI/CD setup
- **Test Infrastructure Analysis**: Locates test directories and testing frameworks
- **Framework Exclusion Strategy**: Completely excludes SuperClaude framework directories from analysis to prevent recursive processing
**What it actually does:**
- Enumerates up to 100 files for performance (limits via `files[:100]`)
- Detects project type by checking for manifest files:
- `package.json` → nodejs
- `pyproject.toml` or `setup.py` → python
- `Cargo.toml` → rust
- `go.mod` → go
- Identifies frameworks by parsing package.json dependencies (React, Vue, Angular, Express)
- Checks for test directories and production indicators (Dockerfile, .env.production)
- Returns analysis dict with project_type, framework_detected, has_tests, is_production, etc.
**Code Implementation:**
```python
def _analyze_project_structure(self, project_path: Path) -> dict:
# Quick enumeration with performance limit
files = list(project_path.rglob('*'))[:100]
# Technology detection via manifest files
if (project_path / 'package.json').exists():
analysis['project_type'] = 'nodejs'
# Framework detection through dependency analysis
with open(package_json) as f:
deps = {**pkg_data.get('dependencies', {}), **pkg_data.get('devDependencies', {})}
if 'react' in deps: analysis['framework_detected'] = 'react'
```
### 2. User Intent Analysis and Mode Detection
### 2. Automatic Mode Detection and Activation
**Implementation**: The `_analyze_user_intent()` method examines user input to determine operation type and complexity.
**Implementation**: Uses pattern recognition algorithms to detect user intent and automatically activate appropriate SuperClaude behavioral modes.
**What it actually does:**
- Analyzes user input text for operation keywords:
- "build", "create", "implement" → BUILD operation (complexity +0.3)
- "fix", "debug", "troubleshoot" → ANALYZE operation (complexity +0.2)
- "refactor", "restructure" → REFACTOR operation (complexity +0.4)
- "test", "validate" → TEST operation (complexity +0.1)
- Detects brainstorming needs via keywords: "not sure", "thinking about", "maybe", "brainstorm"
- Calculates complexity score (0.0-1.0) based on operation type and complexity indicators
- The `_activate_intelligent_modes()` method activates modes based on detected patterns:
- brainstorming mode if `brainstorming_likely` is True
- task_management mode if recommended by pattern detection
- token_efficiency mode if recommended by pattern detection
**Detection Algorithms:**
- **Intent Analysis**: Natural language processing of user input for operation type detection
- **Complexity Scoring**: Multi-factor analysis including file count, operation type, and complexity indicators
- **Brainstorming Detection**: Identifies uncertainty indicators ("not sure", "maybe", "thinking about")
- **Task Management Triggers**: Detects multi-step operations and delegation opportunities
- **Token Efficiency Needs**: Identifies resource constraints and optimization requirements
### 3. MCP Server Configuration
**Mode Activation Logic:**
```python
def _activate_intelligent_modes(self, context: dict, recommendations: dict) -> list:
activated_modes = []
# Brainstorming mode activation
if context.get('brainstorming_likely', False):
activated_modes.append({'name': 'brainstorming', 'trigger': 'user input'})
# Task management mode activation
if 'task_management' in recommendations.get('recommended_modes', []):
activated_modes.append({'name': 'task_management', 'trigger': 'pattern detection'})
```
**Implementation**: The `_create_mcp_activation_plan()` and `_configure_mcp_servers()` methods determine which MCP servers to activate.
### 3. MCP Server Intelligence Routing
**What it actually does:**
- Uses MCPIntelligence class to create activation plans based on:
- User intent analysis
- Context characteristics (file count, complexity score, operation type)
- Project analysis results
- Returns MCP plan with:
- `servers_to_activate`: List of servers to enable
- `activation_order`: Sequence for server activation
- `coordination_strategy`: How servers should work together
- `estimated_cost_ms`: Performance impact estimate
- `fallback_strategy`: Backup plan if servers fail
**Implementation**: Intelligent analysis of project context and user intent to determine optimal MCP server activation strategy.
### 4. Learning Engine Integration
**Routing Intelligence:**
- **Context-Aware Selection**: Matches MCP server capabilities to detected project needs
- **Performance Optimization**: Considers server resource profiles and coordination costs
- **Fallback Strategy Planning**: Establishes backup activation patterns for server failures
- **Coordination Strategy**: Determines optimal server interaction patterns (parallel vs sequential)
**Implementation**: The `_apply_learning_adaptations()` method applies learned patterns to improve session configuration.
**Server Selection Matrix:**
- **Context7**: Activated for external library dependencies and framework integration needs
- **Sequential**: Enabled for complex analysis requirements and multi-step reasoning
- **Magic**: Triggered by UI component requests and design system needs
- **Playwright**: Activated for testing requirements and browser automation
- **Morphllm**: Enabled for pattern-based editing and token optimization scenarios
- **Serena**: Activated for semantic analysis and project memory management
**What it actually does:**
- Uses LearningEngine (initialized with `~/.claude/cache` directory) to:
- Apply previous adaptations to current recommendations
- Store user preferences (preferred tools per operation type)
- Update project-specific information (project type, framework)
- Record learning events for future sessions
- The `_record_session_learning()` method stores session initialization patterns for continuous improvement
### 4. User Preference Adaptation
### 5. Lazy Loading Architecture
**Implementation**: Applies machine learning-based adaptations from previous sessions to personalize the session configuration.
**Implementation**: The hook uses lazy loading via Python properties to minimize initialization time.
**Learning Integration:**
- **Historical Pattern Analysis**: Analyzes successful configurations from previous sessions
- **User Expertise Detection**: Infers user skill level from interaction patterns and terminology
- **Preference Extraction**: Identifies consistent user choices and optimization preferences
- **Adaptive Configuration**: Applies learned preferences to current session setup
**Learning Engine Integration:**
```python
def _apply_learning_adaptations(self, context: dict, detection_result: dict) -> dict:
enhanced_recommendations = self.learning_engine.apply_adaptations(
context, base_recommendations
)
return enhanced_recommendations
```
### 5. Performance-Optimized Initialization
**Implementation**: Comprehensive performance optimization strategy that balances intelligence with speed.
**Optimization Techniques:**
- **Lazy Loading**: Defers non-critical analysis until actual usage
- **Intelligent Caching**: Reuses previous analysis results when project context unchanged
- **Parallel Processing**: Concurrent execution of independent analysis components
- **Resource-Aware Configuration**: Adapts initialization depth based on available resources
- **Progressive Enhancement**: Enables additional features as resource budget allows
**What it actually does:**
- Core components are loaded immediately: `FrameworkLogic()`
- Other components use lazy loading properties:
- `pattern_detector` property loads `PatternDetector()` only when first accessed
- `mcp_intelligence` property loads `MCPIntelligence()` only when needed
- `compression_engine` property loads `CompressionEngine()` only when used
- `learning_engine` property loads `LearningEngine()` only when required
- This reduces initialization overhead and improves the <50ms performance target
## Implementation Details
@@ -304,122 +274,93 @@ def _detect_session_patterns(self, context: dict) -> dict:
### framework_logic.py
**Purpose**: Implements core SuperClaude decision-making algorithms from RULES.md, PRINCIPLES.md, and ORCHESTRATOR.md.
**Purpose**: Provides SuperClaude framework decision-making capabilities.
**Key Components Used:**
- `OperationType` enum for operation classification
- `OperationContext` dataclass for structured context management
- `RiskLevel` assessment for quality gate determination
- Quality gate configuration based on operation context
**Usage in session_start:**
```python
from framework_logic import FrameworkLogic, OperationContext, OperationType, RiskLevel
# Quality gate configuration
operation_context = OperationContext(
operation_type=context.get('operation_type', OperationType.READ),
file_count=context.get('file_count_estimate', 1),
complexity_score=context.get('complexity_score', 0.0),
risk_level=RiskLevel.LOW
)
return self.framework_logic.get_quality_gates(operation_context)
```
**Used in session_start.py:**
- `FrameworkLogic` class for quality gate configuration
- `OperationContext` dataclass for structured context management
- `OperationType` enum for operation classification (READ, WRITE, BUILD, etc.)
- `RiskLevel` enum for risk assessment
- Used in `_configure_quality_gates()` method to determine appropriate quality gates based on operation context
### pattern_detection.py
**Purpose**: Provides intelligent pattern recognition for session configuration.
**Purpose**: Analyzes patterns in user input and context for intelligent routing.
**Key Components Used:**
- Pattern matching algorithms for user intent detection
- Mode recommendation logic based on detected patterns
- MCP server selection recommendations
- Confidence scoring for pattern matches
**Used in session_start.py:**
- `PatternDetector` class (lazy loaded)
- `detect_patterns()` method for analyzing user intent, context, and operation data
- Returns pattern matches, recommended modes, recommended MCP servers, and confidence scores
### mcp_intelligence.py
**Purpose**: Implements intelligent MCP server selection and coordination.
**Purpose**: Provides MCP server activation planning and coordination strategies.
**Key Components Used:**
- MCP activation plan generation
- Server coordination strategy determination
- Performance cost estimation
- Fallback strategy planning
**Used in session_start.py:**
- `MCPIntelligence` class (lazy loaded)
- `create_activation_plan()` method for determining optimal MCP server coordination
- Returns activation plans with servers, order, cost estimates, and coordination strategies
### compression_engine.py
**Purpose**: Provides intelligent compression strategy selection for token efficiency.
**Purpose**: Handles compression strategy selection for token efficiency.
**Key Components Used:**
- Compression level determination based on context
- Quality impact estimation
- Compression savings calculation
- Selective compression configuration
**Used in session_start.py:**
- `CompressionEngine` class (lazy loaded)
- `determine_compression_level()` method for context-based compression decisions
- Used in `_configure_compression()` to set session compression strategy
### learning_engine.py
**Purpose**: Enables adaptive learning and preference application.
**Purpose**: Provides learning and adaptation capabilities for continuous improvement.
**Key Components Used:**
- Learning event recording for session patterns
- Adaptation application from previous sessions
- Effectiveness measurement and feedback loops
- Pattern recognition and improvement suggestions
**Used in session_start.py:**
- `LearningEngine` class (lazy loaded, initialized with `~/.claude/cache` directory)
- `apply_adaptations()` method for applying learned patterns
- `record_learning_event()` method for storing session initialization data
- `update_project_info()` and preference tracking methods
### yaml_loader.py
**Purpose**: Provides configuration loading and management capabilities.
**Purpose**: Configuration loading with fallback strategies.
**Key Components Used:**
- Hook-specific configuration loading
- YAML configuration file management
- Fallback configuration strategies
- Hot-reload configuration support
**Used in session_start.py:**
- `config_loader.get_hook_config()` for hook-specific configuration
- `config_loader.load_config()` for YAML configuration files with FileNotFoundError handling
- Fallback to hook configuration when YAML files are missing
### logger.py
**Purpose**: Provides comprehensive logging and metrics collection.
**Purpose**: Structured logging for hook execution tracking.
**Key Components Used:**
- Hook execution logging with timing
- Decision logging for audit trails
- Error logging with context preservation
- Performance metrics collection
**Used in session_start.py:**
- `log_hook_start()` and `log_hook_end()` for execution timing
- `log_decision()` for mode activation and MCP server selection decisions
- `log_error()` for error context preservation
## Error Handling
### Comprehensive Error Recovery Strategy
**Implementation**: The main `initialize_session()` method includes comprehensive error handling with graceful fallback.
**Error Categories and Responses:**
**What actually happens on errors:**
**1. Project Analysis Failures**
```python
def _analyze_project_structure(self, project_path: Path) -> dict:
try:
# Full project analysis
return comprehensive_analysis
except Exception:
# Return partial analysis with safe defaults
return basic_analysis_with_defaults
```
**2. Pattern Detection Failures**
- Fallback to basic mode configuration
- Use cached patterns from previous sessions
- Apply conservative intelligence settings
- Maintain core functionality without advanced features
**3. MCP Server Planning Failures**
- Disable problematic servers
- Use fallback server combinations
- Apply conservative coordination strategies
- Maintain basic tool functionality
**4. Learning System Failures**
- Disable adaptive features temporarily
- Use static configuration defaults
- Log errors for future analysis
- Preserve session functionality
1. **Exception Handling**: All errors are caught in the main try-except block
2. **Error Logging**: Errors are logged via `log_error()` with context
3. **Fallback Configuration**: `_create_fallback_session_config()` returns:
```python
{
'session_id': session_context.get('session_id', 'unknown'),
'superclaude_enabled': False,
'fallback_mode': True,
'error': error,
'basic_config': {
'compression_level': 'minimal',
'mcp_servers_enabled': False,
'learning_disabled': True
}
}
```
4. **Session Continuity**: Basic Claude Code functionality is preserved even when SuperClaude features fail
### Error Learning Integration

View File

@@ -1,33 +1,22 @@
# Stop Hook Documentation
## Overview
The Stop Hook is a comprehensive session analytics and persistence engine that runs at the end of each Claude Code session. It implements the `/sc:save` logic with advanced performance tracking, providing detailed analytics about session effectiveness, learning consolidation, and intelligent session data storage.
## Purpose
The Stop Hook serves as the primary session analytics and persistence system for SuperClaude Framework, delivering:
The `stop` hook provides session analytics and persistence when Claude Code sessions end. It implements session summarization, learning consolidation, and data storage for continuous framework improvement.
- **Session Analytics**: Comprehensive performance and effectiveness metrics
- **Learning Consolidation**: Consolidation of learning events from the entire session
- **Session Persistence**: Intelligent session data storage with compression
- **Performance Optimization**: Recommendations for future sessions based on analytics
- **Quality Assessment**: Session success evaluation and improvement suggestions
- **Framework Effectiveness**: Measurement of SuperClaude framework impact
**Core Implementation**: Analyzes complete session history, consolidates learning events, generates performance metrics, and persists session data for future analysis with a target execution time of <200ms.
## Execution Context
### When This Hook Runs
- **Trigger**: Session termination in Claude Code
- **Context**: End of user session, before final cleanup
- **Data Available**: Complete session history, operations log, error records
- **Timing**: After all user operations completed, before session cleanup
The stop hook runs at Claude Code session termination. According to `settings.json`, it has a 15-second timeout and executes via: `python3 ~/.claude/hooks/stop.py`
### Hook Integration Points
- **Session Lifecycle**: Final stage of session processing
- **MCP Intelligence**: Coordinates with MCP servers for enhanced analytics
- **Learning Engine**: Consolidates learning events and adaptations
- **Framework Logic**: Applies SuperClaude framework patterns for analysis
**Actual Execution Flow:**
1. Receives session termination data via stdin (JSON)
2. Initializes StopHook class with analytics and learning components
3. Analyzes complete session history and performance data
4. Consolidates learning events and generates session insights
5. Persists session data and analytics for future reference
6. Outputs session summary and analytics via stdout (JSON)
## Performance Target

View File

@@ -2,31 +2,26 @@
## Purpose
The `subagent_stop` hook implements **MODE_Task_Management delegation coordination and analytics** by analyzing subagent task completion performance and providing comprehensive delegation effectiveness measurement. This hook specializes in **task delegation analytics and coordination**, measuring multi-agent collaboration effectiveness and optimizing wave orchestration strategies.
The `subagent_stop` hook analyzes subagent task completion and provides delegation effectiveness measurement after subagent operations. It implements MODE_Task_Management delegation coordination analytics for multi-agent collaboration optimization.
**Core Responsibilities:**
- Analyze subagent task completion and performance metrics
- Measure delegation effectiveness and coordination success
- Learn from parallel execution patterns and cross-agent coordination
- Optimize wave orchestration strategies for multi-agent operations
- Coordinate cross-agent knowledge sharing and learning
- Track task management framework effectiveness across delegated operations
**Core Implementation**: Measures delegation effectiveness, analyzes cross-agent coordination patterns, and optimizes wave orchestration strategies with a target execution time of <150ms.
## Execution Context
The `subagent_stop` hook executes **after subagent operations complete** in Claude Code, specifically when:
The subagent_stop hook runs after subagent operations complete in Claude Code. According to `settings.json`, it has a 15-second timeout and executes via: `python3 ~/.claude/hooks/subagent_stop.py`
- **Subagent Task Completion**: When individual subagents finish their delegated tasks
- **Multi-Agent Coordination End**: After parallel task execution completes
- **Wave Orchestration Completion**: When wave-based task coordination finishes
- **Delegation Strategy Assessment**: For analyzing effectiveness of different delegation approaches
- **Cross-Agent Learning**: When coordination patterns need to be captured for future optimization
**Execution Triggers:**
- Individual subagent task completion
- Multi-agent coordination end
- Wave orchestration completion
- Delegation strategy assessment
**Integration Points:**
- Integrates with Claude Code's subagent delegation system
- Coordinates with MODE_Task_Management for delegation analytics
- Synchronizes with wave orchestration for multi-agent coordination
- Links with learning engine for continuous delegation improvement
**Actual Processing:**
1. Receives subagent completion data via stdin (JSON)
2. Analyzes delegation effectiveness and coordination patterns
3. Measures multi-agent collaboration success
4. Records learning events for delegation optimization
5. Outputs coordination analytics via stdout (JSON)
## Performance Target