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,995 +0,0 @@
1
- /**
2
- * Snow-Flow System Health Monitoring
3
- * Comprehensive health checks for all components
4
- */
5
-
6
- import { EventEmitter } from 'events';
7
- import { MemorySystem } from '../memory/memory-system';
8
- import { MCPServerManager } from '../utils/mcp-server-manager';
9
- import { ServiceNowClient } from '../utils/servicenow-client';
10
- import { Logger } from '../utils/logger';
11
- import os from 'os';
12
- import fs from 'fs';
13
- import { execSync } from 'child_process';
14
-
15
- export interface HealthCheckResult {
16
- component: string;
17
- status: 'healthy' | 'degraded' | 'unhealthy' | 'unknown';
18
- message: string;
19
- details?: Record<string, any>;
20
- timestamp: Date;
21
- responseTime?: number;
22
- error?: string;
23
- }
24
-
25
- export interface SystemHealthStatus {
26
- healthy: boolean;
27
- status: 'healthy' | 'degraded' | 'unhealthy';
28
- timestamp: Date;
29
- components: {
30
- memory: HealthCheckResult;
31
- mcp: HealthCheckResult;
32
- servicenow: HealthCheckResult;
33
- queen: HealthCheckResult;
34
- system: HealthCheckResult;
35
- performance: HealthCheckResult;
36
- };
37
- metrics: {
38
- uptime: number;
39
- totalChecks: number;
40
- failedChecks: number;
41
- avgResponseTime: number;
42
- systemResources: SystemResources;
43
- };
44
- }
45
-
46
- export interface SystemResources {
47
- cpuUsage: number;
48
- memoryUsage: number;
49
- memoryTotal: number;
50
- diskUsage: number;
51
- diskTotal: number;
52
- loadAverage: number[];
53
- processCount: number;
54
- }
55
-
56
- export interface HealthThresholds {
57
- responseTime: number;
58
- memoryUsage: number;
59
- cpuUsage: number;
60
- queueSize: number;
61
- errorRate: number;
62
- }
63
-
64
- interface HealthConfig {
65
- memory: MemorySystem;
66
- mcpManager: MCPServerManager;
67
- config: {
68
- checks: {
69
- memory: boolean;
70
- mcp: boolean;
71
- servicenow: boolean;
72
- queen: boolean;
73
- };
74
- thresholds: HealthThresholds;
75
- };
76
- }
77
-
78
- export class SystemHealth extends EventEmitter {
79
- private memory: MemorySystem;
80
- private mcpManager: MCPServerManager;
81
- private logger: Logger;
82
- private config: HealthConfig['config'];
83
- private serviceNowClient?: ServiceNowClient;
84
- private checkInterval?: NodeJS.Timeout;
85
- private checkHistory: HealthCheckResult[] = [];
86
- private startTime: number;
87
- private totalChecks = 0;
88
- private failedChecks = 0;
89
- private lastCPUInfo: any = null;
90
- private cpuCheckInterval?: NodeJS.Timeout;
91
-
92
- constructor(options: HealthConfig) {
93
- super();
94
- this.memory = options.memory;
95
- this.mcpManager = options.mcpManager;
96
- this.config = options.config;
97
- this.logger = new Logger('SystemHealth');
98
- this.startTime = Date.now();
99
- }
100
-
101
- /**
102
- * Initialize health monitoring
103
- */
104
- async initialize(): Promise<void> {
105
- this.logger.info('Initializing System Health monitoring...');
106
-
107
- // Initialize ServiceNow client for health checks
108
- try {
109
- this.serviceNowClient = new ServiceNowClient();
110
- // Note: ServiceNowClient may not have an initialize method
111
- // await this.serviceNowClient.initialize();
112
- } catch (error) {
113
- this.logger.warn('ServiceNow client initialization failed:', error);
114
- }
115
-
116
- // Create health check tables
117
- await this.createHealthTables();
118
-
119
- // Perform initial health check
120
- await this.performHealthCheck();
121
-
122
- this.logger.info('System Health monitoring initialized');
123
- }
124
-
125
- /**
126
- * Start periodic health monitoring
127
- */
128
- async startMonitoring(intervalMs: number = 60000): Promise<void> {
129
- if (this.checkInterval) {
130
- this.logger.warn('Health monitoring already started');
131
- return;
132
- }
133
-
134
- this.logger.info(`Starting health monitoring with ${intervalMs}ms interval`);
135
-
136
- this.checkInterval = setInterval(async () => {
137
- try {
138
- await this.performHealthCheck();
139
- } catch (error) {
140
- this.logger.error('Health check failed:', error);
141
- }
142
- }, intervalMs);
143
-
144
- // Perform immediate check
145
- await this.performHealthCheck();
146
- }
147
-
148
- /**
149
- * Stop health monitoring
150
- */
151
- async stopMonitoring(): Promise<void> {
152
- if (this.checkInterval) {
153
- clearInterval(this.checkInterval);
154
- this.checkInterval = undefined;
155
- this.logger.info('Health monitoring stopped');
156
- }
157
-
158
- if (this.cpuCheckInterval) {
159
- clearInterval(this.cpuCheckInterval);
160
- this.cpuCheckInterval = undefined;
161
- }
162
- }
163
-
164
- /**
165
- * Perform comprehensive health check
166
- */
167
- async performHealthCheck(): Promise<SystemHealthStatus> {
168
- this.totalChecks++;
169
- const startTime = Date.now();
170
-
171
- this.logger.debug('Performing system health check...');
172
-
173
- // Run all health checks in parallel
174
- const [memory, mcp, servicenow, queen, system, performance] = await Promise.all([
175
- this.config.checks.memory ? this.checkMemory() : this.createSkippedResult('memory'),
176
- this.config.checks.mcp ? this.checkMCP() : this.createSkippedResult('mcp'),
177
- this.config.checks.servicenow ? this.checkServiceNow() : this.createSkippedResult('servicenow'),
178
- this.config.checks.queen ? this.checkQueen() : this.createSkippedResult('queen'),
179
- this.checkSystem(),
180
- this.checkPerformance()
181
- ]);
182
-
183
- const components = { memory, mcp, servicenow, queen, system, performance };
184
-
185
- // Determine overall health status
186
- const unhealthyCount = Object.values(components).filter(c => c.status === 'unhealthy').length;
187
- const degradedCount = Object.values(components).filter(c => c.status === 'degraded').length;
188
-
189
- let overallStatus: 'healthy' | 'degraded' | 'unhealthy';
190
- if (unhealthyCount > 0) {
191
- overallStatus = 'unhealthy';
192
- this.failedChecks++;
193
- } else if (degradedCount > 0) {
194
- overallStatus = 'degraded';
195
- } else {
196
- overallStatus = 'healthy';
197
- }
198
-
199
- const status: SystemHealthStatus = {
200
- healthy: overallStatus === 'healthy',
201
- status: overallStatus,
202
- timestamp: new Date(),
203
- components,
204
- metrics: {
205
- uptime: Date.now() - this.startTime,
206
- totalChecks: this.totalChecks,
207
- failedChecks: this.failedChecks,
208
- avgResponseTime: this.calculateAverageResponseTime(),
209
- systemResources: await this.getSystemResources()
210
- }
211
- };
212
-
213
- // Store health check result
214
- await this.storeHealthResult(status);
215
-
216
- // Emit health status
217
- this.emit('health:check', status);
218
-
219
- // Check for alerts
220
- this.checkAlerts(status);
221
-
222
- const duration = Date.now() - startTime;
223
- this.logger.debug(`Health check completed in ${duration}ms - Status: ${overallStatus}`);
224
-
225
- return status;
226
- }
227
-
228
- /**
229
- * Get full health status
230
- */
231
- async getFullStatus(): Promise<SystemHealthStatus> {
232
- return this.performHealthCheck();
233
- }
234
-
235
- /**
236
- * Get health history
237
- */
238
- async getHealthHistory(limit: number = 100): Promise<HealthCheckResult[]> {
239
- return this.memory.query<HealthCheckResult>(`
240
- SELECT * FROM health_checks
241
- ORDER BY timestamp DESC
242
- LIMIT ?
243
- `, [limit]);
244
- }
245
-
246
- /**
247
- * Check if system is healthy
248
- */
249
- async isHealthy(): Promise<boolean> {
250
- const status = await this.performHealthCheck();
251
- return status.healthy;
252
- }
253
-
254
- /**
255
- * Private health check methods
256
- */
257
- private async checkMemory(): Promise<HealthCheckResult> {
258
- const startTime = Date.now();
259
-
260
- try {
261
- // Check if memory system is responsive
262
- const testKey = `health_check_${Date.now()}`;
263
- await this.memory.store(testKey, { test: true }, 60000); // 1 minute TTL
264
- const retrieved = await this.memory.get(testKey);
265
- await this.memory.delete(testKey);
266
-
267
- if (!retrieved) {
268
- throw new Error('Memory store/retrieve test failed');
269
- }
270
-
271
- // Check memory database size
272
- const dbStats = await this.memory.getDatabaseStats();
273
- const dbSizeMB = dbStats.size / 1024 / 1024;
274
-
275
- // Check cache performance
276
- const cacheStats = await this.memory.getCacheStats();
277
- const cacheHitRate = cacheStats.hits / (cacheStats.hits + cacheStats.misses) || 0;
278
-
279
- const responseTime = Date.now() - startTime;
280
-
281
- // Determine status
282
- let status: 'healthy' | 'degraded' | 'unhealthy' = 'healthy';
283
- let message = 'Memory system operating normally';
284
-
285
- if (dbSizeMB > 1000) { // > 1GB
286
- status = 'degraded';
287
- message = 'Database size exceeding recommended limits';
288
- }
289
-
290
- if (cacheHitRate < 0.5 && cacheStats.hits + cacheStats.misses > 100) {
291
- status = 'degraded';
292
- message = 'Low cache hit rate';
293
- }
294
-
295
- if (responseTime > this.config.thresholds.responseTime) {
296
- status = 'unhealthy';
297
- message = 'Memory system response time too high';
298
- }
299
-
300
- return {
301
- component: 'memory',
302
- status,
303
- message,
304
- details: {
305
- dbSizeMB,
306
- cacheHitRate,
307
- cacheStats,
308
- responseTime
309
- },
310
- timestamp: new Date(),
311
- responseTime
312
- };
313
-
314
- } catch (error) {
315
- return {
316
- component: 'memory',
317
- status: 'unhealthy',
318
- message: 'Memory system check failed',
319
- error: (error as Error).message,
320
- timestamp: new Date(),
321
- responseTime: Date.now() - startTime
322
- };
323
- }
324
- }
325
-
326
- private async checkMCP(): Promise<HealthCheckResult> {
327
- const startTime = Date.now();
328
-
329
- try {
330
- const serverStatuses = this.mcpManager.getServerStatus();
331
- const totalServers = serverStatuses.length;
332
- const healthyServers = serverStatuses.filter(s => s.status === 'running').length;
333
- const unhealthyServers = serverStatuses.filter(s => s.status === 'error').length;
334
-
335
- const responseTime = Date.now() - startTime;
336
-
337
- let status: 'healthy' | 'degraded' | 'unhealthy' = 'healthy';
338
- let message = `All ${totalServers} MCP servers running`;
339
-
340
- if (unhealthyServers > 0) {
341
- status = unhealthyServers >= totalServers / 2 ? 'unhealthy' : 'degraded';
342
- message = `${unhealthyServers} of ${totalServers} MCP servers not running`;
343
- }
344
-
345
- return {
346
- component: 'mcp',
347
- status,
348
- message,
349
- details: {
350
- totalServers,
351
- healthyServers,
352
- unhealthyServers,
353
- serverStatuses
354
- },
355
- timestamp: new Date(),
356
- responseTime
357
- };
358
-
359
- } catch (error) {
360
- return {
361
- component: 'mcp',
362
- status: 'unhealthy',
363
- message: 'MCP server check failed',
364
- error: (error as Error).message,
365
- timestamp: new Date(),
366
- responseTime: Date.now() - startTime
367
- };
368
- }
369
- }
370
-
371
- private async checkServiceNow(): Promise<HealthCheckResult> {
372
- const startTime = Date.now();
373
-
374
- try {
375
- if (!this.serviceNowClient) {
376
- return {
377
- component: 'servicenow',
378
- status: 'unknown',
379
- message: 'ServiceNow client not initialized',
380
- timestamp: new Date(),
381
- responseTime: Date.now() - startTime
382
- };
383
- }
384
-
385
- // Perform a simple API call to check connectivity
386
- const testResult = await this.serviceNowClient.testConnection();
387
- const responseTime = Date.now() - startTime;
388
-
389
- if (!testResult.success) {
390
- return {
391
- component: 'servicenow',
392
- status: 'unhealthy',
393
- message: 'ServiceNow connection test failed',
394
- error: testResult.error,
395
- timestamp: new Date(),
396
- responseTime
397
- };
398
- }
399
-
400
- let status: 'healthy' | 'degraded' | 'unhealthy' = 'healthy';
401
- let message = 'ServiceNow connection healthy';
402
-
403
- if (responseTime > this.config.thresholds.responseTime) {
404
- status = 'degraded';
405
- message = 'ServiceNow response time high';
406
- }
407
-
408
- return {
409
- component: 'servicenow',
410
- status,
411
- message,
412
- details: {
413
- connected: true,
414
- responseTime
415
- },
416
- timestamp: new Date(),
417
- responseTime
418
- };
419
-
420
- } catch (error) {
421
- return {
422
- component: 'servicenow',
423
- status: 'unhealthy',
424
- message: 'ServiceNow check failed',
425
- error: (error as Error).message,
426
- timestamp: new Date(),
427
- responseTime: Date.now() - startTime
428
- };
429
- }
430
- }
431
-
432
- private async checkQueen(): Promise<HealthCheckResult> {
433
- const startTime = Date.now();
434
-
435
- try {
436
- // Check active queen sessions
437
- const activeSessions = await this.memory.query<any>(`
438
- SELECT COUNT(*) as count FROM swarm_sessions
439
- WHERE status = 'active'
440
- `);
441
-
442
- // Check agent coordination
443
- const activeAgents = await this.memory.query<any>(`
444
- SELECT COUNT(*) as count FROM agent_coordination
445
- WHERE status IN ('spawned', 'active')
446
- `);
447
-
448
- const responseTime = Date.now() - startTime;
449
-
450
- let status: 'healthy' | 'degraded' | 'unhealthy' = 'healthy';
451
- let message = 'Queen coordination system healthy';
452
-
453
- const sessionCount = activeSessions[0]?.count || 0;
454
- const agentCount = activeAgents[0]?.count || 0;
455
-
456
- if (agentCount > this.config.thresholds.queueSize) {
457
- status = 'degraded';
458
- message = 'High number of active agents';
459
- }
460
-
461
- return {
462
- component: 'queen',
463
- status,
464
- message,
465
- details: {
466
- activeSessions: sessionCount,
467
- activeAgents: agentCount,
468
- responseTime
469
- },
470
- timestamp: new Date(),
471
- responseTime
472
- };
473
-
474
- } catch (error) {
475
- return {
476
- component: 'queen',
477
- status: 'unhealthy',
478
- message: 'Queen system check failed',
479
- error: (error as Error).message,
480
- timestamp: new Date(),
481
- responseTime: Date.now() - startTime
482
- };
483
- }
484
- }
485
-
486
- private async checkSystem(): Promise<HealthCheckResult> {
487
- const startTime = Date.now();
488
-
489
- try {
490
- const resources = await this.getSystemResources();
491
- const enhancedMetrics = await this.getEnhancedSystemMetrics();
492
- const responseTime = Date.now() - startTime;
493
-
494
- let status: 'healthy' | 'degraded' | 'unhealthy' = 'healthy';
495
- let message = 'System resources within normal limits';
496
- const issues: string[] = [];
497
-
498
- // Check CPU usage
499
- if (resources.cpuUsage > this.config.thresholds.cpuUsage * 100) {
500
- status = 'degraded';
501
- issues.push(`High CPU usage: ${resources.cpuUsage.toFixed(1)}%`);
502
- }
503
-
504
- // Check memory usage
505
- const memoryUsagePercent = (resources.memoryUsage / resources.memoryTotal) * 100;
506
- if (memoryUsagePercent > this.config.thresholds.memoryUsage * 100) {
507
- status = status === 'degraded' ? 'unhealthy' : 'degraded';
508
- issues.push(`High memory usage: ${memoryUsagePercent.toFixed(1)}%`);
509
- }
510
-
511
- // Check disk usage
512
- if (resources.diskUsage > 90) {
513
- status = 'unhealthy';
514
- issues.push(`Critical disk usage: ${resources.diskUsage.toFixed(1)}%`);
515
- } else if (resources.diskUsage > 80) {
516
- status = status === 'healthy' ? 'degraded' : status;
517
- issues.push(`High disk usage: ${resources.diskUsage.toFixed(1)}%`);
518
- }
519
-
520
- // Check process memory
521
- const heapUsagePercent = (enhancedMetrics.process.memory.heapUsed / enhancedMetrics.process.memory.heapTotal) * 100;
522
- if (heapUsagePercent > 90) {
523
- status = status === 'degraded' ? 'unhealthy' : 'degraded';
524
- issues.push(`High heap usage: ${heapUsagePercent.toFixed(1)}%`);
525
- }
526
-
527
- // Check network connectivity
528
- if (!enhancedMetrics.network.connected) {
529
- status = 'degraded';
530
- issues.push('Network connectivity issues detected');
531
- }
532
-
533
- if (issues.length > 0) {
534
- message = issues.join(', ');
535
- }
536
-
537
- return {
538
- component: 'system',
539
- status,
540
- message,
541
- details: {
542
- ...resources,
543
- enhanced: enhancedMetrics
544
- },
545
- timestamp: new Date(),
546
- responseTime
547
- };
548
-
549
- } catch (error) {
550
- return {
551
- component: 'system',
552
- status: 'unhealthy',
553
- message: 'System resource check failed',
554
- error: (error as Error).message,
555
- timestamp: new Date(),
556
- responseTime: Date.now() - startTime
557
- };
558
- }
559
- }
560
-
561
- private async checkPerformance(): Promise<HealthCheckResult> {
562
- const startTime = Date.now();
563
-
564
- try {
565
- // Get recent performance metrics
566
- const recentMetrics = await this.memory.query<any>(`
567
- SELECT
568
- COUNT(*) as total_operations,
569
- SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) as successful_operations,
570
- AVG(duration) as avg_duration,
571
- MAX(duration) as max_duration
572
- FROM performance_metrics
573
- WHERE start_time > ?
574
- `, [Date.now() - 300000]); // Last 5 minutes
575
-
576
- const metrics = recentMetrics[0] || {};
577
- const errorRate = metrics.total_operations > 0
578
- ? (metrics.total_operations - metrics.successful_operations) / metrics.total_operations
579
- : 0;
580
-
581
- const responseTime = Date.now() - startTime;
582
-
583
- let status: 'healthy' | 'degraded' | 'unhealthy' = 'healthy';
584
- let message = 'Performance metrics within normal limits';
585
-
586
- if (errorRate > this.config.thresholds.errorRate) {
587
- status = 'degraded';
588
- message = `High error rate: ${(errorRate * 100).toFixed(1)}%`;
589
- }
590
-
591
- if (metrics.avg_duration > this.config.thresholds.responseTime) {
592
- status = status === 'degraded' ? 'unhealthy' : 'degraded';
593
- message = `High average response time: ${metrics.avg_duration}ms`;
594
- }
595
-
596
- return {
597
- component: 'performance',
598
- status,
599
- message,
600
- details: {
601
- totalOperations: metrics.total_operations || 0,
602
- successfulOperations: metrics.successful_operations || 0,
603
- errorRate,
604
- avgDuration: metrics.avg_duration || 0,
605
- maxDuration: metrics.max_duration || 0
606
- },
607
- timestamp: new Date(),
608
- responseTime
609
- };
610
-
611
- } catch (error) {
612
- return {
613
- component: 'performance',
614
- status: 'unhealthy',
615
- message: 'Performance check failed',
616
- error: (error as Error).message,
617
- timestamp: new Date(),
618
- responseTime: Date.now() - startTime
619
- };
620
- }
621
- }
622
-
623
- private createSkippedResult(component: string): HealthCheckResult {
624
- return {
625
- component,
626
- status: 'unknown',
627
- message: 'Health check skipped',
628
- timestamp: new Date()
629
- };
630
- }
631
-
632
- private async getSystemResources(): Promise<SystemResources> {
633
- const cpus = os.cpus();
634
- const totalMemory = os.totalmem();
635
- const freeMemory = os.freemem();
636
- const usedMemory = totalMemory - freeMemory;
637
-
638
- // Calculate CPU usage with averaging
639
- const cpuUsage = await this.calculateCPUUsage();
640
-
641
- // Get real disk usage
642
- const { diskUsage, diskTotal } = await this.getDiskUsage();
643
-
644
- return {
645
- cpuUsage,
646
- memoryUsage: usedMemory / 1024 / 1024, // MB
647
- memoryTotal: totalMemory / 1024 / 1024, // MB
648
- diskUsage,
649
- diskTotal,
650
- loadAverage: os.loadavg(),
651
- processCount: cpus.length
652
- };
653
- }
654
-
655
- private async createHealthTables(): Promise<void> {
656
- await this.memory.execute(`
657
- CREATE TABLE IF NOT EXISTS health_checks (
658
- id TEXT PRIMARY KEY,
659
- component TEXT NOT NULL,
660
- status TEXT NOT NULL,
661
- message TEXT,
662
- details TEXT,
663
- error TEXT,
664
- response_time INTEGER,
665
- timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
666
- );
667
-
668
- CREATE INDEX IF NOT EXISTS idx_health_component ON health_checks(component);
669
- CREATE INDEX IF NOT EXISTS idx_health_timestamp ON health_checks(timestamp);
670
-
671
- CREATE TABLE IF NOT EXISTS health_alerts (
672
- id TEXT PRIMARY KEY,
673
- alert_type TEXT NOT NULL,
674
- severity TEXT NOT NULL,
675
- message TEXT NOT NULL,
676
- details TEXT,
677
- timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
678
- acknowledged BOOLEAN DEFAULT FALSE
679
- );
680
- `);
681
- }
682
-
683
- private async storeHealthResult(status: SystemHealthStatus): Promise<void> {
684
- // Store individual component results
685
- for (const [component, result] of Object.entries(status.components)) {
686
- await this.memory.insert('health_checks', {
687
- id: `${component}_${Date.now()}`,
688
- component,
689
- status: result.status,
690
- message: result.message,
691
- details: JSON.stringify(result.details),
692
- error: result.error,
693
- response_time: result.responseTime,
694
- timestamp: result.timestamp
695
- });
696
- }
697
-
698
- // Add to history
699
- this.checkHistory.push(...Object.values(status.components));
700
-
701
- // Limit history size
702
- if (this.checkHistory.length > 1000) {
703
- this.checkHistory = this.checkHistory.slice(-500);
704
- }
705
- }
706
-
707
- private checkAlerts(status: SystemHealthStatus): void {
708
- // Check for critical conditions
709
- const unhealthyComponents = Object.entries(status.components)
710
- .filter(([_, result]) => result.status === 'unhealthy');
711
-
712
- if (unhealthyComponents.length > 0) {
713
- this.emit('health:alert', {
714
- type: 'component_failure',
715
- severity: 'critical',
716
- message: `${unhealthyComponents.length} components unhealthy`,
717
- components: unhealthyComponents.map(([name]) => name)
718
- });
719
- }
720
-
721
- // Check system resources
722
- const resources = status.metrics.systemResources;
723
- if (resources.cpuUsage > 90) {
724
- this.emit('health:alert', {
725
- type: 'resource_critical',
726
- severity: 'critical',
727
- message: `CPU usage critical: ${resources.cpuUsage}%`
728
- });
729
- }
730
-
731
- if ((resources.memoryUsage / resources.memoryTotal) > 0.9) {
732
- this.emit('health:alert', {
733
- type: 'resource_critical',
734
- severity: 'critical',
735
- message: `Memory usage critical: ${(resources.memoryUsage / resources.memoryTotal * 100).toFixed(1)}%`
736
- });
737
- }
738
- }
739
-
740
- private calculateAverageResponseTime(): number {
741
- if (this.checkHistory.length === 0) return 0;
742
-
743
- const responseTimes = this.checkHistory
744
- .map(h => h.responseTime || 0)
745
- .filter(t => t > 0);
746
-
747
- if (responseTimes.length === 0) return 0;
748
-
749
- return responseTimes.reduce((a, b) => a + b, 0) / responseTimes.length;
750
- }
751
-
752
- /**
753
- * Calculate real CPU usage with averaging
754
- */
755
- private async calculateCPUUsage(): Promise<number> {
756
- const cpus = os.cpus();
757
-
758
- const currentCPUInfo = cpus.map(cpu => {
759
- const total = Object.values(cpu.times).reduce((acc, time) => acc + time, 0);
760
- return {
761
- idle: cpu.times.idle,
762
- total: total
763
- };
764
- });
765
-
766
- if (!this.lastCPUInfo) {
767
- this.lastCPUInfo = currentCPUInfo;
768
- // Wait a bit and calculate again for initial reading
769
- await new Promise(resolve => setTimeout(resolve, 100));
770
- return this.calculateCPUUsage();
771
- }
772
-
773
- let totalIdleDiff = 0;
774
- let totalDiff = 0;
775
-
776
- for (let i = 0; i < cpus.length; i++) {
777
- const lastCPU = this.lastCPUInfo[i];
778
- const currentCPU = currentCPUInfo[i];
779
-
780
- const idleDiff = currentCPU.idle - lastCPU.idle;
781
- const totalCPUDiff = currentCPU.total - lastCPU.total;
782
-
783
- totalIdleDiff += idleDiff;
784
- totalDiff += totalCPUDiff;
785
- }
786
-
787
- this.lastCPUInfo = currentCPUInfo;
788
-
789
- if (totalDiff === 0) return 0;
790
-
791
- const idlePercentage = (totalIdleDiff / totalDiff) * 100;
792
- const usagePercentage = 100 - idlePercentage;
793
-
794
- return Math.max(0, Math.min(100, usagePercentage));
795
- }
796
-
797
- /**
798
- * Get real disk usage statistics
799
- */
800
- private async getDiskUsage(): Promise<{ diskUsage: number; diskTotal: number }> {
801
- try {
802
- // Platform-specific disk usage calculation
803
- if (process.platform === 'darwin' || process.platform === 'linux') {
804
- return this.getUnixDiskUsage();
805
- } else if (process.platform === 'win32') {
806
- return this.getWindowsDiskUsage();
807
- } else {
808
- // Fallback for unsupported platforms
809
- return { diskUsage: 0, diskTotal: 0 };
810
- }
811
- } catch (error) {
812
- this.logger.warn('Failed to get disk usage:', error);
813
- return { diskUsage: 0, diskTotal: 0 };
814
- }
815
- }
816
-
817
- /**
818
- * Get disk usage for Unix-based systems (macOS, Linux)
819
- */
820
- private getUnixDiskUsage(): { diskUsage: number; diskTotal: number } {
821
- try {
822
- // Get current working directory's mount point
823
- const cwd = process.cwd();
824
-
825
- // Get disk usage for the filesystem containing the current directory
826
- const output = execSync(`df -k "${cwd}"`, { encoding: 'utf8' });
827
- const lines = output.trim().split('\n');
828
-
829
- if (lines.length < 2) {
830
- throw new Error('Unexpected df output format');
831
- }
832
-
833
- // Handle cases where the output might span multiple lines
834
- let dataLine = lines[1];
835
- if (lines.length > 2 && !lines[1].includes('/')) {
836
- // Some systems split long filesystem names across lines
837
- dataLine = lines[1] + ' ' + lines[2];
838
- }
839
-
840
- // Parse the data line
841
- const parts = dataLine.split(/\s+/);
842
-
843
- // Find the numeric values (skip filesystem name)
844
- let totalBlocks = 0;
845
- let usedBlocks = 0;
846
- let foundNumbers = false;
847
-
848
- for (let i = 0; i < parts.length; i++) {
849
- const num = parseInt(parts[i], 10);
850
- if (!isNaN(num) && !foundNumbers) {
851
- totalBlocks = num;
852
- if (i + 1 < parts.length) {
853
- usedBlocks = parseInt(parts[i + 1], 10);
854
- foundNumbers = true;
855
- break;
856
- }
857
- }
858
- }
859
-
860
- if (!foundNumbers || isNaN(totalBlocks) || isNaN(usedBlocks)) {
861
- throw new Error('Failed to parse disk usage numbers');
862
- }
863
-
864
- const diskTotal = totalBlocks / 1024 / 1024; // Convert to GB
865
- const diskUsed = usedBlocks / 1024 / 1024; // Convert to GB
866
- const diskUsage = (diskUsed / diskTotal) * 100;
867
-
868
- return {
869
- diskUsage: Math.round(diskUsage * 10) / 10, // Round to 1 decimal
870
- diskTotal: Math.round(diskTotal * 10) / 10
871
- };
872
- } catch (error) {
873
- this.logger.error('Unix disk usage check failed:', error);
874
- throw error;
875
- }
876
- }
877
-
878
- /**
879
- * Get disk usage for Windows systems
880
- */
881
- private getWindowsDiskUsage(): { diskUsage: number; diskTotal: number } {
882
- try {
883
- // Get disk usage for C: drive using WMIC
884
- const output = execSync('wmic logicaldisk where caption="C:" get size,freespace /value', { encoding: 'utf8' });
885
-
886
- const sizeMatch = output.match(/Size=(\d+)/);
887
- const freeMatch = output.match(/FreeSpace=(\d+)/);
888
-
889
- if (!sizeMatch || !freeMatch) {
890
- throw new Error('Failed to parse Windows disk usage');
891
- }
892
-
893
- const totalBytes = parseInt(sizeMatch[1], 10);
894
- const freeBytes = parseInt(freeMatch[1], 10);
895
- const usedBytes = totalBytes - freeBytes;
896
-
897
- const diskTotal = totalBytes / 1024 / 1024 / 1024; // Convert to GB
898
- const diskUsed = usedBytes / 1024 / 1024 / 1024; // Convert to GB
899
- const diskUsage = (diskUsed / diskTotal) * 100;
900
-
901
- return {
902
- diskUsage: Math.round(diskUsage * 10) / 10,
903
- diskTotal: Math.round(diskTotal * 10) / 10
904
- };
905
- } catch (error) {
906
- this.logger.error('Windows disk usage check failed:', error);
907
- throw error;
908
- }
909
- }
910
-
911
- /**
912
- * Get process-specific memory usage
913
- */
914
- private getProcessMemoryUsage() {
915
- const usage = process.memoryUsage();
916
- return {
917
- heapUsed: usage.heapUsed / 1024 / 1024, // MB
918
- heapTotal: usage.heapTotal / 1024 / 1024, // MB
919
- rss: usage.rss / 1024 / 1024, // MB
920
- external: usage.external / 1024 / 1024, // MB
921
- arrayBuffers: usage.arrayBuffers / 1024 / 1024 // MB
922
- };
923
- }
924
-
925
- /**
926
- * Check network connectivity
927
- */
928
- private async checkNetworkConnectivity(): Promise<boolean> {
929
- try {
930
- // Simple DNS lookup to check network connectivity
931
- const dns = await import('dns').then(m => m.promises);
932
- await dns.lookup('google.com');
933
- return true;
934
- } catch (error) {
935
- return false;
936
- }
937
- }
938
-
939
- /**
940
- * Get additional SQLite database statistics
941
- */
942
- private async getExtendedDatabaseStats(): Promise<any> {
943
- try {
944
- // Use the existing memory system stats
945
- const dbStats = await this.memory.getDatabaseStats();
946
-
947
- // Get additional table information if possible
948
- try {
949
- const tableInfo = await this.memory.query(`
950
- SELECT
951
- COUNT(DISTINCT name) as table_count,
952
- SUM(CASE WHEN type = 'index' THEN 1 ELSE 0 END) as index_count
953
- FROM sqlite_master
954
- WHERE type IN ('table', 'index')
955
- `);
956
-
957
- return {
958
- ...dbStats,
959
- tables: tableInfo[0]?.table_count || 0,
960
- indexes: tableInfo[0]?.index_count || 0
961
- };
962
- } catch (error) {
963
- // If query fails, just return basic stats
964
- return dbStats;
965
- }
966
- } catch (error) {
967
- this.logger.warn('Failed to get extended database stats:', error);
968
- return null;
969
- }
970
- }
971
-
972
- /**
973
- * Enhanced system check with more detailed metrics
974
- */
975
- private async getEnhancedSystemMetrics() {
976
- const processMemory = this.getProcessMemoryUsage();
977
- const networkConnected = await this.checkNetworkConnectivity();
978
- const dbStats = await this.getExtendedDatabaseStats();
979
-
980
- return {
981
- process: {
982
- memory: processMemory,
983
- uptime: process.uptime(),
984
- pid: process.pid,
985
- version: process.version,
986
- platform: process.platform,
987
- arch: process.arch
988
- },
989
- network: {
990
- connected: networkConnected
991
- },
992
- database: dbStats
993
- };
994
- }
995
- }