snow-flow 2.0.2 → 2.0.3

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 (173) hide show
  1. package/{.claude/mcp-config.json → .mcp.json} +13 -12
  2. package/.releaserc.json +47 -0
  3. package/README.md +6 -0
  4. package/package.json +1 -1
  5. package/.claude/claude-settings.json +0 -15
  6. package/.claude/commands/analysis/README.md +0 -9
  7. package/.claude/commands/automation/README.md +0 -9
  8. package/.claude/commands/github/README.md +0 -11
  9. package/.claude/commands/helpers/standard-checkpoint-hooks.sh +0 -179
  10. package/.claude/commands/hooks/README.md +0 -11
  11. package/.claude/commands/monitoring/README.md +0 -9
  12. package/.claude/commands/optimization/README.md +0 -9
  13. package/.claude/commands/training/README.md +0 -9
  14. package/.claude/commands/workflows/README.md +0 -9
  15. package/.claude/config.json +0 -36
  16. package/.claude/helpers/github-setup.sh +0 -28
  17. package/.claude/helpers/quick-start.sh +0 -19
  18. package/.claude/helpers/setup-mcp.sh +0 -18
  19. package/.claude/settings.json +0 -114
  20. package/.claude/settings.local.json +0 -33
  21. package/.claude-flow/metrics/agent-metrics.json +0 -1
  22. package/.claude-flow/metrics/performance.json +0 -9
  23. package/.claude-flow/metrics/system-metrics.json +0 -15986
  24. package/.claude-flow/metrics/task-metrics.json +0 -10
  25. package/.roo/README.md +0 -402
  26. package/.roo/mcp-list.txt +0 -257
  27. package/.roo/mcp.json +0 -32
  28. package/.roo/workflows/basic-tdd.json +0 -32
  29. package/.roomodes +0 -201
  30. package/CLAUDE.md +0 -393
  31. package/bin/snow-flow.js +0 -3
  32. package/dist/cli.js.bak +0 -2052
  33. package/dist/config/snow-flow-config.d.ts +0 -1492
  34. package/dist/config/snow-flow-config.js +0 -938
  35. package/scripts/create-env.js +0 -91
  36. package/scripts/postinstall.js +0 -30
  37. package/scripts/register-mcp-servers.js +0 -210
  38. package/scripts/reset-mcp-servers.js +0 -246
  39. package/scripts/setup-mcp.js +0 -106
  40. package/scripts/update-version.js +0 -31
  41. package/src/agents/README.md +0 -192
  42. package/src/agents/base-agent.ts +0 -251
  43. package/src/agents/coordinator.ts +0 -971
  44. package/src/agents/index.ts +0 -18
  45. package/src/agents/queen-403-handler.ts +0 -230
  46. package/src/agents/queen-agent.ts +0 -1399
  47. package/src/agents/script-writer-agent.ts +0 -769
  48. package/src/agents/security-agent.ts +0 -726
  49. package/src/agents/widget-creator-agent.ts +0 -568
  50. package/src/api/error-handling.ts +0 -1758
  51. package/src/api/natural-language-mapper.ts +0 -630
  52. package/src/api/performance-optimizer.ts +0 -891
  53. package/src/api/transaction-manager.ts +0 -754
  54. package/src/cli/deploy-artifact.ts +0 -304
  55. package/src/cli/snow-flow-cli-integration.ts +0 -434
  56. package/src/cli.ts +0 -4455
  57. package/src/cli.ts.bak +0 -5616
  58. package/src/compliance/advanced-compliance-system.ts +0 -1268
  59. package/src/compliance/index.ts +0 -19
  60. package/src/config/snow-flow-config.ts +0 -1019
  61. package/src/documentation/index.ts +0 -16
  62. package/src/documentation/self-documenting-system.ts +0 -1421
  63. package/src/dynamic-version.ts +0 -44
  64. package/src/healing/index.ts +0 -20
  65. package/src/healing/self-healing-system.ts +0 -1435
  66. package/src/health/README.md +0 -161
  67. package/src/health/system-health.ts +0 -995
  68. package/src/index.ts +0 -60
  69. package/src/intelligence/acl-analyzer.ts +0 -377
  70. package/src/intelligence/auto-resolution-engine.ts +0 -643
  71. package/src/intelligence/gap-analysis-engine.ts +0 -488
  72. package/src/intelligence/manual-instructions-generator.ts +0 -744
  73. package/src/intelligence/mcp-coverage-analyzer.ts +0 -708
  74. package/src/intelligence/multi-pass-requirements-analyzer.ts +0 -603
  75. package/src/intelligence/performance-recommendations-engine.ts +0 -1223
  76. package/src/intelligence/requirements-analyzer.ts +0 -1148
  77. package/src/intelligence/task-analyzer.ts +0 -628
  78. package/src/managers/scope-manager.ts +0 -555
  79. package/src/mcp/advanced/servicenow-advanced-features-mcp.ts +0 -16110
  80. package/src/mcp/base-mcp-server.ts +0 -660
  81. package/src/mcp/http-transport-wrapper.ts +0 -426
  82. package/src/mcp/service-discovery-client.ts +0 -312
  83. package/src/mcp/servicenow-automation-mcp-refactored.ts +0 -678
  84. package/src/mcp/servicenow-automation-mcp.ts +0 -838
  85. package/src/mcp/servicenow-deployment-mcp-refactored.ts +0 -1292
  86. package/src/mcp/servicenow-deployment-mcp.ts +0 -7244
  87. package/src/mcp/servicenow-graph-memory-mcp-refactored.ts +0 -721
  88. package/src/mcp/servicenow-graph-memory-mcp.ts +0 -832
  89. package/src/mcp/servicenow-integration-mcp-refactored.ts +0 -655
  90. package/src/mcp/servicenow-integration-mcp.ts +0 -819
  91. package/src/mcp/servicenow-intelligent-mcp-refactored.ts +0 -977
  92. package/src/mcp/servicenow-intelligent-mcp.ts +0 -4638
  93. package/src/mcp/servicenow-mcp-server.ts +0 -728
  94. package/src/mcp/servicenow-memory-mcp.ts +0 -474
  95. package/src/mcp/servicenow-operations-mcp-refactored.ts +0 -1995
  96. package/src/mcp/servicenow-operations-mcp.ts +0 -3384
  97. package/src/mcp/servicenow-platform-development-mcp-refactored.ts +0 -611
  98. package/src/mcp/servicenow-platform-development-mcp.ts +0 -970
  99. package/src/mcp/servicenow-progressive-indexer.ts +0 -370
  100. package/src/mcp/servicenow-reporting-analytics-mcp-refactored.ts +0 -695
  101. package/src/mcp/servicenow-reporting-analytics-mcp.ts +0 -1123
  102. package/src/mcp/servicenow-security-compliance-mcp-refactored.ts +0 -642
  103. package/src/mcp/servicenow-security-compliance-mcp.ts +0 -1157
  104. package/src/mcp/servicenow-update-set-mcp-refactored.ts +0 -751
  105. package/src/mcp/servicenow-update-set-mcp.ts +0 -811
  106. package/src/mcp/shared/agent-context-provider.ts +0 -365
  107. package/src/mcp/shared/base-mcp-server.ts +0 -2463
  108. package/src/mcp/shared/mcp-memory-manager.ts +0 -540
  109. package/src/mcp/shared/mcp-resource-manager.ts +0 -367
  110. package/src/mcp/snow-flow-mcp.ts +0 -911
  111. package/src/mcp/start-all-mcp-servers.ts +0 -102
  112. package/src/mcp/start-servicenow-mcp.ts +0 -67
  113. package/src/monitoring/enhanced-monitoring-system.ts +0 -1345
  114. package/src/monitoring/performance-tracker.ts +0 -777
  115. package/src/optimization/cost-optimization-engine.ts +0 -1125
  116. package/src/optimization/index.ts +0 -10
  117. package/src/queen/README.md +0 -403
  118. package/src/queen/agent-factory.ts +0 -574
  119. package/src/queen/index.ts +0 -94
  120. package/src/queen/mcp-execution-bridge.ts +0 -681
  121. package/src/queen/neural-learning.ts +0 -319
  122. package/src/queen/parallel-agent-engine.ts +0 -848
  123. package/src/queen/queen-memory-system.ts +0 -490
  124. package/src/queen/queen-memory.ts +0 -456
  125. package/src/queen/servicenow-queen.ts +0 -1029
  126. package/src/queen/types.ts +0 -87
  127. package/src/rollback/smart-rollback-system.ts +0 -866
  128. package/src/schemas/deployment.schema.json +0 -58
  129. package/src/schemas/flow.schema.json +0 -79
  130. package/src/schemas/widget.schema.json +0 -72
  131. package/src/snow-flow-system.ts +0 -541
  132. package/src/sparc/sparc-help.ts +0 -49
  133. package/src/sparc/team-sparc.ts +0 -88
  134. package/src/strategies/global-scope-strategy.ts +0 -736
  135. package/src/templates/base/application.template.json +0 -45
  136. package/src/templates/base/business_rule.template.json +0 -33
  137. package/src/templates/base/script_include.template.json +0 -18
  138. package/src/templates/base/table.template.json +0 -64
  139. package/src/templates/base/widget.template.json +0 -25
  140. package/src/templates/patterns/composite.incident-management.template.json +0 -140
  141. package/src/templates/patterns/widget.dashboard.template.json +0 -238
  142. package/src/templates/patterns/widget.datatable.template.json +0 -292
  143. package/src/testing/integration-test-suite.ts +0 -1276
  144. package/src/types/index.ts +0 -183
  145. package/src/types/neo4j-driver.d.ts +0 -23
  146. package/src/types/servicenow.types.ts +0 -307
  147. package/src/types/snow-flow.types.ts +0 -186
  148. package/src/types/todo.types.ts +0 -70
  149. package/src/utils/action-type-cache.ts +0 -286
  150. package/src/utils/agent-detector.ts +0 -573
  151. package/src/utils/artifact-tracker.ts +0 -379
  152. package/src/utils/dependency-detector.ts +0 -233
  153. package/src/utils/deployment-metadata-handler.ts +0 -518
  154. package/src/utils/error-recovery.ts +0 -680
  155. package/src/utils/logger.ts +0 -60
  156. package/src/utils/mcp-auth-middleware.ts +0 -262
  157. package/src/utils/mcp-config-manager.ts +0 -270
  158. package/src/utils/mcp-server-manager.ts +0 -446
  159. package/src/utils/mcp-tool-registry.ts +0 -298
  160. package/src/utils/migrate-snow-flow.ts +0 -98
  161. package/src/utils/oauth-html-templates.ts +0 -188
  162. package/src/utils/scope-utils.ts +0 -443
  163. package/src/utils/servicenow-client.ts +0 -3321
  164. package/src/utils/servicenow-id-generator.ts +0 -181
  165. package/src/utils/snow-memory-manager.ts +0 -605
  166. package/src/utils/snow-oauth.ts +0 -797
  167. package/src/utils/template-engine.ts +0 -463
  168. package/src/utils/theme-manager.ts +0 -295
  169. package/src/utils/unified-auth-store.ts +0 -222
  170. package/src/utils/update-set-importer.ts +0 -422
  171. package/src/utils/update-set-xml-packager.ts +0 -371
  172. package/src/utils/widget-template-generator.ts +0 -1744
  173. package/src/version.ts +0 -1950
