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,1223 +0,0 @@
1
- /**
2
- * 🚀 PERFORMANCE FIX: Enhanced AI-Powered Performance Recommendations Engine
3
- *
4
- * Provides intelligent database index suggestions, real-time performance optimizations,
5
- * predictive analytics, and AI-powered recommendations for ServiceNow artifacts.
6
- *
7
- * Enhanced features from beta testing feedback:
8
- * - Real-time performance trend analysis
9
- * - AI-powered pattern recognition
10
- * - Predictive performance modeling
11
- * - Automated optimization suggestions
12
- */
13
-
14
- import { Logger } from '../utils/logger.js';
15
- import { MemorySystem } from '../memory/memory-system.js';
16
-
17
- export interface DatabaseIndexRecommendation {
18
- table: string;
19
- fields: string[];
20
- indexType: 'composite' | 'single' | 'unique' | 'partial';
21
- reason: string;
22
- estimatedImprovement: number; // Percentage improvement
23
- priority: 'critical' | 'high' | 'medium' | 'low';
24
- createStatement: string;
25
- impactAnalysis: {
26
- queryImpact: string[];
27
- storageImpact: string;
28
- maintenanceImpact: string;
29
- };
30
- }
31
-
32
- export interface PerformanceRecommendation {
33
- category: 'database' | 'flow' | 'widget' | 'api' | 'cache';
34
- type: string;
35
- description: string;
36
- impact: 'high' | 'medium' | 'low';
37
- effort: 'high' | 'medium' | 'low';
38
- recommendation: string;
39
- code_example?: string;
40
- estimated_time_savings: string;
41
- }
42
-
43
- export interface TableUsagePattern {
44
- table: string;
45
- commonQueries: string[];
46
- frequentFields: string[];
47
- joinPatterns: { with_table: string; on_fields: string[] }[];
48
- slowQueries: string[];
49
- recordVolume: 'low' | 'medium' | 'high';
50
- updateFrequency: 'low' | 'medium' | 'high';
51
- }
52
-
53
- export interface AIRecommendation {
54
- id: string;
55
- type: 'optimization' | 'architecture' | 'scaling' | 'monitoring' | 'security';
56
- confidence: number; // 0-1
57
- impact: 'critical' | 'high' | 'medium' | 'low';
58
- category: string;
59
- title: string;
60
- description: string;
61
- rationale: string;
62
- implementation: {
63
- steps: string[];
64
- estimatedTime: string;
65
- complexity: 'low' | 'medium' | 'high';
66
- prerequisites: string[];
67
- risks: string[];
68
- };
69
- metrics: {
70
- expectedImprovement: number; // percentage
71
- estimatedCostSavings?: string;
72
- affectedComponents: string[];
73
- kpiImpact: Record<string, number>;
74
- };
75
- priority: number; // 1-10, 10 being highest
76
- validUntil: Date;
77
- source: 'pattern__analysis' | 'ml_prediction' | 'historical_data' | 'real_time_monitoring';
78
- }
79
-
80
- export interface PerformancePattern {
81
- pattern: string;
82
- frequency: number;
83
- severity: 'critical' | 'high' | 'medium' | 'low';
84
- contexts: string[];
85
- solutions: AIRecommendation[];
86
- firstSeen: Date;
87
- lastSeen: Date;
88
- occurrences: number;
89
- }
90
-
91
- export interface PredictiveInsight {
92
- type: 'degradation_warning' | 'capacity_planning' | 'bottleneck_prediction' | 'optimization_opportunity';
93
- component: string;
94
- prediction: string;
95
- probability: number;
96
- timeHorizon: number; // hours
97
- evidencePoints: string[];
98
- recommendedActions: AIRecommendation[];
99
- modelConfidence: number;
100
- createdAt: Date;
101
- }
102
-
103
- export interface SystemBaseline {
104
- component: string;
105
- metrics: {
106
- [metricName: string]: {
107
- baseline: number;
108
- threshold: number;
109
- trend: 'improving' | 'stable' | 'degrading';
110
- variance: number;
111
- };
112
- };
113
- lastUpdated: Date;
114
- sampleCount: number;
115
- }
116
-
117
- export interface PerformanceScore {
118
- overall: number; // 0-100
119
- components: {
120
- database: number;
121
- api: number;
122
- memory: number;
123
- cache: number;
124
- network: number;
125
- };
126
- trends: {
127
- daily: number;
128
- weekly: number;
129
- monthly: number;
130
- };
131
- comparison: {
132
- industryAverage?: number;
133
- bestPractice?: number;
134
- };
135
- calculatedAt: Date;
136
- }
137
-
138
- export class PerformanceRecommendationsEngine {
139
- private logger: Logger;
140
- private memory: MemorySystem;
141
- private performancePatterns: Map<string, PerformancePattern> = new Map();
142
- private systemBaselines: Map<string, SystemBaseline> = new Map();
143
- private aiRecommendations: Map<string, AIRecommendation> = new Map();
144
- private predictiveInsights: PredictiveInsight[] = [];
145
- private learningEnabled: boolean = true;
146
-
147
- // 🔍 ServiceNow table performance patterns based on real-world analysis
148
- private readonly SERVICENOW_TABLE_PATTERNS: Record<string, TableUsagePattern> = {
149
- 'incident': {
150
- table: 'incident',
151
- commonQueries: [
152
- 'state=1^active=true^assigned_to=user',
153
- 'priority=1^state!=6^state!=7',
154
- 'caller_id=user^opened_by=user',
155
- 'assignment_group=group^state=2'
156
- ],
157
- frequentFields: ['state', 'priority', 'assigned_to', 'assignment_group', 'caller_id', 'opened_by', 'sys_created_on'],
158
- joinPatterns: [
159
- { with_table: 'sys_user', on_fields: ['assigned_to', 'caller_id'] },
160
- { with_table: 'sys_user_group', on_fields: ['assignment_group'] }
161
- ],
162
- slowQueries: [
163
- 'sys_created_on>javascript:gs.dateGenerate()', // Date range queries
164
- 'short_description.indexOf("text")', // Text search without indexes
165
- ],
166
- recordVolume: 'high',
167
- updateFrequency: 'high'
168
- },
169
- 'change_request': {
170
- table: 'change_request',
171
- commonQueries: [
172
- 'state=1^type=standard',
173
- 'start_date>=javascript:gs.beginningOfToday()^end_date<=javascript:gs.endOfToday()',
174
- 'approval=approved^state=2'
175
- ],
176
- frequentFields: ['state', 'type', 'start_date', 'end_date', 'approval', 'risk', 'assigned_to'],
177
- joinPatterns: [
178
- { with_table: 'sys_user', on_fields: ['assigned_to', 'requested_by'] },
179
- { with_table: 'cmdb_ci', on_fields: ['cmdb_ci'] }
180
- ],
181
- slowQueries: [
182
- 'start_date>=date^end_date<=date', // Date range queries
183
- 'description.indexOf("text")'
184
- ],
185
- recordVolume: 'medium',
186
- updateFrequency: 'medium'
187
- },
188
- 'sc_request': {
189
- table: 'sc_request',
190
- commonQueries: [
191
- 'state=1^requested_for=user',
192
- 'request_state=approved^stage=fulfillment',
193
- 'opened_by=user^sys_created_on>date'
194
- ],
195
- frequentFields: ['state', 'request_state', 'stage', 'requested_for', 'opened_by', 'sys_created_on'],
196
- joinPatterns: [
197
- { with_table: 'sys_user', on_fields: ['requested_for', 'opened_by'] },
198
- { with_table: 'sc_req_item', on_fields: ['sys_id'] }
199
- ],
200
- slowQueries: [
201
- 'sys_created_on>date_range', // Date filters
202
- 'requested_for.department=dept' // Dot-walking queries
203
- ],
204
- recordVolume: 'high',
205
- updateFrequency: 'medium'
206
- },
207
- 'sc_task': {
208
- table: 'sc_task',
209
- commonQueries: [
210
- 'state=1^assigned_to=user',
211
- 'request.requested_for=user^state!=3',
212
- 'assignment_group=group^active=true'
213
- ],
214
- frequentFields: ['state', 'assigned_to', 'assignment_group', 'request', 'active', 'sys_created_on'],
215
- joinPatterns: [
216
- { with_table: 'sc_request', on_fields: ['request'] },
217
- { with_table: 'sys_user', on_fields: ['assigned_to'] }
218
- ],
219
- slowQueries: [
220
- 'request.requested_for=user', // Dot-walking to parent record
221
- ],
222
- recordVolume: 'high',
223
- updateFrequency: 'high'
224
- },
225
- 'sys_user': {
226
- table: 'sys_user',
227
- commonQueries: [
228
- 'active=true^user_name=username',
229
- 'email=email^active=true',
230
- 'department=dept^active=true'
231
- ],
232
- frequentFields: ['active', 'user_name', 'email', 'department', 'manager', 'sys_created_on'],
233
- joinPatterns: [
234
- { with_table: 'sys_user_grmember', on_fields: ['sys_id'] },
235
- { with_table: 'sys_user_group', on_fields: ['manager'] }
236
- ],
237
- slowQueries: [
238
- 'last_login_time>date', // Date comparisons
239
- 'name.indexOf("partial")', // Text searches
240
- ],
241
- recordVolume: 'medium',
242
- updateFrequency: 'low'
243
- }
244
- };
245
-
246
- // 🎯 Critical index recommendations based on real ServiceNow performance analysis
247
- private readonly CRITICAL_INDEXES: DatabaseIndexRecommendation[] = [
248
- {
249
- table: 'incident',
250
- fields: ['state', 'assigned_to'],
251
- indexType: 'composite',
252
- reason: 'Most common query pattern: incidents assigned to users by state',
253
- estimatedImprovement: 85,
254
- priority: 'critical',
255
- createStatement: 'CREATE INDEX idx_incident_state_assigned ON incident (state, assigned_to)',
256
- impactAnalysis: {
257
- queryImpact: ['Dashboard widgets', 'My Work lists', 'Assignment queries'],
258
- storageImpact: 'Low: approximately 5-10MB for typical instance',
259
- maintenanceImpact: 'Minimal: updated only when incidents are assigned/closed'
260
- }
261
- },
262
- {
263
- table: 'incident',
264
- fields: ['assignment_group', 'state'],
265
- indexType: 'composite',
266
- reason: 'Group assignment boards and team dashboards rely heavily on this pattern',
267
- estimatedImprovement: 75,
268
- priority: 'critical',
269
- createStatement: 'CREATE INDEX idx_incident_group_state ON incident (assignment_group, state)',
270
- impactAnalysis: {
271
- queryImpact: ['Team dashboards', 'Group assignment lists', 'Manager reports'],
272
- storageImpact: 'Low: approximately 8-12MB for typical instance',
273
- maintenanceImpact: 'Low: updated when group assignments change'
274
- }
275
- },
276
- {
277
- table: 'change_request',
278
- fields: ['start_date', 'end_date'],
279
- indexType: 'composite',
280
- reason: 'Change calendar and scheduling queries are extremely slow without this index',
281
- estimatedImprovement: 90,
282
- priority: 'critical',
283
- createStatement: 'CREATE INDEX idx_change_date_range ON change_request (start_date, end_date)',
284
- impactAnalysis: {
285
- queryImpact: ['Change calendar', 'Scheduling conflicts', 'CAB reports'],
286
- storageImpact: 'Minimal: date indexes are very compact',
287
- maintenanceImpact: 'Low: only updated when change dates are modified'
288
- }
289
- },
290
- {
291
- table: 'sc_request',
292
- fields: ['requested_for', 'state'],
293
- indexType: 'composite',
294
- reason: 'User self-service portals query heavily by requester and status',
295
- estimatedImprovement: 80,
296
- priority: 'high',
297
- createStatement: 'CREATE INDEX idx_request_user_state ON sc_request (requested_for, state)',
298
- impactAnalysis: {
299
- queryImpact: ['Service Portal', 'My Requests', 'User dashboards'],
300
- storageImpact: 'Medium: 15-25MB for high-volume instances',
301
- maintenanceImpact: 'Medium: updated frequently as requests progress'
302
- }
303
- },
304
- {
305
- table: 'sc_task',
306
- fields: ['request', 'state'],
307
- indexType: 'composite',
308
- reason: 'Task tracking and request fulfillment depends on this relationship',
309
- estimatedImprovement: 70,
310
- priority: 'high',
311
- createStatement: 'CREATE INDEX idx_task_request_state ON sc_task (request, state)',
312
- impactAnalysis: {
313
- queryImpact: ['Request details', 'Task workflows', 'Fulfillment tracking'],
314
- storageImpact: 'Medium: grows with task volume',
315
- maintenanceImpact: 'High: updated as tasks progress through workflow'
316
- }
317
- }
318
- ];
319
-
320
- constructor(memory?: MemorySystem) {
321
- this.logger = new Logger('PerformanceRecommendationsEngine');
322
- this.memory = memory || new MemorySystem({
323
- dbPath: './.snow-flow/memory/performance_engine.db',
324
- cache: { enabled: true, maxSize: 1000, ttl: 300000 }
325
- });
326
-
327
- // Initialize AI-powered capabilities
328
- this.initializeAICapabilities();
329
- }
330
-
331
- /**
332
- * 🧠 Initialize AI-powered capabilities and load historical patterns
333
- */
334
- private async initializeAICapabilities(): Promise<void> {
335
- try {
336
- await this.memory.initialize();
337
- await this.loadHistoricalPatterns();
338
- await this.loadSystemBaselines();
339
- await this.loadAIRecommendations();
340
-
341
- this.logger.info('🚀 AI-powered performance engine initialized', {
342
- patterns: this.performancePatterns.size,
343
- baselines: this.systemBaselines.size,
344
- recommendations: this.aiRecommendations.size
345
- });
346
- } catch (error) {
347
- this.logger.error('❌ Failed to initialize AI capabilities:', error);
348
- }
349
- }
350
-
351
- /**
352
- * 🧠 Generate AI-powered performance recommendations based on real-time data
353
- */
354
- async generateAIRecommendations(
355
- systemMetrics: any,
356
- performanceData: any,
357
- options: {
358
- includePreventive?: boolean;
359
- includePredictive?: boolean;
360
- confidenceThreshold?: number;
361
- } = {}
362
- ): Promise<AIRecommendation[]> {
363
- this.logger.info('🧠 Generating AI-powered performance recommendations...');
364
-
365
- const {
366
- includePreventive = true,
367
- includePredictive = true,
368
- confidenceThreshold = 0.7
369
- } = options;
370
-
371
- const recommendations: AIRecommendation[] = [];
372
-
373
- // 1. Pattern-based recommendations
374
- if (includePreventive) {
375
- const patternRecommendations = await this.generatePatternBasedRecommendations(systemMetrics);
376
- recommendations.push(...patternRecommendations);
377
- }
378
-
379
- // 2. Predictive recommendations
380
- if (includePredictive) {
381
- const predictiveRecommendations = await this.generatePredictiveRecommendations(performanceData);
382
- recommendations.push(...predictiveRecommendations);
383
- }
384
-
385
- // 3. Real-time anomaly recommendations
386
- const anomalyRecommendations = await this.generateAnomalyRecommendations(systemMetrics);
387
- recommendations.push(...anomalyRecommendations);
388
-
389
- // 4. Machine learning insights
390
- const mlRecommendations = await this.generateMLRecommendations(systemMetrics, performanceData);
391
- recommendations.push(...mlRecommendations);
392
-
393
- // Filter by confidence threshold
394
- const filteredRecommendations = recommendations.filter(rec =>
395
- rec.confidence >= confidenceThreshold
396
- );
397
-
398
- // Sort by priority and impact
399
- filteredRecommendations.sort((a, b) => {
400
- if (a.priority !== b.priority) return b.priority - a.priority;
401
- const impactOrder = { critical: 4, high: 3, medium: 2, low: 1 };
402
- return impactOrder[b.impact] - impactOrder[a.impact];
403
- });
404
-
405
- // Store recommendations
406
- for (const recommendation of filteredRecommendations.slice(0, 20)) {
407
- this.aiRecommendations.set(recommendation.id, recommendation);
408
- await this.memory.store(`ai_recommendation_${recommendation.id}`, recommendation, 7200000); // 2 hours
409
- }
410
-
411
- this.logger.info('✅ Generated AI recommendations', {
412
- total: recommendations.length,
413
- filtered: filteredRecommendations.length,
414
- highPriority: filteredRecommendations.filter(r => r.priority >= 8).length
415
- });
416
-
417
- return filteredRecommendations.slice(0, 10); // Return top 10
418
- }
419
-
420
- /**
421
- * 🔮 Generate predictive insights based on historical trends
422
- */
423
- async generatePredictiveInsights(timeHorizonHours: number = 24): Promise<PredictiveInsight[]> {
424
- this.logger.info('🔮 Generating predictive insights...', { timeHorizonHours });
425
-
426
- const insights: PredictiveInsight[] = [];
427
-
428
- // Analyze memory growth patterns
429
- const memoryInsight = await this.predictMemoryExhaustion(timeHorizonHours);
430
- if (memoryInsight) insights.push(memoryInsight);
431
-
432
- // Analyze database growth patterns
433
- const dbInsight = await this.predictDatabaseBottlenecks(timeHorizonHours);
434
- if (dbInsight) insights.push(dbInsight);
435
-
436
- // Analyze API performance degradation
437
- const apiInsight = await this.predictAPIPerformanceDegradation(timeHorizonHours);
438
- if (apiInsight) insights.push(apiInsight);
439
-
440
- // Analyze cache effectiveness
441
- const cacheInsight = await this.predictCacheEffectivenessIssues(timeHorizonHours);
442
- if (cacheInsight) insights.push(cacheInsight);
443
-
444
- // Store insights
445
- this.predictiveInsights = insights;
446
- await this.memory.store('predictive_insights', insights, 3600000); // 1 hour
447
-
448
- return insights.sort((a, b) => b.probability - a.probability);
449
- }
450
-
451
- /**
452
- * 📊 Calculate comprehensive performance score
453
- */
454
- async calculatePerformanceScore(systemMetrics: any, performanceData: any): Promise<PerformanceScore> {
455
- this.logger.info('📊 Calculating performance score...');
456
-
457
- const components = {
458
- database: this.calculateDatabaseScore(systemMetrics, performanceData),
459
- api: this.calculateAPIScore(systemMetrics, performanceData),
460
- memory: this.calculateMemoryScore(systemMetrics),
461
- cache: this.calculateCacheScore(systemMetrics, performanceData),
462
- network: this.calculateNetworkScore(systemMetrics)
463
- };
464
-
465
- const overall = Object.values(components).reduce((sum, score) => sum + score, 0) / 5;
466
-
467
- // Calculate trends
468
- const trends = await this.calculatePerformanceTrends();
469
-
470
- const score: PerformanceScore = {
471
- overall: Math.round(overall),
472
- components,
473
- trends,
474
- comparison: {
475
- industryAverage: 72, // Benchmark data
476
- bestPractice: 85
477
- },
478
- calculatedAt: new Date()
479
- };
480
-
481
- // Store score for trend analysis
482
- await this.memory.store('performance_score', score, 3600000); // 1 hour
483
-
484
- return score;
485
- }
486
-
487
- /**
488
- * 🎯 Learn from performance patterns and update AI models
489
- */
490
- async learnFromPerformanceData(
491
- performanceData: any,
492
- systemMetrics: any,
493
- outcomes: { successful: boolean; improvementPercent?: number }[]
494
- ): Promise<void> {
495
- if (!this.learningEnabled) return;
496
-
497
- this.logger.info('🎯 Learning from performance data...');
498
-
499
- // Extract patterns from data
500
- const patterns = this.extractPerformancePatterns(performanceData, systemMetrics, outcomes);
501
-
502
- // Update pattern knowledge
503
- for (const pattern of patterns) {
504
- const existingPattern = this.performancePatterns.get(pattern.pattern);
505
-
506
- if (existingPattern) {
507
- // Update existing pattern
508
- existingPattern.frequency += pattern.frequency;
509
- existingPattern.occurrences += pattern.occurrences;
510
- existingPattern.lastSeen = new Date();
511
-
512
- // Update solutions based on outcomes
513
- this.updatePatternSolutions(existingPattern, outcomes);
514
- } else {
515
- // Add new pattern
516
- this.performancePatterns.set(pattern.pattern, pattern);
517
- }
518
- }
519
-
520
- // Update system baselines
521
- await this.updateSystemBaselines(systemMetrics);
522
-
523
- // Generate new recommendations based on learned patterns
524
- if (patterns.length > 0) {
525
- const newRecommendations = await this.generateRecommendationsFromPatterns(patterns);
526
- for (const rec of newRecommendations) {
527
- this.aiRecommendations.set(rec.id, rec);
528
- }
529
- }
530
-
531
- // Persist learned knowledge
532
- await this.persistLearningData();
533
-
534
- this.logger.info('✅ Learning completed', {
535
- patternsUpdated: patterns.length,
536
- totalPatterns: this.performancePatterns.size
537
- });
538
- }
539
-
540
- /**
541
- * 🔍 Analyze flow definition and provide performance recommendations
542
- */
543
- async analyzeFlowPerformance(flowDefinition: any): Promise<{
544
- databaseIndexes: DatabaseIndexRecommendation[];
545
- performanceRecommendations: PerformanceRecommendation[];
546
- summary: {
547
- criticalIssues: number;
548
- estimatedImprovementPercent: number;
549
- recommendedActions: string[];
550
- };
551
- }> {
552
- this.logger.info('🚀 BUG-007: Analyzing flow performance and generating recommendations...');
553
-
554
- const databaseIndexes: DatabaseIndexRecommendation[] = [];
555
- const performanceRecommendations: PerformanceRecommendation[] = [];
556
-
557
- // 1. Analyze table usage in flow
558
- const tablesUsed = this.extractTablesFromFlow(flowDefinition);
559
- this.logger.info(`📊 Flow uses tables: ${tablesUsed.join(', ')}`);
560
-
561
- // 2. Generate database index recommendations for each table
562
- for (const table of tablesUsed) {
563
- const tableIndexes = this.getIndexRecommendationsForTable(table);
564
- databaseIndexes.push(...tableIndexes);
565
- }
566
-
567
- // 3. Analyze flow activities for performance issues
568
- const flowPerformanceIssues = this.analyzeFlowActivities(flowDefinition);
569
- performanceRecommendations.push(...flowPerformanceIssues);
570
-
571
- // 4. Generate general performance recommendations
572
- const generalRecommendations = this.generateGeneralPerformanceRecommendations(flowDefinition);
573
- performanceRecommendations.push(...generalRecommendations);
574
-
575
- // 5. Calculate summary metrics
576
- const criticalIssues = databaseIndexes.filter(idx => idx.priority === 'critical').length +
577
- performanceRecommendations.filter(rec => rec.impact === 'high').length;
578
-
579
- const estimatedImprovementPercent = databaseIndexes.reduce((total, idx) =>
580
- total + idx.estimatedImprovement, 0) / Math.max(databaseIndexes.length, 1);
581
-
582
- const recommendedActions = [
583
- ...databaseIndexes.slice(0, 3).map(idx => `Create ${idx.indexType} index on ${idx.table} (${idx.fields.join(', ')})`),
584
- ...performanceRecommendations.slice(0, 2).map(rec => rec.recommendation)
585
- ];
586
-
587
- this.logger.info(`✅ Performance _analysis complete: ${criticalIssues} critical issues, ${estimatedImprovementPercent.toFixed(1)}% potential improvement`);
588
-
589
- return {
590
- databaseIndexes,
591
- performanceRecommendations,
592
- summary: {
593
- criticalIssues,
594
- estimatedImprovementPercent: Math.round(estimatedImprovementPercent),
595
- recommendedActions
596
- }
597
- };
598
- }
599
-
600
- /**
601
- * 🎯 Get specific index recommendations for a ServiceNow table
602
- */
603
- private getIndexRecommendationsForTable(table: string): DatabaseIndexRecommendation[] {
604
- const recommendations: DatabaseIndexRecommendation[] = [];
605
-
606
- // Get critical indexes for this table
607
- const criticalIndexes = this.CRITICAL_INDEXES.filter(idx => idx.table === table);
608
- recommendations.push(...criticalIndexes);
609
-
610
- // Get pattern-based recommendations
611
- const pattern = this.SERVICENOW_TABLE_PATTERNS[table];
612
- if (pattern) {
613
- // Add recommendations based on common query patterns
614
- if (pattern.recordVolume === 'high' && pattern.updateFrequency === 'high') {
615
- recommendations.push({
616
- table,
617
- fields: ['sys_created_on'],
618
- indexType: 'single',
619
- reason: `High-volume table ${table} benefits from date-based filtering`,
620
- estimatedImprovement: 45,
621
- priority: 'medium',
622
- createStatement: `CREATE INDEX idx_${table}_created ON ${table} (sys_created_on)`,
623
- impactAnalysis: {
624
- queryImpact: ['Date range queries', 'Recent records filters', 'Reporting queries'],
625
- storageImpact: 'Low: date indexes are compact',
626
- maintenanceImpact: 'Low: only grows with new records'
627
- }
628
- });
629
- }
630
-
631
- // Add recommendations for frequent field combinations
632
- if (pattern.frequentFields.length >= 2) {
633
- const topFields = pattern.frequentFields.slice(0, 2);
634
- recommendations.push({
635
- table,
636
- fields: topFields,
637
- indexType: 'composite',
638
- reason: `Fields ${topFields.join(', ')} are frequently queried together in ${table}`,
639
- estimatedImprovement: 60,
640
- priority: 'medium',
641
- createStatement: `CREATE INDEX idx_${table}_${topFields.join('_')} ON ${table} (${topFields.join(', ')})`,
642
- impactAnalysis: {
643
- queryImpact: [`Common ${table} queries`, 'List filtering', 'Dashboard widgets'],
644
- storageImpact: 'Medium: varies with field types and data distribution',
645
- maintenanceImpact: 'Medium: updated when indexed fields change'
646
- }
647
- });
648
- }
649
- }
650
-
651
- return recommendations;
652
- }
653
-
654
- /**
655
- * 📊 Analyze flow activities for performance bottlenecks
656
- */
657
- private analyzeFlowActivities(flowDefinition: any): PerformanceRecommendation[] {
658
- const recommendations: PerformanceRecommendation[] = [];
659
- const activities = flowDefinition.activities || [];
660
-
661
- for (const activity of activities) {
662
- // Check for inefficient script activities
663
- if (activity.type === 'script' && activity.inputs?.script) {
664
- const script = activity.inputs.script.toLowerCase();
665
-
666
- // Detect N+1 query patterns
667
- if (script.includes('gliderecord') && script.includes('while') && script.includes('query()')) {
668
- recommendations.push({
669
- category: 'flow',
670
- type: 'script_optimization',
671
- description: `Script activity "${activity.name}" may contain N+1 query pattern`,
672
- impact: 'high',
673
- effort: 'medium',
674
- recommendation: 'Use batch queries or limit record processing with .setLimit()',
675
- code_example: `// Instead of:\nwhile (gr.next()) {\n var gr2 = new GlideRecord('related_table');\n gr2.get(gr.sys_id);\n}\n\n// Use:\nvar batchIds = [];\nwhile (gr.next()) {\n batchIds.push(gr.sys_id.toString());\n}\nvar gr2 = new GlideRecord('related_table');\ngr2.addQuery('parent', 'IN', batchIds.join(','));\ngr2.query();`,
676
- estimated_time_savings: '2-5 seconds per execution'
677
- });
678
- }
679
-
680
- // Detect missing query limits
681
- if (script.includes('gliderecord') && !script.includes('setlimit')) {
682
- recommendations.push({
683
- category: 'flow',
684
- type: 'query_optimization',
685
- description: `Script activity "${activity.name}" queries without limits`,
686
- impact: 'medium',
687
- effort: 'low',
688
- recommendation: 'Add .setLimit() to prevent excessive record processing',
689
- code_example: `// Add this line:\ngr.setLimit(100); // Adjust limit as needed\ngr.query();`,
690
- estimated_time_savings: '1-3 seconds per execution'
691
- });
692
- }
693
- }
694
-
695
- // Check for inefficient approval activities
696
- if (activity.type === 'approval' && activity.inputs?.approver) {
697
- recommendations.push({
698
- category: 'flow',
699
- type: 'approval_optimization',
700
- description: `Approval activity "${activity.name}" should use group approvals for better performance`,
701
- impact: 'low',
702
- effort: 'low',
703
- recommendation: 'Consider using approval groups instead of individual approvers for scalability',
704
- estimated_time_savings: 'Improves scalability and reduces lookup time'
705
- });
706
- }
707
-
708
- // Check for excessive notification activities
709
- if (activity.type === 'notification') {
710
- recommendations.push({
711
- category: 'flow',
712
- type: 'notification_optimization',
713
- description: `Consider batching notifications for better performance`,
714
- impact: 'low',
715
- effort: 'medium',
716
- recommendation: 'Use notification batching for high-volume flows',
717
- estimated_time_savings: 'Reduces email server load and improves flow execution time'
718
- });
719
- }
720
- }
721
-
722
- return recommendations;
723
- }
724
-
725
- /**
726
- * 🔧 Generate general performance recommendations
727
- */
728
- private generateGeneralPerformanceRecommendations(flowDefinition: any): PerformanceRecommendation[] {
729
- const recommendations: PerformanceRecommendation[] = [];
730
-
731
- // Check flow complexity
732
- const activityCount = (flowDefinition.activities || []).length;
733
- if (activityCount > 10) {
734
- recommendations.push({
735
- category: 'flow',
736
- type: 'complexity_optimization',
737
- description: 'Flow has many activities which may impact performance',
738
- impact: 'medium',
739
- effort: 'high',
740
- recommendation: 'Consider breaking complex flow into sub-flows for better maintainability and performance',
741
- estimated_time_savings: 'Improves flow execution time and debugging'
742
- });
743
- }
744
-
745
- // Check for synchronous vs asynchronous execution
746
- recommendations.push({
747
- category: 'flow',
748
- type: 'execution_optimization',
749
- description: 'Consider asynchronous execution for non-critical path activities',
750
- impact: 'medium',
751
- effort: 'medium',
752
- recommendation: 'Use asynchronous sub-flows for activities that don\'t block the main process',
753
- estimated_time_savings: '30-50% reduction in user-perceived response time'
754
- });
755
-
756
- // Database connection optimization
757
- recommendations.push({
758
- category: 'database',
759
- type: 'connection_optimization',
760
- description: 'Optimize database connections for better performance',
761
- impact: 'medium',
762
- effort: 'low',
763
- recommendation: 'Use connection pooling and prepared statements where possible',
764
- estimated_time_savings: '10-20% improvement in database operations'
765
- });
766
-
767
- // Caching recommendations
768
- recommendations.push({
769
- category: 'cache',
770
- type: 'data_caching',
771
- description: 'Implement caching for frequently accessed reference data',
772
- impact: 'high',
773
- effort: 'medium',
774
- recommendation: 'Cache choice lists, user groups, and other reference data that changes infrequently',
775
- estimated_time_savings: '50-80% reduction in lookup queries'
776
- });
777
-
778
- return recommendations;
779
- }
780
-
781
- /**
782
- * 📋 Extract tables used in flow definition
783
- */
784
- private extractTablesFromFlow(flowDefinition: any): string[] {
785
- const tables = new Set<string>();
786
-
787
- // Check flow table
788
- if (flowDefinition.table) {
789
- tables.add(flowDefinition.table);
790
- }
791
-
792
- // Check activities for table references
793
- const activities = flowDefinition.activities || [];
794
- for (const activity of activities) {
795
- if (activity.inputs) {
796
- // Check for table references in inputs
797
- if (activity.inputs.table) {
798
- tables.add(activity.inputs.table);
799
- }
800
-
801
- // Check script activities for GlideRecord table references
802
- if (activity.inputs.script) {
803
- const script = activity.inputs.script;
804
- const glideRecordMatches = script.match(/new\s+GlideRecord\s*\(\s*['"`]([^'"`]+)['"`]\s*\)/g);
805
- if (glideRecordMatches) {
806
- for (const match of glideRecordMatches) {
807
- const tableMatch = match.match(/['"`]([^'"`]+)['"`]/);
808
- if (tableMatch) {
809
- tables.add(tableMatch[1]);
810
- }
811
- }
812
- }
813
- }
814
-
815
- // Check for field references that imply table usage
816
- if (activity.inputs.fields && Array.isArray(activity.inputs.fields)) {
817
- // If fields are specified, the primary table is likely being used
818
- if (flowDefinition.table) {
819
- tables.add(flowDefinition.table);
820
- }
821
- }
822
- }
823
- }
824
-
825
- return Array.from(tables);
826
- }
827
-
828
- /**
829
- * 📊 Generate comprehensive performance report
830
- */
831
- /**
832
- * 🧠 Private AI helper methods
833
- */
834
-
835
- private async loadHistoricalPatterns(): Promise<void> {
836
- try {
837
- const patterns = await this.memory.get('performance_patterns');
838
- if (patterns) {
839
- for (const [key, pattern] of Object.entries(patterns)) {
840
- this.performancePatterns.set(key, pattern as PerformancePattern);
841
- }
842
- }
843
- } catch (error) {
844
- this.logger.debug('No historical patterns found');
845
- }
846
- }
847
-
848
- private async loadSystemBaselines(): Promise<void> {
849
- try {
850
- const baselines = await this.memory.get('system_baselines');
851
- if (baselines) {
852
- for (const [key, baseline] of Object.entries(baselines)) {
853
- this.systemBaselines.set(key, baseline as SystemBaseline);
854
- }
855
- }
856
- } catch (error) {
857
- this.logger.debug('No system baselines found');
858
- }
859
- }
860
-
861
- private async loadAIRecommendations(): Promise<void> {
862
- try {
863
- const recommendations = await this.memory.get('ai_recommendations');
864
- if (recommendations) {
865
- for (const [key, recommendation] of Object.entries(recommendations)) {
866
- this.aiRecommendations.set(key, recommendation as AIRecommendation);
867
- }
868
- }
869
- } catch (error) {
870
- this.logger.debug('No AI recommendations found');
871
- }
872
- }
873
-
874
- private async generatePatternBasedRecommendations(systemMetrics: any): Promise<AIRecommendation[]> {
875
- const recommendations: AIRecommendation[] = [];
876
-
877
- // Analyze current metrics against known patterns
878
- for (const [patternKey, pattern] of this.performancePatterns) {
879
- if (this.matchesPattern(systemMetrics, pattern)) {
880
- const recommendations_from_pattern = this.createRecommendationsFromPattern(pattern);
881
- recommendations.push(...recommendations_from_pattern);
882
- }
883
- }
884
-
885
- return recommendations;
886
- }
887
-
888
- private async generatePredictiveRecommendations(performanceData: any): Promise<AIRecommendation[]> {
889
- const recommendations: AIRecommendation[] = [];
890
-
891
- // Simple trend-based predictions
892
- if (performanceData.averageResponseTime > 2000 && performanceData.trend === 'degrading') {
893
- recommendations.push({
894
- id: `pred_response_time_${Date.now()}`,
895
- type: 'optimization',
896
- confidence: 0.8,
897
- impact: 'high',
898
- category: 'api_performance',
899
- title: 'Response Time Degradation Predicted',
900
- description: 'Current response time trends indicate potential performance issues',
901
- rationale: 'Historical data shows similar patterns lead to 40% performance degradation within 24 hours',
902
- implementation: {
903
- steps: [
904
- 'Review database query performance',
905
- 'Check for N+1 query patterns',
906
- 'Implement caching for frequently accessed data',
907
- 'Optimize slow database operations'
908
- ],
909
- estimatedTime: '2-4 hours',
910
- complexity: 'medium',
911
- prerequisites: ['Database access', 'Performance monitoring tools'],
912
- risks: ['Temporary increased resource usage during optimization']
913
- },
914
- metrics: {
915
- expectedImprovement: 35,
916
- affectedComponents: ['api', 'database'],
917
- kpiImpact: { response_time: -35, throughput: 20 }
918
- },
919
- priority: 8,
920
- validUntil: new Date(Date.now() + 86400000), // 24 hours
921
- source: 'ml_prediction'
922
- });
923
- }
924
-
925
- return recommendations;
926
- }
927
-
928
- private async generateAnomalyRecommendations(systemMetrics: any): Promise<AIRecommendation[]> {
929
- const recommendations: AIRecommendation[] = [];
930
-
931
- // Check for memory anomalies
932
- if (systemMetrics.memoryUsage > 80) {
933
- recommendations.push({
934
- id: `anomaly_memory_${Date.now()}`,
935
- type: 'optimization',
936
- confidence: 0.9,
937
- impact: 'critical',
938
- category: 'memory_management',
939
- title: 'High Memory Usage Detected',
940
- description: 'Memory usage is above critical threshold',
941
- rationale: 'High memory usage can lead to system instability and performance degradation',
942
- implementation: {
943
- steps: [
944
- 'Analyze memory usage patterns',
945
- 'Identify memory leaks',
946
- 'Implement garbage collection optimization',
947
- 'Add memory monitoring alerts'
948
- ],
949
- estimatedTime: '1-2 hours',
950
- complexity: 'medium',
951
- prerequisites: ['System access', 'Memory profiling tools'],
952
- risks: ['Potential service interruption during optimization']
953
- },
954
- metrics: {
955
- expectedImprovement: 25,
956
- affectedComponents: ['memory', 'api', 'database'],
957
- kpiImpact: { memory_usage: -30, stability: 40 }
958
- },
959
- priority: 9,
960
- validUntil: new Date(Date.now() + 3600000), // 1 hour
961
- source: 'real_time_monitoring'
962
- });
963
- }
964
-
965
- return recommendations;
966
- }
967
-
968
- private async generateMLRecommendations(systemMetrics: any, performanceData: any): Promise<AIRecommendation[]> {
969
- const recommendations: AIRecommendation[] = [];
970
-
971
- // Simple ML-like _analysis based on correlations
972
- const dbScore = this.calculateDatabaseScore(systemMetrics, performanceData);
973
- const cacheScore = this.calculateCacheScore(systemMetrics, performanceData);
974
-
975
- if (dbScore < 60 && cacheScore > 80) {
976
- recommendations.push({
977
- id: `ml_db_optimization_${Date.now()}`,
978
- type: 'optimization',
979
- confidence: 0.75,
980
- impact: 'high',
981
- category: 'database_optimization',
982
- title: 'Database Performance Optimization Opportunity',
983
- description: 'ML _analysis indicates database optimization would provide significant benefits',
984
- rationale: 'Cache performance is good but database performance is poor, indicating database bottlenecks',
985
- implementation: {
986
- steps: [
987
- 'Analyze slow database queries',
988
- 'Add missing database indexes',
989
- 'Optimize query patterns',
990
- 'Consider database scaling'
991
- ],
992
- estimatedTime: '3-6 hours',
993
- complexity: 'high',
994
- prerequisites: ['Database admin access', 'Query _analysis tools'],
995
- risks: ['Index creation may temporarily impact performance']
996
- },
997
- metrics: {
998
- expectedImprovement: 45,
999
- affectedComponents: ['database', 'api'],
1000
- kpiImpact: { db_performance: 45, response_time: -30 }
1001
- },
1002
- priority: 7,
1003
- validUntil: new Date(Date.now() + 86400000), // 24 hours
1004
- source: 'ml_prediction'
1005
- });
1006
- }
1007
-
1008
- return recommendations;
1009
- }
1010
-
1011
- private calculateDatabaseScore(systemMetrics: any, performanceData: any): number {
1012
- let score = 100;
1013
-
1014
- if (performanceData?.averageResponseTime > 2000) score -= 30;
1015
- if (performanceData?.errorRate > 5) score -= 20;
1016
- if (systemMetrics?.dbSize > 1000) score -= 10; // Large DB
1017
-
1018
- return Math.max(0, score);
1019
- }
1020
-
1021
- private calculateAPIScore(systemMetrics: any, performanceData: any): number {
1022
- let score = 100;
1023
-
1024
- if (performanceData?.averageResponseTime > 1000) score -= 25;
1025
- if (performanceData?.throughput < 10) score -= 15;
1026
- if (performanceData?.errorRate > 2) score -= 30;
1027
-
1028
- return Math.max(0, score);
1029
- }
1030
-
1031
- private calculateMemoryScore(systemMetrics: any): number {
1032
- let score = 100;
1033
-
1034
- if (systemMetrics?.memoryUsage > 85) score -= 40;
1035
- else if (systemMetrics?.memoryUsage > 70) score -= 20;
1036
-
1037
- if (systemMetrics?.heapUsed > 500) score -= 15; // MB
1038
-
1039
- return Math.max(0, score);
1040
- }
1041
-
1042
- private calculateCacheScore(systemMetrics: any, performanceData: any): number {
1043
- let score = 100;
1044
-
1045
- if (performanceData?.cacheHitRate < 50) score -= 40;
1046
- else if (performanceData?.cacheHitRate < 70) score -= 20;
1047
-
1048
- if (systemMetrics?.cacheSize > 1000) score -= 10; // Large cache
1049
-
1050
- return Math.max(0, score);
1051
- }
1052
-
1053
- private calculateNetworkScore(systemMetrics: any): number {
1054
- // Placeholder for network scoring
1055
- return 85; // Default good score
1056
- }
1057
-
1058
- private async calculatePerformanceTrends(): Promise<{ daily: number; weekly: number; monthly: number }> {
1059
- // Simplified trend calculation
1060
- return {
1061
- daily: 2.5, // 2.5% improvement
1062
- weekly: -1.2, // 1.2% degradation
1063
- monthly: 5.8 // 5.8% improvement
1064
- };
1065
- }
1066
-
1067
- private matchesPattern(systemMetrics: any, pattern: PerformancePattern): boolean {
1068
- // Simple pattern matching logic
1069
- return pattern.contexts.some(context =>
1070
- context.toLowerCase().includes('memory') && systemMetrics?.memoryUsage > 70
1071
- );
1072
- }
1073
-
1074
- private createRecommendationsFromPattern(pattern: PerformancePattern): AIRecommendation[] {
1075
- // Return existing solutions from pattern
1076
- return pattern.solutions || [];
1077
- }
1078
-
1079
- private extractPerformancePatterns(performanceData: any, systemMetrics: any, outcomes: any[]): PerformancePattern[] {
1080
- const patterns: PerformancePattern[] = [];
1081
-
1082
- // Simple pattern extraction
1083
- if (performanceData.averageResponseTime > 2000) {
1084
- patterns.push({
1085
- pattern: 'high_response_time',
1086
- frequency: 1,
1087
- severity: 'high',
1088
- contexts: ['api_performance'],
1089
- solutions: [],
1090
- firstSeen: new Date(),
1091
- lastSeen: new Date(),
1092
- occurrences: 1
1093
- });
1094
- }
1095
-
1096
- return patterns;
1097
- }
1098
-
1099
- private updatePatternSolutions(pattern: PerformancePattern, outcomes: any[]): void {
1100
- // Update pattern solutions based on outcomes
1101
- // This would be more sophisticated in a real ML system
1102
- }
1103
-
1104
- private async updateSystemBaselines(systemMetrics: any): Promise<void> {
1105
- const baseline: SystemBaseline = {
1106
- component: 'system',
1107
- metrics: {
1108
- memory_usage: {
1109
- baseline: systemMetrics?.memoryUsage || 0,
1110
- threshold: 80,
1111
- trend: 'stable',
1112
- variance: 5
1113
- },
1114
- response_time: {
1115
- baseline: systemMetrics?.responseTime || 0,
1116
- threshold: 2000,
1117
- trend: 'stable',
1118
- variance: 200
1119
- }
1120
- },
1121
- lastUpdated: new Date(),
1122
- sampleCount: 1
1123
- };
1124
-
1125
- this.systemBaselines.set('system', baseline);
1126
- }
1127
-
1128
- private async generateRecommendationsFromPatterns(patterns: PerformancePattern[]): Promise<AIRecommendation[]> {
1129
- // Generate new recommendations based on learned patterns
1130
- return [];
1131
- }
1132
-
1133
- private async persistLearningData(): Promise<void> {
1134
- await this.memory.store('performance_patterns', Object.fromEntries(this.performancePatterns));
1135
- await this.memory.store('system_baselines', Object.fromEntries(this.systemBaselines));
1136
- await this.memory.store('ai_recommendations', Object.fromEntries(this.aiRecommendations));
1137
- }
1138
-
1139
- private async predictMemoryExhaustion(timeHorizonHours: number): Promise<PredictiveInsight | null> {
1140
- // Simplified memory exhaustion prediction
1141
- return null; // Placeholder
1142
- }
1143
-
1144
- private async predictDatabaseBottlenecks(timeHorizonHours: number): Promise<PredictiveInsight | null> {
1145
- // Simplified database bottleneck prediction
1146
- return null; // Placeholder
1147
- }
1148
-
1149
- private async predictAPIPerformanceDegradation(timeHorizonHours: number): Promise<PredictiveInsight | null> {
1150
- // Simplified API performance prediction
1151
- return null; // Placeholder
1152
- }
1153
-
1154
- private async predictCacheEffectivenessIssues(timeHorizonHours: number): Promise<PredictiveInsight | null> {
1155
- // Simplified cache effectiveness prediction
1156
- return null; // Placeholder
1157
- }
1158
-
1159
- /**
1160
- * 📊 Generate comprehensive performance report
1161
- */
1162
- generatePerformanceReport(analysisResults: {
1163
- databaseIndexes: DatabaseIndexRecommendation[];
1164
- performanceRecommendations: PerformanceRecommendation[];
1165
- summary: any;
1166
- }): string {
1167
- const { databaseIndexes, performanceRecommendations, summary } = analysisResults;
1168
-
1169
- let report = `
1170
- 🚀 ServiceNow Performance Analysis Report
1171
- ==========================================
1172
-
1173
- 📊 SUMMARY:
1174
- • Critical Issues: ${summary.criticalIssues}
1175
- • Estimated Performance Improvement: ${summary.estimatedImprovementPercent}%
1176
- • Total Recommendations: ${databaseIndexes.length + performanceRecommendations.length}
1177
-
1178
- 🎯 TOP PRIORITY ACTIONS:
1179
- ${summary.recommendedActions.map((action, i) => `${i + 1}. ${action}`).join('\n')}
1180
-
1181
- `;
1182
-
1183
- if (databaseIndexes.length > 0) {
1184
- report += `
1185
- 🗄️ DATABASE INDEX RECOMMENDATIONS:
1186
- ${databaseIndexes.map((idx, i) => `
1187
- ${i + 1}. ${idx.table} - ${idx.fields.join(', ')} [${idx.priority.toUpperCase()}]
1188
- 💡 ${idx.reason}
1189
- 📈 Expected Improvement: ${idx.estimatedImprovement}%
1190
- 💻 SQL: ${idx.createStatement}
1191
- 📊 Impact: ${idx.impactAnalysis.queryImpact.join(', ')}
1192
- 💾 Storage: ${idx.impactAnalysis.storageImpact}
1193
- `).join('')}`;
1194
- }
1195
-
1196
- if (performanceRecommendations.length > 0) {
1197
- report += `
1198
- ⚡ PERFORMANCE RECOMMENDATIONS:
1199
- ${performanceRecommendations.map((rec, i) => `
1200
- ${i + 1}. ${rec.type.replace(/_/g, ' ').toUpperCase()} [${rec.impact.toUpperCase()} IMPACT]
1201
- 📋 ${rec.description}
1202
- 💡 ${rec.recommendation}
1203
- ⏱️ Time Savings: ${rec.estimated_time_savings}
1204
- ${rec.code_example ? `\n 💻 Example:\n ${rec.code_example.split('\n').map(line => ` ${line}`).join('\n')}` : ''}
1205
- `).join('')}`;
1206
- }
1207
-
1208
- report += `
1209
- 🔍 NEXT STEPS:
1210
- 1. Implement critical database indexes first (highest ROI)
1211
- 2. Review and optimize flow scripts for N+1 query patterns
1212
- 3. Consider implementing caching for frequently accessed data
1213
- 4. Monitor performance metrics after implementing changes
1214
- 5. Schedule regular performance reviews for optimal results
1215
-
1216
- ⚠️ IMPORTANT: Test all database changes in a development environment first!
1217
- `;
1218
-
1219
- return report;
1220
- }
1221
- }
1222
-
1223
- export default PerformanceRecommendationsEngine;