claude-mpm 3.9.9__py3-none-any.whl → 3.9.11__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- claude_mpm/VERSION +1 -1
- claude_mpm/agents/templates/memory_manager.json +155 -0
- claude_mpm/cli/__init__.py +15 -2
- claude_mpm/cli/commands/__init__.py +3 -0
- claude_mpm/cli/commands/mcp.py +280 -134
- claude_mpm/cli/commands/run_guarded.py +511 -0
- claude_mpm/cli/parser.py +8 -2
- claude_mpm/config/experimental_features.py +219 -0
- claude_mpm/config/memory_guardian_yaml.py +335 -0
- claude_mpm/constants.py +1 -0
- claude_mpm/core/memory_aware_runner.py +353 -0
- claude_mpm/services/infrastructure/context_preservation.py +537 -0
- claude_mpm/services/infrastructure/graceful_degradation.py +616 -0
- claude_mpm/services/infrastructure/health_monitor.py +775 -0
- claude_mpm/services/infrastructure/memory_dashboard.py +479 -0
- claude_mpm/services/infrastructure/memory_guardian.py +189 -15
- claude_mpm/services/infrastructure/restart_protection.py +642 -0
- claude_mpm/services/infrastructure/state_manager.py +774 -0
- claude_mpm/services/mcp_gateway/__init__.py +11 -11
- claude_mpm/services/mcp_gateway/core/__init__.py +2 -2
- claude_mpm/services/mcp_gateway/core/interfaces.py +10 -9
- claude_mpm/services/mcp_gateway/main.py +35 -5
- claude_mpm/services/mcp_gateway/manager.py +334 -0
- claude_mpm/services/mcp_gateway/registry/service_registry.py +4 -8
- claude_mpm/services/mcp_gateway/server/__init__.py +2 -2
- claude_mpm/services/mcp_gateway/server/{mcp_server.py → mcp_gateway.py} +60 -59
- claude_mpm/services/mcp_gateway/tools/base_adapter.py +1 -2
- claude_mpm/services/ticket_manager.py +8 -8
- claude_mpm/services/ticket_manager_di.py +5 -5
- claude_mpm/storage/__init__.py +9 -0
- claude_mpm/storage/state_storage.py +556 -0
- {claude_mpm-3.9.9.dist-info → claude_mpm-3.9.11.dist-info}/METADATA +25 -2
- {claude_mpm-3.9.9.dist-info → claude_mpm-3.9.11.dist-info}/RECORD +37 -24
- claude_mpm/services/mcp_gateway/server/mcp_server_simple.py +0 -444
- {claude_mpm-3.9.9.dist-info → claude_mpm-3.9.11.dist-info}/WHEEL +0 -0
- {claude_mpm-3.9.9.dist-info → claude_mpm-3.9.11.dist-info}/entry_points.txt +0 -0
- {claude_mpm-3.9.9.dist-info → claude_mpm-3.9.11.dist-info}/licenses/LICENSE +0 -0
- {claude_mpm-3.9.9.dist-info → claude_mpm-3.9.11.dist-info}/top_level.txt +0 -0
| @@ -0,0 +1,479 @@ | |
| 1 | 
            +
            """Memory monitoring dashboard for Memory Guardian system.
         | 
| 2 | 
            +
             | 
| 3 | 
            +
            Provides real-time memory usage display, restart history, and metrics export.
         | 
| 4 | 
            +
            """
         | 
| 5 | 
            +
             | 
| 6 | 
            +
            import asyncio
         | 
| 7 | 
            +
            import json
         | 
| 8 | 
            +
            import time
         | 
| 9 | 
            +
            from dataclasses import dataclass
         | 
| 10 | 
            +
            from datetime import datetime, timedelta
         | 
| 11 | 
            +
            from pathlib import Path
         | 
| 12 | 
            +
            from typing import Dict, List, Optional, Any, Tuple
         | 
| 13 | 
            +
             | 
| 14 | 
            +
            from claude_mpm.services.core.base import BaseService
         | 
| 15 | 
            +
            from claude_mpm.services.infrastructure.memory_guardian import MemoryGuardian, MemoryState
         | 
| 16 | 
            +
            from claude_mpm.services.infrastructure.restart_protection import RestartProtection
         | 
| 17 | 
            +
            from claude_mpm.services.infrastructure.health_monitor import HealthMonitor
         | 
| 18 | 
            +
            from claude_mpm.services.infrastructure.graceful_degradation import GracefulDegradation
         | 