@@ -1,1435 +0,0 @@
1
- /**
2
- * 🤖 Self-Healing System for Autonomous Error Recovery
3
- *
4
- * Advanced autonomous system that detects, diagnoses, and automatically
5
- * recovers from errors without manual intervention, ensuring maximum
6
- * system availability and reliability.
7
- */
8
-
9
- import { Logger } from '../utils/logger.js';
10
- import { ServiceNowClient } from '../utils/servicenow-client.js';
11
- import { MemorySystem } from '../memory/memory-system.js';
12
-
13
- export interface HealingProfile {
14
- id: string;
15
- systemName: string;
16
- assessmentDate: string;
17
- healthScore: number;
18
- incidents: HealthIncident[];
19
- healingActions: HealingAction[];
20
- patterns: ErrorPattern[];
21
- predictions: HealthPrediction[];
22
- recoveryStrategies: RecoveryStrategy[];
23
- systemMetrics: SystemMetrics;
24
- recommendations: HealingRecommendation[];
25
- metadata: HealingMetadata;
26
- }
27
-
28
- export interface HealthIncident {
29
- id: string;
30
- type: 'error' | 'performance' | 'availability' | 'security' | 'data-integrity';
31
- severity: 'critical' | 'high' | 'medium' | 'low';
32
- title: string;
33
- description: string;
34
- detectedAt: string;
35
- status: 'active' | 'healing' | 'resolved' | 'escalated';
36
- rootCause?: RootCause;
37
- impact: IncidentImpact;
38
- healingAttempts: number;
39
- resolvedAt?: string;
40
- resolutionMethod?: string;
41
- }
42
-
43
- export interface RootCause {
44
- id: string;
45
- category: 'code' | 'configuration' | 'resource' | 'external' | 'data' | 'network';
46
- description: string;
47
- confidence: number; // 0-1
48
- evidence: string[];
49
- relatedIncidents: string[];
50
- preventable: boolean;
51
- }
52
-
53
- export interface IncidentImpact {
54
- users: number;
55
- services: string[];
56
- availability: number; // percentage
57
- performance: number; // degradation percentage
58
- dataLoss: boolean;
59
- financialImpact?: number;
60
- duration: number; // milliseconds
61
- }
62
-
63
- export interface HealingAction {
64
- id: string;
65
- incidentId: string;
66
- type: 'restart' | 'rollback' | 'patch' | 'scale' | 'reroute' | 'cleanup' | 'restore';
67
- title: string;
68
- description: string;
69
- status: 'pending' | 'executing' | 'completed' | 'failed' | 'rolled-back';
70
- automated: boolean;
71
- executionSteps: HealingStep[];
72
- startTime?: string;
73
- endTime?: string;
74
- result?: HealingResult;
75
- rollbackPlan?: string;
76
- }
77
-
78
- export interface HealingStep {
79
- order: number;
80
- action: string;
81
- target: string;
82
- parameters: Record<string, any>;
83
- status: 'pending' | 'executing' | 'completed' | 'failed' | 'skipped';
84
- output?: string;
85
- error?: string;
86
- duration?: number;
87
- }
88
-
89
- export interface HealingResult {
90
- success: boolean;
91
- message: string;
92
- metricsAfter: {
93
- availability: number;
94
- performance: number;
95
- errorRate: number;
96
- };
97
- sideEffects: string[];
98
- verificationPassed: boolean;
99
- }
100
-
101
- export interface ErrorPattern {
102
- id: string;
103
- name: string;
104
- description: string;
105
- signature: PatternSignature;
106
- occurrences: number;
107
- lastSeen: string;
108
- avgResolutionTime: number;
109
- successRate: number;
110
- recommendedActions: string[];
111
- autoHealable: boolean;
112
- }
113
-
114
- export interface PatternSignature {
115
- errorTypes: string[];
116
- keywords: string[];
117
- frequency: 'sporadic' | 'recurring' | 'persistent';
118
- timePattern?: string;
119
- correlations: string[];
120
- }
121
-
122
- export interface HealthPrediction {
123
- id: string;
124
- type: 'failure' | 'degradation' | 'capacity' | 'security';
125
- component: string;
126
- probability: number; // 0-1
127
- timeframe: string;
128
- impact: 'critical' | 'high' | 'medium' | 'low';
129
- preventiveActions: PreventiveAction[];
130
- confidence: number; // 0-1
131
- basedOn: string[];
132
- }
133
-
134
- export interface PreventiveAction {
135
- action: string;
136
- priority: 'immediate' | 'high' | 'medium' | 'low';
137
- estimatedPrevention: number; // percentage
138
- cost: 'minimal' | 'moderate' | 'significant';
139
- automatable: boolean;
140
- }
141
-
142
- export interface RecoveryStrategy {
143
- id: string;
144
- name: string;
145
- description: string;
146
- applicableTo: string[];
147
- steps: RecoveryStep[];
148
- estimatedTime: number;
149
- successRate: number;
150
- requirements: string[];
151
- risks: string[];
152
- }
153
-
154
- export interface RecoveryStep {
155
- order: number;
156
- action: string;
157
- automated: boolean;
158
- timeout: number;
159
- verification: string;
160
- fallback?: string;
161
- }
162
-
163
- export interface SystemMetrics {
164
- availability: {
165
- current: number;
166
- target: number;
167
- trend: 'improving' | 'stable' | 'degrading';
168
- };
169
- performance: {
170
- responseTime: number;
171
- throughput: number;
172
- errorRate: number;
173
- trend: 'improving' | 'stable' | 'degrading';
174
- };
175
- reliability: {
176
- mtbf: number; // mean time between failures
177
- mttr: number; // mean time to recovery
178
- failureRate: number;
179
- };
180
- capacity: {
181
- cpu: number;
182
- memory: number;
183
- storage: number;
184
- network: number;
185
- };
186
- }
187
-
188
- export interface HealingRecommendation {
189
- id: string;
190
- category: 'architecture' | 'monitoring' | 'redundancy' | 'automation' | 'capacity';
191
- priority: 'critical' | 'high' | 'medium' | 'low';
192
- title: string;
193
- description: string;
194
- benefit: string;
195
- effort: 'minimal' | 'moderate' | 'significant' | 'major';
196
- preventedIncidents: number;
197
- roi: number; // return on investment percentage
198
- }
199
-
200
- export interface HealingMetadata {
201
- monitoringEnabled: boolean;
202
- autoHealingEnabled: boolean;
203
- learningMode: boolean;
204
- retentionDays: number;
205
- integrations: string[];
206
- lastFullScan: string;
207
- nextScheduledScan: string;
208
- }
209
-
210
- export interface HealingRequest {
211
- scope?: 'full' | 'incremental' | 'specific-services';
212
- services?: string[];
213
- autoHeal?: boolean;
214
- predictive?: boolean;
215
- learning?: boolean;
216
- }
217
-
218
- export interface HealingResponse {
219
- success: boolean;
220
- profile: HealingProfile;
221
- incidentsDetected: number;
222
- incidentsHealed: number;
223
- predictionsGenerated: number;
224
- recommendations: string[];
225
- warnings: string[];
226
- }
227
-
228
- export class SelfHealingSystem {
229
- private logger: Logger;
230
- private client: ServiceNowClient;
231
- private memory: MemorySystem;
232
- private healingProfiles: Map<string, HealingProfile> = new Map();
233
- private activeIncidents: Map<string, HealthIncident> = new Map();
234
- private errorPatterns: Map<string, ErrorPattern> = new Map();
235
- private recoveryStrategies: Map<string, RecoveryStrategy> = new Map();
236
- private monitoringActive: boolean = true;
237
- private learningEngine: LearningEngine;
238
-
239
- constructor(client: ServiceNowClient, memory: MemorySystem) {
240
- this.logger = new Logger('SelfHealingSystem');
241
- this.client = client;
242
- this.memory = memory;
243
- this.learningEngine = new LearningEngine(memory);
244
-
245
- this.initializeRecoveryStrategies();
246
- this.startHealthMonitoring();
247
- }
248
-
249
- /**
250
- * Perform system health assessment and healing
251
- */
252
- async performHealthCheck(request: HealingRequest = {}): Promise<HealingResponse> {
253
- this.logger.info('🏥 Performing system health check', request);
254
-
255
- const profileId = `heal_${Date.now()}_${Math.random().toString(36).substr(2, 8)}`;
256
- const startTime = Date.now();
257
-
258
- try {
259
- // Detect health incidents
260
- const incidents = await this.detectHealthIncidents(request);
261
-
262
- // Analyze root causes
263
- for (const incident of incidents) {
264
- incident.rootCause = await this.analyzeRootCause(incident);
265
- }
266
-
267
- // Identify error patterns
268
- const patterns = await this.identifyErrorPatterns(incidents);
269
-
270
- // Generate predictions if requested
271
- let predictions: HealthPrediction[] = [];
272
- if (request.predictive) {
273
- predictions = await this.generateHealthPredictions(incidents, patterns);
274
- }
275
-
276
- // Create healing actions
277
- const healingActions = await this.createHealingActions(incidents);
278
-
279
- // Execute auto-healing if enabled
280
- let healedCount = 0;
281
- if (request.autoHeal) {
282
- healedCount = await this.executeAutoHealing(healingActions);
283
- }
284
-
285
- // Generate recovery strategies
286
- const strategies = await this.generateRecoveryStrategies(patterns);
287
-
288
- // Collect system metrics
289
- const metrics = await this.collectSystemMetrics();
290
-
291
- // Generate recommendations
292
- const recommendations = await this.generateHealingRecommendations(incidents, patterns, metrics);
293
-
294
- const profile: HealingProfile = {
295
- id: profileId,
296
- systemName: 'ServiceNow Multi-Agent System',
297
- assessmentDate: new Date().toISOString(),
298
- healthScore: this.calculateHealthScore(metrics, incidents),
299
- incidents,
300
- healingActions,
301
- patterns,
302
- predictions,
303
- recoveryStrategies: strategies,
304
- systemMetrics: metrics,
305
- recommendations,
306
- metadata: {
307
- monitoringEnabled: true,
308
- autoHealingEnabled: request.autoHeal || false,
309
- learningMode: request.learning || true,
310
- retentionDays: 90,
311
- integrations: ['ServiceNow', 'Memory System', 'Monitoring'],
312
- lastFullScan: new Date().toISOString(),
313
- nextScheduledScan: new Date(Date.now() + 3600000).toISOString()
314
- }
315
- };
316
-
317
- // Store profile
318
- this.healingProfiles.set(profileId, profile);
319
- await this.memory.store(`healing_profile_${profileId}`, profile, 7776000000); // 90 days
320
-
321
- // Update learning engine if enabled
322
- if (request.learning) {
323
- await this.learningEngine.learn(incidents, healingActions);
324
- }
325
-
326
- this.logger.info('✅ Health check completed', {
327
- profileId,
328
- healthScore: profile.healthScore,
329
- incidentsDetected: incidents.length,
330
- incidentsHealed: healedCount,
331
- predictionsGenerated: predictions.length
332
- });
333
-
334
- return {
335
- success: true,
336
- profile,
337
- incidentsDetected: incidents.length,
338
- incidentsHealed: healedCount,
339
- predictionsGenerated: predictions.length,
340
- recommendations: recommendations.map(r => r.title),
341
- warnings: this.generateWarnings(profile)
342
- };
343
-
344
- } catch (error) {
345
- this.logger.error('❌ Health check failed', error);
346
- throw error;
347
- }
348
- }
349
-
350
- /**
351
- * Start autonomous self-healing
352
- */
353
- async startAutonomousHealing(options: {
354
- checkInterval?: number;
355
- healingThreshold?: number;
356
- maxRetries?: number;
357
- preventive?: boolean;
358
- } = {}): Promise<void> {
359
- this.logger.info('🤖 Starting autonomous self-healing', options);
360
-
361
- const interval = options.checkInterval || 300000; // Default: 5 minutes
362
- const threshold = options.healingThreshold || 0.8; // 80% confidence
363
-
364
- setInterval(async () => {
365
- try {
366
- // Perform incremental health check
367
- const result = await this.performHealthCheck({
368
- scope: 'incremental',
369
- autoHeal: true,
370
- predictive: options.preventive || true,
371
- learning: true
372
- });
373
-
374
- // Handle critical incidents
375
- const criticalIncidents = result.profile.incidents.filter(
376
- i => i.severity === 'critical' && i.status === 'active'
377
- );
378
-
379
- if (criticalIncidents.length > 0) {
380
- await this.handleCriticalIncidents(criticalIncidents);
381
- }
382
-
383
- // Execute preventive actions
384
- if (options.preventive) {
385
- await this.executePreventiveActions(result.profile.predictions);
386
- }
387
-
388
- } catch (error) {
389
- this.logger.error('Error in autonomous healing', error);
390
- // Self-heal the self-healing system
391
- await this.healSelf(error);
392
- }
393
- }, interval);
394
- }
395
-
396
- /**
397
- * Get real-time health dashboard
398
- */
399
- async getHealthDashboard(): Promise<{
400
- systemHealth: string;
401
- healthScore: number;
402
- activeIncidents: HealthIncident[];
403
- recentHealing: HealingAction[];
404
- systemMetrics: SystemMetrics;
405
- predictions: HealthPrediction[];
406
- recommendations: HealingRecommendation[];
407
- }> {
408
- const latestProfile = this.getLatestHealingProfile();
409
-
410
- if (!latestProfile) {
411
- const result = await this.performHealthCheck();
412
- return this.generateDashboard(result.profile);
413
- }
414
-
415
- return this.generateDashboard(latestProfile);
416
- }
417
-
418
- /**
419
- * Manually trigger healing action
420
- */
421
- async executeHealingAction(
422
- actionId: string,
423
- options: {
424
- verify?: boolean;
425
- monitor?: boolean;
426
- rollbackOnFailure?: boolean;
427
- } = {}
428
- ): Promise<{
429
- success: boolean;
430
- result: HealingResult;
431
- duration: number;
432
- }> {
433
- this.logger.info('💊 Executing healing action', { actionId, options });
434
-
435
- const action = await this.getHealingAction(actionId);
436
- if (!action) {
437
- throw new Error(`Healing action not found: ${actionId}`);
438
- }
439
-
440
- const startTime = Date.now();
441
-
442
- try {
443
- // Verify if requested
444
- if (options.verify) {
445
- const verification = await this.verifyHealingSafety(action);
446
- if (!verification.safe) {
447
- throw new Error(`Healing verification failed: ${verification.reason}`);
448
- }
449
- }
450
-
451
- // Execute healing steps
452
- action.status = 'executing';
453
- action.startTime = new Date().toISOString();
454
-
455
- const result = await this.executeHealingSteps(action);
456
-
457
- // Monitor if requested
458
- if (options.monitor) {
459
- await this.monitorHealingProgress(action, result);
460
- }
461
-
462
- // Handle failure with rollback
463
- if (!result.success && options.rollbackOnFailure) {
464
- await this.rollbackHealing(action);
465
- throw new Error(`Healing failed and was rolled back: ${result.message}`);
466
- }
467
-
468
- // Update action status
469
- action.status = result.success ? 'completed' : 'failed';
470
- action.endTime = new Date().toISOString();
471
- action.result = result;
472
-
473
- const duration = Date.now() - startTime;
474
-
475
- return {
476
- success: result.success,
477
- result,
478
- duration
479
- };
480
-
481
- } catch (error) {
482
- this.logger.error('❌ Healing action failed', error);
483
- action.status = 'failed';
484
- throw error;
485
- }
486
- }
487
-
488
- /**
489
- * Private helper methods
490
- */
491
-
492
- private initializeRecoveryStrategies(): void {
493
- // Initialize common recovery strategies
494
- this.recoveryStrategies.set('restart_service', {
495
- id: 'restart_service',
496
- name: 'Service Restart',
497
- description: 'Restart affected service to clear transient errors',
498
- applicableTo: ['error', 'performance'],
499
- steps: [
500
- {
501
- order: 1,
502
- action: 'Gracefully stop service',
503
- automated: true,
504
- timeout: 30000,
505
- verification: 'Service stopped',
506
- fallback: 'Force stop service'
507
- },
508
- {
509
- order: 2,
510
- action: 'Clear temporary data',
511
- automated: true,
512
- timeout: 10000,
513
- verification: 'Temp data cleared'
514
- },
515
- {
516
- order: 3,
517
- action: 'Start service',
518
- automated: true,
519
- timeout: 60000,
520
- verification: 'Service healthy'
521
- }
522
- ],
523
- estimatedTime: 120000,
524
- successRate: 85,
525
- requirements: ['Service control permissions'],
526
- risks: ['Brief downtime']
527
- });
528
-
529
- this.recoveryStrategies.set('rollback_deployment', {
530
- id: 'rollback_deployment',
531
- name: 'Deployment Rollback',
532
- description: 'Rollback to previous stable version',
533
- applicableTo: ['error', 'availability'],
534
- steps: [
535
- {
536
- order: 1,
537
- action: 'Identify rollback point',
538
- automated: true,
539
- timeout: 5000,
540
- verification: 'Rollback point valid'
541
- },
542
- {
543
- order: 2,
544
- action: 'Execute rollback',
545
- automated: true,
546
- timeout: 300000,
547
- verification: 'Rollback completed'
548
- },
549
- {
550
- order: 3,
551
- action: 'Verify system stability',
552
- automated: true,
553
- timeout: 60000,
554
- verification: 'System stable'
555
- }
556
- ],
557
- estimatedTime: 600000,
558
- successRate: 95,
559
- requirements: ['Rollback points available'],
560
- risks: ['Feature regression']
561
- });
562
-
563
- this.recoveryStrategies.set('scale_resources', {
564
- id: 'scale_resources',
565
- name: 'Resource Scaling',
566
- description: 'Scale up resources to handle load',
567
- applicableTo: ['performance', 'availability'],
568
- steps: [
569
- {
570
- order: 1,
571
- action: 'Analyze resource usage',
572
- automated: true,
573
- timeout: 10000,
574
- verification: 'Bottleneck identified'
575
- },
576
- {
577
- order: 2,
578
- action: 'Scale resources',
579
- automated: true,
580
- timeout: 120000,
581
- verification: 'Resources scaled'
582
- },
583
- {
584
- order: 3,
585
- action: 'Load balance traffic',
586
- automated: true,
587
- timeout: 30000,
588
- verification: 'Traffic balanced'
589
- }
590
- ],
591
- estimatedTime: 180000,
592
- successRate: 90,
593
- requirements: ['Scaling capability'],
594
- risks: ['Increased costs']
595
- });
596
- }
597
-
598
- private async detectHealthIncidents(request: HealingRequest): Promise<HealthIncident[]> {
599
- const incidents: HealthIncident[] = [];
600
-
601
- // Check system logs for errors
602
- const errorLogs = await this.checkErrorLogs();
603
- for (const error of errorLogs) {
604
- incidents.push({
605
- id: `inc_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`,
606
- type: 'error',
607
- severity: this.determineSeverity(error),
608
- title: error.message,
609
- description: error.stack || error.message,
610
- detectedAt: new Date().toISOString(),
611
- status: 'active',
612
- impact: {
613
- users: error.affectedUsers || 0,
614
- services: error.affectedServices || [],
615
- availability: 100,
616
- performance: 0,
617
- dataLoss: false,
618
- duration: 0
619
- },
620
- healingAttempts: 0
621
- });
622
- }
623
-
624
- // Check performance metrics
625
- const perfIssues = await this.checkPerformanceMetrics();
626
- for (const issue of perfIssues) {
627
- incidents.push({
628
- id: `inc_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`,
629
- type: 'performance',
630
- severity: issue.severity,
631
- title: `Performance degradation in ${issue.service}`,
632
- description: `Response time increased by ${issue.degradation}%`,
633
- detectedAt: new Date().toISOString(),
634
- status: 'active',
635
- impact: {
636
- users: issue.affectedUsers,
637
- services: [issue.service],
638
- availability: 100,
639
- performance: issue.degradation,
640
- dataLoss: false,
641
- duration: issue.duration
642
- },
643
- healingAttempts: 0
644
- });
645
- }
646
-
647
- // Check availability
648
- const availabilityIssues = await this.checkAvailability();
649
- for (const issue of availabilityIssues) {
650
- incidents.push({
651
- id: `inc_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`,
652
- type: 'availability',
653
- severity: 'critical',
654
- title: `Service unavailable: ${issue.service}`,
655
- description: issue.reason,
656
- detectedAt: new Date().toISOString(),
657
- status: 'active',
658
- impact: {
659
- users: issue.affectedUsers,
660
- services: [issue.service],
661
- availability: 0,
662
- performance: 100,
663
- dataLoss: false,
664
- duration: issue.downtime
665
- },
666
- healingAttempts: 0
667
- });
668
- }
669
-
670
- return incidents;
671
- }
672
-
673
- private async analyzeRootCause(incident: HealthIncident): Promise<RootCause> {
674
- // AI-powered root cause analysis
675
- const relatedLogs = await this.getRelatedLogs(incident);
676
- const systemState = await this.getSystemStateAt(incident.detectedAt);
677
-
678
- // Analyze patterns
679
- const category = this.categorizeRootCause(incident, relatedLogs);
680
- const confidence = this.calculateConfidence(relatedLogs, systemState);
681
-
682
- return {
683
- id: `rc_${Date.now()}`,
684
- category,
685
- description: this.generateRootCauseDescription(incident, category, relatedLogs),
686
- confidence,
687
- evidence: relatedLogs.map(l => l.message),
688
- relatedIncidents: await this.findRelatedIncidents(incident),
689
- preventable: confidence > 0.7
690
- };
691
- }
692
-
693
- private async identifyErrorPatterns(incidents: HealthIncident[]): Promise<ErrorPattern[]> {
694
- const patterns: ErrorPattern[] = [];
695
-
696
- // Group incidents by similarity
697
- const groups = this.groupIncidentsBySimilarity(incidents);
698
-
699
- for (const group of groups) {
700
- if (group.length >= 2) { // Pattern requires at least 2 occurrences
701
- const pattern: ErrorPattern = {
702
- id: `pat_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`,
703
- name: this.generatePatternName(group),
704
- description: this.generatePatternDescription(group),
705
- signature: {
706
- errorTypes: [...new Set(group.map(i => i.type))],
707
- keywords: this.extractKeywords(group),
708
- frequency: this.determineFrequency(group),
709
- correlations: this.findCorrelations(group)
710
- },
711
- occurrences: group.length,
712
- lastSeen: group[group.length - 1].detectedAt,
713
- avgResolutionTime: this.calculateAvgResolutionTime(group),
714
- successRate: this.calculateSuccessRate(group),
715
- recommendedActions: this.getRecommendedActions(group),
716
- autoHealable: this.isAutoHealable(group)
717
- };
718
-
719
- patterns.push(pattern);
720
- this.errorPatterns.set(pattern.id, pattern);
721
- }
722
- }
723
-
724
- return patterns;
725
- }
726
-
727
- private async generateHealthPredictions(
728
- incidents: HealthIncident[],
729
- patterns: ErrorPattern[]
730
- ): Promise<HealthPrediction[]> {
731
- const predictions: HealthPrediction[] = [];
732
-
733
- // Analyze trends
734
- const trends = await this.analyzeTrends(incidents, patterns);
735
-
736
- // Capacity predictions
737
- const capacityIssues = await this.predictCapacityIssues();
738
- for (const issue of capacityIssues) {
739
- predictions.push({
740
- id: `pred_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`,
741
- type: 'capacity',
742
- component: issue.component,
743
- probability: issue.probability,
744
- timeframe: issue.timeframe,
745
- impact: issue.impact,
746
- preventiveActions: [
747
- {
748
- action: `Scale ${issue.component} capacity`,
749
- priority: issue.probability > 0.8 ? 'immediate' : 'high',
750
- estimatedPrevention: 90,
751
- cost: 'moderate',
752
- automatable: true
753
- }
754
- ],
755
- confidence: issue.confidence,
756
- basedOn: ['Historical usage patterns', 'Current growth rate']
757
- });
758
- }
759
-
760
- // Failure predictions based on patterns
761
- for (const pattern of patterns) {
762
- if ((pattern as any).frequency === 'recurring' || (pattern as any).frequency === 'persistent') {
763
- const nextOccurrence = this.predictNextOccurrence(pattern);
764
- if (nextOccurrence.probability > 0.6) {
765
- predictions.push({
766
- id: `pred_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`,
767
- type: 'failure',
768
- component: 'System',
769
- probability: nextOccurrence.probability,
770
- timeframe: nextOccurrence.timeframe,
771
- impact: 'high',
772
- preventiveActions: pattern.recommendedActions.map(action => ({
773
- action,
774
- priority: 'high',
775
- estimatedPrevention: 80,
776
- cost: 'minimal',
777
- automatable: pattern.autoHealable
778
- })),
779
- confidence: 0.85,
780
- basedOn: [`Pattern: ${pattern.name}`, `${pattern.occurrences} previous occurrences`]
781
- });
782
- }
783
- }
784
- }
785
-
786
- return predictions;
787
- }
788
-
789
- private async createHealingActions(incidents: HealthIncident[]): Promise<HealingAction[]> {
790
- const actions: HealingAction[] = [];
791
-
792
- for (const incident of incidents) {
793
- // Find matching recovery strategy
794
- const strategy = this.findBestStrategy(incident);
795
- if (!strategy) continue;
796
-
797
- const action: HealingAction = {
798
- id: `heal_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`,
799
- incidentId: incident.id,
800
- type: this.determineActionType(incident, strategy),
801
- title: `Heal: ${incident.title}`,
802
- description: `Apply ${strategy.name} to resolve ${incident.type} issue`,
803
- status: 'pending',
804
- automated: strategy.steps.every(s => s.automated),
805
- executionSteps: strategy.steps.map(s => ({
806
- order: s.order,
807
- action: s.action,
808
- target: incident.impact.services[0] || 'System',
809
- parameters: {},
810
- status: 'pending'
811
- })),
812
- rollbackPlan: 'Restore from pre-healing snapshot'
813
- };
814
-
815
- actions.push(action);
816
- incident.healingAttempts++;
817
- }
818
-
819
- return actions;
820
- }
821
-
822
- private async executeAutoHealing(actions: HealingAction[]): Promise<number> {
823
- let healedCount = 0;
824
-
825
- for (const action of actions) {
826
- if (action.automated && action.status === 'pending') {
827
- try {
828
- const result = await this.executeHealingSteps(action);
829
- if (result.success) {
830
- action.status = 'completed';
831
- healedCount++;
832
-
833
- // Update incident status
834
- const incident = this.activeIncidents.get(action.incidentId);
835
- if (incident) {
836
- incident.status = 'resolved';
837
- incident.resolvedAt = new Date().toISOString();
838
- incident.resolutionMethod = action.type;
839
- }
840
- }
841
- } catch (error) {
842
- this.logger.error(`Failed to auto-heal action ${action.id}`, error);
843
- action.status = 'failed';
844
- }
845
- }
846
- }
847
-
848
- return healedCount;
849
- }
850
-
851
- private async executeHealingSteps(action: HealingAction): Promise<HealingResult> {
852
- const metricsBefor = await this.captureMetrics();
853
- const sideEffects: string[] = [];
854
-
855
- try {
856
- for (const step of action.executionSteps) {
857
- step.status = 'executing';
858
-
859
- // Execute step based on action
860
- switch (step.action) {
861
- case 'Gracefully stop service':
862
- await this.stopService(step.target);
863
- step.output = 'Service stopped successfully';
864
- break;
865
- case 'Clear temporary data':
866
- await this.clearTempData(step.target);
867
- step.output = 'Temporary data cleared';
868
- break;
869
- case 'Start service':
870
- await this.startService(step.target);
871
- step.output = 'Service started successfully';
872
- break;
873
- default:
874
- // Simulate other healing actions
875
- await new Promise(resolve => setTimeout(resolve, 1000));
876
- step.output = `${step.action} completed`;
877
- }
878
-
879
- step.status = 'completed';
880
- step.duration = 1000; // Simulated duration
881
- }
882
-
883
- const metricsAfter = await this.captureMetrics();
884
-
885
- return {
886
- success: true,
887
- message: 'Healing completed successfully',
888
- metricsAfter: {
889
- availability: metricsAfter.availability,
890
- performance: metricsAfter.performance,
891
- errorRate: metricsAfter.errorRate
892
- },
893
- sideEffects,
894
- verificationPassed: true
895
- };
896
-
897
- } catch (error) {
898
- return {
899
- success: false,
900
- message: `Healing failed: ${error instanceof Error ? error.message : String(error)}`,
901
- metricsAfter: metricsBefor,
902
- sideEffects,
903
- verificationPassed: false
904
- };
905
- }
906
- }
907
-
908
- private async generateRecoveryStrategies(patterns: ErrorPattern[]): Promise<RecoveryStrategy[]> {
909
- const strategies: RecoveryStrategy[] = Array.from(this.recoveryStrategies.values());
910
-
911
- // Generate pattern-specific strategies
912
- for (const pattern of patterns) {
913
- if (pattern.autoHealable) {
914
- const customStrategy: RecoveryStrategy = {
915
- id: `strat_${pattern.id}`,
916
- name: `Auto-heal ${pattern.name}`,
917
- description: `Automated recovery for ${pattern.description}`,
918
- applicableTo: pattern.signature.errorTypes,
919
- steps: this.generateCustomSteps(pattern),
920
- estimatedTime: pattern.avgResolutionTime,
921
- successRate: pattern.successRate,
922
- requirements: [],
923
- risks: []
924
- };
925
-
926
- strategies.push(customStrategy);
927
- }
928
- }
929
-
930
- return strategies;
931
- }
932
-
933
- private async collectSystemMetrics(): Promise<SystemMetrics> {
934
- // Collect real-time system metrics
935
- return {
936
- availability: {
937
- current: 99.5,
938
- target: 99.9,
939
- trend: 'stable'
940
- },
941
- performance: {
942
- responseTime: 250, // ms
943
- throughput: 1000, // requests/sec
944
- errorRate: 0.5, // percentage
945
- trend: 'improving'
946
- },
947
- reliability: {
948
- mtbf: 720, // hours
949
- mttr: 15, // minutes
950
- failureRate: 0.14 // failures per day
951
- },
952
- capacity: {
953
- cpu: 45, // percentage
954
- memory: 60,
955
- storage: 35,
956
- network: 20
957
- }
958
- };
959
- }
960
-
961
- private async generateHealingRecommendations(
962
- incidents: HealthIncident[],
963
- patterns: ErrorPattern[],
964
- metrics: SystemMetrics
965
- ): Promise<HealingRecommendation[]> {
966
- const recommendations: HealingRecommendation[] = [];
967
-
968
- // Redundancy recommendations
969
- if (metrics.availability.current < metrics.availability.target) {
970
- recommendations.push({
971
- id: `rec_${Date.now()}_1`,
972
- category: 'redundancy',
973
- priority: 'high',
974
- title: 'Implement Service Redundancy',
975
- description: 'Add redundant instances to improve availability',
976
- benefit: 'Increase availability to target 99.9%',
977
- effort: 'moderate',
978
- preventedIncidents: Math.round(incidents.filter(i => i.type === 'availability').length * 0.8),
979
- roi: 250
980
- });
981
- }
982
-
983
- // Monitoring recommendations
984
- if (patterns.some(p => p.autoHealable && p.successRate < 80)) {
985
- recommendations.push({
986
- id: `rec_${Date.now()}_2`,
987
- category: 'monitoring',
988
- priority: 'medium',
989
- title: 'Enhanced Monitoring Coverage',
990
- description: 'Improve monitoring to detect issues earlier',
991
- benefit: 'Reduce MTTR by 50%',
992
- effort: 'minimal',
993
- preventedIncidents: Math.round(incidents.length * 0.3),
994
- roi: 400
995
- });
996
- }
997
-
998
- // Automation recommendations
999
- const manualActions = incidents.filter(i =>
1000
- !patterns.find(p => p.signature.errorTypes.includes(i.type))?.autoHealable
1001
- );
1002
- if (manualActions.length > 0) {
1003
- recommendations.push({
1004
- id: `rec_${Date.now()}_3`,
1005
- category: 'automation',
1006
- priority: 'medium',
1007
- title: 'Automate Manual Recovery Processes',
1008
- description: `Automate recovery for ${manualActions.length} manual processes`,
1009
- benefit: 'Reduce recovery time by 80%',
1010
- effort: 'significant',
1011
- preventedIncidents: manualActions.length,
1012
- roi: 300
1013
- });
1014
- }
1015
-
1016
- return recommendations;
1017
- }
1018
-
1019
- private calculateHealthScore(metrics: SystemMetrics, incidents: HealthIncident[]): number {
1020
- let score = 100;
1021
-
1022
- // Availability impact (40% weight)
1023
- const availabilityScore = (metrics.availability.current / metrics.availability.target) * 40;
1024
- score = Math.min(score, availabilityScore + 60);
1025
-
1026
- // Performance impact (30% weight)
1027
- const performanceScore = Math.max(0, 30 - (metrics.performance.errorRate * 6));
1028
- score = Math.min(score, availabilityScore + performanceScore + 30);
1029
-
1030
- // Active incidents impact (30% weight)
1031
- const activeIncidents = incidents.filter(i => i.status === 'active');
1032
- const incidentImpact = activeIncidents.reduce((sum, i) => {
1033
- const severityWeight = { critical: 10, high: 5, medium: 2, low: 1 };
1034
- return sum + severityWeight[i.severity];
1035
- }, 0);
1036
- const incidentScore = Math.max(0, 30 - incidentImpact);
1037
-
1038
- return Math.round(availabilityScore + performanceScore + incidentScore);
1039
- }
1040
-
1041
- private async handleCriticalIncidents(incidents: HealthIncident[]): Promise<void> {
1042
- this.logger.error(`🚨 Handling ${incidents.length} critical incidents`);
1043
-
1044
- for (const incident of incidents) {
1045
- // Create emergency healing action
1046
- const emergencyAction: HealingAction = {
1047
- id: `emergency_${Date.now()}`,
1048
- incidentId: incident.id,
1049
- type: 'restart',
1050
- title: `Emergency: ${incident.title}`,
1051
- description: 'Emergency healing for critical incident',
1052
- status: 'executing',
1053
- automated: true,
1054
- executionSteps: [
1055
- {
1056
- order: 1,
1057
- action: 'Isolate affected component',
1058
- target: incident.impact.services[0] || 'System',
1059
- parameters: {},
1060
- status: 'pending'
1061
- },
1062
- {
1063
- order: 2,
1064
- action: 'Apply emergency fix',
1065
- target: incident.impact.services[0] || 'System',
1066
- parameters: {},
1067
- status: 'pending'
1068
- }
1069
- ]
1070
- };
1071
-
1072
- await this.executeHealingSteps(emergencyAction);
1073
- }
1074
- }
1075
-
1076
- private async executePreventiveActions(predictions: HealthPrediction[]): Promise<void> {
1077
- for (const prediction of predictions) {
1078
- if (prediction.probability > 0.8 && prediction.impact === 'critical') {
1079
- for (const action of prediction.preventiveActions) {
1080
- if (action.priority === 'immediate' && action.automatable) {
1081
- this.logger.info(`Executing preventive action: ${action.action}`);
1082
- // Execute preventive action
1083
- await this.executePreventiveAction(action);
1084
- }
1085
- }
1086
- }
1087
- }
1088
- }
1089
-
1090
- private async healSelf(error: any): Promise<void> {
1091
- this.logger.warn('🏥 Self-healing the healing system', error);
1092
-
1093
- // Restart monitoring
1094
- this.monitoringActive = false;
1095
- await new Promise(resolve => setTimeout(resolve, 5000));
1096
- this.monitoringActive = true;
1097
-
1098
- // Clear error state
1099
- this.activeIncidents.clear();
1100
-
1101
- // Reinitialize
1102
- this.startHealthMonitoring();
1103
- }
1104
-
1105
- private startHealthMonitoring(): void {
1106
- if (!this.monitoringActive) return;
1107
-
1108
- // Monitor system health continuously
1109
- setInterval(async () => {
1110
- try {
1111
- await this.checkSystemHealth();
1112
- } catch (error) {
1113
- this.logger.error('Error in health monitoring', error);
1114
- }
1115
- }, 60000); // Every minute
1116
- }
1117
-
1118
- private async checkSystemHealth(): Promise<void> {
1119
- // Quick health check
1120
- const metrics = await this.collectSystemMetrics();
1121
-
1122
- if (metrics.availability.current < 95) {
1123
- // Create availability incident
1124
- const incident: HealthIncident = {
1125
- id: `inc_auto_${Date.now()}`,
1126
- type: 'availability',
1127
- severity: 'high',
1128
- title: 'Low system availability detected',
1129
- description: `Availability dropped to ${metrics.availability.current}%`,
1130
- detectedAt: new Date().toISOString(),
1131
- status: 'active',
1132
- impact: {
1133
- users: 1000,
1134
- services: ['All'],
1135
- availability: metrics.availability.current,
1136
- performance: 0,
1137
- dataLoss: false,
1138
- duration: 0
1139
- },
1140
- healingAttempts: 0
1141
- };
1142
-
1143
- this.activeIncidents.set(incident.id, incident);
1144
- }
1145
- }
1146
-
1147
- // Utility methods
1148
- private getLatestHealingProfile(): HealingProfile | null {
1149
- const profiles = Array.from(this.healingProfiles.values());
1150
- if (profiles.length === 0) return null;
1151
-
1152
- return profiles.sort((a, b) =>
1153
- new Date(b.assessmentDate).getTime() -
1154
- new Date(a.assessmentDate).getTime()
1155
- )[0];
1156
- }
1157
-
1158
- private async generateDashboard(profile: HealingProfile): Promise<any> {
1159
- return {
1160
- systemHealth: profile.healthScore >= 90 ? 'Healthy' :
1161
- profile.healthScore >= 70 ? 'Degraded' : 'Critical',
1162
- healthScore: profile.healthScore,
1163
- activeIncidents: profile.incidents.filter(i => i.status === 'active'),
1164
- recentHealing: profile.healingActions.slice(0, 5),
1165
- systemMetrics: profile.systemMetrics,
1166
- predictions: profile.predictions.filter(p => p.probability > 0.6),
1167
- recommendations: profile.recommendations.slice(0, 3)
1168
- };
1169
- }
1170
-
1171
- private generateWarnings(profile: HealingProfile): string[] {
1172
- const warnings: string[] = [];
1173
-
1174
- const criticalIncidents = profile.incidents.filter(i => i.severity === 'critical' && i.status === 'active');
1175
- if (criticalIncidents.length > 0) {
1176
- warnings.push(`${criticalIncidents.length} critical incidents require immediate attention`);
1177
- }
1178
-
1179
- if (profile.systemMetrics.availability.current < 99) {
1180
- warnings.push('System availability below target threshold');
1181
- }
1182
-
1183
- return warnings;
1184
- }
1185
-
1186
- private async checkErrorLogs(): Promise<any[]> {
1187
- // Simulate error log checking
1188
- return [];
1189
- }
1190
-
1191
- private async checkPerformanceMetrics(): Promise<any[]> {
1192
- // Simulate performance checking
1193
- return [];
1194
- }
1195
-
1196
- private async checkAvailability(): Promise<any[]> {
1197
- // Simulate availability checking
1198
- return [];
1199
- }
1200
-
1201
- private determineSeverity(error: any): 'critical' | 'high' | 'medium' | 'low' {
1202
- if (error.message.includes('CRITICAL') || error.message.includes('FATAL')) return 'critical';
1203
- if (error.message.includes('ERROR')) return 'high';
1204
- if (error.message.includes('WARNING')) return 'medium';
1205
- return 'low';
1206
- }
1207
-
1208
- private async getRelatedLogs(incident: HealthIncident): Promise<any[]> {
1209
- return [];
1210
- }
1211
-
1212
- private async getSystemStateAt(timestamp: string): Promise<any> {
1213
- return {};
1214
- }
1215
-
1216
- private categorizeRootCause(incident: HealthIncident, logs: any[]): 'code' | 'configuration' | 'resource' | 'external' | 'data' | 'network' {
1217
- // Simple categorization logic
1218
- if (incident.type === 'performance') return 'resource';
1219
- if (incident.type === 'availability') return 'network';
1220
- return 'code';
1221
- }
1222
-
1223
- private calculateConfidence(logs: any[], state: any): number {
1224
- // Simple confidence calculation
1225
- return 0.75 + (logs.length * 0.05);
1226
- }
1227
-
1228
- private generateRootCauseDescription(incident: HealthIncident, category: string, logs: any[]): string {
1229
- return `${category} issue detected: ${incident.description}`;
1230
- }
1231
-
1232
- private async findRelatedIncidents(incident: HealthIncident): Promise<string[]> {
1233
- return [];
1234
- }
1235
-
1236
- private groupIncidentsBySimilarity(incidents: HealthIncident[]): HealthIncident[][] {
1237
- // Simple grouping by type
1238
- const groups: Record<string, HealthIncident[]> = {};
1239
-
1240
- for (const incident of incidents) {
1241
- const key = `${incident.type}_${incident.severity}`;
1242
- if (!groups[key]) groups[key] = [];
1243
- groups[key].push(incident);
1244
- }
1245
-
1246
- return Object.values(groups);
1247
- }
1248
-
1249
- private generatePatternName(group: HealthIncident[]): string {
1250
- return `${group[0].type} pattern #${Date.now()}`;
1251
- }
1252
-
1253
- private generatePatternDescription(group: HealthIncident[]): string {
1254
- return `Recurring ${group[0].type} issue affecting ${group[0].impact.services.join(', ')}`;
1255
- }
1256
-
1257
- private extractKeywords(group: HealthIncident[]): string[] {
1258
- const keywords = new Set<string>();
1259
- for (const incident of group) {
1260
- incident.title.split(' ').forEach(word => keywords.add(word.toLowerCase()));
1261
- }
1262
- return Array.from(keywords);
1263
- }
1264
-
1265
- private determineFrequency(group: HealthIncident[]): 'sporadic' | 'recurring' | 'persistent' {
1266
- if (group.length > 10) return 'persistent';
1267
- if (group.length > 3) return 'recurring';
1268
- return 'sporadic';
1269
- }
1270
-
1271
- private findCorrelations(group: HealthIncident[]): string[] {
1272
- return [];
1273
- }
1274
-
1275
- private calculateAvgResolutionTime(group: HealthIncident[]): number {
1276
- const resolved = group.filter(i => i.resolvedAt);
1277
- if (resolved.length === 0) return 300000; // 5 minutes default
1278
-
1279
- const times = resolved.map(i =>
1280
- new Date(i.resolvedAt!).getTime() - new Date(i.detectedAt).getTime()
1281
- );
1282
-
1283
- return times.reduce((a, b) => a + b, 0) / times.length;
1284
- }
1285
-
1286
- private calculateSuccessRate(group: HealthIncident[]): number {
1287
- const resolved = group.filter(i => i.status === 'resolved').length;
1288
- return group.length > 0 ? (resolved / group.length) * 100 : 0;
1289
- }
1290
-
1291
- private getRecommendedActions(group: HealthIncident[]): string[] {
1292
- const actions: string[] = [];
1293
-
1294
- if (group[0].type === 'error') actions.push('Apply error handling patch');
1295
- if (group[0].type === 'performance') actions.push('Optimize resource allocation');
1296
- if (group[0].type === 'availability') actions.push('Implement redundancy');
1297
-
1298
- return actions;
1299
- }
1300
-
1301
- private isAutoHealable(group: HealthIncident[]): boolean {
1302
- // Check if pattern can be auto-healed
1303
- return group[0].type !== 'security' && this.calculateSuccessRate(group) > 70;
1304
- }
1305
-
1306
- private async analyzeTrends(incidents: HealthIncident[], patterns: ErrorPattern[]): Promise<any> {
1307
- return {};
1308
- }
1309
-
1310
- private async predictCapacityIssues(): Promise<any[]> {
1311
- return [
1312
- {
1313
- component: 'Memory',
1314
- probability: 0.75,
1315
- timeframe: '7 days',
1316
- impact: 'high',
1317
- confidence: 0.85
1318
- }
1319
- ];
1320
- }
1321
-
1322
- private predictNextOccurrence(pattern: ErrorPattern): { probability: number; timeframe: string } {
1323
- // Simple prediction based on frequency
1324
- if ((pattern as any).frequency === 'persistent') {
1325
- return { probability: 0.9, timeframe: '1 hour' };
1326
- }
1327
- if ((pattern as any).frequency === 'recurring') {
1328
- return { probability: 0.7, timeframe: '24 hours' };
1329
- }
1330
- return { probability: 0.3, timeframe: '7 days' };
1331
- }
1332
-
1333
- private findBestStrategy(incident: HealthIncident): RecoveryStrategy | null {
1334
- for (const strategy of this.recoveryStrategies.values()) {
1335
- if (strategy.applicableTo.includes(incident.type)) {
1336
- return strategy;
1337
- }
1338
- }
1339
- return null;
1340
- }
1341
-
1342
- private determineActionType(incident: HealthIncident, strategy: RecoveryStrategy): HealingAction['type'] {
1343
- if (strategy.id === 'restart_service') return 'restart';
1344
- if (strategy.id === 'rollback_deployment') return 'rollback';
1345
- if (strategy.id === 'scale_resources') return 'scale';
1346
- return 'patch';
1347
- }
1348
-
1349
- private async captureMetrics(): Promise<any> {
1350
- const metrics = await this.collectSystemMetrics();
1351
- return {
1352
- availability: metrics.availability.current,
1353
- performance: metrics.performance.responseTime,
1354
- errorRate: metrics.performance.errorRate
1355
- };
1356
- }
1357
-
1358
- private async stopService(target: string): Promise<void> {
1359
- this.logger.info(`Stopping service: ${target}`);
1360
- await new Promise(resolve => setTimeout(resolve, 2000));
1361
- }
1362
-
1363
- private async clearTempData(target: string): Promise<void> {
1364
- this.logger.info(`Clearing temp data for: ${target}`);
1365
- await new Promise(resolve => setTimeout(resolve, 1000));
1366
- }
1367
-
1368
- private async startService(target: string): Promise<void> {
1369
- this.logger.info(`Starting service: ${target}`);
1370
- await new Promise(resolve => setTimeout(resolve, 3000));
1371
- }
1372
-
1373
- private generateCustomSteps(pattern: ErrorPattern): RecoveryStep[] {
1374
- return pattern.recommendedActions.map((action, index) => ({
1375
- order: index + 1,
1376
- action,
1377
- automated: pattern.autoHealable,
1378
- timeout: 60000,
1379
- verification: 'Action completed successfully'
1380
- }));
1381
- }
1382
-
1383
- private async getHealingAction(actionId: string): Promise<HealingAction | null> {
1384
- for (const profile of this.healingProfiles.values()) {
1385
- const action = profile.healingActions.find(a => a.id === actionId);
1386
- if (action) return action;
1387
- }
1388
- return null;
1389
- }
1390
-
1391
- private async verifyHealingSafety(action: HealingAction): Promise<{ safe: boolean; reason?: string }> {
1392
- // Verify it's safe to execute healing
1393
- if (action.type === 'rollback' && !action.rollbackPlan) {
1394
- return { safe: false, reason: 'No rollback plan available' };
1395
- }
1396
- return { safe: true };
1397
- }
1398
-
1399
- private async monitorHealingProgress(action: HealingAction, result: HealingResult): Promise<void> {
1400
- this.logger.info(`Monitoring healing progress for action ${action.id}`);
1401
- // Monitor the healing impact
1402
- }
1403
-
1404
- private async rollbackHealing(action: HealingAction): Promise<void> {
1405
- this.logger.warn(`Rolling back healing action ${action.id}`);
1406
- // Implement rollback logic
1407
- }
1408
-
1409
- private async executePreventiveAction(action: PreventiveAction): Promise<void> {
1410
- this.logger.info(`Executing preventive action: ${action.action}`);
1411
- // Execute the preventive action
1412
- }
1413
- }
1414
-
1415
- // Learning engine for pattern recognition
1416
- class LearningEngine {
1417
- private memory: MemorySystem;
1418
-
1419
- constructor(memory: MemorySystem) {
1420
- this.memory = memory;
1421
- }
1422
-
1423
- async learn(incidents: HealthIncident[], actions: HealingAction[]): Promise<void> {
1424
- // Store patterns for future recognition
1425
- const learningData = {
1426
- incidents,
1427
- actions,
1428
- timestamp: new Date().toISOString()
1429
- };
1430
-
1431
- await this.memory.store('healing_patterns', learningData, 2592000000); // 30 days
1432
- }
1433
- }
1434
-
1435
- export default SelfHealingSystem;