All files / agent/src healthMonitor.ts

89.98% Statements 656/729
78.7% Branches 85/108
91.66% Functions 33/36
89.98% Lines 656/729

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 7291x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x 1x 1x 1x 1x 5x       5x 5x 5x 5x 5x 5x 5x 5x 5x 5x   5x 5x 5x 5x 4x 4x 4x 4x 4x     5x 5x 5x 5x 1x 1x 1x 1x 1x 10x 5x 5x 5x 10x 10x 10x 10x 10x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x     20x 20x 20x 20x       20x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 1x 1x 1x 1x 1x 20x 3x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 20x 20x 20x 20x 20x 20x 20x 20x 20x 4x 4x 4x 20x       16x 1x 1x 1x 20x 1x 1x 1x 1x 1x 4x               4x                   4x 1x 1x 1x 1x 1x 4x                                         4x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 8x 2x 2x 8x     6x 8x 4x 4x 4x 1x 1x 1x 1x 1x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 1x 1x 1x 1x 1x 3x 3x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 30x 30x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 4x 1x 1x 4x     3x 4x 1x 1x 1x 1x 1x 4x 3x 3x 3x 3x 3x 2x 2x 2x     3x 3x 3x 3x 3x 3x 3x 3x 4x 1x 1x 1x 1x 1x 4x 4x 4x 4x 1x 1x 4x 3x 3x 4x     4x   4x 4x 4x 4x 1x 1x 1x 1x 1x 4x 4x 4x 1x 1x 1x 1x 1x 1x       1x 1x 1x 3x 3x 3x 1x 1x       1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 3x 3x 3x 3x 1x 1x 3x 3x 3x 3x 3x 3x     3x 1x 1x 3x 3x 3x 3x 1x
/**
 * Health Monitor Module
 * 
 * Advanced health monitoring system for the BuildHive agent including:
 * - System resource monitoring
 * - Performance metrics tracking
 * - Predictive health analysis
 * - Automated recovery actions
 * 
 * Requirements: 6.1
 */
 
import * as os from 'os';
import * as fs from 'fs';
import * as path from 'path';
import { EventEmitter } from 'events';
import { createLogger } from './utils/logger.js';
 
const logger = createLogger('health-monitor');
 
export interface HealthMetrics {
  timestamp: Date;
  system: {
    cpuUsage: number;
    memoryUsage: number;
    diskUsage: number;
    loadAverage: number[];
    uptime: number;
    networkConnections: number;
  };
  process: {
    memoryUsage: NodeJS.MemoryUsage;
    cpuUsage: NodeJS.CpuUsage;
    uptime: number;
    activeHandles: number;
    activeRequests: number;
  };
  application: {
    activeJobs: number;
    jobSuccessRate: number;
    averageJobDuration: number;
    errorRate: number;
    responseTime: number;
  };
}
 
export interface HealthThresholds {
  cpu: { warning: number; critical: number };
  memory: { warning: number; critical: number };
  disk: { warning: number; critical: number };
  errorRate: { warning: number; critical: number };
  responseTime: { warning: number; critical: number };
}
 
export interface HealthAlert {
  id: string;
  severity: 'info' | 'warning' | 'critical';
  category: 'system' | 'process' | 'application';
  metric: string;
  message: string;
  value: number;
  threshold: number;
  timestamp: Date;
  resolved?: Date;
}
 
export interface HealthTrend {
  metric: string;
  direction: 'improving' | 'stable' | 'degrading';
  confidence: number; // 0-100
  prediction: {
    nextValue: number;
    timeToThreshold?: number; // seconds
  };
}
 
export class HealthMonitor extends EventEmitter {
  private thresholds: HealthThresholds;
  private metrics: HealthMetrics[] = [];
  private alerts: Map<string, HealthAlert> = new Map();
  private monitoringInterval: NodeJS.Timeout | null = null;
  private isMonitoring = false;
  private maxMetricsHistory = 1000;
  private jobStats: Array<{ duration: number; success: boolean; timestamp: Date }> = [];
 