| 19 | 
            +
             | 
| 20 | 
            +
             | 
| 21 | 
            +
            @dataclass
         | 
| 22 | 
            +
            class DashboardMetrics:
         | 
| 23 | 
            +
                """Dashboard metrics snapshot."""
         | 
| 24 | 
            +
                timestamp: float
         | 
| 25 | 
            +
                memory_current_mb: float
         | 
| 26 | 
            +
                memory_peak_mb: float
         | 
| 27 | 
            +
                memory_average_mb: float
         | 
| 28 | 
            +
                memory_state: str
         | 
| 29 | 
            +
                process_state: str
         | 
| 30 | 
            +
                process_uptime_hours: float
         | 
| 31 | 
            +
                total_restarts: int
         | 
| 32 | 
            +
                recent_restarts: int
         | 
| 33 | 
            +
                health_status: str
         | 
| 34 | 
            +
                degradation_level: str
         | 
| 35 | 
            +
                active_features: int
         | 
| 36 | 
            +
                degraded_features: int
         | 
| 37 | 
            +
                
         | 
| 38 | 
            +
                def to_dict(self) -> Dict[str, Any]:
         | 
| 39 | 
            +
                    """Convert to dictionary."""
         | 
| 40 | 
            +
                    return {
         | 
| 41 | 
            +
                        'timestamp': self.timestamp,
         | 
| 42 | 
            +
                        'timestamp_iso': datetime.fromtimestamp(self.timestamp).isoformat(),
         | 
| 43 | 
            +
                        'memory': {
         | 
| 44 | 
            +
                            'current_mb': round(self.memory_current_mb, 2),
         | 
| 45 | 
            +
                            'peak_mb': round(self.memory_peak_mb, 2),
         | 
| 46 | 
            +
                            'average_mb': round(self.memory_average_mb, 2),
         | 
| 47 | 
            +
                            'state': self.memory_state
         | 
| 48 | 
            +
                        },
         | 
| 49 | 
            +
                        'process': {
         | 
| 50 | 
            +
                            'state': self.process_state,
         | 
| 51 | 
            +
                            'uptime_hours': round(self.process_uptime_hours, 2)
         | 
| 52 | 
            +
                        },
         | 
| 53 | 
            +
                        'restarts': {
         | 
| 54 | 
            +
                            'total': self.total_restarts,
         | 
| 55 | 
            +
                            'recent': self.recent_restarts
         | 
| 56 | 
            +
                        },
         | 
| 57 | 
            +
                        'health': {
         | 
| 58 | 
            +
                            'status': self.health_status,
         | 
| 59 | 
            +
                            'degradation_level': self.degradation_level,
         | 
| 60 | 
            +
                            'active_features': self.active_features,
         | 
| 61 | 
            +
                            'degraded_features': self.degraded_features
         | 
| 62 | 
            +
                        }
         | 
| 63 | 
            +
                    }
         | 
| 64 | 
            +
             | 
| 65 | 
            +
             | 
| 66 | 
            +
            class MemoryDashboard(BaseService):
         | 
| 67 | 
            +
                """Dashboard service for memory monitoring visualization and metrics."""
         | 
| 68 | 
            +
                
         | 
| 69 | 
            +
                def __init__(
         | 
| 70 | 
            +
                    self,
         | 
| 71 | 
            +
                    memory_guardian: Optional[MemoryGuardian] = None,
         | 
| 72 | 
            +
                    restart_protection: Optional[RestartProtection] = None,
         | 
| 73 | 
            +
                    health_monitor: Optional[HealthMonitor] = None,
         | 
| 74 | 
            +
                    graceful_degradation: Optional[GracefulDegradation] = None,
         | 
| 75 | 
            +
                    metrics_file: Optional[Path] = None,
         | 
| 76 | 
            +
                    export_interval_seconds: int = 60
         | 
| 77 | 
            +
                ):
         | 
| 78 | 
            +
                    """Initialize memory dashboard service.
         | 
| 79 | 
            +
                    
         | 
| 80 | 
            +
                    Args:
         | 
| 81 | 
            +
                        memory_guardian: MemoryGuardian service instance
         | 
| 82 | 
            +
                        restart_protection: RestartProtection service instance
         | 
| 83 | 
            +
                        health_monitor: HealthMonitor service instance
         | 
| 84 | 
            +
                        graceful_degradation: GracefulDegradation service instance
         | 
| 85 | 
            +
                        metrics_file: Optional file for metrics export
         | 
| 86 | 
            +
                        export_interval_seconds: Interval for metrics export
         | 
| 87 | 
            +
                    """
         | 
