claude-flow 2.7.35 → 2.7.36

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.
Files changed (121) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/bin/claude-flow +1 -1
  3. package/dist/src/__tests__/benchmarks/performance.bench.js +0 -19
  4. package/dist/src/__tests__/benchmarks/performance.bench.js.map +1 -1
  5. package/dist/src/__tests__/hook-matchers.test.js.map +1 -1
  6. package/dist/src/agents/agent-registry.js.map +1 -1
  7. package/dist/src/api/auth-service.js.map +1 -1
  8. package/dist/src/api/claude-client-enhanced.js +4 -2
  9. package/dist/src/api/claude-client-enhanced.js.map +1 -1
  10. package/dist/src/api/claude-client.js +4 -2
  11. package/dist/src/api/claude-client.js.map +1 -1
  12. package/dist/src/api/database-service.js.map +1 -1
  13. package/dist/src/api/swarm-api.js +1 -1
  14. package/dist/src/api/swarm-api.js.map +1 -1
  15. package/dist/src/cli/commands/hive-mind/wizard.js +1 -1
  16. package/dist/src/cli/commands/hive-mind/wizard.js.map +1 -1
  17. package/dist/src/cli/simple-cli.js +172 -182
  18. package/dist/src/cli/simple-cli.js.map +1 -1
  19. package/dist/src/cli/simple-commands/init/skills-copier.js +1 -1
  20. package/dist/src/cli/simple-commands/init/skills-copier.js.map +1 -1
  21. package/dist/src/cli/simple-orchestrator.js +1 -1
  22. package/dist/src/cli/simple-orchestrator.js.map +1 -1
  23. package/dist/src/coordination/conflict-resolution.js +1 -1
  24. package/dist/src/coordination/conflict-resolution.js.map +1 -1
  25. package/dist/src/coordination/load-balancer.js +1 -1
  26. package/dist/src/coordination/load-balancer.js.map +1 -1
  27. package/dist/src/core/config.js +1 -1
  28. package/dist/src/core/config.js.map +1 -1
  29. package/dist/src/core/version.js +1 -1
  30. package/dist/src/enterprise/audit-manager.js +1 -1
  31. package/dist/src/enterprise/audit-manager.js.map +1 -1
  32. package/dist/src/providers/openai-provider.js +2 -2
  33. package/dist/src/providers/openai-provider.js.map +1 -1
  34. package/dist/src/sdk/checkpoint-manager.js +1 -1
  35. package/dist/src/sdk/checkpoint-manager.js.map +1 -1
  36. package/dist/src/services/agentic-flow-hooks/workflow-hooks.js +1 -1
  37. package/dist/src/services/agentic-flow-hooks/workflow-hooks.js.map +1 -1
  38. package/dist/src/swarm/coordinator.js +1 -1
  39. package/dist/src/swarm/coordinator.js.map +1 -1
  40. package/dist/src/utils/key-redactor.js.map +1 -1
  41. package/dist/src/utils/metrics-reader.js.map +1 -1
  42. package/dist/src/verification/rollback.js +2 -2
  43. package/dist/src/verification/rollback.js.map +1 -1
  44. package/dist/src/verification/tests/mocks/false-reporting-scenarios.test.js +4 -2
  45. package/dist/src/verification/tests/mocks/false-reporting-scenarios.test.js.map +1 -1
  46. package/docs/.claude-flow/metrics/performance.json +3 -3
  47. package/docs/.claude-flow/metrics/task-metrics.json +3 -3
  48. package/docs/architecture/README.md +555 -0
  49. package/docs/architecture/github-workflows-optimization-strategy.md +1079 -0
  50. package/docs/architecture/workflow-architecture-diagram.md +615 -0
  51. package/docs/architecture/workflow-optimization-implementation-guide.md +593 -0
  52. package/docs/fixes/WORKFLOW_FIXES.md +292 -0
  53. package/docs/fixes/WORKFLOW_FIXES_FINAL_STATUS.md +291 -0
  54. package/docs/fixes/github-workflow-fixes-pr888.md +279 -0
  55. package/docs/fixes/workflow-fixes-action-plan.md +388 -0
  56. package/docs/github-workflow-fixes.md +219 -0
  57. package/docs/reviews/github-workflows-analysis-report.md +820 -0
  58. package/docs/reviews/pr-888-review-report.md +560 -0
  59. package/docs/validation/workflow-fix-verification.md +206 -0
  60. package/package.json +7 -7
  61. package/src/__tests__/benchmarks/performance.bench.ts +2 -25
  62. package/src/__tests__/hook-matchers.test.ts +2 -0
  63. package/src/agents/agent-registry.ts +1 -1
  64. package/src/api/auth-service.ts +1 -1
  65. package/src/api/claude-client-enhanced.ts +2 -1
  66. package/src/api/claude-client.ts +2 -2
  67. package/src/api/database-service.ts +1 -2
  68. package/src/api/swarm-api.ts +2 -2
  69. package/src/cli/commands/hive-mind/wizard.ts +1 -1
  70. package/src/cli/simple-commands/init/skills-copier.js +1 -1
  71. package/src/cli/simple-orchestrator.ts +1 -1
  72. package/src/coordination/conflict-resolution.ts +1 -1
  73. package/src/coordination/load-balancer.ts +1 -1
  74. package/src/core/config.ts +1 -1
  75. package/src/enterprise/audit-manager.ts +1 -1
  76. package/src/providers/openai-provider.ts +2 -2
  77. package/src/sdk/checkpoint-manager.ts +1 -1
  78. package/src/services/agentic-flow-hooks/workflow-hooks.ts +1 -1
  79. package/src/swarm/coordinator.ts +1 -1
  80. package/src/verification/rollback.ts +2 -2
  81. package/src/verification/tests/mocks/false-reporting-scenarios.test.ts +6 -3
  82. /package/docs/{BUG_REPORT_MEMORY_STATS.md → bug-reports/BUG_REPORT_MEMORY_STATS.md} +0 -0
  83. /package/docs/{AUTOMATIC_ERROR_RECOVERY_v2.7.35.md → features/AUTOMATIC_ERROR_RECOVERY_v2.7.35.md} +0 -0
  84. /package/docs/{MCP_2025_FEATURE_CONFIRMATION.md → features/MCP_2025_FEATURE_CONFIRMATION.md} +0 -0
  85. /package/docs/{OPTIONAL_LOCAL_EMBEDDINGS.md → features/OPTIONAL_LOCAL_EMBEDDINGS.md} +0 -0
  86. /package/docs/{mcp-2025-implementation-summary.md → features/mcp-2025-implementation-summary.md} +0 -0
  87. /package/docs/{mcp-spec-2025-implementation-plan.md → features/mcp-spec-2025-implementation-plan.md} +0 -0
  88. /package/docs/{AGENTIC_FLOW_ENABLED_LOG_FIX.md → fixes/AGENTIC_FLOW_ENABLED_LOG_FIX.md} +0 -0
  89. /package/docs/{MEMORY_COMMAND_FIX.md → fixes/MEMORY_COMMAND_FIX.md} +0 -0
  90. /package/docs/{NPX_MEMORY_FIX_v2.7.19.md → fixes/NPX_MEMORY_FIX_v2.7.19.md} +0 -0
  91. /package/docs/{REMOTE_INSTALL_FIX.md → fixes/REMOTE_INSTALL_FIX.md} +0 -0
  92. /package/docs/{SQLITE_FIX_COMPLETE_v2.7.21.md → fixes/SQLITE_FIX_COMPLETE_v2.7.21.md} +0 -0
  93. /package/docs/{NPM_PUBLISH_GUIDE_v2.7.33.md → guides/NPM_PUBLISH_GUIDE_v2.7.33.md} +0 -0
  94. /package/docs/{SWARM_INITIALIZATION_GUIDE.md → guides/SWARM_INITIALIZATION_GUIDE.md} +0 -0
  95. /package/docs/{AGENTDB_BRANCH_MERGE_VERIFICATION.md → integration/AGENTDB_BRANCH_MERGE_VERIFICATION.md} +0 -0
  96. /package/docs/{INTEGRATION_STATUS_FINAL.md → integration/INTEGRATION_STATUS_FINAL.md} +0 -0
  97. /package/docs/{agentic-flow-agentdb-mcp-integration.md → integration/agentic-flow-agentdb-mcp-integration.md} +0 -0
  98. /package/docs/{phase-1-2-implementation-summary.md → integration/phase-1-2-implementation-summary.md} +0 -0
  99. /package/docs/{.github-release-issue-v2.7.33.md → releases/.github-release-issue-v2.7.33.md} +0 -0
  100. /package/docs/{RELEASE_NOTES_v2.7.15.md → releases/RELEASE_NOTES_v2.7.15.md} +0 -0
  101. /package/docs/{RELEASE_NOTES_v2.7.33.md → releases/RELEASE_NOTES_v2.7.33.md} +0 -0
  102. /package/docs/{RELEASE_READINESS_SUMMARY.md → releases/RELEASE_READINESS_SUMMARY.md} +0 -0
  103. /package/docs/{RELEASE_SUMMARY_v2.7.33.md → releases/RELEASE_SUMMARY_v2.7.33.md} +0 -0
  104. /package/docs/{V2.7.14_RELEASE_NOTES.md → releases/V2.7.14_RELEASE_NOTES.md} +0 -0
  105. /package/docs/{V2.7.25_RELEASE_NOTES.md → releases/V2.7.25_RELEASE_NOTES.md} +0 -0
  106. /package/docs/{V2.7.26_RELEASE_SUMMARY.md → releases/V2.7.26_RELEASE_SUMMARY.md} +0 -0
  107. /package/docs/{V2.7.27_RELEASE_NOTES.md → releases/V2.7.27_RELEASE_NOTES.md} +0 -0
  108. /package/docs/{V2.7.28_RELEASE_NOTES.md → releases/V2.7.28_RELEASE_NOTES.md} +0 -0
  109. /package/docs/{AGENTIC_FLOW_INTEGRATION_REVIEW.md → reviews/AGENTIC_FLOW_INTEGRATION_REVIEW.md} +0 -0
  110. /package/docs/{BRANCH_REVIEW_SUMMARY.md → reviews/BRANCH_REVIEW_SUMMARY.md} +0 -0
  111. /package/docs/{DEEP_CODE_REVIEW_v2.7.33.md → reviews/DEEP_CODE_REVIEW_v2.7.33.md} +0 -0
  112. /package/docs/{LATEST_LIBRARIES_REVIEW.md → reviews/LATEST_LIBRARIES_REVIEW.md} +0 -0
  113. /package/docs/{CONFIRMATION_AUTOMATIC_ERROR_RECOVERY.md → testing/CONFIRMATION_AUTOMATIC_ERROR_RECOVERY.md} +0 -0
  114. /package/docs/{DOCKER_TEST_RESULTS_v2.7.35.md → testing/DOCKER_TEST_RESULTS_v2.7.35.md} +0 -0
  115. /package/docs/{REGRESSION_TEST_REPORT_v2.7.33.md → testing/REGRESSION_TEST_REPORT_v2.7.33.md} +0 -0
  116. /package/docs/{V2.7.27_TEST_REPORT.md → testing/V2.7.27_TEST_REPORT.md} +0 -0
  117. /package/docs/{regression-analysis-phase-1-2.md → testing/regression-analysis-phase-1-2.md} +0 -0
  118. /package/docs/{TRANSFORMER_INITIALIZATION_ISSUE.md → troubleshooting/TRANSFORMER_INITIALIZATION_ISSUE.md} +0 -0
  119. /package/docs/{FIX_VERIFICATION_MEMORY_STATS.md → validation/FIX_VERIFICATION_MEMORY_STATS.md} +0 -0
  120. /package/docs/{TOOL_VALIDATION_REPORT.md → validation/TOOL_VALIDATION_REPORT.md} +0 -0
  121. /package/docs/{VALIDATION_REPORT_v2.7.1.md → validation/VALIDATION_REPORT_v2.7.1.md} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/verification/rollback.ts"],"sourcesContent":["/**\n * Comprehensive Rollback Manager System\n * \n * Provides atomic rollback operations with state management, automated recovery,\n * and git integration for maintaining system integrity.\n * \n * Features:\n * - StateManager: Captures and manages system snapshots\n * - RollbackTrigger: Configurable thresholds and automated monitoring\n * - AutomatedRecovery: Multi-tier recovery strategies\n * - RollbackHistory: Compressed history tracking with TTL\n * - Git Integration: Code rollbacks with atomic commits\n */\n\nimport { promises as fs } from 'fs';\nimport { join } from 'path';\nimport { exec, spawn } from 'child_process';\nimport { promisify } from 'util';\nimport { createHash } from 'crypto';\nimport { EventEmitter } from 'events';\nimport { gzip, gunzip } from 'zlib';\n\nconst execAsync = promisify(exec);\nconst gzipAsync = promisify(gzip);\nconst gunzipAsync = promisify(gunzip);\n\n// ============================================================================\n// Type Definitions\n// ============================================================================\n\nexport interface SystemSnapshot {\n id: string;\n timestamp: number;\n version: string;\n metadata: {\n description: string;\n tags: string[];\n triggeredBy: string;\n severity: 'low' | 'medium' | 'high' | 'critical';\n };\n state: {\n config: Record<string, any>;\n memory: Record<string, any>;\n processes: ProcessState[];\n files: FileSnapshot[];\n git: GitState;\n };\n integrity: {\n checksum: string;\n compressed: boolean;\n size: number;\n };\n}\n\nexport interface ProcessState {\n pid: number;\n name: string;\n status: string;\n memory: number;\n cpu: number;\n env: Record<string, string>;\n}\n\nexport interface FileSnapshot {\n path: string;\n content: string | Buffer;\n stats: {\n size: number;\n mtime: number;\n mode: number;\n };\n checksum: string;\n}\n\nexport interface GitState {\n branch: string;\n commit: string;\n status: string;\n staged: string[];\n modified: string[];\n untracked: string[];\n}\n\nexport interface RollbackTriggerConfig {\n enabled: boolean;\n thresholds: {\n errorRate: number; // Errors per minute\n memoryUsage: number; // Percentage\n cpuUsage: number; // Percentage\n responseTime: number; // Milliseconds\n diskSpace: number; // Percentage free\n consecutiveFailures: number; // Count\n };\n monitoring: {\n interval: number; // Monitoring check interval (ms)\n cooldown: number; // Cooldown period after rollback (ms)\n gracePeriod: number; // Grace period before triggering (ms)\n };\n notifications: {\n webhook?: string;\n email?: string[];\n slack?: string;\n };\n}\n\nexport interface RecoveryStrategy {\n name: string;\n priority: number;\n enabled: boolean;\n timeout: number;\n retries: number;\n conditions: (metrics: SystemMetrics) => boolean;\n execute: (snapshot: SystemSnapshot, context: RecoveryContext) => Promise<boolean>;\n}\n\nexport interface SystemMetrics {\n timestamp: number;\n errors: {\n count: number;\n rate: number;\n recent: Error[];\n };\n performance: {\n memory: { used: number; total: number; percentage: number; };\n cpu: { usage: number; load: number[]; };\n disk: { used: number; total: number; free: number; };\n network: { in: number; out: number; };\n };\n health: {\n status: 'healthy' | 'degraded' | 'critical';\n score: number;\n checks: HealthCheck[];\n };\n}\n\nexport interface HealthCheck {\n name: string;\n status: 'pass' | 'fail' | 'warn';\n message: string;\n duration: number;\n}\n\nexport interface RecoveryContext {\n triggeredBy: string;\n reason: string;\n metrics: SystemMetrics;\n previousAttempts: RecoveryAttempt[];\n}\n\nexport interface RecoveryAttempt {\n strategy: string;\n timestamp: number;\n success: boolean;\n error?: string;\n duration: number;\n}\n\nexport interface RollbackHistoryEntry {\n id: string;\n timestamp: number;\n snapshot: SystemSnapshot;\n trigger: {\n type: 'manual' | 'automatic';\n reason: string;\n metrics?: SystemMetrics;\n };\n recovery: {\n strategy: string;\n success: boolean;\n duration: number;\n attempts: RecoveryAttempt[];\n };\n verification: {\n passed: boolean;\n checks: HealthCheck[];\n rollbackRequired: boolean;\n };\n}\n\n// ============================================================================\n// StateManager - Captures and manages system snapshots\n// ============================================================================\n\nexport class StateManager extends EventEmitter {\n private snapshots: Map<string, SystemSnapshot> = new Map();\n private snapshotDir: string;\n private maxSnapshots: number;\n private compressionEnabled: boolean;\n\n constructor(\n snapshotDir: string = './snapshots',\n maxSnapshots: number = 100,\n compressionEnabled: boolean = true\n ) {\n super();\n this.snapshotDir = snapshotDir;\n this.maxSnapshots = maxSnapshots;\n this.compressionEnabled = compressionEnabled;\n this.initializeStorage();\n }\n\n private async initializeStorage(): Promise<void> {\n try {\n await fs.mkdir(this.snapshotDir, { recursive: true });\n await this.loadExistingSnapshots();\n } catch (error) {\n this.emit('error', new Error(`Failed to initialize storage: ${error}`));\n }\n }\n\n private async loadExistingSnapshots(): Promise<void> {\n try {\n const files = await fs.readdir(this.snapshotDir);\n const snapshotFiles = files.filter(f => f.endsWith('.snapshot.json'));\n \n for (const file of snapshotFiles) {\n try {\n const content = await fs.readFile(join(this.snapshotDir, file), 'utf-8');\n const snapshot: SystemSnapshot = JSON.parse(content);\n this.snapshots.set(snapshot.id, snapshot);\n } catch (error) {\n console.warn(`Failed to load snapshot ${file}:`, error);\n }\n }\n \n this.emit('snapshots_loaded', this.snapshots.size);\n } catch (error) {\n this.emit('error', new Error(`Failed to load snapshots: ${error}`));\n }\n }\n\n /**\n * Creates a comprehensive system snapshot with atomic operations\n */\n public async captureSnapshot(\n description: string,\n tags: string[] = [],\n triggeredBy: string = 'manual'\n ): Promise<SystemSnapshot> {\n const id = this.generateSnapshotId();\n const timestamp = Date.now();\n\n try {\n // Capture system state atomically\n const [config, memory, processes, files, git] = await Promise.all([\n this.captureConfig(),\n this.captureMemory(),\n this.captureProcesses(),\n this.captureFiles(),\n this.captureGitState()\n ]);\n\n const snapshot: SystemSnapshot = {\n id,\n timestamp,\n version: '1.0.0',\n metadata: {\n description,\n tags,\n triggeredBy,\n severity: 'medium'\n },\n state: {\n config,\n memory,\n processes,\n files,\n git\n },\n integrity: {\n checksum: '',\n compressed: this.compressionEnabled,\n size: 0\n }\n };\n\n // Calculate integrity checksum\n const serialized = JSON.stringify(snapshot.state);\n snapshot.integrity.checksum = createHash('sha256').update(serialized).digest('hex');\n snapshot.integrity.size = Buffer.byteLength(serialized, 'utf8');\n\n // Store snapshot\n await this.storeSnapshot(snapshot);\n this.snapshots.set(id, snapshot);\n\n // Cleanup old snapshots\n await this.cleanupOldSnapshots();\n\n this.emit('snapshot_created', snapshot);\n return snapshot;\n\n } catch (error) {\n this.emit('error', new Error(`Failed to capture snapshot: ${error}`));\n throw error;\n }\n }\n\n private async captureConfig(): Promise<Record<string, any>> {\n try {\n // Capture application configuration\n const configPaths = [\n './claude-flow.config.json',\n './package.json',\n './tsconfig.json',\n './.env'\n ];\n\n const config: Record<string, any> = {};\n \n for (const path of configPaths) {\n try {\n const content = await fs.readFile(path, 'utf-8');\n config[path] = JSON.parse(content);\n } catch {\n // File might not exist or be invalid JSON\n }\n }\n\n return config;\n } catch (error) {\n return {};\n }\n }\n\n private async captureMemory(): Promise<Record<string, any>> {\n try {\n // Capture memory-related state\n const memoryPaths = [\n './memory/memory-store.json',\n './memory/claude-flow-data.json',\n './swarm-memory/state.json'\n ];\n\n const memory: Record<string, any> = {};\n \n for (const path of memoryPaths) {\n try {\n const content = await fs.readFile(path, 'utf-8');\n memory[path] = JSON.parse(content);\n } catch {\n // File might not exist\n }\n }\n\n return memory;\n } catch (error) {\n return {};\n }\n }\n\n private async captureProcesses(): Promise<ProcessState[]> {\n try {\n // Capture running processes related to claude-flow\n const { stdout } = await execAsync('ps aux | grep -E \"(claude-flow|node)\" | grep -v grep');\n const lines = stdout.trim().split('\\n');\n \n return lines.map(line => {\n const parts = line.trim().split(/\\s+/);\n return {\n pid: parseInt(parts[1]) || 0,\n name: parts[10] || 'unknown',\n status: 'running',\n memory: parseFloat(parts[5]) || 0,\n cpu: parseFloat(parts[2]) || 0,\n env: process.env as Record<string, string>\n };\n });\n } catch {\n return [];\n }\n }\n\n private async captureFiles(): Promise<FileSnapshot[]> {\n try {\n // Capture critical files\n const criticalPaths = [\n './src/verification/rollback.ts',\n './src/core/orchestrator.ts',\n './src/memory/manager.ts',\n './src/mcp/server.ts'\n ];\n\n const files: FileSnapshot[] = [];\n \n for (const path of criticalPaths) {\n try {\n const [content, stats] = await Promise.all([\n fs.readFile(path, 'utf-8'),\n fs.stat(path)\n ]);\n \n files.push({\n path,\n content,\n stats: {\n size: stats.size,\n mtime: stats.mtime.getTime(),\n mode: stats.mode\n },\n checksum: createHash('md5').update(content).digest('hex')\n });\n } catch {\n // File might not exist\n }\n }\n\n return files;\n } catch {\n return [];\n }\n }\n\n private async captureGitState(): Promise<GitState> {\n try {\n const [branch, commit, status, staged, modified, untracked] = await Promise.all([\n execAsync('git rev-parse --abbrev-ref HEAD').then(r => r.stdout.trim()).catch(() => 'unknown'),\n execAsync('git rev-parse HEAD').then(r => r.stdout.trim()).catch(() => 'unknown'),\n execAsync('git status --porcelain').then(r => r.stdout.trim()).catch(() => ''),\n execAsync('git diff --cached --name-only').then(r => r.stdout.trim().split('\\n').filter(Boolean)).catch(() => []),\n execAsync('git diff --name-only').then(r => r.stdout.trim().split('\\n').filter(Boolean)).catch(() => []),\n execAsync('git ls-files --others --exclude-standard').then(r => r.stdout.trim().split('\\n').filter(Boolean)).catch(() => [])\n ]);\n\n return {\n branch,\n commit,\n status,\n staged,\n modified,\n untracked\n };\n } catch {\n return {\n branch: 'unknown',\n commit: 'unknown',\n status: '',\n staged: [],\n modified: [],\n untracked: []\n };\n }\n }\n\n private async storeSnapshot(snapshot: SystemSnapshot): Promise<void> {\n const filename = `${snapshot.id}.snapshot.json`;\n const filepath = join(this.snapshotDir, filename);\n\n let content = JSON.stringify(snapshot, null, 2);\n \n if (this.compressionEnabled) {\n const compressed = await gzipAsync(Buffer.from(content, 'utf-8'));\n await fs.writeFile(filepath + '.gz', compressed);\n } else {\n await fs.writeFile(filepath, content);\n }\n }\n\n private async cleanupOldSnapshots(): Promise<void> {\n if (this.snapshots.size <= this.maxSnapshots) return;\n\n const sorted = Array.from(this.snapshots.values())\n .sort((a, b) => a.timestamp - b.timestamp);\n \n const toDelete = sorted.slice(0, sorted.length - this.maxSnapshots);\n \n for (const snapshot of toDelete) {\n try {\n const filename = `${snapshot.id}.snapshot.json`;\n const filepath = join(this.snapshotDir, filename);\n \n await fs.unlink(filepath).catch(() => {});\n await fs.unlink(filepath + '.gz').catch(() => {});\n \n this.snapshots.delete(snapshot.id);\n } catch (error) {\n console.warn(`Failed to delete snapshot ${snapshot.id}:`, error);\n }\n }\n }\n\n private generateSnapshotId(): string {\n return `snapshot_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n }\n\n public async getSnapshot(id: string): Promise<SystemSnapshot | null> {\n return this.snapshots.get(id) || null;\n }\n\n public listSnapshots(): SystemSnapshot[] {\n return Array.from(this.snapshots.values())\n .sort((a, b) => b.timestamp - a.timestamp);\n }\n\n public async deleteSnapshot(id: string): Promise<boolean> {\n try {\n const filename = `${id}.snapshot.json`;\n const filepath = join(this.snapshotDir, filename);\n \n await fs.unlink(filepath).catch(() => {});\n await fs.unlink(filepath + '.gz').catch(() => {});\n \n this.snapshots.delete(id);\n this.emit('snapshot_deleted', id);\n return true;\n } catch {\n return false;\n }\n }\n}\n\n// ============================================================================\n// RollbackTrigger - Configurable thresholds and monitoring\n// ============================================================================\n\nexport class RollbackTrigger extends EventEmitter {\n private config: RollbackTriggerConfig;\n private monitoring: boolean = false;\n private metrics: SystemMetrics[] = [];\n private monitoringInterval?: NodeJS.Timeout;\n private lastRollback: number = 0;\n\n constructor(config: Partial<RollbackTriggerConfig> = {}) {\n super();\n this.config = this.mergeConfig(config);\n }\n\n private mergeConfig(config: Partial<RollbackTriggerConfig>): RollbackTriggerConfig {\n return {\n enabled: config.enabled ?? true,\n thresholds: {\n errorRate: config.thresholds?.errorRate ?? 10,\n memoryUsage: config.thresholds?.memoryUsage ?? 90,\n cpuUsage: config.thresholds?.cpuUsage ?? 95,\n responseTime: config.thresholds?.responseTime ?? 5000,\n diskSpace: config.thresholds?.diskSpace ?? 10,\n consecutiveFailures: config.thresholds?.consecutiveFailures ?? 3\n },\n monitoring: {\n interval: config.monitoring?.interval ?? 30000,\n cooldown: config.monitoring?.cooldown ?? 300000,\n gracePeriod: config.monitoring?.gracePeriod ?? 60000\n },\n notifications: {\n webhook: config.notifications?.webhook,\n email: config.notifications?.email,\n slack: config.notifications?.slack\n }\n };\n }\n\n public startMonitoring(): void {\n if (this.monitoring) return;\n \n this.monitoring = true;\n this.monitoringInterval = setInterval(\n () => this.checkThresholds(),\n this.config.monitoring.interval\n );\n \n this.emit('monitoring_started');\n }\n\n public stopMonitoring(): void {\n if (!this.monitoring) return;\n \n this.monitoring = false;\n if (this.monitoringInterval) {\n clearInterval(this.monitoringInterval);\n this.monitoringInterval = undefined;\n }\n \n this.emit('monitoring_stopped');\n }\n\n private async checkThresholds(): Promise<void> {\n if (!this.config.enabled) return;\n \n // Check cooldown period\n if (Date.now() - this.lastRollback < this.config.monitoring.cooldown) {\n return;\n }\n\n try {\n const metrics = await this.collectMetrics();\n this.metrics.push(metrics);\n \n // Keep only recent metrics (last hour)\n const oneHourAgo = Date.now() - 3600000;\n this.metrics = this.metrics.filter(m => m.timestamp > oneHourAgo);\n \n const violations = this.evaluateThresholds(metrics);\n \n if (violations.length > 0) {\n this.emit('threshold_violated', { metrics, violations });\n \n // Check grace period\n const recentViolations = this.metrics\n .filter(m => m.timestamp > Date.now() - this.config.monitoring.gracePeriod)\n .filter(m => this.evaluateThresholds(m).length > 0);\n \n if (recentViolations.length >= 2) {\n this.triggerRollback(metrics, violations);\n }\n }\n \n } catch (error) {\n this.emit('monitoring_error', error);\n }\n }\n\n private async collectMetrics(): Promise<SystemMetrics> {\n const timestamp = Date.now();\n \n try {\n const [memInfo, cpuInfo, diskInfo] = await Promise.all([\n this.getMemoryInfo(),\n this.getCpuInfo(),\n this.getDiskInfo()\n ]);\n\n return {\n timestamp,\n errors: {\n count: 0, // Would be tracked by error handler\n rate: 0,\n recent: []\n },\n performance: {\n memory: memInfo,\n cpu: cpuInfo,\n disk: diskInfo,\n network: { in: 0, out: 0 }\n },\n health: {\n status: 'healthy',\n score: 100,\n checks: []\n }\n };\n \n } catch (error) {\n return {\n timestamp,\n errors: { count: 1, rate: 1, recent: [error as Error] },\n performance: {\n memory: { used: 0, total: 0, percentage: 0 },\n cpu: { usage: 0, load: [0, 0, 0] },\n disk: { used: 0, total: 0, free: 0 },\n network: { in: 0, out: 0 }\n },\n health: {\n status: 'critical',\n score: 0,\n checks: [{ name: 'metrics_collection', status: 'fail', message: error?.toString() || 'Unknown error', duration: 0 }]\n }\n };\n }\n }\n\n private async getMemoryInfo() {\n try {\n const meminfo = await fs.readFile('/proc/meminfo', 'utf-8');\n const lines = meminfo.split('\\n');\n \n const memTotal = parseInt(lines.find(l => l.startsWith('MemTotal:'))?.split(/\\s+/)[1] || '0') * 1024;\n const memAvailable = parseInt(lines.find(l => l.startsWith('MemAvailable:'))?.split(/\\s+/)[1] || '0') * 1024;\n const memUsed = memTotal - memAvailable;\n \n return {\n used: memUsed,\n total: memTotal,\n percentage: memTotal > 0 ? (memUsed / memTotal) * 100 : 0\n };\n } catch {\n return { used: 0, total: 0, percentage: 0 };\n }\n }\n\n private async getCpuInfo() {\n try {\n const loadavg = await fs.readFile('/proc/loadavg', 'utf-8');\n const loads = loadavg.trim().split(' ').slice(0, 3).map(parseFloat);\n \n return {\n usage: loads[0] * 100, // Approximate CPU usage from 1-min load\n load: loads\n };\n } catch {\n return { usage: 0, load: [0, 0, 0] };\n }\n }\n\n private async getDiskInfo() {\n try {\n const { stdout } = await execAsync('df -h . | tail -1');\n const parts = stdout.trim().split(/\\s+/);\n \n const total = this.parseSize(parts[1]);\n const used = this.parseSize(parts[2]);\n const free = this.parseSize(parts[3]);\n \n return { used, total, free };\n } catch {\n return { used: 0, total: 0, free: 0 };\n }\n }\n\n private parseSize(sizeStr: string): number {\n const match = sizeStr.match(/^(\\d+(?:\\.\\d+)?)(K|M|G|T)?$/);\n if (!match) return 0;\n \n const value = parseFloat(match[1]);\n const unit = match[2] || '';\n \n const multipliers: Record<string, number> = {\n '': 1,\n 'K': 1024,\n 'M': 1024 * 1024,\n 'G': 1024 * 1024 * 1024,\n 'T': 1024 * 1024 * 1024 * 1024\n };\n \n return value * (multipliers[unit] || 1);\n }\n\n private evaluateThresholds(metrics: SystemMetrics): string[] {\n const violations: string[] = [];\n \n if (metrics.performance.memory.percentage > this.config.thresholds.memoryUsage) {\n violations.push(`Memory usage: ${metrics.performance.memory.percentage.toFixed(1)}% > ${this.config.thresholds.memoryUsage}%`);\n }\n \n if (metrics.performance.cpu.usage > this.config.thresholds.cpuUsage) {\n violations.push(`CPU usage: ${metrics.performance.cpu.usage.toFixed(1)}% > ${this.config.thresholds.cpuUsage}%`);\n }\n \n const diskFreePercentage = (metrics.performance.disk.free / metrics.performance.disk.total) * 100;\n if (diskFreePercentage < this.config.thresholds.diskSpace) {\n violations.push(`Disk space: ${diskFreePercentage.toFixed(1)}% free < ${this.config.thresholds.diskSpace}%`);\n }\n \n if (metrics.errors.rate > this.config.thresholds.errorRate) {\n violations.push(`Error rate: ${metrics.errors.rate}/min > ${this.config.thresholds.errorRate}/min`);\n }\n \n return violations;\n }\n\n private async triggerRollback(metrics: SystemMetrics, violations: string[]): Promise<void> {\n this.lastRollback = Date.now();\n \n this.emit('rollback_triggered', {\n reason: 'threshold_violations',\n violations,\n metrics\n });\n \n // Send notifications\n await this.sendNotifications(violations, metrics);\n }\n\n private async sendNotifications(violations: string[], metrics: SystemMetrics): Promise<void> {\n const message = `🚨 Rollback triggered due to threshold violations:\\n${violations.join('\\n')}`;\n \n try {\n if (this.config.notifications.webhook) {\n // Send webhook notification\n // Implementation would depend on the webhook service\n }\n \n if (this.config.notifications.slack) {\n // Send Slack notification\n // Implementation would depend on Slack integration\n }\n \n if (this.config.notifications.email) {\n // Send email notification\n // Implementation would depend on email service\n }\n } catch (error) {\n this.emit('notification_error', error);\n }\n }\n\n public updateConfig(config: Partial<RollbackTriggerConfig>): void {\n this.config = this.mergeConfig(config);\n this.emit('config_updated', this.config);\n }\n\n public getCurrentMetrics(): SystemMetrics | null {\n return this.metrics[this.metrics.length - 1] || null;\n }\n\n public getMetricsHistory(): SystemMetrics[] {\n return [...this.metrics];\n }\n}\n\n// ============================================================================\n// AutomatedRecovery - Multi-tier recovery strategies\n// ============================================================================\n\nexport class AutomatedRecovery extends EventEmitter {\n private strategies: Map<string, RecoveryStrategy> = new Map();\n private recoveryHistory: RecoveryAttempt[] = [];\n private stateManager: StateManager;\n private isRecovering: boolean = false;\n\n constructor(stateManager: StateManager) {\n super();\n this.stateManager = stateManager;\n this.initializeDefaultStrategies();\n }\n\n private initializeDefaultStrategies(): void {\n // Strategy 1: Service Restart\n this.registerStrategy({\n name: 'service_restart',\n priority: 1,\n enabled: true,\n timeout: 30000,\n retries: 2,\n conditions: (metrics) => metrics.health.status === 'degraded',\n execute: async (snapshot, context) => {\n try {\n this.emit('recovery_step', { strategy: 'service_restart', action: 'restarting_services' });\n \n // Restart critical services\n await execAsync('pkill -f \"claude-flow\" && sleep 2');\n \n // Wait for services to restart\n await new Promise(resolve => setTimeout(resolve, 5000));\n \n return true;\n } catch (error) {\n this.emit('recovery_error', { strategy: 'service_restart', error });\n return false;\n }\n }\n });\n\n // Strategy 2: Memory Cleanup\n this.registerStrategy({\n name: 'memory_cleanup',\n priority: 2,\n enabled: true,\n timeout: 15000,\n retries: 1,\n conditions: (metrics) => metrics.performance.memory.percentage > 85,\n execute: async (snapshot, context) => {\n try {\n this.emit('recovery_step', { strategy: 'memory_cleanup', action: 'clearing_memory' });\n \n // Force garbage collection\n if (global.gc) {\n global.gc();\n }\n \n // Clear caches\n await this.clearApplicationCaches();\n \n return true;\n } catch (error) {\n this.emit('recovery_error', { strategy: 'memory_cleanup', error });\n return false;\n }\n }\n });\n\n // Strategy 3: Configuration Reset\n this.registerStrategy({\n name: 'config_reset',\n priority: 3,\n enabled: true,\n timeout: 20000,\n retries: 1,\n conditions: (metrics) => metrics.health.status === 'critical',\n execute: async (snapshot, context) => {\n try {\n this.emit('recovery_step', { strategy: 'config_reset', action: 'resetting_config' });\n \n // Restore configuration from snapshot\n await this.restoreConfiguration(snapshot);\n \n return true;\n } catch (error) {\n this.emit('recovery_error', { strategy: 'config_reset', error });\n return false;\n }\n }\n });\n\n // Strategy 4: Full State Rollback\n this.registerStrategy({\n name: 'full_rollback',\n priority: 10,\n enabled: true,\n timeout: 60000,\n retries: 1,\n conditions: () => true, // Last resort\n execute: async (snapshot, context) => {\n try {\n this.emit('recovery_step', { strategy: 'full_rollback', action: 'rolling_back_state' });\n \n // Full system rollback\n await this.performFullRollback(snapshot);\n \n return true;\n } catch (error) {\n this.emit('recovery_error', { strategy: 'full_rollback', error });\n return false;\n }\n }\n });\n }\n\n public registerStrategy(strategy: RecoveryStrategy): void {\n this.strategies.set(strategy.name, strategy);\n this.emit('strategy_registered', strategy.name);\n }\n\n public async executeRecovery(\n metrics: SystemMetrics,\n triggerReason: string,\n preferredSnapshot?: string\n ): Promise<boolean> {\n if (this.isRecovering) {\n this.emit('recovery_blocked', 'Recovery already in progress');\n return false;\n }\n\n this.isRecovering = true;\n \n try {\n this.emit('recovery_started', { reason: triggerReason, metrics });\n \n // Get appropriate snapshot\n const snapshots = this.stateManager.listSnapshots();\n const snapshot = preferredSnapshot \n ? await this.stateManager.getSnapshot(preferredSnapshot)\n : snapshots[0]; // Most recent snapshot\n \n if (!snapshot) {\n throw new Error('No snapshot available for recovery');\n }\n\n // Get applicable strategies\n const applicableStrategies = Array.from(this.strategies.values())\n .filter(s => s.enabled && s.conditions(metrics))\n .sort((a, b) => a.priority - b.priority);\n\n if (applicableStrategies.length === 0) {\n throw new Error('No applicable recovery strategies found');\n }\n\n const context: RecoveryContext = {\n triggeredBy: triggerReason,\n reason: triggerReason,\n metrics,\n previousAttempts: this.recoveryHistory.slice(-10) // Last 10 attempts\n };\n\n // Execute strategies in priority order\n for (const strategy of applicableStrategies) {\n const success = await this.executeStrategy(strategy, snapshot, context);\n \n if (success) {\n this.emit('recovery_success', { \n strategy: strategy.name, \n snapshot: snapshot.id,\n duration: Date.now() - metrics.timestamp \n });\n return true;\n }\n }\n\n throw new Error('All recovery strategies failed');\n \n } catch (error) {\n this.emit('recovery_failed', { error: error?.toString(), metrics });\n return false;\n } finally {\n this.isRecovering = false;\n }\n }\n\n private async executeStrategy(\n strategy: RecoveryStrategy,\n snapshot: SystemSnapshot,\n context: RecoveryContext\n ): Promise<boolean> {\n const startTime = Date.now();\n \n for (let attempt = 0; attempt <= strategy.retries; attempt++) {\n try {\n this.emit('strategy_attempt', { \n strategy: strategy.name, \n attempt: attempt + 1,\n maxAttempts: strategy.retries + 1\n });\n \n // Execute with timeout\n const success = await Promise.race([\n strategy.execute(snapshot, context),\n new Promise<boolean>((_, reject) => \n setTimeout(() => reject(new Error('Strategy timeout')), strategy.timeout)\n )\n ]);\n\n const duration = Date.now() - startTime;\n \n const recoveryAttempt: RecoveryAttempt = {\n strategy: strategy.name,\n timestamp: Date.now(),\n success,\n duration\n };\n \n this.recoveryHistory.push(recoveryAttempt);\n \n if (success) {\n this.emit('strategy_success', { strategy: strategy.name, attempt, duration });\n return true;\n }\n \n } catch (error) {\n const duration = Date.now() - startTime;\n \n const recoveryAttempt: RecoveryAttempt = {\n strategy: strategy.name,\n timestamp: Date.now(),\n success: false,\n error: error?.toString(),\n duration\n };\n \n this.recoveryHistory.push(recoveryAttempt);\n \n this.emit('strategy_failed', { \n strategy: strategy.name, \n attempt, \n error: error?.toString(),\n duration \n });\n \n if (attempt === strategy.retries) {\n return false; // All retries exhausted\n }\n \n // Wait before retry\n await new Promise(resolve => setTimeout(resolve, 1000 * (attempt + 1)));\n }\n }\n \n return false;\n }\n\n private async clearApplicationCaches(): Promise<void> {\n try {\n // Clear memory caches\n const memoryPaths = [\n './memory/cache',\n './swarm-memory/cache',\n './temp'\n ];\n \n for (const path of memoryPaths) {\n try {\n await fs.rm(path, { recursive: true, force: true });\n await fs.mkdir(path, { recursive: true });\n } catch {\n // Path might not exist\n }\n }\n } catch (error) {\n throw new Error(`Failed to clear caches: ${error}`);\n }\n }\n\n private async restoreConfiguration(snapshot: SystemSnapshot): Promise<void> {\n try {\n // Restore configuration files from snapshot\n for (const [path, content] of Object.entries(snapshot.state.config)) {\n try {\n await fs.writeFile(path, JSON.stringify(content, null, 2));\n } catch (error) {\n console.warn(`Failed to restore config file ${path}:`, error);\n }\n }\n } catch (error) {\n throw new Error(`Failed to restore configuration: ${error}`);\n }\n }\n\n private async performFullRollback(snapshot: SystemSnapshot): Promise<void> {\n try {\n // 1. Stop services\n await execAsync('pkill -f \"claude-flow\"').catch(() => {});\n \n // 2. Restore files\n for (const file of snapshot.state.files) {\n try {\n await fs.writeFile(file.path, file.content);\n await fs.chmod(file.path, file.stats.mode);\n } catch (error) {\n console.warn(`Failed to restore file ${file.path}:`, error);\n }\n }\n \n // 3. Restore memory\n for (const [path, content] of Object.entries(snapshot.state.memory)) {\n try {\n await fs.writeFile(path, JSON.stringify(content, null, 2));\n } catch (error) {\n console.warn(`Failed to restore memory file ${path}:`, error);\n }\n }\n \n // 4. Git rollback if needed\n if (snapshot.state.git.commit !== 'unknown') {\n try {\n await execAsync(`git reset --hard ${snapshot.state.git.commit}`);\n } catch (error) {\n console.warn('Failed to perform git rollback:', error);\n }\n }\n \n // 5. Restart services\n await new Promise(resolve => setTimeout(resolve, 2000));\n \n } catch (error) {\n throw new Error(`Failed to perform full rollback: ${error}`);\n }\n }\n\n public getStrategyNames(): string[] {\n return Array.from(this.strategies.keys());\n }\n\n public getStrategy(name: string): RecoveryStrategy | undefined {\n return this.strategies.get(name);\n }\n\n public enableStrategy(name: string): boolean {\n const strategy = this.strategies.get(name);\n if (strategy) {\n strategy.enabled = true;\n this.emit('strategy_enabled', name);\n return true;\n }\n return false;\n }\n\n public disableStrategy(name: string): boolean {\n const strategy = this.strategies.get(name);\n if (strategy) {\n strategy.enabled = false;\n this.emit('strategy_disabled', name);\n return true;\n }\n return false;\n }\n\n public getRecoveryHistory(): RecoveryAttempt[] {\n return [...this.recoveryHistory];\n }\n}\n\n// ============================================================================\n// RollbackHistory - Compressed history tracking with TTL\n// ============================================================================\n\nexport class RollbackHistory extends EventEmitter {\n private history: Map<string, RollbackHistoryEntry> = new Map();\n private historyDir: string;\n private maxHistorySize: number;\n private compressionEnabled: boolean;\n private ttlMs: number;\n private cleanupInterval?: NodeJS.Timeout;\n\n constructor(\n historyDir: string = './rollback-history',\n maxHistorySize: number = 1000,\n ttlDays: number = 30,\n compressionEnabled: boolean = true\n ) {\n super();\n this.historyDir = historyDir;\n this.maxHistorySize = maxHistorySize;\n this.ttlMs = ttlDays * 24 * 60 * 60 * 1000; // Convert days to ms\n this.compressionEnabled = compressionEnabled;\n \n this.initializeStorage();\n this.startCleanupInterval();\n }\n\n private async initializeStorage(): Promise<void> {\n try {\n await fs.mkdir(this.historyDir, { recursive: true });\n await this.loadExistingHistory();\n } catch (error) {\n this.emit('error', new Error(`Failed to initialize history storage: ${error}`));\n }\n }\n\n private async loadExistingHistory(): Promise<void> {\n try {\n const files = await fs.readdir(this.historyDir);\n const historyFiles = files.filter(f => f.endsWith('.history.json') || f.endsWith('.history.json.gz'));\n \n for (const file of historyFiles) {\n try {\n const filepath = join(this.historyDir, file);\n let content: string;\n \n if (file.endsWith('.gz')) {\n const compressed = await fs.readFile(filepath);\n const decompressed = await gunzipAsync(compressed);\n content = decompressed.toString('utf-8');\n } else {\n content = await fs.readFile(filepath, 'utf-8');\n }\n \n const entry: RollbackHistoryEntry = JSON.parse(content);\n this.history.set(entry.id, entry);\n } catch (error) {\n console.warn(`Failed to load history entry ${file}:`, error);\n }\n }\n \n this.emit('history_loaded', this.history.size);\n } catch (error) {\n this.emit('error', new Error(`Failed to load history: ${error}`));\n }\n }\n\n private startCleanupInterval(): void {\n // Run cleanup every 6 hours\n this.cleanupInterval = setInterval(() => {\n this.cleanupExpiredEntries();\n }, 6 * 60 * 60 * 1000);\n }\n\n public async addEntry(\n snapshot: SystemSnapshot,\n triggerType: 'manual' | 'automatic',\n triggerReason: string,\n triggerMetrics: SystemMetrics | undefined,\n recoveryStrategy: string,\n recoverySuccess: boolean,\n recoveryDuration: number,\n recoveryAttempts: RecoveryAttempt[],\n verificationChecks: HealthCheck[],\n verificationPassed: boolean,\n rollbackRequired: boolean\n ): Promise<string> {\n const id = this.generateHistoryId();\n \n const entry: RollbackHistoryEntry = {\n id,\n timestamp: Date.now(),\n snapshot,\n trigger: {\n type: triggerType,\n reason: triggerReason,\n metrics: triggerMetrics\n },\n recovery: {\n strategy: recoveryStrategy,\n success: recoverySuccess,\n duration: recoveryDuration,\n attempts: recoveryAttempts\n },\n verification: {\n passed: verificationPassed,\n checks: verificationChecks,\n rollbackRequired\n }\n };\n\n try {\n await this.storeHistoryEntry(entry);\n this.history.set(id, entry);\n \n // Cleanup if we exceed max size\n await this.cleanupOldEntries();\n \n this.emit('entry_added', entry);\n return id;\n \n } catch (error) {\n this.emit('error', new Error(`Failed to add history entry: ${error}`));\n throw error;\n }\n }\n\n private async storeHistoryEntry(entry: RollbackHistoryEntry): Promise<void> {\n const filename = `${entry.id}.history.json`;\n const filepath = join(this.historyDir, filename);\n\n let content = JSON.stringify(entry, null, 2);\n \n if (this.compressionEnabled) {\n const compressed = await gzipAsync(Buffer.from(content, 'utf-8'));\n await fs.writeFile(filepath + '.gz', compressed);\n } else {\n await fs.writeFile(filepath, content);\n }\n }\n\n private async cleanupExpiredEntries(): Promise<void> {\n const now = Date.now();\n const expiredEntries: string[] = [];\n \n for (const [id, entry] of this.history.entries()) {\n if (now - entry.timestamp > this.ttlMs) {\n expiredEntries.push(id);\n }\n }\n \n for (const id of expiredEntries) {\n await this.deleteEntry(id);\n }\n \n if (expiredEntries.length > 0) {\n this.emit('entries_expired', expiredEntries.length);\n }\n }\n\n private async cleanupOldEntries(): Promise<void> {\n if (this.history.size <= this.maxHistorySize) return;\n\n const sorted = Array.from(this.history.values())\n .sort((a, b) => a.timestamp - b.timestamp);\n \n const toDelete = sorted.slice(0, sorted.length - this.maxHistorySize);\n \n for (const entry of toDelete) {\n await this.deleteEntry(entry.id);\n }\n }\n\n private async deleteEntry(id: string): Promise<void> {\n try {\n const filename = `${id}.history.json`;\n const filepath = join(this.historyDir, filename);\n \n await fs.unlink(filepath).catch(() => {});\n await fs.unlink(filepath + '.gz').catch(() => {});\n \n this.history.delete(id);\n } catch (error) {\n console.warn(`Failed to delete history entry ${id}:`, error);\n }\n }\n\n private generateHistoryId(): string {\n return `history_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n }\n\n public getEntry(id: string): RollbackHistoryEntry | null {\n return this.history.get(id) || null;\n }\n\n public getRecentEntries(limit: number = 50): RollbackHistoryEntry[] {\n return Array.from(this.history.values())\n .sort((a, b) => b.timestamp - a.timestamp)\n .slice(0, limit);\n }\n\n public getEntriesByDateRange(startDate: Date, endDate: Date): RollbackHistoryEntry[] {\n const startTime = startDate.getTime();\n const endTime = endDate.getTime();\n \n return Array.from(this.history.values())\n .filter(entry => entry.timestamp >= startTime && entry.timestamp <= endTime)\n .sort((a, b) => b.timestamp - a.timestamp);\n }\n\n public getSuccessRate(timeframe: number = 24 * 60 * 60 * 1000): number {\n const cutoff = Date.now() - timeframe;\n const recentEntries = Array.from(this.history.values())\n .filter(entry => entry.timestamp > cutoff);\n \n if (recentEntries.length === 0) return 100;\n \n const successCount = recentEntries.filter(entry => entry.recovery.success).length;\n return (successCount / recentEntries.length) * 100;\n }\n\n public getStatistics(): {\n totalEntries: number;\n successRate: number;\n averageRecoveryTime: number;\n mostCommonFailureReason: string;\n rollbacksByTrigger: Record<string, number>;\n } {\n const entries = Array.from(this.history.values());\n \n if (entries.length === 0) {\n return {\n totalEntries: 0,\n successRate: 100,\n averageRecoveryTime: 0,\n mostCommonFailureReason: 'none',\n rollbacksByTrigger: {}\n };\n }\n \n const successCount = entries.filter(e => e.recovery.success).length;\n const successRate = (successCount / entries.length) * 100;\n \n const totalRecoveryTime = entries.reduce((sum, e) => sum + e.recovery.duration, 0);\n const averageRecoveryTime = totalRecoveryTime / entries.length;\n \n const failureReasons = entries\n .filter(e => !e.recovery.success)\n .map(e => e.trigger.reason);\n \n const reasonCounts = failureReasons.reduce((acc, reason) => {\n acc[reason] = (acc[reason] || 0) + 1;\n return acc;\n }, {} as Record<string, number>);\n \n const mostCommonFailureReason = Object.entries(reasonCounts)\n .sort(([,a], [,b]) => b - a)[0]?.[0] || 'none';\n \n const rollbacksByTrigger = entries.reduce((acc, entry) => {\n acc[entry.trigger.type] = (acc[entry.trigger.type] || 0) + 1;\n return acc;\n }, {} as Record<string, number>);\n \n return {\n totalEntries: entries.length,\n successRate,\n averageRecoveryTime,\n mostCommonFailureReason,\n rollbacksByTrigger\n };\n }\n\n public destroy(): void {\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n this.cleanupInterval = undefined;\n }\n }\n}\n\n// ============================================================================\n// GitRollbackManager - Git integration for code rollbacks\n// ============================================================================\n\nexport class GitRollbackManager extends EventEmitter {\n private gitDir: string;\n private backupBranch: string;\n private safetyChecks: boolean;\n\n constructor(\n gitDir: string = './',\n backupBranch: string = 'rollback-backup',\n safetyChecks: boolean = true\n ) {\n super();\n this.gitDir = gitDir;\n this.backupBranch = backupBranch;\n this.safetyChecks = safetyChecks;\n }\n\n /**\n * Creates an atomic git commit with rollback marker\n */\n public async createRollbackPoint(\n message: string = 'Automated rollback point',\n tags: string[] = []\n ): Promise<string> {\n try {\n // Ensure we're in a git repository\n await this.ensureGitRepo();\n \n if (this.safetyChecks) {\n await this.performSafetyChecks();\n }\n \n // Create backup branch\n await this.createBackupBranch();\n \n // Stage all changes\n await execAsync('git add -A', { cwd: this.gitDir });\n \n // Create commit with rollback metadata\n const rollbackMessage = this.formatRollbackMessage(message, tags);\n await execAsync(`git commit -m \"${rollbackMessage}\"`, { cwd: this.gitDir });\n \n // Get commit hash\n const { stdout: commitHash } = await execAsync('git rev-parse HEAD', { cwd: this.gitDir });\n const hash = commitHash.trim();\n \n // Create tag for easy reference\n const tagName = `rollback-${Date.now()}`;\n await execAsync(`git tag -a \"${tagName}\" -m \"Rollback point: ${message}\"`, { cwd: this.gitDir });\n \n this.emit('rollback_point_created', { hash, tag: tagName, message });\n return hash;\n \n } catch (error) {\n this.emit('error', new Error(`Failed to create rollback point: ${error}`));\n throw error;\n }\n }\n\n /**\n * Performs atomic rollback to a specific commit\n */\n public async rollbackToCommit(\n commitHash: string,\n strategy: 'hard' | 'soft' | 'mixed' = 'mixed',\n preserveUntracked: boolean = true\n ): Promise<boolean> {\n try {\n if (this.safetyChecks) {\n await this.performSafetyChecks();\n await this.validateCommit(commitHash);\n }\n \n // Stash any current changes if preserving untracked files\n let stashRef: string | null = null;\n if (preserveUntracked) {\n try {\n await execAsync('git stash push -u -m \"Pre-rollback stash\"', { cwd: this.gitDir });\n stashRef = await this.getLastStashRef();\n } catch {\n // No changes to stash\n }\n }\n \n // Perform the rollback\n await execAsync(`git reset --${strategy} ${commitHash}`, { cwd: this.gitDir });\n \n // If hard reset and preserving untracked, restore stashed files\n if (strategy === 'hard' && stashRef && preserveUntracked) {\n try {\n // Only restore untracked files from stash\n await execAsync(`git stash show -p ${stashRef} | git apply --index`, { cwd: this.gitDir });\n await execAsync(`git stash drop ${stashRef}`, { cwd: this.gitDir });\n } catch {\n // Stash restoration failed, but rollback succeeded\n this.emit('warning', 'Rollback completed but failed to restore untracked files');\n }\n }\n \n // Verify rollback success\n const { stdout: currentHash } = await execAsync('git rev-parse HEAD', { cwd: this.gitDir });\n const success = currentHash.trim() === commitHash;\n \n if (success) {\n this.emit('rollback_completed', { commitHash, strategy });\n } else {\n throw new Error('Rollback verification failed');\n }\n \n return success;\n \n } catch (error) {\n this.emit('error', new Error(`Rollback failed: ${error}`));\n \n // Attempt emergency recovery\n try {\n await this.emergencyRecovery();\n } catch (recoveryError) {\n this.emit('error', new Error(`Emergency recovery failed: ${recoveryError}`));\n }\n \n return false;\n }\n }\n\n /**\n * Rolls back specific files to their state at a given commit\n */\n public async rollbackFiles(\n files: string[],\n commitHash: string\n ): Promise<boolean> {\n try {\n if (this.safetyChecks) {\n await this.validateCommit(commitHash);\n await this.validateFiles(files);\n }\n \n // Backup current state of files\n const backupStash = await this.createFileBackup(files);\n \n try {\n // Rollback each file\n for (const file of files) {\n await execAsync(`git checkout ${commitHash} -- \"${file}\"`, { cwd: this.gitDir });\n }\n \n this.emit('files_rolled_back', { files, commitHash });\n return true;\n \n } catch (error) {\n // Restore from backup on failure\n if (backupStash) {\n await this.restoreFileBackup(backupStash, files);\n }\n throw error;\n }\n \n } catch (error) {\n this.emit('error', new Error(`File rollback failed: ${error}`));\n return false;\n }\n }\n\n /**\n * Creates a branch from current state for safe rollback testing\n */\n public async createTestBranch(name?: string): Promise<string> {\n try {\n const branchName = name || `rollback-test-${Date.now()}`;\n \n await execAsync(`git checkout -b \"${branchName}\"`, { cwd: this.gitDir });\n \n this.emit('test_branch_created', branchName);\n return branchName;\n \n } catch (error) {\n this.emit('error', new Error(`Failed to create test branch: ${error}`));\n throw error;\n }\n }\n\n /**\n * Lists available rollback points (commits with rollback markers)\n */\n public async listRollbackPoints(): Promise<Array<{\n hash: string;\n date: Date;\n message: string;\n tags: string[];\n }>> {\n try {\n // Get commits with rollback markers\n const { stdout } = await execAsync(\n 'git log --grep=\"\\\\[ROLLBACK\\\\]\" --oneline --format=\"%H|%ai|%s\" -n 50',\n { cwd: this.gitDir }\n );\n \n const commits = stdout.trim().split('\\n').filter(Boolean).map(line => {\n const [hash, dateStr, message] = line.split('|');\n return {\n hash,\n date: new Date(dateStr),\n message: message.replace(/\\[ROLLBACK\\]/, '').trim(),\n tags: this.extractTagsFromMessage(message)\n };\n });\n \n // Also get tagged rollback points\n const { stdout: tagOutput } = await execAsync(\n 'git tag -l \"rollback-*\" --format=\"%(refname:short)|%(creatordate)|%(subject)\"',\n { cwd: this.gitDir }\n ).catch(() => ({ stdout: '' }));\n \n const taggedCommits = tagOutput.trim().split('\\n').filter(Boolean).map(line => {\n const [tag, dateStr, message] = line.split('|');\n return {\n hash: tag,\n date: new Date(dateStr),\n message: message || 'Tagged rollback point',\n tags: [tag]\n };\n });\n \n return [...commits, ...taggedCommits].sort((a, b) => b.date.getTime() - a.date.getTime());\n \n } catch (error) {\n this.emit('error', new Error(`Failed to list rollback points: ${error}`));\n return [];\n }\n }\n\n private async ensureGitRepo(): Promise<void> {\n try {\n await execAsync('git rev-parse --git-dir', { cwd: this.gitDir });\n } catch {\n throw new Error('Not a git repository');\n }\n }\n\n private async performSafetyChecks(): Promise<void> {\n // Check for uncommitted changes\n const { stdout: status } = await execAsync('git status --porcelain', { cwd: this.gitDir });\n if (status.trim()) {\n this.emit('warning', 'Uncommitted changes detected');\n }\n \n // Check if we're on a protected branch\n const { stdout: branch } = await execAsync('git rev-parse --abbrev-ref HEAD', { cwd: this.gitDir });\n const currentBranch = branch.trim();\n \n const protectedBranches = ['main', 'master', 'production', 'release'];\n if (protectedBranches.includes(currentBranch)) {\n this.emit('warning', `Operating on protected branch: ${currentBranch}`);\n }\n }\n\n private async createBackupBranch(): Promise<void> {\n try {\n // Delete existing backup branch if it exists\n await execAsync(`git branch -D \"${this.backupBranch}\"`, { cwd: this.gitDir }).catch(() => {});\n \n // Create new backup branch\n await execAsync(`git checkout -b \"${this.backupBranch}\"`, { cwd: this.gitDir });\n \n // Switch back to original branch\n await execAsync('git checkout -', { cwd: this.gitDir });\n \n } catch (error) {\n this.emit('warning', `Failed to create backup branch: ${error}`);\n }\n }\n\n private formatRollbackMessage(message: string, tags: string[]): string {\n const tagStr = tags.length > 0 ? ` [${tags.join(', ')}]` : '';\n return `[ROLLBACK] ${message}${tagStr}`;\n }\n\n private extractTagsFromMessage(message: string): string[] {\n const match = message.match(/\\[([^\\]]+)\\]/g);\n if (!match) return [];\n \n return match.map(tag => tag.slice(1, -1)).filter(tag => tag !== 'ROLLBACK');\n }\n\n private async validateCommit(commitHash: string): Promise<void> {\n try {\n await execAsync(`git cat-file -e ${commitHash}`, { cwd: this.gitDir });\n } catch {\n throw new Error(`Invalid commit hash: ${commitHash}`);\n }\n }\n\n private async validateFiles(files: string[]): Promise<void> {\n for (const file of files) {\n try {\n await fs.access(join(this.gitDir, file));\n } catch {\n throw new Error(`File not found: ${file}`);\n }\n }\n }\n\n private async getLastStashRef(): Promise<string> {\n const { stdout } = await execAsync('git stash list -1 --format=\"%H\"', { cwd: this.gitDir });\n return stdout.trim();\n }\n\n private async createFileBackup(files: string[]): Promise<string | null> {\n try {\n // Create a stash with only the specified files\n for (const file of files) {\n await execAsync(`git add \"${file}\"`, { cwd: this.gitDir });\n }\n \n await execAsync('git stash push -m \"File backup before rollback\"', { cwd: this.gitDir });\n return await this.getLastStashRef();\n \n } catch {\n return null;\n }\n }\n\n private async restoreFileBackup(stashRef: string, files: string[]): Promise<void> {\n try {\n // Restore files from stash\n await execAsync(`git stash show -p ${stashRef} | git apply`, { cwd: this.gitDir });\n await execAsync(`git stash drop ${stashRef}`, { cwd: this.gitDir });\n } catch (error) {\n this.emit('error', new Error(`Failed to restore file backup: ${error}`));\n }\n }\n\n private async emergencyRecovery(): Promise<void> {\n try {\n // Try to recover using backup branch\n if (this.backupBranch) {\n await execAsync(`git checkout \"${this.backupBranch}\"`, { cwd: this.gitDir });\n await execAsync('git checkout -b \"emergency-recovery\"', { cwd: this.gitDir });\n this.emit('emergency_recovery_completed', 'emergency-recovery');\n }\n } catch (error) {\n throw new Error(`Emergency recovery failed: ${error}`);\n }\n }\n}\n\n// ============================================================================\n// Main RollbackManager - Orchestrates all rollback components\n// ============================================================================\n\nexport class RollbackManager extends EventEmitter {\n private stateManager: StateManager;\n private rollbackTrigger: RollbackTrigger;\n private automatedRecovery: AutomatedRecovery;\n private rollbackHistory: RollbackHistory;\n private gitRollbackManager: GitRollbackManager;\n private isInitialized: boolean = false;\n\n constructor(config: {\n snapshotDir?: string;\n historyDir?: string;\n gitDir?: string;\n maxSnapshots?: number;\n maxHistorySize?: number;\n historyTtlDays?: number;\n compressionEnabled?: boolean;\n triggerConfig?: Partial<RollbackTriggerConfig>;\n } = {}) {\n super();\n \n // Initialize components\n this.stateManager = new StateManager(\n config.snapshotDir,\n config.maxSnapshots,\n config.compressionEnabled\n );\n \n this.rollbackTrigger = new RollbackTrigger(config.triggerConfig);\n this.automatedRecovery = new AutomatedRecovery(this.stateManager);\n \n this.rollbackHistory = new RollbackHistory(\n config.historyDir,\n config.maxHistorySize,\n config.historyTtlDays,\n config.compressionEnabled\n );\n \n this.gitRollbackManager = new GitRollbackManager(config.gitDir);\n \n this.setupEventHandlers();\n }\n\n private setupEventHandlers(): void {\n // Connect rollback trigger to automated recovery\n this.rollbackTrigger.on('rollback_triggered', async (event) => {\n await this.handleAutomaticRollback(event.metrics, event.reason);\n });\n \n // Forward important events\n this.stateManager.on('error', (error) => this.emit('error', error));\n this.rollbackTrigger.on('error', (error) => this.emit('error', error));\n this.automatedRecovery.on('error', (error) => this.emit('error', error));\n this.rollbackHistory.on('error', (error) => this.emit('error', error));\n this.gitRollbackManager.on('error', (error) => this.emit('error', error));\n \n // Aggregate events\n this.stateManager.on('snapshot_created', (snapshot) => \n this.emit('snapshot_created', snapshot));\n this.automatedRecovery.on('recovery_success', (event) => \n this.emit('recovery_success', event));\n this.gitRollbackManager.on('rollback_completed', (event) => \n this.emit('git_rollback_completed', event));\n }\n\n public async initialize(): Promise<void> {\n if (this.isInitialized) return;\n \n try {\n // Start monitoring\n this.rollbackTrigger.startMonitoring();\n \n this.isInitialized = true;\n this.emit('initialized');\n \n } catch (error) {\n this.emit('error', new Error(`Failed to initialize RollbackManager: ${error}`));\n throw error;\n }\n }\n\n public async shutdown(): Promise<void> {\n if (!this.isInitialized) return;\n \n try {\n this.rollbackTrigger.stopMonitoring();\n this.rollbackHistory.destroy();\n \n this.isInitialized = false;\n this.emit('shutdown');\n \n } catch (error) {\n this.emit('error', new Error(`Failed to shutdown RollbackManager: ${error}`));\n }\n }\n\n /**\n * Creates a comprehensive system checkpoint\n */\n public async createCheckpoint(\n description: string,\n tags: string[] = []\n ): Promise<string> {\n try {\n // Create system snapshot\n const snapshot = await this.stateManager.captureSnapshot(\n description,\n tags,\n 'manual_checkpoint'\n );\n \n // Create git rollback point\n await this.gitRollbackManager.createRollbackPoint(\n description,\n tags\n );\n \n this.emit('checkpoint_created', { snapshot: snapshot.id, description, tags });\n return snapshot.id;\n \n } catch (error) {\n this.emit('error', new Error(`Failed to create checkpoint: ${error}`));\n throw error;\n }\n }\n\n /**\n * Performs a manual rollback to a specific checkpoint\n */\n public async rollbackToCheckpoint(\n snapshotId: string,\n strategy: 'graceful' | 'immediate' = 'graceful'\n ): Promise<boolean> {\n try {\n const snapshot = await this.stateManager.getSnapshot(snapshotId);\n if (!snapshot) {\n throw new Error(`Snapshot not found: ${snapshotId}`);\n }\n \n const startTime = Date.now();\n \n // Execute rollback based on strategy\n let success: boolean;\n if (strategy === 'graceful') {\n success = await this.performGracefulRollback(snapshot);\n } else {\n success = await this.performImmediateRollback(snapshot);\n }\n \n const duration = Date.now() - startTime;\n \n // Record in history\n await this.rollbackHistory.addEntry(\n snapshot,\n 'manual',\n `Manual rollback to checkpoint ${snapshotId}`,\n undefined, // No trigger metrics for manual rollback\n strategy,\n success,\n duration,\n [], // No recovery attempts for manual rollback\n [], // Would need to run verification\n success,\n !success\n );\n \n if (success) {\n this.emit('manual_rollback_success', { snapshotId, strategy, duration });\n } else {\n this.emit('manual_rollback_failed', { snapshotId, strategy, duration });\n }\n \n return success;\n \n } catch (error) {\n this.emit('error', new Error(`Manual rollback failed: ${error}`));\n return false;\n }\n }\n\n private async handleAutomaticRollback(\n metrics: SystemMetrics,\n reason: string\n ): Promise<void> {\n try {\n const success = await this.automatedRecovery.executeRecovery(metrics, reason);\n \n if (success) {\n this.emit('automatic_rollback_success', { reason, metrics });\n } else {\n this.emit('automatic_rollback_failed', { reason, metrics });\n }\n \n } catch (error) {\n this.emit('error', new Error(`Automatic rollback failed: ${error}`));\n }\n }\n\n private async performGracefulRollback(snapshot: SystemSnapshot): Promise<boolean> {\n try {\n // 1. Create backup of current state\n await this.stateManager.captureSnapshot(\n 'Pre-rollback backup',\n ['auto-backup'],\n 'rollback_backup'\n );\n \n // 2. Gradually restore components\n const restoreSteps = [\n () => this.restoreConfiguration(snapshot),\n () => this.restoreMemoryState(snapshot),\n () => this.restoreFileSystem(snapshot),\n () => this.performGitRollback(snapshot)\n ];\n \n for (const step of restoreSteps) {\n await step();\n // Small delay between steps\n await new Promise(resolve => setTimeout(resolve, 1000));\n }\n \n return true;\n \n } catch (error) {\n this.emit('graceful_rollback_error', error);\n return false;\n }\n }\n\n private async performImmediateRollback(snapshot: SystemSnapshot): Promise<boolean> {\n try {\n // Perform all restoration steps in parallel for speed\n await Promise.all([\n this.restoreConfiguration(snapshot),\n this.restoreMemoryState(snapshot),\n this.restoreFileSystem(snapshot),\n this.performGitRollback(snapshot)\n ]);\n \n return true;\n \n } catch (error) {\n this.emit('immediate_rollback_error', error);\n return false;\n }\n }\n\n private async restoreConfiguration(snapshot: SystemSnapshot): Promise<void> {\n for (const [path, content] of Object.entries(snapshot.state.config)) {\n try {\n await fs.writeFile(path, JSON.stringify(content, null, 2));\n } catch (error) {\n console.warn(`Failed to restore config ${path}:`, error);\n }\n }\n }\n\n private async restoreMemoryState(snapshot: SystemSnapshot): Promise<void> {\n for (const [path, content] of Object.entries(snapshot.state.memory)) {\n try {\n await fs.writeFile(path, JSON.stringify(content, null, 2));\n } catch (error) {\n console.warn(`Failed to restore memory ${path}:`, error);\n }\n }\n }\n\n private async restoreFileSystem(snapshot: SystemSnapshot): Promise<void> {\n for (const file of snapshot.state.files) {\n try {\n await fs.writeFile(file.path, file.content);\n await fs.chmod(file.path, file.stats.mode);\n } catch (error) {\n console.warn(`Failed to restore file ${file.path}:`, error);\n }\n }\n }\n\n private async performGitRollback(snapshot: SystemSnapshot): Promise<void> {\n if (snapshot.state.git.commit !== 'unknown') {\n try {\n await this.gitRollbackManager.rollbackToCommit(snapshot.state.git.commit);\n } catch (error) {\n console.warn('Git rollback failed:', error);\n }\n }\n }\n\n // Public API methods\n public getStateManager(): StateManager { return this.stateManager; }\n public getRollbackTrigger(): RollbackTrigger { return this.rollbackTrigger; }\n public getAutomatedRecovery(): AutomatedRecovery { return this.automatedRecovery; }\n public getRollbackHistory(): RollbackHistory { return this.rollbackHistory; }\n public getGitRollbackManager(): GitRollbackManager { return this.gitRollbackManager; }\n\n public async getSystemStatus(): Promise<{\n isMonitoring: boolean;\n snapshotCount: number;\n historyEntries: number;\n lastCheckpoint: string | null;\n healthScore: number;\n }> {\n const snapshots = this.stateManager.listSnapshots();\n const recentEntries = this.rollbackHistory.getRecentEntries(10);\n const successRate = this.rollbackHistory.getSuccessRate();\n \n return {\n isMonitoring: this.rollbackTrigger.getCurrentMetrics() !== null,\n snapshotCount: snapshots.length,\n historyEntries: recentEntries.length,\n lastCheckpoint: snapshots[0]?.id || null,\n healthScore: successRate\n };\n }\n}\n\n// Export the main class and interfaces\nexport default RollbackManager;"],"names":["promises","fs","join","exec","promisify","createHash","EventEmitter","gzip","gunzip","execAsync","gzipAsync","gunzipAsync","StateManager","snapshots","Map","snapshotDir","maxSnapshots","compressionEnabled","initializeStorage","mkdir","recursive","loadExistingSnapshots","error","emit","Error","files","readdir","snapshotFiles","filter","f","endsWith","file","content","readFile","snapshot","JSON","parse","set","id","console","warn","size","captureSnapshot","description","tags","triggeredBy","generateSnapshotId","timestamp","Date","now","config","memory","processes","git","Promise","all","captureConfig","captureMemory","captureProcesses","captureFiles","captureGitState","version","metadata","severity","state","integrity","checksum","compressed","serialized","stringify","update","digest","Buffer","byteLength","storeSnapshot","cleanupOldSnapshots","configPaths","path","memoryPaths","stdout","lines","trim","split","map","line","parts","pid","parseInt","name","status","parseFloat","cpu","env","process","criticalPaths","stats","stat","push","mtime","getTime","mode","branch","commit","staged","modified","untracked","then","r","catch","Boolean","filename","filepath","from","writeFile","sorted","Array","values","sort","a","b","toDelete","slice","length","unlink","delete","Math","random","toString","substr","getSnapshot","get","listSnapshots","deleteSnapshot","RollbackTrigger","monitoring","metrics","monitoringInterval","lastRollback","mergeConfig","enabled","thresholds","errorRate","memoryUsage","cpuUsage","responseTime","diskSpace","consecutiveFailures","interval","cooldown","gracePeriod","notifications","webhook","email","slack","startMonitoring","setInterval","checkThresholds","stopMonitoring","clearInterval","undefined","collectMetrics","oneHourAgo","m","violations","evaluateThresholds","recentViolations","triggerRollback","memInfo","cpuInfo","diskInfo","getMemoryInfo","getCpuInfo","getDiskInfo","errors","count","rate","recent","performance","disk","network","in","out","health","score","checks","used","total","percentage","usage","load","free","message","duration","meminfo","memTotal","find","l","startsWith","memAvailable","memUsed","loadavg","loads","parseSize","sizeStr","match","value","unit","multipliers","toFixed","diskFreePercentage","reason","sendNotifications","updateConfig","getCurrentMetrics","getMetricsHistory","AutomatedRecovery","strategies","recoveryHistory","stateManager","isRecovering","initializeDefaultStrategies","registerStrategy","priority","timeout","retries","conditions","execute","context","strategy","action","resolve","setTimeout","global","gc","clearApplicationCaches","restoreConfiguration","performFullRollback","executeRecovery","triggerReason","preferredSnapshot","applicableStrategies","s","previousAttempts","success","executeStrategy","startTime","attempt","maxAttempts","race","_","reject","recoveryAttempt","rm","force","Object","entries","chmod","getStrategyNames","keys","getStrategy","enableStrategy","disableStrategy","getRecoveryHistory","RollbackHistory","history","historyDir","maxHistorySize","ttlMs","cleanupInterval","ttlDays","startCleanupInterval","loadExistingHistory","historyFiles","decompressed","entry","cleanupExpiredEntries","addEntry","triggerType","triggerMetrics","recoveryStrategy","recoverySuccess","recoveryDuration","recoveryAttempts","verificationChecks","verificationPassed","rollbackRequired","generateHistoryId","trigger","type","recovery","attempts","verification","passed","storeHistoryEntry","cleanupOldEntries","expiredEntries","deleteEntry","getEntry","getRecentEntries","limit","getEntriesByDateRange","startDate","endDate","endTime","getSuccessRate","timeframe","cutoff","recentEntries","successCount","getStatistics","totalEntries","successRate","averageRecoveryTime","mostCommonFailureReason","rollbacksByTrigger","e","totalRecoveryTime","reduce","sum","failureReasons","reasonCounts","acc","destroy","GitRollbackManager","gitDir","backupBranch","safetyChecks","createRollbackPoint","ensureGitRepo","performSafetyChecks","createBackupBranch","cwd","rollbackMessage","formatRollbackMessage","commitHash","hash","tagName","tag","rollbackToCommit","preserveUntracked","validateCommit","stashRef","getLastStashRef","currentHash","emergencyRecovery","recoveryError","rollbackFiles","validateFiles","backupStash","createFileBackup","restoreFileBackup","createTestBranch","branchName","listRollbackPoints","commits","dateStr","date","replace","extractTagsFromMessage","tagOutput","taggedCommits","currentBranch","protectedBranches","includes","tagStr","access","RollbackManager","rollbackTrigger","automatedRecovery","rollbackHistory","gitRollbackManager","isInitialized","triggerConfig","historyTtlDays","setupEventHandlers","on","event","handleAutomaticRollback","initialize","shutdown","createCheckpoint","rollbackToCheckpoint","snapshotId","performGracefulRollback","performImmediateRollback","restoreSteps","restoreMemoryState","restoreFileSystem","performGitRollback","step","getStateManager","getRollbackTrigger","getAutomatedRecovery","getRollbackHistory","getGitRollbackManager","getSystemStatus","isMonitoring","snapshotCount","historyEntries","lastCheckpoint","healthScore"],"mappings":"AAcA,SAASA,YAAYC,EAAE,QAAQ,KAAK;AACpC,SAASC,IAAI,QAAQ,OAAO;AAC5B,SAASC,IAAI,QAAe,gBAAgB;AAC5C,SAASC,SAAS,QAAQ,OAAO;AACjC,SAASC,UAAU,QAAQ,SAAS;AACpC,SAASC,YAAY,QAAQ,SAAS;AACtC,SAASC,IAAI,EAAEC,MAAM,QAAQ,OAAO;AAEpC,MAAMC,YAAYL,UAAUD;AAC5B,MAAMO,YAAYN,UAAUG;AAC5B,MAAMI,cAAcP,UAAUI;AA+J9B,OAAO,MAAMI,qBAAqBN;IACxBO,YAAyC,IAAIC,MAAM;IACnDC,YAAoB;IACpBC,aAAqB;IACrBC,mBAA4B;IAEpC,YACEF,cAAsB,aAAa,EACnCC,eAAuB,GAAG,EAC1BC,qBAA8B,IAAI,CAClC;QACA,KAAK;QACL,IAAI,CAACF,WAAW,GAAGA;QACnB,IAAI,CAACC,YAAY,GAAGA;QACpB,IAAI,CAACC,kBAAkB,GAAGA;QAC1B,IAAI,CAACC,iBAAiB;IACxB;IAEA,MAAcA,oBAAmC;QAC/C,IAAI;YACF,MAAMjB,GAAGkB,KAAK,CAAC,IAAI,CAACJ,WAAW,EAAE;gBAAEK,WAAW;YAAK;YACnD,MAAM,IAAI,CAACC,qBAAqB;QAClC,EAAE,OAAOC,OAAO;YACd,IAAI,CAACC,IAAI,CAAC,SAAS,IAAIC,MAAM,CAAC,8BAA8B,EAAEF,OAAO;QACvE;IACF;IAEA,MAAcD,wBAAuC;QACnD,IAAI;YACF,MAAMI,QAAQ,MAAMxB,GAAGyB,OAAO,CAAC,IAAI,CAACX,WAAW;YAC/C,MAAMY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AC,CAAC,CAAC,EAAEvD;YACvD;QACF;IACF;IAEA,MAAc8W,mBAAmBlW,QAAwB,EAAiB;QACxE,IAAIA,SAAS8B,KAAK,CAACX,GAAG,CAACiD,MAAM,KAAK,WAAW;YAC3C,IAAI;gBACF,MAAM,IAAI,CAAC4Q,kBAAkB,CAAChC,gBAAgB,CAAChT,SAAS8B,KAAK,CAACX,GAAG,CAACiD,MAAM;YAC1E,EAAE,OAAOhF,OAAO;gBACdiB,QAAQC,IAAI,CAAC,wBAAwBlB;YACvC;QACF;IACF;IAGOgX,kBAAgC;QAAE,OAAO,IAAI,CAAC5K,YAAY;IAAE;IAC5D6K,qBAAsC;QAAE,OAAO,IAAI,CAACxB,eAAe;IAAE;IACrEyB,uBAA0C;QAAE,OAAO,IAAI,CAACxB,iBAAiB;IAAE;IAC3EyB,qBAAsC;QAAE,OAAO,IAAI,CAACxB,eAAe;IAAE;IACrEyB,wBAA4C;QAAE,OAAO,IAAI,CAACxB,kBAAkB;IAAE;IAErF,MAAayB,kBAMV;QACD,MAAM9X,YAAY,IAAI,CAAC6M,YAAY,CAACvF,aAAa;QACjD,MAAMgL,gBAAgB,IAAI,CAAC8D,eAAe,CAACvE,gBAAgB,CAAC;QAC5D,MAAMa,cAAc,IAAI,CAAC0D,eAAe,CAACjE,cAAc;QAEvD,OAAO;YACL4F,cAAc,IAAI,CAAC7B,eAAe,CAAC1J,iBAAiB,OAAO;YAC3DwL,eAAehY,UAAU6G,MAAM;YAC/BoR,gBAAgB3F,cAAczL,MAAM;YACpCqR,gBAAgBlY,SAAS,CAAC,EAAE,EAAEyB,MAAM;YACpC0W,aAAazF;QACf;IACF;AACF;AAGA,eAAeuD,gBAAgB"}