  constructor(thresholds?: Partial<HealthThresholds>) {
    super();
    
    this.thresholds = {
      cpu: { warning: 70, critical: 90 },
      memory: { warning: 80, critical: 95 },
      disk: { warning: 85, critical: 95 },
      errorRate: { warning: 10, critical: 25 },
      responseTime: { warning: 30, critical: 60 },
      ...thresholds
    };
  }
 
  /**
   * Start health monitoring
   */
  start(intervalSeconds: number = 30): void {
    if (this.isMonitoring) {
      logger.warn('Health monitoring is already running');
      return;
    }
 
    logger.info('Starting health monitoring', {
      interval: intervalSeconds,
      thresholds: this.thresholds
    });
 
    this.isMonitoring = true;
 
    // Perform initial health check
    this.collectMetrics().catch(error => {
      logger.error('Initial health check failed:', error);
    });
 
    // Schedule periodic monitoring
    this.monitoringInterval = setInterval(async () => {
      try {
        await this.collectMetrics();
        await this.analyzeHealth();
        await this.checkForRecovery();
      } catch (error) {
        logger.error('Health monitoring cycle failed:', error);
      }
    }, intervalSeconds * 1000);
 
    this.emit('started');
  }
 
  /**
   * Stop health monitoring
   */
  stop(): void {
    if (this.monitoringInterval) {
      clearInterval(this.monitoringInterval);
      this.monitoringInterval = null;
    }
 
    this.isMonitoring = false;
    logger.info('Health monitoring stopped');
    this.emit('stopped');
  }
 
  /**
   * Get current health status
   */
  getCurrentHealth(): {
    status: 'healthy' | 'warning' | 'critical';
    metrics: HealthMetrics | null;
    activeAlerts: HealthAlert[];
    trends: HealthTrend[];
    score: number; // 0-100
  } {
    const latestMetrics = this.metrics[this.metrics.length - 1] || null;
    const activeAlerts = Array.from(this.alerts.values()).filter(alert => !alert.resolved);
    const trends = this.calculateTrends();
    
    const status = this.determineOverallStatus(activeAlerts);
    const score = this.calculateHealthScore(latestMetrics, activeAlerts);
 
    return {
      status,
      metrics: latestMetrics,
      activeAlerts,
      trends,
      score
    };
  }
 