| 88 | 
            +
                    super().__init__("MemoryDashboard")
         | 
| 89 | 
            +
                    
         | 
| 90 | 
            +
                    # Service dependencies
         | 
| 91 | 
            +
                    self.memory_guardian = memory_guardian
         | 
| 92 | 
            +
                    self.restart_protection = restart_protection
         | 
| 93 | 
            +
                    self.health_monitor = health_monitor
         | 
| 94 | 
            +
                    self.graceful_degradation = graceful_degradation
         | 
| 95 | 
            +
                    
         | 
| 96 | 
            +
                    # Configuration
         | 
| 97 | 
            +
                    self.metrics_file = metrics_file
         | 
| 98 | 
            +
                    self.export_interval = export_interval_seconds
         | 
| 99 | 
            +
                    
         | 
| 100 | 
            +
                    # Metrics tracking
         | 
| 101 | 
            +
                    self.metrics_history: List[DashboardMetrics] = []
         | 
| 102 | 
            +
                    self.export_task: Optional[asyncio.Task] = None
         | 
| 103 | 
            +
                    self.dashboard_active = False
         | 
| 104 | 
            +
                    
         | 
| 105 | 
            +
                    self.log_info("Memory dashboard initialized")
         | 
| 106 | 
            +
                
         | 
| 107 | 
            +
                async def initialize(self) -> bool:
         | 
| 108 | 
            +
                    """Initialize the memory dashboard service.
         | 
| 109 | 
            +
                    
         | 
| 110 | 
            +
                    Returns:
         | 
| 111 | 
            +
                        True if initialization successful
         | 
| 112 | 
            +
                    """
         | 
| 113 | 
            +
                    try:
         | 
| 114 | 
            +
                        self.log_info("Initializing memory dashboard service")
         | 
| 115 | 
            +
                        
         | 
| 116 | 
            +
                        # Verify service dependencies
         | 
| 117 | 
            +
                        if not self.memory_guardian:
         | 
| 118 | 
            +
                            self.log_warning("Memory Guardian not available, dashboard running in limited mode")
         | 
| 119 | 
            +
                        
         | 
| 120 | 
            +
                        # Start metrics export if configured
         | 
| 121 | 
            +
                        if self.metrics_file and self.export_interval > 0:
         | 
| 122 | 
            +
                            self.export_task = asyncio.create_task(self._export_metrics_loop())
         | 
| 123 | 
            +
                        
         | 
| 124 | 
            +
                        self._initialized = True
         | 
| 125 | 
            +
                        self.log_info("Memory dashboard service initialized successfully")
         | 
| 126 | 
            +
                        return True
         | 
| 127 | 
            +
                        
         | 
| 128 | 
            +
                    except Exception as e:
         | 
| 129 | 
            +
                        self.log_error(f"Failed to initialize memory dashboard: {e}")
         | 
| 130 | 
            +
                        return False
         | 
| 131 | 
            +
                
         | 
| 132 | 
            +
                async def shutdown(self) -> None:
         | 
| 133 | 
            +
                    """Shutdown the memory dashboard service."""
         | 
| 134 | 
            +
                    try:
         | 
| 135 | 
            +
                        self.log_info("Shutting down memory dashboard service")
         | 
| 136 | 
            +
                        
         | 
| 137 | 
            +
                        # Stop export task
         | 
| 138 | 
            +
                        if self.export_task:
         | 
| 139 | 
            +
                            self.export_task.cancel()
         | 
| 140 | 
            +
                            try:
         | 
| 141 | 
            +
                                await self.export_task
         | 
| 142 | 
            +
                            except asyncio.CancelledError:
         | 
| 143 | 
            +
                                pass
         | 
| 144 | 
            +
                        
         | 
| 145 | 
            +
                        # Export final metrics
         | 
| 146 | 
            +
                        if self.metrics_file:
         | 
| 147 | 
            +
                            self._export_metrics()
         | 
| 148 | 
            +
                        
         | 
| 149 | 
            +
                        self._shutdown = True
         | 
| 150 | 
            +
                        self.log_info("Memory dashboard service shutdown complete")
         | 
| 151 | 
            +
                        
         | 
| 152 | 
            +
                    except Exception as e:
         | 
| 153 | 
            +
                        self.log_error(f"Error during memory dashboard shutdown: {e}")
         | 