1
+ {"version":3,"sources":["../../../src/verification/rollback.ts"],"sourcesContent":["/**\n * Comprehensive Rollback Manager System\n * \n * Provides atomic rollback operations with state management, automated recovery,\n * and git integration for maintaining system integrity.\n * \n * Features:\n * - StateManager: Captures and manages system snapshots\n * - RollbackTrigger: Configurable thresholds and automated monitoring\n * - AutomatedRecovery: Multi-tier recovery strategies\n * - RollbackHistory: Compressed history tracking with TTL\n * - Git Integration: Code rollbacks with atomic commits\n */\n\nimport { promises as fs } from 'fs';\nimport { join } from 'path';\nimport { exec, spawn } from 'child_process';\nimport { promisify } from 'util';\nimport { createHash } from 'crypto';\nimport { EventEmitter } from 'events';\nimport { gzip, gunzip } from 'zlib';\n\nconst execAsync = promisify(exec);\nconst gzipAsync = promisify(gzip);\nconst gunzipAsync = promisify(gunzip);\n\n// ============================================================================\n// Type Definitions\n// ============================================================================\n\nexport interface SystemSnapshot {\n id: string;\n timestamp: number;\n version: string;\n metadata: {\n description: string;\n tags: string[];\n triggeredBy: string;\n severity: 'low' | 'medium' | 'high' | 'critical';\n };\n state: {\n config: Record<string, any>;\n memory: Record<string, any>;\n processes: ProcessState[];\n files: FileSnapshot[];\n git: GitState;\n };\n integrity: {\n checksum: string;\n compressed: boolean;\n size: number;\n };\n}\n\nexport interface ProcessState {\n pid: number;\n name: string;\n status: string;\n memory: number;\n cpu: number;\n env: Record<string, string>;\n}\n\nexport interface FileSnapshot {\n path: string;\n content: string | Buffer;\n stats: {\n size: number;\n mtime: number;\n mode: number;\n };\n checksum: string;\n}\n\nexport interface GitState {\n branch: string;\n commit: string;\n status: string;\n staged: string[];\n modified: string[];\n untracked: string[];\n}\n\nexport interface RollbackTriggerConfig {\n enabled: boolean;\n thresholds: {\n errorRate: number; // Errors per minute\n memoryUsage: number; // Percentage\n cpuUsage: number; // Percentage\n responseTime: number; // Milliseconds\n diskSpace: number; // Percentage free\n consecutiveFailures: number; // Count\n };\n monitoring: {\n interval: number; // Monitoring check interval (ms)\n cooldown: number; // Cooldown period after rollback (ms)\n gracePeriod: number; // Grace period before triggering (ms)\n };\n notifications: {\n webhook?: string;\n email?: string[];\n slack?: string;\n };\n}\n\nexport interface RecoveryStrategy {\n name: string;\n priority: number;\n enabled: boolean;\n timeout: number;\n retries: number;\n conditions: (metrics: SystemMetrics) => boolean;\n execute: (snapshot: SystemSnapshot, context: RecoveryContext) => Promise<boolean>;\n}\n\nexport interface SystemMetrics {\n timestamp: number;\n errors: {\n count: number;\n rate: number;\n recent: Error[];\n };\n performance: {\n memory: { used: number; total: number; percentage: number; };\n cpu: { usage: number; load: number[]; };\n disk: { used: number; total: number; free: number; };\n network: { in: number; out: number; };\n };\n health: {\n status: 'healthy' | 'degraded' | 'critical';\n score: number;\n checks: HealthCheck[];\n };\n}\n\nexport interface HealthCheck {\n name: string;\n status: 'pass' | 'fail' | 'warn';\n message: string;\n duration: number;\n}\n\nexport interface RecoveryContext {\n triggeredBy: string;\n reason: string;\n metrics: SystemMetrics;\n previousAttempts: RecoveryAttempt[];\n}\n\nexport interface RecoveryAttempt {\n strategy: string;\n timestamp: number;\n success: boolean;\n error?: string;\n duration: number;\n}\n\nexport interface RollbackHistoryEntry {\n id: string;\n timestamp: number;\n snapshot: SystemSnapshot;\n trigger: {\n type: 'manual' | 'automatic';\n reason: string;\n metrics?: SystemMetrics;\n };\n recovery: {\n strategy: string;\n success: boolean;\n duration: number;\n attempts: RecoveryAttempt[];\n };\n verification: {\n passed: boolean;\n checks: HealthCheck[];\n rollbackRequired: boolean;\n };\n}\n\n// ============================================================================\n// StateManager - Captures and manages system snapshots\n// ============================================================================\n\nexport class StateManager extends EventEmitter {\n private snapshots: Map<string, SystemSnapshot> = new Map();\n private snapshotDir: string;\n private maxSnapshots: number;\n private compressionEnabled: boolean;\n\n constructor(\n snapshotDir: string = './snapshots',\n maxSnapshots: number = 100,\n compressionEnabled: boolean = true\n ) {\n super();\n this.snapshotDir = snapshotDir;\n this.maxSnapshots = maxSnapshots;\n this.compressionEnabled = compressionEnabled;\n this.initializeStorage();\n }\n\n private async initializeStorage(): Promise<void> {\n try {\n await fs.mkdir(this.snapshotDir, { recursive: true });\n await this.loadExistingSnapshots();\n } catch (error) {\n this.emit('error', new Error(`Failed to initialize storage: ${error}`));\n }\n }\n\n private async loadExistingSnapshots(): Promise<void> {\n try {\n const files = await fs.readdir(this.snapshotDir);\n const snapshotFiles = files.filter(f => f.endsWith('.snapshot.json'));\n \n for (const file of snapshotFiles) {\n try {\n const content = await fs.readFile(join(this.snapshotDir, file), 'utf-8');\n const snapshot: SystemSnapshot = JSON.parse(content);\n this.snapshots.set(snapshot.id, snapshot);\n } catch (error) {\n console.warn(`Failed to load snapshot ${file}:`, error);\n }\n }\n \n this.emit('snapshots_loaded', this.snapshots.size);\n } catch (error) {\n this.emit('error', new Error(`Failed to load snapshots: ${error}`));\n }\n }\n\n /**\n * Creates a comprehensive system snapshot with atomic operations\n */\n public async captureSnapshot(\n description: string,\n tags: string[] = [],\n triggeredBy: string = 'manual'\n ): Promise<SystemSnapshot> {\n const id = this.generateSnapshotId();\n const timestamp = Date.now();\n\n try {\n // Capture system state atomically\n const [config, memory, processes, files, git] = await Promise.all([\n this.captureConfig(),\n this.captureMemory(),\n this.captureProcesses(),\n this.captureFiles(),\n this.captureGitState()\n ]);\n\n const snapshot: SystemSnapshot = {\n id,\n timestamp,\n version: '1.0.0',\n metadata: {\n description,\n tags,\n triggeredBy,\n severity: 'medium'\n },\n state: {\n config,\n memory,\n processes,\n files,\n git\n },\n integrity: {\n checksum: '',\n compressed: this.compressionEnabled,\n size: 0\n }\n };\n\n // Calculate integrity checksum\n const serialized = JSON.stringify(snapshot.state);\n snapshot.integrity.checksum = createHash('sha256').update(serialized).digest('hex');\n snapshot.integrity.size = Buffer.byteLength(serialized, 'utf8');\n\n // Store snapshot\n await this.storeSnapshot(snapshot);\n this.snapshots.set(id, snapshot);\n\n // Cleanup old snapshots\n await this.cleanupOldSnapshots();\n\n this.emit('snapshot_created', snapshot);\n return snapshot;\n\n } catch (error) {\n this.emit('error', new Error(`Failed to capture snapshot: ${error}`));\n throw error;\n }\n }\n\n private async captureConfig(): Promise<Record<string, any>> {\n try {\n // Capture application configuration\n const configPaths = [\n './claude-flow.config.json',\n './package.json',\n './tsconfig.json',\n './.env'\n ];\n\n const config: Record<string, any> = {};\n \n for (const path of configPaths) {\n try {\n const content = await fs.readFile(path, 'utf-8');\n config[path] = JSON.parse(content);\n } catch {\n // File might not exist or be invalid JSON\n }\n }\n\n return config;\n } catch (error) {\n return {};\n }\n }\n\n private async captureMemory(): Promise<Record<string, any>> {\n try {\n // Capture memory-related state\n const memoryPaths = [\n './memory/memory-store.json',\n './memory/claude-flow-data.json',\n './swarm-memory/state.json'\n ];\n\n const memory: Record<string, any> = {};\n \n for (const path of memoryPaths) {\n try {\n const content = await fs.readFile(path, 'utf-8');\n memory[path] = JSON.parse(content);\n } catch {\n // File might not exist\n }\n }\n\n return memory;\n } catch (error) {\n return {};\n }\n }\n\n private async captureProcesses(): Promise<ProcessState[]> {\n try {\n // Capture running processes related to claude-flow\n const { stdout } = await execAsync('ps aux | grep -E \"(claude-flow|node)\" | grep -v grep');\n const lines = stdout.trim().split('\\n');\n \n return lines.map(line => {\n const parts = line.trim().split(/\\s+/);\n return {\n pid: parseInt(parts[1]) || 0,\n name: parts[10] || 'unknown',\n status: 'running',\n memory: parseFloat(parts[5]) || 0,\n cpu: parseFloat(parts[2]) || 0,\n env: process.env as Record<string, string>\n };\n });\n } catch {\n return [];\n }\n }\n\n private async captureFiles(): Promise<FileSnapshot[]> {\n try {\n // Capture critical files\n const criticalPaths = [\n './src/verification/rollback.ts',\n './src/core/orchestrator.ts',\n './src/memory/manager.ts',\n './src/mcp/server.ts'\n ];\n\n const files: FileSnapshot[] = [];\n \n for (const path of criticalPaths) {\n try {\n const [content, stats] = await Promise.all([\n fs.readFile(path, 'utf-8'),\n fs.stat(path)\n ]);\n \n files.push({\n path,\n content,\n stats: {\n size: stats.size,\n mtime: stats.mtime.getTime(),\n mode: stats.mode\n },\n checksum: createHash('md5').update(content).digest('hex')\n });\n } catch {\n // File might not exist\n }\n }\n\n return files;\n } catch {\n return [];\n }\n }\n\n private async captureGitState(): Promise<GitState> {\n try {\n const [branch, commit, status, staged, modified, untracked] = await Promise.all([\n execAsync('git rev-parse --abbrev-ref HEAD').then(r => r.stdout.trim()).catch(() => 'unknown'),\n execAsync('git rev-parse HEAD').then(r => r.stdout.trim()).catch(() => 'unknown'),\n execAsync('git status --porcelain').then(r => r.stdout.trim()).catch(() => ''),\n execAsync('git diff --cached --name-only').then(r => r.stdout.trim().split('\\n').filter(Boolean)).catch(() => []),\n execAsync('git diff --name-only').then(r => r.stdout.trim().split('\\n').filter(Boolean)).catch(() => []),\n execAsync('git ls-files --others --exclude-standard').then(r => r.stdout.trim().split('\\n').filter(Boolean)).catch(() => [])\n ]);\n\n return {\n branch,\n commit,\n status,\n staged,\n modified,\n untracked\n };\n } catch {\n return {\n branch: 'unknown',\n commit: 'unknown',\n status: '',\n staged: [],\n modified: [],\n untracked: []\n };\n }\n }\n\n private async storeSnapshot(snapshot: SystemSnapshot): Promise<void> {\n const filename = `${snapshot.id}.snapshot.json`;\n const filepath = join(this.snapshotDir, filename);\n\n const content = JSON.stringify(snapshot, null, 2);\n \n if (this.compressionEnabled) {\n const compressed = await gzipAsync(Buffer.from(content, 'utf-8'));\n await fs.writeFile(filepath + '.gz', compressed);\n } else {\n await fs.writeFile(filepath, content);\n }\n }\n\n private async cleanupOldSnapshots(): Promise<void> {\n if (this.snapshots.size <= this.maxSnapshots) return;\n\n const sorted = Array.from(this.snapshots.values())\n .sort((a, b) => a.timestamp - b.timestamp);\n \n const toDelete = sorted.slice(0, sorted.length - this.maxSnapshots);\n \n for (const snapshot of toDelete) {\n try {\n const filename = `${snapshot.id}.snapshot.json`;\n const filepath = join(this.snapshotDir, filename);\n \n await fs.unlink(filepath).catch(() => {});\n await fs.unlink(filepath + '.gz').catch(() => {});\n \n this.snapshots.delete(snapshot.id);\n } catch (error) {\n console.warn(`Failed to delete snapshot ${snapshot.id}:`, error);\n }\n }\n }\n\n private generateSnapshotId(): string {\n return `snapshot_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n }\n\n public async getSnapshot(id: string): Promise<SystemSnapshot | null> {\n return this.snapshots.get(id) || null;\n }\n\n public listSnapshots(): SystemSnapshot[] {\n return Array.from(this.snapshots.values())\n .sort((a, b) => b.timestamp - a.timestamp);\n }\n\n public async deleteSnapshot(id: string): Promise<boolean> {\n try {\n const filename = `${id}.snapshot.json`;\n const filepath = join(this.snapshotDir, filename);\n \n await fs.unlink(filepath).catch(() => {});\n await fs.unlink(filepath + '.gz').catch(() => {});\n \n this.snapshots.delete(id);\n this.emit('snapshot_deleted', id);\n return true;\n } catch {\n return false;\n }\n }\n}\n\n// ============================================================================\n// RollbackTrigger - Configurable thresholds and monitoring\n// ============================================================================\n\nexport class RollbackTrigger extends EventEmitter {\n private config: RollbackTriggerConfig;\n private monitoring: boolean = false;\n private metrics: SystemMetrics[] = [];\n private monitoringInterval?: NodeJS.Timeout;\n private lastRollback: number = 0;\n\n constructor(config: Partial<RollbackTriggerConfig> = {}) {\n super();\n this.config = this.mergeConfig(config);\n }\n\n private mergeConfig(config: Partial<RollbackTriggerConfig>): RollbackTriggerConfig {\n return {\n enabled: config.enabled ?? true,\n thresholds: {\n errorRate: config.thresholds?.errorRate ?? 10,\n memoryUsage: config.thresholds?.memoryUsage ?? 90,\n cpuUsage: config.thresholds?.cpuUsage ?? 95,\n responseTime: config.thresholds?.responseTime ?? 5000,\n diskSpace: config.thresholds?.diskSpace ?? 10,\n consecutiveFailures: config.thresholds?.consecutiveFailures ?? 3\n },\n monitoring: {\n interval: config.monitoring?.interval ?? 30000,\n cooldown: config.monitoring?.cooldown ?? 300000,\n gracePeriod: config.monitoring?.gracePeriod ?? 60000\n },\n notifications: {\n webhook: config.notifications?.webhook,\n email: config.notifications?.email,\n slack: config.notifications?.slack\n }\n };\n }\n\n public startMonitoring(): void {\n if (this.monitoring) return;\n \n this.monitoring = true;\n this.monitoringInterval = setInterval(\n () => this.checkThresholds(),\n this.config.monitoring.interval\n );\n \n this.emit('monitoring_started');\n }\n\n public stopMonitoring(): void {\n if (!this.monitoring) return;\n \n this.monitoring = false;\n if (this.monitoringInterval) {\n clearInterval(this.monitoringInterval);\n this.monitoringInterval = undefined;\n }\n \n this.emit('monitoring_stopped');\n }\n\n private async checkThresholds(): Promise<void> {\n if (!this.config.enabled) return;\n \n // Check cooldown period\n if (Date.now() - this.lastRollback < this.config.monitoring.cooldown) {\n return;\n }\n\n try {\n const metrics = await this.collectMetrics();\n this.metrics.push(metrics);\n \n // Keep only recent metrics (last hour)\n const oneHourAgo = Date.now() - 3600000;\n this.metrics = this.metrics.filter(m => m.timestamp > oneHourAgo);\n \n const violations = this.evaluateThresholds(metrics);\n \n if (violations.length > 0) {\n this.emit('threshold_violated', { metrics, violations });\n \n // Check grace period\n const recentViolations = this.metrics\n .filter(m => m.timestamp > Date.now() - this.config.monitoring.gracePeriod)\n .filter(m => this.evaluateThresholds(m).length > 0);\n \n if (recentViolations.length >= 2) {\n this.triggerRollback(metrics, violations);\n }\n }\n \n } catch (error) {\n this.emit('monitoring_error', error);\n }\n }\n\n private async collectMetrics(): Promise<SystemMetrics> {\n const timestamp = Date.now();\n \n try {\n const [memInfo, cpuInfo, diskInfo] = await Promise.all([\n this.getMemoryInfo(),\n this.getCpuInfo(),\n this.getDiskInfo()\n ]);\n\n return {\n timestamp,\n errors: {\n count: 0, // Would be tracked by error handler\n rate: 0,\n recent: []\n },\n performance: {\n memory: memInfo,\n cpu: cpuInfo,\n disk: diskInfo,\n network: { in: 0, out: 0 }\n },\n health: {\n status: 'healthy',\n score: 100,\n checks: []\n }\n };\n \n } catch (error) {\n return {\n timestamp,\n errors: { count: 1, rate: 1, recent: [error as Error] },\n performance: {\n memory: { used: 0, total: 0, percentage: 0 },\n cpu: { usage: 0, load: [0, 0, 0] },\n disk: { used: 0, total: 0, free: 0 },\n network: { in: 0, out: 0 }\n },\n health: {\n status: 'critical',\n score: 0,\n checks: [{ name: 'metrics_collection', status: 'fail', message: error?.toString() || 'Unknown error', duration: 0 }]\n }\n };\n }\n }\n\n private async getMemoryInfo() {\n try {\n const meminfo = await fs.readFile('/proc/meminfo', 'utf-8');\n const lines = meminfo.split('\\n');\n \n const memTotal = parseInt(lines.find(l => l.startsWith('MemTotal:'))?.split(/\\s+/)[1] || '0') * 1024;\n const memAvailable = parseInt(lines.find(l => l.startsWith('MemAvailable:'))?.split(/\\s+/)[1] || '0') * 1024;\n const memUsed = memTotal - memAvailable;\n \n return {\n used: memUsed,\n total: memTotal,\n percentage: memTotal > 0 ? (memUsed / memTotal) * 100 : 0\n };\n } catch {\n return { used: 0, total: 0, percentage: 0 };\n }\n }\n\n private async getCpuInfo() {\n try {\n const loadavg = await fs.readFile('/proc/loadavg', 'utf-8');\n const loads = loadavg.trim().split(' ').slice(0, 3).map(parseFloat);\n \n return {\n usage: loads[0] * 100, // Approximate CPU usage from 1-min load\n load: loads\n };\n } catch {\n return { usage: 0, load: [0, 0, 0] };\n }\n }\n\n private async getDiskInfo() {\n try {\n const { stdout } = await execAsync('df -h . | tail -1');\n const parts = stdout.trim().split(/\\s+/);\n \n const total = this.parseSize(parts[1]);\n const used = this.parseSize(parts[2]);\n const free = this.parseSize(parts[3]);\n \n return { used, total, free };\n } catch {\n return { used: 0, total: 0, free: 0 };\n }\n }\n\n private parseSize(sizeStr: string): number {\n const match = sizeStr.match(/^(\\d+(?:\\.\\d+)?)(K|M|G|T)?$/);\n if (!match) return 0;\n \n const value = parseFloat(match[1]);\n const unit = match[2] || '';\n \n const multipliers: Record<string, number> = {\n '': 1,\n 'K': 1024,\n 'M': 1024 * 1024,\n 'G': 1024 * 1024 * 1024,\n 'T': 1024 * 1024 * 1024 * 1024\n };\n \n return value * (multipliers[unit] || 1);\n }\n\n private evaluateThresholds(metrics: SystemMetrics): string[] {\n const violations: string[] = [];\n \n if (metrics.performance.memory.percentage > this.config.thresholds.memoryUsage) {\n violations.push(`Memory usage: ${metrics.performance.memory.percentage.toFixed(1)}% > ${this.config.thresholds.memoryUsage}%`);\n }\n \n if (metrics.performance.cpu.usage > this.config.thresholds.cpuUsage) {\n violations.push(`CPU usage: ${metrics.performance.cpu.usage.toFixed(1)}% > ${this.config.thresholds.cpuUsage}%`);\n }\n \n const diskFreePercentage = (metrics.performance.disk.free / metrics.performance.disk.total) * 100;\n if (diskFreePercentage < this.config.thresholds.diskSpace) {\n violations.push(`Disk space: ${diskFreePercentage.toFixed(1)}% free < ${this.config.thresholds.diskSpace}%`);\n }\n \n if (metrics.errors.rate > this.config.thresholds.errorRate) {\n violations.push(`Error rate: ${metrics.errors.rate}/min > ${this.config.thresholds.errorRate}/min`);\n }\n \n return violations;\n }\n\n private async triggerRollback(metrics: SystemMetrics, violations: string[]): Promise<void> {\n this.lastRollback = Date.now();\n \n this.emit('rollback_triggered', {\n reason: 'threshold_violations',\n violations,\n metrics\n });\n \n // Send notifications\n await this.sendNotifications(violations, metrics);\n }\n\n private async sendNotifications(violations: string[], metrics: SystemMetrics): Promise<void> {\n const message = `🚨 Rollback triggered due to threshold violations:\\n${violations.join('\\n')}`;\n \n try {\n if (this.config.notifications.webhook) {\n // Send webhook notification\n // Implementation would depend on the webhook service\n }\n \n if (this.config.notifications.slack) {\n // Send Slack notification\n // Implementation would depend on Slack integration\n }\n \n if (this.config.notifications.email) {\n // Send email notification\n // Implementation would depend on email service\n }\n } catch (error) {\n this.emit('notification_error', error);\n }\n }\n\n public updateConfig(config: Partial<RollbackTriggerConfig>): void {\n this.config = this.mergeConfig(config);\n this.emit('config_updated', this.config);\n }\n\n public getCurrentMetrics(): SystemMetrics | null {\n return this.metrics[this.metrics.length - 1] || null;\n }\n\n public getMetricsHistory(): SystemMetrics[] {\n return [...this.metrics];\n }\n}\n\n// ============================================================================\n// AutomatedRecovery - Multi-tier recovery strategies\n// ============================================================================\n\nexport class AutomatedRecovery extends EventEmitter {\n private strategies: Map<string, RecoveryStrategy> = new Map();\n private recoveryHistory: RecoveryAttempt[] = [];\n private stateManager: StateManager;\n private isRecovering: boolean = false;\n\n constructor(stateManager: StateManager) {\n super();\n this.stateManager = stateManager;\n this.initializeDefaultStrategies();\n }\n\n private initializeDefaultStrategies(): void {\n // Strategy 1: Service Restart\n this.registerStrategy({\n name: 'service_restart',\n priority: 1,\n enabled: true,\n timeout: 30000,\n retries: 2,\n conditions: (metrics) => metrics.health.status === 'degraded',\n execute: async (snapshot, context) => {\n try {\n this.emit('recovery_step', { strategy: 'service_restart', action: 'restarting_services' });\n \n // Restart critical services\n await execAsync('pkill -f \"claude-flow\" && sleep 2');\n \n // Wait for services to restart\n await new Promise(resolve => setTimeout(resolve, 5000));\n \n return true;\n } catch (error) {\n this.emit('recovery_error', { strategy: 'service_restart', error });\n return false;\n }\n }\n });\n\n // Strategy 2: Memory Cleanup\n this.registerStrategy({\n name: 'memory_cleanup',\n priority: 2,\n enabled: true,\n timeout: 15000,\n retries: 1,\n conditions: (metrics) => metrics.performance.memory.percentage > 85,\n execute: async (snapshot, context) => {\n try {\n this.emit('recovery_step', { strategy: 'memory_cleanup', action: 'clearing_memory' });\n \n // Force garbage collection\n if (global.gc) {\n global.gc();\n }\n \n // Clear caches\n await this.clearApplicationCaches();\n \n return true;\n } catch (error) {\n this.emit('recovery_error', { strategy: 'memory_cleanup', error });\n return false;\n }\n }\n });\n\n // Strategy 3: Configuration Reset\n this.registerStrategy({\n name: 'config_reset',\n priority: 3,\n enabled: true,\n timeout: 20000,\n retries: 1,\n conditions: (metrics) => metrics.health.status === 'critical',\n execute: async (snapshot, context) => {\n try {\n this.emit('recovery_step', { strategy: 'config_reset', action: 'resetting_config' });\n \n // Restore configuration from snapshot\n await this.restoreConfiguration(snapshot);\n \n return true;\n } catch (error) {\n this.emit('recovery_error', { strategy: 'config_reset', error });\n return false;\n }\n }\n });\n\n // Strategy 4: Full State Rollback\n this.registerStrategy({\n name: 'full_rollback',\n priority: 10,\n enabled: true,\n timeout: 60000,\n retries: 1,\n conditions: () => true, // Last resort\n execute: async (snapshot, context) => {\n try {\n this.emit('recovery_step', { strategy: 'full_rollback', action: 'rolling_back_state' });\n \n // Full system rollback\n await this.performFullRollback(snapshot);\n \n return true;\n } catch (error) {\n this.emit('recovery_error', { strategy: 'full_rollback', error });\n return false;\n }\n }\n });\n }\n\n public registerStrategy(strategy: RecoveryStrategy): void {\n this.strategies.set(strategy.name, strategy);\n this.emit('strategy_registered', strategy.name);\n }\n\n public async executeRecovery(\n metrics: SystemMetrics,\n triggerReason: string,\n preferredSnapshot?: string\n ): Promise<boolean> {\n if (this.isRecovering) {\n this.emit('recovery_blocked', 'Recovery already in progress');\n return false;\n }\n\n this.isRecovering = true;\n \n try {\n this.emit('recovery_started', { reason: triggerReason, metrics });\n \n // Get appropriate snapshot\n const snapshots = this.stateManager.listSnapshots();\n const snapshot = preferredSnapshot \n ? await this.stateManager.getSnapshot(preferredSnapshot)\n : snapshots[0]; // Most recent snapshot\n \n if (!snapshot) {\n throw new Error('No snapshot available for recovery');\n }\n\n // Get applicable strategies\n const applicableStrategies = Array.from(this.strategies.values())\n .filter(s => s.enabled && s.conditions(metrics))\n .sort((a, b) => a.priority - b.priority);\n\n if (applicableStrategies.length === 0) {\n throw new Error('No applicable recovery strategies found');\n }\n\n const context: RecoveryContext = {\n triggeredBy: triggerReason,\n reason: triggerReason,\n metrics,\n previousAttempts: this.recoveryHistory.slice(-10) // Last 10 attempts\n };\n\n // Execute strategies in priority order\n for (const strategy of applicableStrategies) {\n const success = await this.executeStrategy(strategy, snapshot, context);\n \n if (success) {\n this.emit('recovery_success', { \n strategy: strategy.name, \n snapshot: snapshot.id,\n duration: Date.now() - metrics.timestamp \n });\n return true;\n }\n }\n\n throw new Error('All recovery strategies failed');\n \n } catch (error) {\n this.emit('recovery_failed', { error: error?.toString(), metrics });\n return false;\n } finally {\n this.isRecovering = false;\n }\n }\n\n private async executeStrategy(\n strategy: RecoveryStrategy,\n snapshot: SystemSnapshot,\n context: RecoveryContext\n ): Promise<boolean> {\n const startTime = Date.now();\n \n for (let attempt = 0; attempt <= strategy.retries; attempt++) {\n try {\n this.emit('strategy_attempt', { \n strategy: strategy.name, \n attempt: attempt + 1,\n maxAttempts: strategy.retries + 1\n });\n \n // Execute with timeout\n const success = await Promise.race([\n strategy.execute(snapshot, context),\n new Promise<boolean>((_, reject) => \n setTimeout(() => reject(new Error('Strategy timeout')), strategy.timeout)\n )\n ]);\n\n const duration = Date.now() - startTime;\n \n const recoveryAttempt: RecoveryAttempt = {\n strategy: strategy.name,\n timestamp: Date.now(),\n success,\n duration\n };\n \n this.recoveryHistory.push(recoveryAttempt);\n \n if (success) {\n this.emit('strategy_success', { strategy: strategy.name, attempt, duration });\n return true;\n }\n \n } catch (error) {\n const duration = Date.now() - startTime;\n \n const recoveryAttempt: RecoveryAttempt = {\n strategy: strategy.name,\n timestamp: Date.now(),\n success: false,\n error: error?.toString(),\n duration\n };\n \n this.recoveryHistory.push(recoveryAttempt);\n \n this.emit('strategy_failed', { \n strategy: strategy.name, \n attempt, \n error: error?.toString(),\n duration \n });\n \n if (attempt === strategy.retries) {\n return false; // All retries exhausted\n }\n \n // Wait before retry\n await new Promise(resolve => setTimeout(resolve, 1000 * (attempt + 1)));\n }\n }\n \n return false;\n }\n\n private async clearApplicationCaches(): Promise<void> {\n try {\n // Clear memory caches\n const memoryPaths = [\n './memory/cache',\n './swarm-memory/cache',\n './temp'\n ];\n \n for (const path of memoryPaths) {\n try {\n await fs.rm(path, { recursive: true, force: true });\n await fs.mkdir(path, { recursive: true });\n } catch {\n // Path might not exist\n }\n }\n } catch (error) {\n throw new Error(`Failed to clear caches: ${error}`);\n }\n }\n\n private async restoreConfiguration(snapshot: SystemSnapshot): Promise<void> {\n try {\n // Restore configuration files from snapshot\n for (const [path, content] of Object.entries(snapshot.state.config)) {\n try {\n await fs.writeFile(path, JSON.stringify(content, null, 2));\n } catch (error) {\n console.warn(`Failed to restore config file ${path}:`, error);\n }\n }\n } catch (error) {\n throw new Error(`Failed to restore configuration: ${error}`);\n }\n }\n\n private async performFullRollback(snapshot: SystemSnapshot): Promise<void> {\n try {\n // 1. Stop services\n await execAsync('pkill -f \"claude-flow\"').catch(() => {});\n \n // 2. Restore files\n for (const file of snapshot.state.files) {\n try {\n await fs.writeFile(file.path, file.content);\n await fs.chmod(file.path, file.stats.mode);\n } catch (error) {\n console.warn(`Failed to restore file ${file.path}:`, error);\n }\n }\n \n // 3. Restore memory\n for (const [path, content] of Object.entries(snapshot.state.memory)) {\n try {\n await fs.writeFile(path, JSON.stringify(content, null, 2));\n } catch (error) {\n console.warn(`Failed to restore memory file ${path}:`, error);\n }\n }\n \n // 4. Git rollback if needed\n if (snapshot.state.git.commit !== 'unknown') {\n try {\n await execAsync(`git reset --hard ${snapshot.state.git.commit}`);\n } catch (error) {\n console.warn('Failed to perform git rollback:', error);\n }\n }\n \n // 5. Restart services\n await new Promise(resolve => setTimeout(resolve, 2000));\n \n } catch (error) {\n throw new Error(`Failed to perform full rollback: ${error}`);\n }\n }\n\n public getStrategyNames(): string[] {\n return Array.from(this.strategies.keys());\n }\n\n public getStrategy(name: string): RecoveryStrategy | undefined {\n return this.strategies.get(name);\n }\n\n public enableStrategy(name: string): boolean {\n const strategy = this.strategies.get(name);\n if (strategy) {\n strategy.enabled = true;\n this.emit('strategy_enabled', name);\n return true;\n }\n return false;\n }\n\n public disableStrategy(name: string): boolean {\n const strategy = this.strategies.get(name);\n if (strategy) {\n strategy.enabled = false;\n this.emit('strategy_disabled', name);\n return true;\n }\n return false;\n }\n\n public getRecoveryHistory(): RecoveryAttempt[] {\n return [...this.recoveryHistory];\n }\n}\n\n// ============================================================================\n// RollbackHistory - Compressed history tracking with TTL\n// ============================================================================\n\nexport class RollbackHistory extends EventEmitter {\n private history: Map<string, RollbackHistoryEntry> = new Map();\n private historyDir: string;\n private maxHistorySize: number;\n private compressionEnabled: boolean;\n private ttlMs: number;\n private cleanupInterval?: NodeJS.Timeout;\n\n constructor(\n historyDir: string = './rollback-history',\n maxHistorySize: number = 1000,\n ttlDays: number = 30,\n compressionEnabled: boolean = true\n ) {\n super();\n this.historyDir = historyDir;\n this.maxHistorySize = maxHistorySize;\n this.ttlMs = ttlDays * 24 * 60 * 60 * 1000; // Convert days to ms\n this.compressionEnabled = compressionEnabled;\n \n this.initializeStorage();\n this.startCleanupInterval();\n }\n\n private async initializeStorage(): Promise<void> {\n try {\n await fs.mkdir(this.historyDir, { recursive: true });\n await this.loadExistingHistory();\n } catch (error) {\n this.emit('error', new Error(`Failed to initialize history storage: ${error}`));\n }\n }\n\n private async loadExistingHistory(): Promise<void> {\n try {\n const files = await fs.readdir(this.historyDir);\n const historyFiles = files.filter(f => f.endsWith('.history.json') || f.endsWith('.history.json.gz'));\n \n for (const file of historyFiles) {\n try {\n const filepath = join(this.historyDir, file);\n let content: string;\n \n if (file.endsWith('.gz')) {\n const compressed = await fs.readFile(filepath);\n const decompressed = await gunzipAsync(compressed);\n content = decompressed.toString('utf-8');\n } else {\n content = await fs.readFile(filepath, 'utf-8');\n }\n \n const entry: RollbackHistoryEntry = JSON.parse(content);\n this.history.set(entry.id, entry);\n } catch (error) {\n console.warn(`Failed to load history entry ${file}:`, error);\n }\n }\n \n this.emit('history_loaded', this.history.size);\n } catch (error) {\n this.emit('error', new Error(`Failed to load history: ${error}`));\n }\n }\n\n private startCleanupInterval(): void {\n // Run cleanup every 6 hours\n this.cleanupInterval = setInterval(() => {\n this.cleanupExpiredEntries();\n }, 6 * 60 * 60 * 1000);\n }\n\n public async addEntry(\n snapshot: SystemSnapshot,\n triggerType: 'manual' | 'automatic',\n triggerReason: string,\n triggerMetrics: SystemMetrics | undefined,\n recoveryStrategy: string,\n recoverySuccess: boolean,\n recoveryDuration: number,\n recoveryAttempts: RecoveryAttempt[],\n verificationChecks: HealthCheck[],\n verificationPassed: boolean,\n rollbackRequired: boolean\n ): Promise<string> {\n const id = this.generateHistoryId();\n \n const entry: RollbackHistoryEntry = {\n id,\n timestamp: Date.now(),\n snapshot,\n trigger: {\n type: triggerType,\n reason: triggerReason,\n metrics: triggerMetrics\n },\n recovery: {\n strategy: recoveryStrategy,\n success: recoverySuccess,\n duration: recoveryDuration,\n attempts: recoveryAttempts\n },\n verification: {\n passed: verificationPassed,\n checks: verificationChecks,\n rollbackRequired\n }\n };\n\n try {\n await this.storeHistoryEntry(entry);\n this.history.set(id, entry);\n \n // Cleanup if we exceed max size\n await this.cleanupOldEntries();\n \n this.emit('entry_added', entry);\n return id;\n \n } catch (error) {\n this.emit('error', new Error(`Failed to add history entry: ${error}`));\n throw error;\n }\n }\n\n private async storeHistoryEntry(entry: RollbackHistoryEntry): Promise<void> {\n const filename = `${entry.id}.history.json`;\n const filepath = join(this.historyDir, filename);\n\n const content = JSON.stringify(entry, null, 2);\n \n if (this.compressionEnabled) {\n const compressed = await gzipAsync(Buffer.from(content, 'utf-8'));\n await fs.writeFile(filepath + '.gz', compressed);\n } else {\n await fs.writeFile(filepath, content);\n }\n }\n\n private async cleanupExpiredEntries(): Promise<void> {\n const now = Date.now();\n const expiredEntries: string[] = [];\n \n for (const [id, entry] of this.history.entries()) {\n if (now - entry.timestamp > this.ttlMs) {\n expiredEntries.push(id);\n }\n }\n \n for (const id of expiredEntries) {\n await this.deleteEntry(id);\n }\n \n if (expiredEntries.length > 0) {\n this.emit('entries_expired', expiredEntries.length);\n }\n }\n\n private async cleanupOldEntries(): Promise<void> {\n if (this.history.size <= this.maxHistorySize) return;\n\n const sorted = Array.from(this.history.values())\n .sort((a, b) => a.timestamp - b.timestamp);\n \n const toDelete = sorted.slice(0, sorted.length - this.maxHistorySize);\n \n for (const entry of toDelete) {\n await this.deleteEntry(entry.id);\n }\n }\n\n private async deleteEntry(id: string): Promise<void> {\n try {\n const filename = `${id}.history.json`;\n const filepath = join(this.historyDir, filename);\n \n await fs.unlink(filepath).catch(() => {});\n await fs.unlink(filepath + '.gz').catch(() => {});\n \n this.history.delete(id);\n } catch (error) {\n console.warn(`Failed to delete history entry ${id}:`, error);\n }\n }\n\n private generateHistoryId(): string {\n return `history_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n }\n\n public getEntry(id: string): RollbackHistoryEntry | null {\n return this.history.get(id) || null;\n }\n\n public getRecentEntries(limit: number = 50): RollbackHistoryEntry[] {\n return Array.from(this.history.values())\n .sort((a, b) => b.timestamp - a.timestamp)\n .slice(0, limit);\n }\n\n public getEntriesByDateRange(startDate: Date, endDate: Date): RollbackHistoryEntry[] {\n const startTime = startDate.getTime();\n const endTime = endDate.getTime();\n \n return Array.from(this.history.values())\n .filter(entry => entry.timestamp >= startTime && entry.timestamp <= endTime)\n .sort((a, b) => b.timestamp - a.timestamp);\n }\n\n public getSuccessRate(timeframe: number = 24 * 60 * 60 * 1000): number {\n const cutoff = Date.now() - timeframe;\n const recentEntries = Array.from(this.history.values())\n .filter(entry => entry.timestamp > cutoff);\n \n if (recentEntries.length === 0) return 100;\n \n const successCount = recentEntries.filter(entry => entry.recovery.success).length;\n return (successCount / recentEntries.length) * 100;\n }\n\n public getStatistics(): {\n totalEntries: number;\n successRate: number;\n averageRecoveryTime: number;\n mostCommonFailureReason: string;\n rollbacksByTrigger: Record<string, number>;\n } {\n const entries = Array.from(this.history.values());\n \n if (entries.length === 0) {\n return {\n totalEntries: 0,\n successRate: 100,\n averageRecoveryTime: 0,\n mostCommonFailureReason: 'none',\n rollbacksByTrigger: {}\n };\n }\n \n const successCount = entries.filter(e => e.recovery.success).length;\n const successRate = (successCount / entries.length) * 100;\n \n const totalRecoveryTime = entries.reduce((sum, e) => sum + e.recovery.duration, 0);\n const averageRecoveryTime = totalRecoveryTime / entries.length;\n \n const failureReasons = entries\n .filter(e => !e.recovery.success)\n .map(e => e.trigger.reason);\n \n const reasonCounts = failureReasons.reduce((acc, reason) => {\n acc[reason] = (acc[reason] || 0) + 1;\n return acc;\n }, {} as Record<string, number>);\n \n const mostCommonFailureReason = Object.entries(reasonCounts)\n .sort(([,a], [,b]) => b - a)[0]?.[0] || 'none';\n \n const rollbacksByTrigger = entries.reduce((acc, entry) => {\n acc[entry.trigger.type] = (acc[entry.trigger.type] || 0) + 1;\n return acc;\n }, {} as Record<string, number>);\n \n return {\n totalEntries: entries.length,\n successRate,\n averageRecoveryTime,\n mostCommonFailureReason,\n rollbacksByTrigger\n };\n }\n\n public destroy(): void {\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n this.cleanupInterval = undefined;\n }\n }\n}\n\n// ============================================================================\n// GitRollbackManager - Git integration for code rollbacks\n// ============================================================================\n\nexport class GitRollbackManager extends EventEmitter {\n private gitDir: string;\n private backupBranch: string;\n private safetyChecks: boolean;\n\n constructor(\n gitDir: string = './',\n backupBranch: string = 'rollback-backup',\n safetyChecks: boolean = true\n ) {\n super();\n this.gitDir = gitDir;\n this.backupBranch = backupBranch;\n this.safetyChecks = safetyChecks;\n }\n\n /**\n * Creates an atomic git commit with rollback marker\n */\n public async createRollbackPoint(\n message: string = 'Automated rollback point',\n tags: string[] = []\n ): Promise<string> {\n try {\n // Ensure we're in a git repository\n await this.ensureGitRepo();\n \n if (this.safetyChecks) {\n await this.performSafetyChecks();\n }\n \n // Create backup branch\n await this.createBackupBranch();\n \n // Stage all changes\n await execAsync('git add -A', { cwd: this.gitDir });\n \n // Create commit with rollback metadata\n const rollbackMessage = this.formatRollbackMessage(message, tags);\n await execAsync(`git commit -m \"${rollbackMessage}\"`, { cwd: this.gitDir });\n \n // Get commit hash\n const { stdout: commitHash } = await execAsync('git rev-parse HEAD', { cwd: this.gitDir });\n const hash = commitHash.trim();\n \n // Create tag for easy reference\n const tagName = `rollback-${Date.now()}`;\n await execAsync(`git tag -a \"${tagName}\" -m \"Rollback point: ${message}\"`, { cwd: this.gitDir });\n \n this.emit('rollback_point_created', { hash, tag: tagName, message });\n return hash;\n \n } catch (error) {\n this.emit('error', new Error(`Failed to create rollback point: ${error}`));\n throw error;\n }\n }\n\n /**\n * Performs atomic rollback to a specific commit\n */\n public async rollbackToCommit(\n commitHash: string,\n strategy: 'hard' | 'soft' | 'mixed' = 'mixed',\n preserveUntracked: boolean = true\n ): Promise<boolean> {\n try {\n if (this.safetyChecks) {\n await this.performSafetyChecks();\n await this.validateCommit(commitHash);\n }\n \n // Stash any current changes if preserving untracked files\n let stashRef: string | null = null;\n if (preserveUntracked) {\n try {\n await execAsync('git stash push -u -m \"Pre-rollback stash\"', { cwd: this.gitDir });\n stashRef = await this.getLastStashRef();\n } catch {\n // No changes to stash\n }\n }\n \n // Perform the rollback\n await execAsync(`git reset --${strategy} ${commitHash}`, { cwd: this.gitDir });\n \n // If hard reset and preserving untracked, restore stashed files\n if (strategy === 'hard' && stashRef && preserveUntracked) {\n try {\n // Only restore untracked files from stash\n await execAsync(`git stash show -p ${stashRef} | git apply --index`, { cwd: this.gitDir });\n await execAsync(`git stash drop ${stashRef}`, { cwd: this.gitDir });\n } catch {\n // Stash restoration failed, but rollback succeeded\n this.emit('warning', 'Rollback completed but failed to restore untracked files');\n }\n }\n \n // Verify rollback success\n const { stdout: currentHash } = await execAsync('git rev-parse HEAD', { cwd: this.gitDir });\n const success = currentHash.trim() === commitHash;\n \n if (success) {\n this.emit('rollback_completed', { commitHash, strategy });\n } else {\n throw new Error('Rollback verification failed');\n }\n \n return success;\n \n } catch (error) {\n this.emit('error', new Error(`Rollback failed: ${error}`));\n \n // Attempt emergency recovery\n try {\n await this.emergencyRecovery();\n } catch (recoveryError) {\n this.emit('error', new Error(`Emergency recovery failed: ${recoveryError}`));\n }\n \n return false;\n }\n }\n\n /**\n * Rolls back specific files to their state at a given commit\n */\n public async rollbackFiles(\n files: string[],\n commitHash: string\n ): Promise<boolean> {\n try {\n if (this.safetyChecks) {\n await this.validateCommit(commitHash);\n await this.validateFiles(files);\n }\n \n // Backup current state of files\n const backupStash = await this.createFileBackup(files);\n \n try {\n // Rollback each file\n for (const file of files) {\n await execAsync(`git checkout ${commitHash} -- \"${file}\"`, { cwd: this.gitDir });\n }\n \n this.emit('files_rolled_back', { files, commitHash });\n return true;\n \n } catch (error) {\n // Restore from backup on failure\n if (backupStash) {\n await this.restoreFileBackup(backupStash, files);\n }\n throw error;\n }\n \n } catch (error) {\n this.emit('error', new Error(`File rollback failed: ${error}`));\n return false;\n }\n }\n\n /**\n * Creates a branch from current state for safe rollback testing\n */\n public async createTestBranch(name?: string): Promise<string> {\n try {\n const branchName = name || `rollback-test-${Date.now()}`;\n \n await execAsync(`git checkout -b \"${branchName}\"`, { cwd: this.gitDir });\n \n this.emit('test_branch_created', branchName);\n return branchName;\n \n } catch (error) {\n this.emit('error', new Error(`Failed to create test branch: ${error}`));\n throw error;\n }\n }\n\n /**\n * Lists available rollback points (commits with rollback markers)\n */\n public async listRollbackPoints(): Promise<Array<{\n hash: string;\n date: Date;\n message: string;\n tags: string[];\n }>> {\n try {\n // Get commits with rollback markers\n const { stdout } = await execAsync(\n 'git log --grep=\"\\\\[ROLLBACK\\\\]\" --oneline --format=\"%H|%ai|%s\" -n 50',\n { cwd: this.gitDir }\n );\n \n const commits = stdout.trim().split('\\n').filter(Boolean).map(line => {\n const [hash, dateStr, message] = line.split('|');\n return {\n hash,\n date: new Date(dateStr),\n message: message.replace(/\\[ROLLBACK\\]/, '').trim(),\n tags: this.extractTagsFromMessage(message)\n };\n });\n \n // Also get tagged rollback points\n const { stdout: tagOutput } = await execAsync(\n 'git tag -l \"rollback-*\" --format=\"%(refname:short)|%(creatordate)|%(subject)\"',\n { cwd: this.gitDir }\n ).catch(() => ({ stdout: '' }));\n \n const taggedCommits = tagOutput.trim().split('\\n').filter(Boolean).map(line => {\n const [tag, dateStr, message] = line.split('|');\n return {\n hash: tag,\n date: new Date(dateStr),\n message: message || 'Tagged rollback point',\n tags: [tag]\n };\n });\n \n return [...commits, ...taggedCommits].sort((a, b) => b.date.getTime() - a.date.getTime());\n \n } catch (error) {\n this.emit('error', new Error(`Failed to list rollback points: ${error}`));\n return [];\n }\n }\n\n private async ensureGitRepo(): Promise<void> {\n try {\n await execAsync('git rev-parse --git-dir', { cwd: this.gitDir });\n } catch {\n throw new Error('Not a git repository');\n }\n }\n\n private async performSafetyChecks(): Promise<void> {\n // Check for uncommitted changes\n const { stdout: status } = await execAsync('git status --porcelain', { cwd: this.gitDir });\n if (status.trim()) {\n this.emit('warning', 'Uncommitted changes detected');\n }\n \n // Check if we're on a protected branch\n const { stdout: branch } = await execAsync('git rev-parse --abbrev-ref HEAD', { cwd: this.gitDir });\n const currentBranch = branch.trim();\n \n const protectedBranches = ['main', 'master', 'production', 'release'];\n if (protectedBranches.includes(currentBranch)) {\n this.emit('warning', `Operating on protected branch: ${currentBranch}`);\n }\n }\n\n private async createBackupBranch(): Promise<void> {\n try {\n // Delete existing backup branch if it exists\n await execAsync(`git branch -D \"${this.backupBranch}\"`, { cwd: this.gitDir }).catch(() => {});\n \n // Create new backup branch\n await execAsync(`git checkout -b \"${this.backupBranch}\"`, { cwd: this.gitDir });\n \n // Switch back to original branch\n await execAsync('git checkout -', { cwd: this.gitDir });\n \n } catch (error) {\n this.emit('warning', `Failed to create backup branch: ${error}`);\n }\n }\n\n private formatRollbackMessage(message: string, tags: string[]): string {\n const tagStr = tags.length > 0 ? ` [${tags.join(', ')}]` : '';\n return `[ROLLBACK] ${message}${tagStr}`;\n }\n\n private extractTagsFromMessage(message: string): string[] {\n const match = message.match(/\\[([^\\]]+)\\]/g);\n if (!match) return [];\n \n return match.map(tag => tag.slice(1, -1)).filter(tag => tag !== 'ROLLBACK');\n }\n\n private async validateCommit(commitHash: string): Promise<void> {\n try {\n await execAsync(`git cat-file -e ${commitHash}`, { cwd: this.gitDir });\n } catch {\n throw new Error(`Invalid commit hash: ${commitHash}`);\n }\n }\n\n private async validateFiles(files: string[]): Promise<void> {\n for (const file of files) {\n try {\n await fs.access(join(this.gitDir, file));\n } catch {\n throw new Error(`File not found: ${file}`);\n }\n }\n }\n\n private async getLastStashRef(): Promise<string> {\n const { stdout } = await execAsync('git stash list -1 --format=\"%H\"', { cwd: this.gitDir });\n return stdout.trim();\n }\n\n private async createFileBackup(files: string[]): Promise<string | null> {\n try {\n // Create a stash with only the specified files\n for (const file of files) {\n await execAsync(`git add \"${file}\"`, { cwd: this.gitDir });\n }\n \n await execAsync('git stash push -m \"File backup before rollback\"', { cwd: this.gitDir });\n return await this.getLastStashRef();\n \n } catch {\n return null;\n }\n }\n\n private async restoreFileBackup(stashRef: string, files: string[]): Promise<void> {\n try {\n // Restore files from stash\n await execAsync(`git stash show -p ${stashRef} | git apply`, { cwd: this.gitDir });\n await execAsync(`git stash drop ${stashRef}`, { cwd: this.gitDir });\n } catch (error) {\n this.emit('error', new Error(`Failed to restore file backup: ${error}`));\n }\n }\n\n private async emergencyRecovery(): Promise<void> {\n try {\n // Try to recover using backup branch\n if (this.backupBranch) {\n await execAsync(`git checkout \"${this.backupBranch}\"`, { cwd: this.gitDir });\n await execAsync('git checkout -b \"emergency-recovery\"', { cwd: this.gitDir });\n this.emit('emergency_recovery_completed', 'emergency-recovery');\n }\n } catch (error) {\n throw new Error(`Emergency recovery failed: ${error}`);\n }\n }\n}\n\n// ============================================================================\n// Main RollbackManager - Orchestrates all rollback components\n// ============================================================================\n\nexport class RollbackManager extends EventEmitter {\n private stateManager: StateManager;\n private rollbackTrigger: RollbackTrigger;\n private automatedRecovery: AutomatedRecovery;\n private rollbackHistory: RollbackHistory;\n private gitRollbackManager: GitRollbackManager;\n private isInitialized: boolean = false;\n\n constructor(config: {\n snapshotDir?: string;\n historyDir?: string;\n gitDir?: string;\n maxSnapshots?: number;\n maxHistorySize?: number;\n historyTtlDays?: number;\n compressionEnabled?: boolean;\n triggerConfig?: Partial<RollbackTriggerConfig>;\n } = {}) {\n super();\n \n // Initialize components\n this.stateManager = new StateManager(\n config.snapshotDir,\n config.maxSnapshots,\n config.compressionEnabled\n );\n \n this.rollbackTrigger = new RollbackTrigger(config.triggerConfig);\n this.automatedRecovery = new AutomatedRecovery(this.stateManager);\n \n this.rollbackHistory = new RollbackHistory(\n config.historyDir,\n config.maxHistorySize,\n config.historyTtlDays,\n config.compressionEnabled\n );\n \n this.gitRollbackManager = new GitRollbackManager(config.gitDir);\n \n this.setupEventHandlers();\n }\n\n private setupEventHandlers(): void {\n // Connect rollback trigger to automated recovery\n this.rollbackTrigger.on('rollback_triggered', async (event) => {\n await this.handleAutomaticRollback(event.metrics, event.reason);\n });\n \n // Forward important events\n this.stateManager.on('error', (error) => this.emit('error', error));\n this.rollbackTrigger.on('error', (error) => this.emit('error', error));\n this.automatedRecovery.on('error', (error) => this.emit('error', error));\n this.rollbackHistory.on('error', (error) => this.emit('error', error));\n this.gitRollbackManager.on('error', (error) => this.emit('error', error));\n \n // Aggregate events\n this.stateManager.on('snapshot_created', (snapshot) => \n this.emit('snapshot_created', snapshot));\n this.automatedRecovery.on('recovery_success', (event) => \n this.emit('recovery_success', event));\n this.gitRollbackManager.on('rollback_completed', (event) => \n this.emit('git_rollback_completed', event));\n }\n\n public async initialize(): Promise<void> {\n if (this.isInitialized) return;\n \n try {\n // Start monitoring\n this.rollbackTrigger.startMonitoring();\n \n this.isInitialized = true;\n this.emit('initialized');\n \n } catch (error) {\n this.emit('error', new Error(`Failed to initialize RollbackManager: ${error}`));\n throw error;\n }\n }\n\n public async shutdown(): Promise<void> {\n if (!this.isInitialized) return;\n \n try {\n this.rollbackTrigger.stopMonitoring();\n this.rollbackHistory.destroy();\n \n this.isInitialized = false;\n this.emit('shutdown');\n \n } catch (error) {\n this.emit('error', new Error(`Failed to shutdown RollbackManager: ${error}`));\n }\n }\n\n /**\n * Creates a comprehensive system checkpoint\n */\n public async createCheckpoint(\n description: string,\n tags: string[] = []\n ): Promise<string> {\n try {\n // Create system snapshot\n const snapshot = await this.stateManager.captureSnapshot(\n description,\n tags,\n 'manual_checkpoint'\n );\n \n // Create git rollback point\n await this.gitRollbackManager.createRollbackPoint(\n description,\n tags\n );\n \n this.emit('checkpoint_created', { snapshot: snapshot.id, description, tags });\n return snapshot.id;\n \n } catch (error) {\n this.emit('error', new Error(`Failed to create checkpoint: ${error}`));\n throw error;\n }\n }\n\n /**\n * Performs a manual rollback to a specific checkpoint\n */\n public async rollbackToCheckpoint(\n snapshotId: string,\n strategy: 'graceful' | 'immediate' = 'graceful'\n ): Promise<boolean> {\n try {\n const snapshot = await this.stateManager.getSnapshot(snapshotId);\n if (!snapshot) {\n throw new Error(`Snapshot not found: ${snapshotId}`);\n }\n \n const startTime = Date.now();\n \n // Execute rollback based on strategy\n let success: boolean;\n if (strategy === 'graceful') {\n success = await this.performGracefulRollback(snapshot);\n } else {\n success = await this.performImmediateRollback(snapshot);\n }\n \n const duration = Date.now() - startTime;\n \n // Record in history\n await this.rollbackHistory.addEntry(\n snapshot,\n 'manual',\n `Manual rollback to checkpoint ${snapshotId}`,\n undefined, // No trigger metrics for manual rollback\n strategy,\n success,\n duration,\n [], // No recovery attempts for manual rollback\n [], // Would need to run verification\n success,\n !success\n );\n \n if (success) {\n this.emit('manual_rollback_success', { snapshotId, strategy, duration });\n } else {\n this.emit('manual_rollback_failed', { snapshotId, strategy, duration });\n }\n \n return success;\n \n } catch (error) {\n this.emit('error', new Error(`Manual rollback failed: ${error}`));\n return false;\n }\n }\n\n private async handleAutomaticRollback(\n metrics: SystemMetrics,\n reason: string\n ): Promise<void> {\n try {\n const success = await this.automatedRecovery.executeRecovery(metrics, reason);\n \n if (success) {\n this.emit('automatic_rollback_success', { reason, metrics });\n } else {\n this.emit('automatic_rollback_failed', { reason, metrics });\n }\n \n } catch (error) {\n this.emit('error', new Error(`Automatic rollback failed: ${error}`));\n }\n }\n\n private async performGracefulRollback(snapshot: SystemSnapshot): Promise<boolean> {\n try {\n // 1. Create backup of current state\n await this.stateManager.captureSnapshot(\n 'Pre-rollback backup',\n ['auto-backup'],\n 'rollback_backup'\n );\n \n // 2. Gradually restore components\n const restoreSteps = [\n () => this.restoreConfiguration(snapshot),\n () => this.restoreMemoryState(snapshot),\n () => this.restoreFileSystem(snapshot),\n () => this.performGitRollback(snapshot)\n ];\n \n for (const step of restoreSteps) {\n await step();\n // Small delay between steps\n await new Promise(resolve => setTimeout(resolve, 1000));\n }\n \n return true;\n \n } catch (error) {\n this.emit('graceful_rollback_error', error);\n return false;\n }\n }\n\n private async performImmediateRollback(snapshot: SystemSnapshot): Promise<boolean> {\n try {\n // Perform all restoration steps in parallel for speed\n await Promise.all([\n this.restoreConfiguration(snapshot),\n this.restoreMemoryState(snapshot),\n this.restoreFileSystem(snapshot),\n this.performGitRollback(snapshot)\n ]);\n \n return true;\n \n } catch (error) {\n this.emit('immediate_rollback_error', error);\n return false;\n }\n }\n\n private async restoreConfiguration(snapshot: SystemSnapshot): Promise<void> {\n for (const [path, content] of Object.entries(snapshot.state.config)) {\n try {\n await fs.writeFile(path, JSON.stringify(content, null, 2));\n } catch (error) {\n console.warn(`Failed to restore config ${path}:`, error);\n }\n }\n }\n\n private async restoreMemoryState(snapshot: SystemSnapshot): Promise<void> {\n for (const [path, content] of Object.entries(snapshot.state.memory)) {\n try {\n await fs.writeFile(path, JSON.stringify(content, null, 2));\n } catch (error) {\n console.warn(`Failed to restore memory ${path}:`, error);\n }\n }\n }\n\n private async restoreFileSystem(snapshot: SystemSnapshot): Promise<void> {\n for (const file of snapshot.state.files) {\n try {\n await fs.writeFile(file.path, file.content);\n await fs.chmod(file.path, file.stats.mode);\n } catch (error) {\n console.warn(`Failed to restore file ${file.path}:`, error);\n }\n }\n }\n\n private async performGitRollback(snapshot: SystemSnapshot): Promise<void> {\n if (snapshot.state.git.commit !== 'unknown') {\n try {\n await this.gitRollbackManager.rollbackToCommit(snapshot.state.git.commit);\n } catch (error) {\n console.warn('Git rollback failed:', error);\n }\n }\n }\n\n // Public API methods\n public getStateManager(): StateManager { return this.stateManager; }\n public getRollbackTrigger(): RollbackTrigger { return this.rollbackTrigger; }\n public getAutomatedRecovery(): AutomatedRecovery { return this.automatedRecovery; }\n public getRollbackHistory(): RollbackHistory { return this.rollbackHistory; }\n public getGitRollbackManager(): GitRollbackManager { return this.gitRollbackManager; }\n\n public async getSystemStatus(): Promise<{\n isMonitoring: boolean;\n snapshotCount: number;\n historyEntries: number;\n lastCheckpoint: string | null;\n healthScore: number;\n }> {\n const snapshots = this.stateManager.listSnapshots();\n const recentEntries = this.rollbackHistory.getRecentEntries(10);\n const successRate = this.rollbackHistory.getSuccessRate();\n \n return {\n isMonitoring: this.rollbackTrigger.getCurrentMetrics() !== null,\n snapshotCount: snapshots.length,\n historyEntries: recentEntries.length,\n lastCheckpoint: snapshots[0]?.id || null,\n healthScore: successRate\n };\n }\n}\n\n// Export the main class and interfaces\nexport default RollbackManager;"],"names":["promises","fs","join","exec","promisify","createHash","EventEmitter","gzip","gunzip","execAsync","gzipAsync","gunzipAsync","StateManager","snapshots","Map","snapshotDir","maxSnapshots","compressionEnabled","initializeStorage","mkdir","recursive","loadExistingSnapshots","error","emit","Error","files","readdir","snapshotFiles","filter","f","endsWith","file","content","readFile","snapshot","JSON","parse","set","id","console","warn","size","captureSnapshot","description","tags","triggeredBy","generateSnapshotId","timestamp","Date","now","config","memory","processes","git","Promise","all","captureConfig","captureMemory","captureProcesses","captureFiles","captureGitState","version","metadata","severity","state","integrity","checksum","compressed","serialized","stringify","update","digest","Buffer","byteLength","storeSnapshot","cleanupOldSnapshots","configPaths","path","memoryPaths","stdout","lines","trim","split","map","line","parts","pid","parseInt","name","status","parseFloat","cpu","env","process","criticalPaths","stats","stat","push","mtime","getTime","mode","branch","commit","staged","modified","untracked","then","r","catch","Boolean","filename","filepath","from","writeFile","sorted","Array","values","sort","a","b","toDelete","slice","length","unlink","delete","Math","random","toString","substr","getSnapshot","get","listSnapshots","deleteSnapshot","RollbackTrigger","monitoring","metrics","monitoringInterval","lastRollback","mergeConfig","enabled","thresholds","errorRate","memoryUsage","cpuUsage","responseTime","diskSpace","consecutiveFailures","interval","cooldown","gracePeriod","notifications","webhook","email","slack","startMonitoring","setInterval","checkThresholds","stopMonitoring","clearInterval","undefined","collectMetrics","oneHourAgo","m","violations","evaluateThresholds","recentViolations","triggerRollback","memInfo","cpuInfo","diskInfo","getMemoryInfo","getCpuInfo","getDiskInfo","errors","count","rate","recent","performance","disk","network","in","out","health","score","checks","used","total","percentage","usage","load","free","message","duration","meminfo","memTotal","find","l","startsWith","memAvailable","memUsed","loadavg","loads","parseSize","sizeStr","match","value","unit","multipliers","toFixed","diskFreePercentage","reason","sendNotifications","updateConfig","getCurrentMetrics","getMetricsHistory","AutomatedRecovery","strategies","recoveryHistory","stateManager","isRecovering","initializeDefaultStrategies","registerStrategy","priority","timeout","retries","conditions","execute","context","strategy","action","resolve","setTimeout","global","gc","clearApplicationCaches","restoreConfiguration","performFullRollback","executeRecovery","triggerReason","preferredSnapshot","applicableStrategies","s","previousAttempts","success","executeStrategy","startTime","attempt","maxAttempts","race","_","reject","recoveryAttempt","rm","force","Object","entries","chmod","getStrategyNames","keys","getStrategy","enableStrategy","disableStrategy","getRecoveryHistory","RollbackHistory","history","historyDir","maxHistorySize","ttlMs","cleanupInterval","ttlDays","startCleanupInterval","loadExistingHistory","historyFiles","decompressed","entry","cleanupExpiredEntries","addEntry","triggerType","triggerMetrics","recoveryStrategy","recoverySuccess","recoveryDuration","recoveryAttempts","verificationChecks","verificationPassed","rollbackRequired","generateHistoryId","trigger","type","recovery","attempts","verification","passed","storeHistoryEntry","cleanupOldEntries","expiredEntries","deleteEntry","getEntry","getRecentEntries","limit","getEntriesByDateRange","startDate","endDate","endTime","getSuccessRate","timeframe","cutoff","recentEntries","successCount","getStatistics","totalEntries","successRate","averageRecoveryTime","mostCommonFailureReason","rollbacksByTrigger","e","totalRecoveryTime","reduce","sum","failureReasons","reasonCounts","acc","destroy","GitRollbackManager","gitDir","backupBranch","safetyChecks","createRollbackPoint","ensureGitRepo","performSafetyChecks","createBackupBranch","cwd","rollbackMessage","formatRollbackMessage","commitHash","hash","tagName","tag","rollbackToCommit","preserveUntracked","validateCommit","stashRef","getLastStashRef","currentHash","emergencyRecovery","recoveryError","rollbackFiles","validateFiles","backupStash","createFileBackup","restoreFileBackup","createTestBranch","branchName","listRollbackPoints","commits","dateStr","date","replace","extractTagsFromMessage","tagOutput","taggedCommits","currentBranch","protectedBranches","includes","tagStr","access","RollbackManager","rollbackTrigger","automatedRecovery","rollbackHistory","gitRollbackManager","isInitialized","triggerConfig","historyTtlDays","setupEventHandlers","on","event","handleAutomaticRollback","initialize","shutdown","createCheckpoint","rollbackToCheckpoint","snapshotId","performGracefulRollback","performImmediateRollback","restoreSteps","restoreMemoryState","restoreFileSystem","performGitRollback","step","getStateManager","getRollbackTrigger","getAutomatedRecovery","getRollbackHistory","getGitRollbackManager","getSystemStatus","isMonitoring","snapshotCount","historyEntries","lastCheckpoint","healthScore"],"mappings":"AAcA,SAASA,YAAYC,EAAE,QAAQ,KAAK;AACpC,SAASC,IAAI,QAAQ,OAAO;AAC5B,SAASC,IAAI,QAAe,gBAAgB;AAC5C,SAASC,SAAS,QAAQ,OAAO;AACjC,SAASC,UAAU,QAAQ,SAAS;AACpC,SAASC,YAAY,QAAQ,SAAS;AACtC,SAASC,IAAI,EAAEC,MAAM,QAAQ,OAAO;AAEpC,MAAMC,YAAYL,UAAUD;AAC5B,MAAMO,YAAYN,UAAUG;AAC5B,MAAMI,cAAcP,UAAUI;AA+J9B,OAAO,MAAMI,qBAAqBN;IACxBO,YAAyC,IAAIC,MAAM;IACnDC,YAAoB;IACpBC,aAAqB;IACrBC,mBAA4B;IAEpC,YACEF,cAAsB,aAAa,EACnCC,eAAuB,GAAG,EAC1BC,qBAA8B,IAAI,CAClC;QACA,KAAK;QACL,IAAI,CAACF,WAAW,GAAGA;QACnB,IAAI,CAACC,YAAY,GAAGA;QACpB,IAAI,CAACC,kBAAkB,GAAGA;QAC1B,IAAI,CAACC,iBAAiB;IACxB;IAEA,MAAcA,oBAAmC;QAC/C,IAAI;YACF,MAAMjB,GAAGkB,KAAK,CAAC,IAAI,CAACJ,WAAW,EAAE;gBAAEK,WAAW;YAAK;YACnD,MAAM,IAAI,CAACC,qBAAqB;QAClC,EAAE,OAAOC,OAAO;YACd,IAAI,CAACC,IAAI,CAAC,SAAS,IAAIC,MAAM,CAAC,8BAA8B,EAAEF,OAAO;QACvE;IACF;IAEA,MAAcD,wBAAuC;QACnD,IAAI;YACF,MAAMI,QAAQ,MAAMxB,GAAGyB,OAAO,CAAC,IAAI,CAACX,WAAW;YAC/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IAAI,CAAC,CAAC,CAAC,EAAEvD;YACvD;QACF;IACF;IAEA,MAAc8W,mBAAmBlW,QAAwB,EAAiB;QACxE,IAAIA,SAAS8B,KAAK,CAACX,GAAG,CAACiD,MAAM,KAAK,WAAW;YAC3C,IAAI;gBACF,MAAM,IAAI,CAAC4Q,kBAAkB,CAAChC,gBAAgB,CAAChT,SAAS8B,KAAK,CAACX,GAAG,CAACiD,MAAM;YAC1E,EAAE,OAAOhF,OAAO;gBACdiB,QAAQC,IAAI,CAAC,wBAAwBlB;YACvC;QACF;IACF;IAGOgX,kBAAgC;QAAE,OAAO,IAAI,CAAC5K,YAAY;IAAE;IAC5D6K,qBAAsC;QAAE,OAAO,IAAI,CAACxB,eAAe;IAAE;IACrEyB,uBAA0C;QAAE,OAAO,IAAI,CAACxB,iBAAiB;IAAE;IAC3EyB,qBAAsC;QAAE,OAAO,IAAI,CAACxB,eAAe;IAAE;IACrEyB,wBAA4C;QAAE,OAAO,IAAI,CAACxB,kBAAkB;IAAE;IAErF,MAAayB,kBAMV;QACD,MAAM9X,YAAY,IAAI,CAAC6M,YAAY,CAACvF,aAAa;QACjD,MAAMgL,gBAAgB,IAAI,CAAC8D,eAAe,CAACvE,gBAAgB,CAAC;QAC5D,MAAMa,cAAc,IAAI,CAAC0D,eAAe,CAACjE,cAAc;QAEvD,OAAO;YACL4F,cAAc,IAAI,CAAC7B,eAAe,CAAC1J,iBAAiB,OAAO;YAC3DwL,eAAehY,UAAU6G,MAAM;YAC/BoR,gBAAgB3F,cAAczL,MAAM;YACpCqR,gBAAgBlY,SAAS,CAAC,EAAE,EAAEyB,MAAM;YACpC0W,aAAazF;QACf;IACF;AACF;AAGA,eAAeuD,gBAAgB"}
@@ -1,7 +1,9 @@
1
1
  import * as fs from 'fs/promises';
2
2
  import * as path from 'path';
3
3
  import * as os from 'os';
4
- import TruthScoreCalculator from '../../../../.claude/helpers/truth-score.js';
4
+ import { createRequire } from 'module';
5
+ const require = createRequire(import.meta.url);
6
+ const TruthScoreCalc = require('../../../../.claude/helpers/truth-score.js');
5
7
  describe('False Reporting Detection Scenarios', ()=>{
6
8
  let tempDir;
7
9
  let truthCalculator;
@@ -9,7 +11,7 @@ describe('False Reporting Detection Scenarios', ()=>{
9
11
  let mockAgents;
10
12
  beforeEach(async ()=>{
11
13
  tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'false-reporting-test-'));
12
- truthCalculator = new TruthScoreCalculator();
14
+ truthCalculator = new TruthScoreCalc();
13
15
  truthCalculator.configPath = path.join(tempDir, 'verification.json');
14
16
  truthCalculator.memoryPath = path.join(tempDir, 'truth-scores');
15
17
  await truthCalculator.init();