  /**
   * Record job execution for health tracking
   */
  recordJobExecution(duration: number, success: boolean): void {
    this.jobStats.push({
      duration,
      success,
      timestamp: new Date()
    });
 
    // Keep only recent job stats
    const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000);
    this.jobStats = this.jobStats.filter(stat => stat.timestamp > oneHourAgo);
  }
 
  /**
   * Get health history
   */
  getHealthHistory(hours: number = 24): HealthMetrics[] {
    const cutoff = new Date(Date.now() - hours * 60 * 60 * 1000);
    return this.metrics.filter(metric => metric.timestamp > cutoff);
  }
 
  /**
   * Get alert history
   */
  getAlertHistory(hours: number = 24): HealthAlert[] {
    const cutoff = new Date(Date.now() - hours * 60 * 60 * 1000);
    return Array.from(this.alerts.values()).filter(alert => alert.timestamp > cutoff);
  }
 
  /**
   * Update health thresholds
   */
  updateThresholds(newThresholds: Partial<HealthThresholds>): void {
    this.thresholds = { ...this.thresholds, ...newThresholds };
    logger.info('Health thresholds updated', this.thresholds);
    this.emit('thresholdsUpdated', this.thresholds);
  }
 
  /**
   * Collect comprehensive health metrics
   */
  private async collectMetrics(): Promise<void> {
    try {
      const timestamp = new Date();
      
      // System metrics
      const systemMetrics = await this.collectSystemMetrics();
      
      // Process metrics
      const processMetrics = this.collectProcessMetrics();
      
      // Application metrics
      const applicationMetrics = this.collectApplicationMetrics();
 
      const metrics: HealthMetrics = {
        timestamp,
        system: systemMetrics,
        process: processMetrics,
        application: applicationMetrics
      };
 
      this.metrics.push(metrics);
 
      // Maintain metrics history limit
      if (this.metrics.length > this.maxMetricsHistory) {
        this.metrics = this.metrics.slice(-this.maxMetricsHistory);
      }
 
      this.emit('metricsCollected', metrics);
 
    } catch (error) {
      logger.error('Failed to collect health metrics:', error);
      throw error;
    }
  }
 
  /**
   * Collect system-level metrics
   */
  private async collectSystemMetrics(): Promise<HealthMetrics['system']> {
    const cpuUsage = await this.getCpuUsage();
    const memoryUsage = this.getMemoryUsage();
    const diskUsage = await this.getDiskUsage();
    const loadAverage = os.loadavg();
    const uptime = os.uptime();
    const networkConnections = await this.getNetworkConnections();
 
    return {
      cpuUsage,
      memoryUsage,
      diskUsage,
      loadAverage,
      uptime,
      networkConnections
    };
  }
 
  /**
   * Collect process-level metrics
   */
  private collectProcessMetrics(): HealthMetrics['process'] {
    const memoryUsage = process.memoryUsage();
    const cpuUsage = process.cpuUsage();
    const uptime = process.uptime();
    
    // Get active handles and requests (Node.js specific)
    const activeHandles = (process as any)._getActiveHandles?.()?.length || 0;
    const activeRequests = (process as any)._getActiveRequests?.()?.length || 0;
 
    return {
      memoryUsage,
      cpuUsage,
      uptime,
      activeHandles,
      activeRequests
    };
  }
 
  /**
   * Collect application-level metrics
   */
  private collectApplicationMetrics(): HealthMetrics['application'] {
    const recentJobs = this.jobStats.filter(job => 
      Date.now() - job.timestamp.getTime() < 60 * 60 * 1000 // Last hour
    );
 
    const totalJobs = recentJobs.length;
    const successfulJobs = recentJobs.filter(job => job.success).length;
    const jobSuccessRate = totalJobs > 0 ? (successfulJobs / totalJobs) * 100 : 100;
    const errorRate = 100 - jobSuccessRate;
    
    const averageJobDuration = totalJobs > 0 ? 
      recentJobs.reduce((sum, job) => sum + job.duration, 0) / totalJobs : 0;
 
    // Mock response time - in real implementation, this would track API response times
    const responseTime = Math.random() * 10 + 5; // 5-15 seconds
 
    return {
      activeJobs: 0, // Would be tracked by the agent
      jobSuccessRate,
      averageJobDuration,
      errorRate,
      responseTime
    };
  }
 
  /**
   * Analyze health and generate alerts
   */
  private async analyzeHealth(): Promise<void> {
    const latestMetrics = this.metrics[this.metrics.length - 1];
    if (!latestMetrics) return;
 
    // Check CPU usage
    this.checkThreshold('cpu', latestMetrics.system.cpuUsage, this.thresholds.cpu, 'system');
 
    // Check memory usage
    this.checkThreshold('memory', latestMetrics.system.memoryUsage, this.thresholds.memory, 'system');
 
    // Check disk usage
    this.checkThreshold('disk', latestMetrics.system.diskUsage, this.thresholds.disk, 'system');
 
    // Check error rate
    this.checkThreshold('errorRate', latestMetrics.application.errorRate, this.thresholds.errorRate, 'application');
 
    // Check response time
    this.checkThreshold('responseTime', latestMetrics.application.responseTime, this.thresholds.responseTime, 'application');
 
    // Check for memory leaks
    this.checkMemoryLeak(latestMetrics);
 
    // Check for performance degradation
    this.checkPerformanceDegradation();
  }
 
  /**
   * Check a metric against thresholds
   */
  private checkThreshold(
    metric: string,
    value: number,
    threshold: { warning: number; critical: number },
    category: HealthAlert['category']
  ): void {
    const alertId = `${category}-${metric}`;
    const existingAlert = this.alerts.get(alertId);
 
    if (value >= threshold.critical) {
      if (!existingAlert || existingAlert.severity !== 'critical') {
        this.createAlert(alertId, 'critical', category, metric, value, threshold.critical);
      }
    } else if (value >= threshold.warning) {
      if (!existingAlert || existingAlert.severity !== 'warning') {
        this.createAlert(alertId, 'warning', category, metric, value, threshold.warning);
      }
    } else if (existingAlert && !existingAlert.resolved) {
      // Resolve existing alert
      this.resolveAlert(alertId);
    }
  }
 
  /**
   * Check for memory leaks
   */
  private checkMemoryLeak(metrics: HealthMetrics): void {
    if (this.metrics.length < 10) return; // Need enough history

    const recentMetrics = this.metrics.slice(-10);
    const memoryTrend = this.calculateLinearTrend(
      recentMetrics.map(m => m.process.memoryUsage.heapUsed)
    );

    // If memory is consistently growing and above threshold
    if (memoryTrend.slope > 1024 * 1024 && metrics.process.memoryUsage.heapUsed > 200 * 1024 * 1024) { // 1MB/check, 200MB total
      this.createAlert(
        'memory-leak',
        'warning',
        'process',
        'memoryLeak',
        metrics.process.memoryUsage.heapUsed,
        200 * 1024 * 1024
      );
    }
  }
 
  /**
   * Check for performance degradation
   */
  private checkPerformanceDegradation(): void {
    if (this.jobStats.length < 10) return;

    const recentJobs = this.jobStats.slice(-10);
    const olderJobs = this.jobStats.slice(-20, -10);

    if (olderJobs.length === 0) return;

    const recentAvgDuration = recentJobs.reduce((sum, job) => sum + job.duration, 0) / recentJobs.length;
    const olderAvgDuration = olderJobs.reduce((sum, job) => sum + job.duration, 0) / olderJobs.length;

    // If recent jobs are taking 50% longer on average
    if (recentAvgDuration > olderAvgDuration * 1.5) {
      this.createAlert(
        'performance-degradation',
        'warning',
        'application',
        'jobDuration',
        recentAvgDuration,
        olderAvgDuration * 1.5
      );
    }
  }
 
  /**
   * Create a new alert
   */
  private createAlert(
    id: string,
    severity: HealthAlert['severity'],
    category: HealthAlert['category'],
    metric: string,
    value: number,
    threshold: number
  ): void {
    const alert: HealthAlert = {
      id,
      severity,
      category,
      metric,
      message: this.generateAlertMessage(metric, value, threshold, severity),
      value,
      threshold,
      timestamp: new Date()
    };
 
    this.alerts.set(id, alert);
    
    logger.warn(`Health alert created: ${alert.message}`, {
      id,
      severity,
      category,
      metric,
      value,
      threshold
    });
 
    this.emit('alert', alert);
 
    // Trigger recovery actions for critical alerts
    if (severity === 'critical') {
      this.triggerRecoveryAction(alert);
    }
  }
 
  /**
   * Resolve an alert
   */
  private resolveAlert(id: string): void {
    const alert = this.alerts.get(id);
    if (alert && !alert.resolved) {
      alert.resolved = new Date();
      
      logger.info(`Health alert resolved: ${alert.message}`, { id });
      this.emit('alertResolved', alert);
    }
  }
 
  /**
   * Generate alert message
   */
  private generateAlertMessage(metric: string, value: number, threshold: number, severity: string): string {
    const formatValue = (val: number) => {
      if (metric.includes('memory') || metric.includes('Memory')) {
        return `${(val / 1024 / 1024).toFixed(1)}MB`;
      }
      if (metric.includes('Usage') || metric.includes('Rate')) {
        return `${val.toFixed(1)}%`;
      }
      return val.toFixed(1);
    };
 
    return `${severity.toUpperCase()}: ${metric} is ${formatValue(value)} (threshold: ${formatValue(threshold)})`;
  }
 
  /**
   * Calculate trends for metrics
   */
  private calculateTrends(): HealthTrend[] {
    if (this.metrics.length < 5) return [];
 
    const trends: HealthTrend[] = [];
    const recentMetrics = this.metrics.slice(-10);
 
    // CPU trend
    const cpuValues = recentMetrics.map(m => m.system.cpuUsage);
    const cpuTrend = this.calculateLinearTrend(cpuValues);
    trends.push(this.createTrend('cpu', cpuTrend, this.thresholds.cpu.warning));
 
    // Memory trend
    const memoryValues = recentMetrics.map(m => m.system.memoryUsage);
    const memoryTrend = this.calculateLinearTrend(memoryValues);
    trends.push(this.createTrend('memory', memoryTrend, this.thresholds.memory.warning));
 
    // Error rate trend
    const errorValues = recentMetrics.map(m => m.application.errorRate);
    const errorTrend = this.calculateLinearTrend(errorValues);
    trends.push(this.createTrend('errorRate', errorTrend, this.thresholds.errorRate.warning));
 
    return trends;
  }
 
  /**
   * Create trend analysis
   */
  private createTrend(metric: string, trend: { slope: number; r2: number }, threshold: number): HealthTrend {
    const direction: HealthTrend['direction'] = 
      Math.abs(trend.slope) < 0.1 ? 'stable' :
      trend.slope > 0 ? 'degrading' : 'improving';
 
    const confidence = Math.min(100, trend.r2 * 100);
    
    // Predict next value (simplified)
    const currentValue = this.metrics[this.metrics.length - 1];
    const nextValue = this.getMetricValue(currentValue, metric) + trend.slope;
    
    // Calculate time to threshold
    let timeToThreshold: number | undefined;
    if (direction === 'degrading' && trend.slope > 0) {
      const currentVal = this.getMetricValue(currentValue, metric);
      if (currentVal < threshold) {
        timeToThreshold = Math.max(0, (threshold - currentVal) / trend.slope * 30); // 30 seconds per data point
      }
    }
 
    return {
      metric,
      direction,
      confidence,
      prediction: {
        nextValue,
        timeToThreshold
      }
    };
  }
 
  /**
   * Get metric value from health metrics
   */
  private getMetricValue(metrics: HealthMetrics, metric: string): number {
    switch (metric) {
      case 'cpu': return metrics.system.cpuUsage;
      case 'memory': return metrics.system.memoryUsage;
      case 'disk': return metrics.system.diskUsage;
      case 'errorRate': return metrics.application.errorRate;
      case 'responseTime': return metrics.application.responseTime;
      default: return 0;
    }
  }
 
  /**
   * Calculate linear trend
   */
  private calculateLinearTrend(values: number[]): { slope: number; r2: number } {
    if (values.length < 2) return { slope: 0, r2: 0 };
 
    const n = values.length;
    const x = Array.from({ length: n }, (_, i) => i);
    const y = values;
 
    const sumX = x.reduce((a, b) => a + b, 0);
    const sumY = y.reduce((a, b) => a + b, 0);
    const sumXY = x.reduce((sum, xi, i) => sum + xi * y[i], 0);
    const sumXX = x.reduce((sum, xi) => sum + xi * xi, 0);
    const sumYY = y.reduce((sum, yi) => sum + yi * yi, 0);
 
    const slope = (n * sumXY - sumX * sumY) / (n * sumXX - sumX * sumX);
    const intercept = (sumY - slope * sumX) / n;
 
    // Calculate R-squared
    const yMean = sumY / n;
    const ssRes = y.reduce((sum, yi, i) => {
      const predicted = slope * x[i] + intercept;
      return sum + Math.pow(yi - predicted, 2);
    }, 0);
    const ssTot = y.reduce((sum, yi) => sum + Math.pow(yi - yMean, 2), 0);
    const r2 = ssTot === 0 ? 1 : 1 - (ssRes / ssTot);
 
    return { slope, r2: Math.max(0, r2) };
  }
 
  /**
   * Determine overall health status
   */
  private determineOverallStatus(alerts: HealthAlert[]): 'healthy' | 'warning' | 'critical' {
    if (alerts.some(alert => alert.severity === 'critical')) {
      return 'critical';
    }
    if (alerts.some(alert => alert.severity === 'warning')) {
      return 'warning';
    }
    return 'healthy';
  }
 
  /**
   * Calculate overall health score
   */
  private calculateHealthScore(metrics: HealthMetrics | null, alerts: HealthAlert[]): number {
    if (!metrics) return 0;
 
    let score = 100;
 
    // Deduct points for active alerts
    alerts.forEach(alert => {
      if (alert.severity === 'critical') {
        score -= 30;
      } else if (alert.severity === 'warning') {
        score -= 15;
      }
    });
 
    // Deduct points based on metric values
    score -= Math.max(0, (metrics.system.cpuUsage - 50) / 2);
    score -= Math.max(0, (metrics.system.memoryUsage - 60) / 2);
    score -= Math.max(0, (metrics.application.errorRate - 5) * 2);
 
    return Math.max(0, Math.min(100, score));
  }
 
  /**
   * Trigger recovery actions for critical alerts
   */
  private triggerRecoveryAction(alert: HealthAlert): void {
    logger.info(`Triggering recovery action for critical alert: ${alert.metric}`);
 
    switch (alert.metric) {
      case 'memory':
        this.triggerGarbageCollection();
        break;
      case 'cpu':
        this.reduceProcessingLoad();
        break;
      case 'disk':
        this.cleanupTempFiles();
        break;
      default:
        logger.debug(`No specific recovery action for metric: ${alert.metric}`);
    }
 
    this.emit('recoveryAction', { alert, action: alert.metric });
  }
 
  /**
   * Check for alert recovery
   */
  private async checkForRecovery(): Promise<void> {
    // This would implement logic to check if critical conditions have improved
    // and potentially restart services or take other recovery actions
  }
 
  /**
   * Recovery action implementations
   */
  private triggerGarbageCollection(): void {
    if (global.gc) {
      global.gc();
      logger.info('Garbage collection triggered');
    }
  }
 
  private reduceProcessingLoad(): void {
    // This would implement logic to reduce CPU load
    logger.info('Processing load reduction triggered');
  }
 
  private cleanupTempFiles(): void {
    // This would implement logic to clean up temporary files
    logger.info('Temporary file cleanup triggered');
  }
 
  /**
   * System metric collection helpers
   */
  private async getCpuUsage(): Promise<number> {
    // Simple CPU usage calculation
    const startUsage = process.cpuUsage();
    await new Promise(resolve => setTimeout(resolve, 100));
    const endUsage = process.cpuUsage(startUsage);
    
    const totalUsage = endUsage.user + endUsage.system;
    return (totalUsage / 100000) / os.cpus().length; // Convert to percentage
  }
 
  private getMemoryUsage(): number {
    const totalMem = os.totalmem();
    const freeMem = os.freemem();
    return ((totalMem - freeMem) / totalMem) * 100;
  }
 
  private async getDiskUsage(): Promise<number> {
    try {
      const stats = fs.statSync(process.cwd());
      // This is a simplified implementation
      // In practice, you'd use a library like 'diskusage' or system commands
      return Math.random() * 100; // Mock value
    } catch (error) {
      return 0;
    }
  }
 
  private async getNetworkConnections(): Promise<number> {
    // This would count active network connections
    // For now, return a mock value
    return Math.floor(Math.random() * 50);
  }
}