| 154 | 
            +
                
         | 
| 155 | 
            +
                def get_current_metrics(self) -> DashboardMetrics:
         | 
| 156 | 
            +
                    """Get current system metrics.
         | 
| 157 | 
            +
                    
         | 
| 158 | 
            +
                    Returns:
         | 
| 159 | 
            +
                        DashboardMetrics snapshot
         | 
| 160 | 
            +
                    """
         | 
| 161 | 
            +
                    # Get memory metrics
         | 
| 162 | 
            +
                    memory_current = 0.0
         | 
| 163 | 
            +
                    memory_peak = 0.0
         | 
| 164 | 
            +
                    memory_average = 0.0
         | 
| 165 | 
            +
                    memory_state = "unknown"
         | 
| 166 | 
            +
                    process_state = "unknown"
         | 
| 167 | 
            +
                    process_uptime = 0.0
         | 
| 168 | 
            +
                    total_restarts = 0
         | 
| 169 | 
            +
                    
         | 
| 170 | 
            +
                    if self.memory_guardian:
         | 
| 171 | 
            +
                        status = self.memory_guardian.get_status()
         | 
| 172 | 
            +
                        memory_current = status['memory']['current_mb']
         | 
| 173 | 
            +
                        memory_peak = status['memory']['peak_mb']
         | 
| 174 | 
            +
                        memory_average = status['memory']['average_mb']
         | 
| 175 | 
            +
                        memory_state = status['memory']['state']
         | 
| 176 | 
            +
                        process_state = status['process']['state']
         | 
| 177 | 
            +
                        process_uptime = status['process']['uptime_hours']
         | 
| 178 | 
            +
                        total_restarts = status['restarts']['total']
         | 
| 179 | 
            +
                    
         | 
| 180 | 
            +
                    # Get restart metrics
         | 
| 181 | 
            +
                    recent_restarts = 0
         | 
| 182 | 
            +
                    if self.restart_protection:
         | 
| 183 | 
            +
                        stats = self.restart_protection.get_restart_statistics()
         | 
| 184 | 
            +
                        recent_restarts = len([
         | 
| 185 | 
            +
                            r for r in self.restart_protection.restart_history
         | 
| 186 | 
            +
                            if r.timestamp >= time.time() - 3600
         | 
| 187 | 
            +
                        ])
         | 
| 188 | 
            +
                    
         | 
| 189 | 
            +
                    # Get health metrics
         | 
| 190 | 
            +
                    health_status = "unknown"
         | 
| 191 | 
            +
                    if self.health_monitor:
         | 
| 192 | 
            +
                        health = self.health_monitor.get_health_status()
         | 
| 193 | 
            +
                        if health:
         | 
| 194 | 
            +
                            health_status = health.status.value
         | 
| 195 | 
            +
                    
         | 
| 196 | 
            +
                    # Get degradation metrics
         | 
| 197 | 
            +
                    degradation_level = "normal"
         | 
| 198 | 
            +
                    active_features = 0
         | 
| 199 | 
            +
                    degraded_features = 0
         | 
| 200 | 
            +
                    if self.graceful_degradation:
         | 
| 201 | 
            +
                        status = self.graceful_degradation.get_status()
         | 
| 202 | 
            +
                        degradation_level = status.level.value
         | 
| 203 | 
            +
                        active_features = status.available_features
         | 
| 204 | 
            +
                        degraded_features = status.degraded_features
         | 
| 205 | 
            +
                    
         | 
| 206 | 
            +
                    return DashboardMetrics(
         | 
| 207 | 
            +
                        timestamp=time.time(),
         | 
| 208 | 
            +
                        memory_current_mb=memory_current,
         | 
| 209 | 
            +
                        memory_peak_mb=memory_peak,
         | 
| 210 | 
            +
                        memory_average_mb=memory_average,
         | 
| 211 | 
            +
                        memory_state=memory_state,
         | 
| 212 | 
            +
                        process_state=process_state,
         | 
| 213 | 
            +
                        process_uptime_hours=process_uptime,
         | 
| 214 | 
            +
                        total_restarts=total_restarts,
         | 
| 215 | 
            +
                        recent_restarts=recent_restarts,
         | 
| 216 | 
            +
                        health_status=health_status,
         | 
| 217 | 
            +
                        degradation_level=degradation_level,
         | 
| 218 | 
            +
                        active_features=active_features,
         | 
| 219 | 
            +
                        degraded_features=degraded_features
         | 
| 220 | 
            +
                    )
         | 
| 221 | 
            +
                
         | 
| 222 | 
            +
                def get_dashboard_data(self) -> Dict[str, Any]:
         | 
| 223 | 
            +
                    """Get comprehensive dashboard data.
         | 
| 224 | 
            +
                    
         | 
| 225 | 
            +
                    Returns:
         | 
| 226 | 
            +
                        Dictionary with all dashboard information
         | 
| 227 | 
            +
                    """
         | 
| 228 | 
            +
                    current_metrics = self.get_current_metrics()
         | 
| 229 | 
            +
                    
         | 
| 230 | 
            +
                    # Get restart history
         | 
| 231 | 
            +
                    restart_history = []
         | 
| 232 | 
            +
                    if self.restart_protection:
         | 
| 233 | 
            +
                        stats = self.restart_protection.get_restart_statistics()
         | 
| 234 | 
            +
                        restart_history = [
         | 
| 235 | 
            +
                            r.to_dict() for r in 
         | 
| 236 | 
            +
                            list(self.restart_protection.restart_history)[-10:]
         | 
| 237 | 
            +
                        ]
         | 
| 238 | 
            +
                    
         | 
| 239 | 
            +
                    # Get health checks
         | 
| 240 | 
            +
                    health_checks = []
         | 
| 241 | 
            +
                    if self.health_monitor:
         | 
| 242 | 
            +
                        health = self.health_monitor.get_health_status()
         | 
| 243 | 
            +
                        if health:
         | 
| 244 | 
            +
                            health_checks = [c.to_dict() for c in health.checks]
         | 
| 245 | 
            +
                    
         | 
| 246 | 
            +
                    # Get feature status
         | 
| 247 | 
            +
                    features = []
         | 
| 248 | 
            +
                    if self.graceful_degradation:
         | 
| 249 | 
            +
                        status = self.graceful_degradation.get_status()
         | 
| 250 | 
            +
                        features = [f.to_dict() for f in status.features]
         | 
| 251 | 
            +
                    
         | 
| 252 | 
            +
                    # Get thresholds
         | 
| 253 | 
            +
                    thresholds = {}
         | 
| 254 | 
            +
                    if self.memory_guardian:
         | 
| 255 | 
            +
                        config = self.memory_guardian.config
         | 
| 256 | 
            +
                        thresholds = {
         | 
| 257 | 
            +
                            'warning_mb': config.thresholds.warning,
         | 
| 258 | 
            +
                            'critical_mb': config.thresholds.critical,
         | 
| 259 | 
            +
                            'emergency_mb': config.thresholds.emergency
         | 
| 260 | 
            +
                        }
         | 
| 261 | 
            +
                    
         | 
| 262 | 
            +
                    return {
         | 
| 263 | 
            +
                        'current_metrics': current_metrics.to_dict(),
         | 
| 264 | 
            +
                        'thresholds': thresholds,
         | 
| 265 | 
            +
                        'restart_history': restart_history,
         | 
| 266 | 
            +
                        'health_checks': health_checks,
         | 
| 267 | 
            +
                        'features': features,
         | 
| 268 | 
            +
                        'metrics_history': [m.to_dict() for m in self.metrics_history[-50:]],
         | 
| 269 | 
            +
                        'timestamp': time.time()
         | 
| 270 | 
            +
                    }
         | 
| 271 | 
            +
                
         | 
| 272 | 
            +
                def get_summary(self) -> str:
         | 
| 273 | 
            +
                    """Get a text summary of current status.
         | 
| 274 | 
            +
                    
         | 
| 275 | 
            +
                    Returns:
         | 
| 276 | 
            +
                        Human-readable status summary
         | 
| 277 | 
            +
                    """
         | 
| 278 | 
            +
                    metrics = self.get_current_metrics()
         | 
| 279 | 
            +
                    
         | 
| 280 | 
            +
                    lines = [
         | 
| 281 | 
            +
                        "=" * 60,
         | 
| 282 | 
            +
                        "MEMORY GUARDIAN DASHBOARD",
         | 
| 283 | 
            +
                        "=" * 60,
         | 
| 284 | 
            +
                        "",
         | 
| 285 | 
            +
                        "MEMORY STATUS",
         | 
| 286 | 
            +
                        "-" * 30,
         | 
| 287 | 
            +
                        f"Current:  {metrics.memory_current_mb:8.2f} MB",
         | 
| 288 | 
            +
                        f"Peak:     {metrics.memory_peak_mb:8.2f} MB",
         | 
| 289 | 
            +
                        f"Average:  {metrics.memory_average_mb:8.2f} MB",
         | 
| 290 | 
            +
                        f"State:    {metrics.memory_state.upper()}",
         | 
| 291 | 
            +
                        "",
         | 
| 292 | 
            +
                        "PROCESS STATUS",
         | 
| 293 | 
            +
                        "-" * 30,
         | 
| 294 | 
            +
                        f"State:    {metrics.process_state}",
         | 
| 295 | 
            +
                        f"Uptime:   {metrics.process_uptime_hours:.2f} hours",
         | 
| 296 | 
            +
                        "",
         | 
| 297 | 
            +
                        "RESTART STATISTICS",
         | 
| 298 | 
            +
                        "-" * 30,
         | 
| 299 | 
            +
                        f"Total:    {metrics.total_restarts}",
         | 
| 300 | 
            +
                        f"Recent:   {metrics.recent_restarts} (last hour)",
         | 
| 301 | 
            +
                        ""
         | 
| 302 | 
            +
                    ]
         | 
| 303 | 
            +
                    
         | 
| 304 | 
            +
                    # Add restart protection info
         | 
| 305 | 
            +
                    if self.restart_protection:
         | 
| 306 | 
            +
                        stats = self.restart_protection.get_restart_statistics()
         | 
| 307 | 
            +
                        lines.extend([
         | 
| 308 | 
            +
                            "RESTART PROTECTION",
         | 
| 309 | 
            +
                            "-" * 30,
         | 
| 310 | 
            +
                            f"Circuit:  {stats.circuit_state.value}",
         | 
| 311 | 
            +
                            f"Failures: {stats.consecutive_failures}",
         | 
| 312 | 
            +
                            ""
         | 
| 313 | 
            +
                        ])
         | 
| 314 | 
            +
                        
         | 
| 315 | 
            +
                        # Add memory trend if available
         | 
| 316 | 
            +
                        if stats.memory_trend and stats.memory_trend.is_leak_suspected:
         | 
| 317 | 
            +
                            lines.extend([
         | 
| 318 | 
            +
                                "⚠️  MEMORY LEAK SUSPECTED",
         | 
| 319 | 
            +
                                f"Growth:   {stats.memory_trend.slope_mb_per_min:.2f} MB/min",
         | 
| 320 | 
            +
                                ""
         | 
| 321 | 
            +
                            ])
         | 
| 322 | 
            +
                    
         | 
| 323 | 
            +
                    # Add health status
         | 
| 324 | 
            +
                    lines.extend([
         | 
| 325 | 
            +
                        "SYSTEM HEALTH",
         | 
| 326 | 
            +
                        "-" * 30,
         | 
| 327 | 
            +
                        f"Status:   {metrics.health_status}",
         | 
| 328 | 
            +
                        f"Level:    {metrics.degradation_level}",
         | 
| 329 | 
            +
                        ""
         | 
| 330 | 
            +
                    ])
         | 
| 331 | 
            +
                    
         | 
| 332 | 
            +
                    # Add feature status if degraded
         | 
| 333 | 
            +
                    if metrics.degraded_features > 0:
         | 
| 334 | 
            +
                        lines.extend([
         | 
| 335 | 
            +
                            "DEGRADED FEATURES",
         | 
| 336 | 
            +
                            "-" * 30
         | 
| 337 | 
            +
                        ])
         | 
| 338 | 
            +
                        
         | 
| 339 | 
            +
                        if self.graceful_degradation:
         | 
| 340 | 
            +
                            status = self.graceful_degradation.get_status()
         | 
| 341 | 
            +
                            for feature in status.features:
         | 
| 342 | 
            +
                                if feature.state.value != 'available':
         | 
| 343 | 
            +
                                    lines.append(f"• {feature.name}: {feature.state.value}")
         | 
| 344 | 
            +
                        
         | 
| 345 | 
            +
                        lines.append("")
         | 
| 346 | 
            +
                    
         | 
| 347 | 
            +
                    # Add timestamp
         | 
| 348 | 
            +
                    lines.extend([
         | 
| 349 | 
            +
                        "-" * 60,
         | 
| 350 | 
            +
                        f"Updated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
         | 
| 351 | 
            +
                    ])
         | 
| 352 | 
            +
                    
         | 
| 353 | 
            +
                    return "\n".join(lines)
         | 
| 354 | 
            +
                
         | 
| 355 | 
            +
                def export_prometheus_metrics(self) -> str:
         | 
| 356 | 
            +
                    """Export metrics in Prometheus format.
         | 
| 357 | 
            +
                    
         | 
| 358 | 
            +
                    Returns:
         | 
| 359 | 
            +
                        Prometheus-formatted metrics string
         | 
| 360 | 
            +
                    """
         | 
| 361 | 
            +
                    metrics = self.get_current_metrics()
         | 
| 362 | 
            +
                    timestamp = int(metrics.timestamp * 1000)
         | 
| 363 | 
            +
                    
         | 
| 364 | 
            +
                    lines = [
         | 
| 365 | 
            +
                        "# HELP memory_current_mb Current memory usage in megabytes",
         | 
| 366 | 
            +
                        "# TYPE memory_current_mb gauge",
         | 
| 367 | 
            +
                        f"memory_current_mb {metrics.memory_current_mb} {timestamp}",
         | 
| 368 | 
            +
                        "",
         | 
| 369 | 
            +
                        "# HELP memory_peak_mb Peak memory usage in megabytes",
         | 
| 370 | 
            +
                        "# TYPE memory_peak_mb gauge",
         | 
| 371 | 
            +
                        f"memory_peak_mb {metrics.memory_peak_mb} {timestamp}",
         | 
| 372 | 
            +
                        "",
         | 
| 373 | 
            +
                        "# HELP memory_average_mb Average memory usage in megabytes",
         | 
| 374 | 
            +
                        "# TYPE memory_average_mb gauge",
         | 
| 375 | 
            +
                        f"memory_average_mb {metrics.memory_average_mb} {timestamp}",
         | 
| 376 | 
            +
                        "",
         | 
| 377 | 
            +
                        "# HELP process_uptime_hours Process uptime in hours",
         | 
| 378 | 
            +
                        "# TYPE process_uptime_hours counter",
         | 
| 379 | 
            +
                        f"process_uptime_hours {metrics.process_uptime_hours} {timestamp}",
         | 
| 380 | 
            +
                        "",
         | 
| 381 | 
            +
                        "# HELP total_restarts Total number of process restarts",
         | 
| 382 | 
            +
                        "# TYPE total_restarts counter",
         | 
| 383 | 
            +
                        f"total_restarts {metrics.total_restarts} {timestamp}",
         | 
| 384 | 
            +
                        "",
         | 
| 385 | 
            +
                        "# HELP recent_restarts Number of restarts in the last hour",
         | 
| 386 | 
            +
                        "# TYPE recent_restarts gauge",
         | 
| 387 | 
            +
                        f"recent_restarts {metrics.recent_restarts} {timestamp}",
         | 
| 388 | 
            +
                        "",
         | 
| 389 | 
            +
                        "# HELP degraded_features Number of degraded system features",
         | 
| 390 | 
            +
                        "# TYPE degraded_features gauge",
         | 
| 391 | 
            +
                        f"degraded_features {metrics.degraded_features} {timestamp}",
         | 
| 392 | 
            +
                        ""
         | 
| 393 | 
            +
                    ]
         | 
| 394 | 
            +
                    
         | 
| 395 | 
            +
                    # Add memory state as labeled metric
         | 
| 396 | 
            +
                    memory_state_value = {
         | 
| 397 | 
            +
                        'normal': 0,
         | 
| 398 | 
            +
                        'warning': 1,
         | 
| 399 | 
            +
                        'critical': 2,
         | 
| 400 | 
            +
                        'emergency': 3
         | 
| 401 | 
            +
                    }.get(metrics.memory_state.lower(), -1)
         | 
| 402 | 
            +
                    
         | 
| 403 | 
            +
                    lines.extend([
         | 
| 404 | 
            +
                        "# HELP memory_state Current memory state (0=normal, 1=warning, 2=critical, 3=emergency)",
         | 
| 405 | 
            +
                        "# TYPE memory_state gauge",
         | 
| 406 | 
            +
                        f"memory_state {memory_state_value} {timestamp}",
         | 
| 407 | 
            +
                        ""
         | 
| 408 | 
            +
                    ])
         | 
| 409 | 
            +
                    
         | 
| 410 | 
            +
                    # Add health status as labeled metric
         | 
| 411 | 
            +
                    health_value = {
         | 
| 412 | 
            +
                        'healthy': 0,
         | 
| 413 | 
            +
                        'degraded': 1,
         | 
| 414 | 
            +
                        'unhealthy': 2,
         | 
| 415 | 
            +
                        'critical': 3
         | 
| 416 | 
            +
                    }.get(metrics.health_status.lower(), -1)
         | 
| 417 | 
            +
                    
         | 
| 418 | 
            +
                    lines.extend([
         | 
| 419 | 
            +
                        "# HELP health_status System health status (0=healthy, 1=degraded, 2=unhealthy, 3=critical)",
         | 
| 420 | 
            +
                        "# TYPE health_status gauge",
         | 
| 421 | 
            +
                        f"health_status {health_value} {timestamp}"
         | 
| 422 | 
            +
                    ])
         | 
| 423 | 
            +
                    
         | 
| 424 | 
            +
                    return "\n".join(lines)
         | 
| 425 | 
            +
                
         | 
| 426 | 
            +
                def export_json_metrics(self) -> str:
         | 
| 427 | 
            +
                    """Export metrics in JSON format.
         | 
| 428 | 
            +
                    
         | 
| 429 | 
            +
                    Returns:
         | 
| 430 | 
            +
                        JSON-formatted metrics string
         | 
| 431 | 
            +
                    """
         | 
| 432 | 
            +
                    data = self.get_dashboard_data()
         | 
| 433 | 
            +
                    return json.dumps(data, indent=2)
         | 
| 434 | 
            +
                
         | 
| 435 | 
            +
                async def _export_metrics_loop(self) -> None:
         | 
| 436 | 
            +
                    """Background task to export metrics periodically."""
         | 
| 437 | 
            +
                    while not self._shutdown:
         | 
| 438 | 
            +
                        try:
         | 
| 439 | 
            +
                            # Collect metrics
         | 
| 440 | 
            +
                            metrics = self.get_current_metrics()
         | 
| 441 | 
            +
                            self.metrics_history.append(metrics)
         | 
| 442 | 
            +
                            
         | 
| 443 | 
            +
                            # Trim history
         | 
| 444 | 
            +
                            if len(self.metrics_history) > 1440:  # Keep 24 hours at 1-minute intervals
         | 
| 445 | 
            +
                                self.metrics_history = self.metrics_history[-1440:]
         | 
| 446 | 
            +
                            
         | 
| 447 | 
            +
                            # Export to file
         | 
| 448 | 
            +
                            if self.metrics_file:
         | 
| 449 | 
            +
                                self._export_metrics()
         | 
| 450 | 
            +
                            
         | 
| 451 | 
            +
                            await asyncio.sleep(self.export_interval)
         | 
| 452 | 
            +
                            
         | 
| 453 | 
            +
                        except Exception as e:
         | 
| 454 | 
            +
                            self.log_error(f"Error in metrics export loop: {e}")
         | 
| 455 | 
            +
                            await asyncio.sleep(self.export_interval)
         | 
| 456 | 
            +
                
         | 
| 457 | 
            +
                def _export_metrics(self) -> None:
         | 
| 458 | 
            +
                    """Export metrics to file."""
         | 
| 459 | 
            +
                    if not self.metrics_file:
         | 
| 460 | 
            +
                        return
         | 
| 461 | 
            +
                    
         | 
| 462 | 
            +
                    try:
         | 
| 463 | 
            +
                        # Determine format from file extension
         | 
| 464 | 
            +
                        if self.metrics_file.suffix == '.json':
         | 
| 465 | 
            +
                            content = self.export_json_metrics()
         | 
| 466 | 
            +
                        elif self.metrics_file.suffix == '.prom':
         | 
| 467 | 
            +
                            content = self.export_prometheus_metrics()
         | 
| 468 | 
            +
                        else:
         | 
| 469 | 
            +
                            # Default to JSON
         | 
| 470 | 
            +
                            content = self.export_json_metrics()
         | 
| 471 | 
            +
                        
         | 
| 472 | 
            +
                        # Write to file
         | 
| 473 | 
            +
                        self.metrics_file.parent.mkdir(parents=True, exist_ok=True)
         | 
| 474 | 
            +
                        self.metrics_file.write_text(content)
         | 
| 475 | 
            +
                        
         | 
| 476 | 
            +
                        self.log_debug(f"Exported metrics to {self.metrics_file}")
         | 
| 477 | 
            +
                        
         | 
| 478 | 
            +
                    except Exception as e:
         | 
| 479 | 
            +
                        self.log_error(f"Failed to export metrics: {e}")
         |