claude-flow-novice 2.0.3 → 2.0.4

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 (272) hide show
  1. package/dist/src/cli/commands/guidance.js +487 -668
  2. package/dist/src/cli/commands/index-validate.js +18 -29
  3. package/dist/src/cli/commands/mcp-troubleshoot.js +230 -282
  4. package/dist/src/cli/commands/neural-goal-init.js +92 -125
  5. package/dist/src/cli/commands/swarm-exec.js +317 -393
  6. package/dist/src/cli/commands/swarm.js +1 -1
  7. package/dist/src/cli/commands/validate-framework.js +983 -1100
  8. package/dist/src/cli/commands/validate.js +144 -223
  9. package/dist/src/cli/simple-commands/__tests__/agent.test.js +265 -277
  10. package/dist/src/cli/simple-commands/__tests__/memory.test.js +6 -7
  11. package/dist/src/cli/simple-commands/__tests__/swarm.test.js +373 -356
  12. package/dist/src/cli/simple-commands/__tests__/task.test.js +6 -7
  13. package/dist/src/cli/simple-commands/agent.js +157 -193
  14. package/dist/src/cli/simple-commands/analysis.js +336 -446
  15. package/dist/src/cli/simple-commands/automation-executor.js +1095 -1339
  16. package/dist/src/cli/simple-commands/automation.js +481 -469
  17. package/dist/src/cli/simple-commands/batch-manager.js +261 -313
  18. package/dist/src/cli/simple-commands/claude-telemetry.js +241 -267
  19. package/dist/src/cli/simple-commands/claude-track.js +68 -90
  20. package/dist/src/cli/simple-commands/concurrent-display.js +266 -320
  21. package/dist/src/cli/simple-commands/config.js +245 -290
  22. package/dist/src/cli/simple-commands/coordination.js +182 -234
  23. package/dist/src/cli/simple-commands/enhanced-ui-views.js +812 -615
  24. package/dist/src/cli/simple-commands/enhanced-webui-complete.js +922 -981
  25. package/dist/src/cli/simple-commands/fix-hook-variables.js +274 -294
  26. package/dist/src/cli/simple-commands/github/gh-coordinator.js +378 -457
  27. package/dist/src/cli/simple-commands/github/github-api.js +535 -574
  28. package/dist/src/cli/simple-commands/github/init.js +276 -303
  29. package/dist/src/cli/simple-commands/github.js +222 -247
  30. package/dist/src/cli/simple-commands/goal.js +51 -63
  31. package/dist/src/cli/simple-commands/hive-mind/auto-save-middleware.js +208 -278
  32. package/dist/src/cli/simple-commands/hive-mind/communication.js +601 -696
  33. package/dist/src/cli/simple-commands/hive-mind/core.js +907 -979
  34. package/dist/src/cli/simple-commands/hive-mind/db-optimizer.js +406 -655
  35. package/dist/src/cli/simple-commands/hive-mind/mcp-wrapper.js +1125 -1245
  36. package/dist/src/cli/simple-commands/hive-mind/memory.js +854 -1090
  37. package/dist/src/cli/simple-commands/hive-mind/performance-optimizer.js +459 -574
  38. package/dist/src/cli/simple-commands/hive-mind/performance-test.js +263 -347
  39. package/dist/src/cli/simple-commands/hive-mind/queen.js +727 -768
  40. package/dist/src/cli/simple-commands/hive-mind/session-manager.js +745 -1049
  41. package/dist/src/cli/simple-commands/hive-mind-optimize.js +227 -283
  42. package/dist/src/cli/simple-commands/hive-mind-wizard.js +174 -217
  43. package/dist/src/cli/simple-commands/hive-mind.js +1842 -2283
  44. package/dist/src/cli/simple-commands/hive.js +90 -79
  45. package/dist/src/cli/simple-commands/hook-safety.js +431 -521
  46. package/dist/src/cli/simple-commands/hooks/session-start-soul.js +203 -254
  47. package/dist/src/cli/simple-commands/hooks.js +1064 -1204
  48. package/dist/src/cli/simple-commands/init/agent-copier.js +294 -319
  49. package/dist/src/cli/simple-commands/init/batch-init.js +496 -562
  50. package/dist/src/cli/simple-commands/init/claude-commands/claude-flow-commands.js +13 -19
  51. package/dist/src/cli/simple-commands/init/claude-commands/optimized-claude-flow-commands.js +13 -19
  52. package/dist/src/cli/simple-commands/init/claude-commands/optimized-slash-commands.js +61 -88
  53. package/dist/src/cli/simple-commands/init/claude-commands/optimized-sparc-commands.js +125 -150
  54. package/dist/src/cli/simple-commands/init/claude-commands/slash-commands.js +42 -49
  55. package/dist/src/cli/simple-commands/init/claude-commands/sparc-commands.js +43 -61
  56. package/dist/src/cli/simple-commands/init/copy-revised-templates.js +141 -147
  57. package/dist/src/cli/simple-commands/init/executable-wrapper.js +31 -44
  58. package/dist/src/cli/simple-commands/init/gitignore-updater.js +64 -90
  59. package/dist/src/cli/simple-commands/init/help.js +104 -107
  60. package/dist/src/cli/simple-commands/init/hive-mind-init.js +509 -528
  61. package/dist/src/cli/simple-commands/init/index.js +1510 -1759
  62. package/dist/src/cli/simple-commands/init/performance-monitor.js +234 -317
  63. package/dist/src/cli/simple-commands/init/rollback/backup-manager.js +441 -504
  64. package/dist/src/cli/simple-commands/init/rollback/index.js +289 -364
  65. package/dist/src/cli/simple-commands/init/rollback/recovery-manager.js +652 -728
  66. package/dist/src/cli/simple-commands/init/rollback/rollback-executor.js +416 -481
  67. package/dist/src/cli/simple-commands/init/rollback/state-tracker.js +369 -448
  68. package/dist/src/cli/simple-commands/init/sparc/roo-readme.js +1 -2
  69. package/dist/src/cli/simple-commands/init/sparc/roomodes-config.js +122 -99
  70. package/dist/src/cli/simple-commands/init/sparc/workflows.js +32 -37
  71. package/dist/src/cli/simple-commands/init/sparc-structure.js +55 -62
  72. package/dist/src/cli/simple-commands/init/template-copier.js +421 -533
  73. package/dist/src/cli/simple-commands/init/templates/coordination-md.js +3 -6
  74. package/dist/src/cli/simple-commands/init/templates/enhanced-templates.js +344 -318
  75. package/dist/src/cli/simple-commands/init/templates/github-safe-enhanced.js +173 -218
  76. package/dist/src/cli/simple-commands/init/templates/github-safe.js +65 -75
  77. package/dist/src/cli/simple-commands/init/templates/memory-bank-md.js +3 -6
  78. package/dist/src/cli/simple-commands/init/templates/readme-files.js +2 -4
  79. package/dist/src/cli/simple-commands/init/templates/safe-hook-patterns.js +187 -230
  80. package/dist/src/cli/simple-commands/init/templates/sparc-modes.js +53 -80
  81. package/dist/src/cli/simple-commands/init/templates/verification-claude-md.js +101 -85
  82. package/dist/src/cli/simple-commands/init/validation/config-validator.js +283 -330
  83. package/dist/src/cli/simple-commands/init/validation/health-checker.js +495 -561
  84. package/dist/src/cli/simple-commands/init/validation/index.js +302 -358
  85. package/dist/src/cli/simple-commands/init/validation/mode-validator.js +308 -359
  86. package/dist/src/cli/simple-commands/init/validation/post-init-validator.js +389 -366
  87. package/dist/src/cli/simple-commands/init/validation/pre-init-validator.js +270 -268
  88. package/dist/src/cli/simple-commands/init/validation/test-runner.js +427 -447
  89. package/dist/src/cli/simple-commands/init.js +1 -2
  90. package/dist/src/cli/simple-commands/mcp-health.js +131 -158
  91. package/dist/src/cli/simple-commands/mcp-integration-layer.js +533 -634
  92. package/dist/src/cli/simple-commands/mcp.js +345 -400
  93. package/dist/src/cli/simple-commands/memory-consolidation.js +426 -537
  94. package/dist/src/cli/simple-commands/memory.js +247 -311
  95. package/dist/src/cli/simple-commands/migrate-hooks.js +39 -46
  96. package/dist/src/cli/simple-commands/monitor.js +294 -363
  97. package/dist/src/cli/simple-commands/neural.js +51 -65
  98. package/dist/src/cli/simple-commands/pair-autofix-only.js +538 -662
  99. package/dist/src/cli/simple-commands/pair-basic.js +528 -656
  100. package/dist/src/cli/simple-commands/pair-old.js +430 -543
  101. package/dist/src/cli/simple-commands/pair-working.js +615 -751
  102. package/dist/src/cli/simple-commands/pair.js +615 -751
  103. package/dist/src/cli/simple-commands/performance-hooks.js +83 -111
  104. package/dist/src/cli/simple-commands/performance-metrics.js +348 -433
  105. package/dist/src/cli/simple-commands/process-ui-enhanced.js +708 -787
  106. package/dist/src/cli/simple-commands/process-ui.js +230 -254
  107. package/dist/src/cli/simple-commands/realtime-update-system.js +525 -611
  108. package/dist/src/cli/simple-commands/sparc/architecture.js +1704 -1530
  109. package/dist/src/cli/simple-commands/sparc/commands.js +438 -516
  110. package/dist/src/cli/simple-commands/sparc/completion.js +1224 -1481
  111. package/dist/src/cli/simple-commands/sparc/coordinator.js +913 -978
  112. package/dist/src/cli/simple-commands/sparc/index.js +241 -298
  113. package/dist/src/cli/simple-commands/sparc/phase-base.js +314 -390
  114. package/dist/src/cli/simple-commands/sparc/pseudocode.js +965 -869
  115. package/dist/src/cli/simple-commands/sparc/refinement.js +980 -1273
  116. package/dist/src/cli/simple-commands/sparc/specification.js +559 -645
  117. package/dist/src/cli/simple-commands/sparc-modes/architect.js +1 -1
  118. package/dist/src/cli/simple-commands/sparc-modes/ask.js +1 -1
  119. package/dist/src/cli/simple-commands/sparc-modes/code.js +1 -1
  120. package/dist/src/cli/simple-commands/sparc-modes/debug.js +1 -1
  121. package/dist/src/cli/simple-commands/sparc-modes/devops.js +1 -1
  122. package/dist/src/cli/simple-commands/sparc-modes/docs-writer.js +1 -1
  123. package/dist/src/cli/simple-commands/sparc-modes/generic.js +1 -1
  124. package/dist/src/cli/simple-commands/sparc-modes/index.js +47 -55
  125. package/dist/src/cli/simple-commands/sparc-modes/integration.js +1 -1
  126. package/dist/src/cli/simple-commands/sparc-modes/mcp.js +1 -1
  127. package/dist/src/cli/simple-commands/sparc-modes/monitoring.js +1 -1
  128. package/dist/src/cli/simple-commands/sparc-modes/optimization.js +1 -1
  129. package/dist/src/cli/simple-commands/sparc-modes/security-review.js +1 -1
  130. package/dist/src/cli/simple-commands/sparc-modes/sparc-orchestrator.js +1 -1
  131. package/dist/src/cli/simple-commands/sparc-modes/spec-pseudocode.js +1 -1
  132. package/dist/src/cli/simple-commands/sparc-modes/supabase-admin.js +1 -1
  133. package/dist/src/cli/simple-commands/sparc-modes/swarm.js +101 -87
  134. package/dist/src/cli/simple-commands/sparc-modes/tdd.js +1 -1
  135. package/dist/src/cli/simple-commands/sparc-modes/tutorial.js +1 -1
  136. package/dist/src/cli/simple-commands/sparc.js +465 -493
  137. package/dist/src/cli/simple-commands/start-ui.js +108 -132
  138. package/dist/src/cli/simple-commands/start-wrapper.js +240 -268
  139. package/dist/src/cli/simple-commands/start.js +1 -1
  140. package/dist/src/cli/simple-commands/status.js +254 -275
  141. package/dist/src/cli/simple-commands/stream-chain-clean.js +128 -171
  142. package/dist/src/cli/simple-commands/stream-chain-fixed.js +61 -82
  143. package/dist/src/cli/simple-commands/stream-chain-real.js +267 -331
  144. package/dist/src/cli/simple-commands/stream-chain-working.js +211 -263
  145. package/dist/src/cli/simple-commands/stream-chain.js +260 -318
  146. package/dist/src/cli/simple-commands/stream-processor.js +290 -315
  147. package/dist/src/cli/simple-commands/swarm-executor.js +189 -222
  148. package/dist/src/cli/simple-commands/swarm-metrics-integration.js +208 -300
  149. package/dist/src/cli/simple-commands/swarm-ui.js +623 -703
  150. package/dist/src/cli/simple-commands/swarm-webui-integration.js +258 -286
  151. package/dist/src/cli/simple-commands/swarm.js +887 -1082
  152. package/dist/src/cli/simple-commands/task.js +161 -206
  153. package/dist/src/cli/simple-commands/timestamp-fix.js +59 -89
  154. package/dist/src/cli/simple-commands/token-tracker.js +258 -316
  155. package/dist/src/cli/simple-commands/tool-execution-framework.js +433 -519
  156. package/dist/src/cli/simple-commands/train-and-stream.js +275 -331
  157. package/dist/src/cli/simple-commands/training-pipeline.js +619 -725
  158. package/dist/src/cli/simple-commands/training.js +170 -227
  159. package/dist/src/cli/simple-commands/verification-hooks.js +261 -284
  160. package/dist/src/cli/simple-commands/verification-integration.js +389 -417
  161. package/dist/src/cli/simple-commands/verification-training-integration.js +486 -606
  162. package/dist/src/cli/simple-commands/verification.js +493 -513
  163. package/dist/src/cli/simple-commands/web-server.js +766 -836
  164. package/dist/src/cli/simple-commands/webui-validator.js +106 -124
  165. package/dist/src/coordination/event-bus/demo-wasm-integration.js +212 -251
  166. package/dist/src/coordination/event-bus/qe-event-bus.js +608 -748
  167. package/dist/src/coordination/event-bus/qe-event-bus.test.js +379 -454
  168. package/dist/src/coordination/iteration-tracker.js +363 -454
  169. package/dist/src/enterprise/analytics-manager.js +1135 -0
  170. package/dist/src/enterprise/audit-manager.js +1115 -0
  171. package/dist/src/enterprise/cloud-manager.js +891 -0
  172. package/dist/src/enterprise/deployment-manager.js +966 -0
  173. package/dist/src/enterprise/index.js +6 -0
  174. package/dist/src/enterprise/project-manager.js +584 -0
  175. package/dist/src/enterprise/security-manager.js +991 -0
  176. package/dist/src/index.js +1 -1
  177. package/dist/src/mcp/DEPRECATED.js +46 -60
  178. package/dist/src/mcp/fixes/mcp-error-fixes.js +115 -134
  179. package/dist/src/mcp/implementations/agent-tracker.js +114 -128
  180. package/dist/src/mcp/implementations/daa-tools.js +292 -350
  181. package/dist/src/mcp/implementations/workflow-tools.js +329 -361
  182. package/dist/src/mcp/mcp-config-manager.js +1183 -1331
  183. package/dist/src/mcp/mcp-server-novice-simplified.js +11 -17
  184. package/dist/src/mcp/mcp-server-novice.js +11 -17
  185. package/dist/src/mcp/mcp-server-sdk.js +11 -17
  186. package/dist/src/mcp/mcp-server.js +1620 -1484
  187. package/dist/src/mcp/ruv-swarm-wrapper.js +209 -239
  188. package/dist/src/memory/advanced-serializer.js +609 -589
  189. package/dist/src/memory/enhanced-examples.js +220 -305
  190. package/dist/src/memory/enhanced-memory.js +295 -336
  191. package/dist/src/memory/enhanced-session-serializer.js +408 -492
  192. package/dist/src/memory/fallback-memory-system.js +900 -1021
  193. package/dist/src/memory/fallback-store.js +93 -131
  194. package/dist/src/memory/high-performance-serialization.js +592 -730
  195. package/dist/src/memory/in-memory-store.js +161 -213
  196. package/dist/src/memory/index.js +123 -157
  197. package/dist/src/memory/lock-free-structures.js +578 -764
  198. package/dist/src/memory/memory-mapped-persistence.js +585 -766
  199. package/dist/src/memory/memory-pressure-manager.js +569 -707
  200. package/dist/src/memory/migration.js +358 -445
  201. package/dist/src/memory/shared-memory.js +641 -768
  202. package/dist/src/memory/sqlite-store.js +245 -325
  203. package/dist/src/memory/sqlite-wrapper.js +122 -151
  204. package/dist/src/memory/swarm-memory.js +470 -603
  205. package/dist/src/memory/test-example.js +126 -134
  206. package/dist/src/memory/ultra-fast-memory-store.js +622 -821
  207. package/dist/src/memory/unified-memory-manager.js +356 -437
  208. package/dist/src/migration/index.js +92 -0
  209. package/dist/src/migration/logger.js +121 -0
  210. package/dist/src/migration/migration-analyzer.js +268 -0
  211. package/dist/src/migration/migration-runner.js +522 -0
  212. package/dist/src/migration/migration-validator.js +285 -0
  213. package/dist/src/migration/progress-reporter.js +150 -0
  214. package/dist/src/migration/rollback-manager.js +321 -0
  215. package/dist/src/migration/tests/migration-system.test.js +7 -0
  216. package/dist/src/migration/types.js +3 -0
  217. package/dist/src/swarm/CodeRefactoringSwarm.js +777 -952
  218. package/dist/src/swarm/__tests__/integration.test.js +227 -0
  219. package/dist/src/swarm/__tests__/prompt-copier.test.js +344 -0
  220. package/dist/src/swarm/advanced-orchestrator.js +1095 -0
  221. package/dist/src/swarm/claude-code-interface.js +961 -0
  222. package/dist/src/swarm/claude-flow-executor.js +229 -0
  223. package/dist/src/swarm/consensus-coordinator.js +475 -0
  224. package/dist/src/swarm/coordinator.js +2993 -0
  225. package/dist/src/swarm/direct-executor.js +1180 -0
  226. package/dist/src/swarm/error-recovery/advanced-error-detection.js +691 -0
  227. package/dist/src/swarm/error-recovery/automated-recovery-workflows.js +998 -0
  228. package/dist/src/swarm/error-recovery/error-recovery-coordinator.js +1197 -0
  229. package/dist/src/swarm/error-recovery/recovery-monitoring.js +772 -0
  230. package/dist/src/swarm/error-recovery/resilience-architecture.js +714 -0
  231. package/dist/src/swarm/error-recovery/self-healing-mechanisms.js +1319 -0
  232. package/dist/src/swarm/error-recovery/test-error-recovery-effectiveness.js +808 -0
  233. package/dist/src/swarm/executor-v2.js +322 -0
  234. package/dist/src/swarm/executor.js +815 -0
  235. package/dist/src/swarm/hive-mind-integration.js +703 -0
  236. package/dist/src/swarm/index.js +41 -0
  237. package/dist/src/swarm/json-output-aggregator.js +267 -0
  238. package/dist/src/swarm/large-scale-coordinator.js +542 -0
  239. package/dist/src/swarm/mcp-integration-wrapper.js +628 -0
  240. package/dist/src/swarm/memory.js +1117 -0
  241. package/dist/src/swarm/optimizations/__tests__/optimization.test.js +348 -0
  242. package/dist/src/swarm/optimizations/async-file-manager.js +285 -0
  243. package/dist/src/swarm/optimizations/circular-buffer.js +162 -0
  244. package/dist/src/swarm/optimizations/connection-pool.js +244 -0
  245. package/dist/src/swarm/optimizations/index.js +28 -0
  246. package/dist/src/swarm/optimizations/optimized-executor.js +320 -0
  247. package/dist/src/swarm/optimizations/ttl-map.js +234 -0
  248. package/dist/src/swarm/prompt-cli.js +200 -0
  249. package/dist/src/swarm/prompt-copier-enhanced.js +202 -0
  250. package/dist/src/swarm/prompt-copier.js +381 -0
  251. package/dist/src/swarm/prompt-manager.js +295 -0
  252. package/dist/src/swarm/prompt-utils.js +310 -0
  253. package/dist/src/swarm/result-aggregator.js +718 -0
  254. package/dist/src/swarm/sparc-executor.js +1568 -0
  255. package/dist/src/swarm/strategies/auto.js +758 -0
  256. package/dist/src/swarm/strategies/base.js +128 -0
  257. package/dist/src/swarm/strategies/research.js +914 -0
  258. package/dist/src/swarm/strategies/strategy-metrics-patch.js +2 -0
  259. package/dist/src/swarm/types.js +52 -0
  260. package/dist/src/swarm/workers/copy-worker.js +56 -0
  261. package/dist/src/utils/__tests__/github-cli-safety-wrapper.test.js +332 -400
  262. package/dist/src/utils/github-cli-safe.js +56 -64
  263. package/dist/src/utils/github-cli-safety-wrapper.js +451 -546
  264. package/dist/src/utils/npx-isolated-cache.js +104 -119
  265. package/dist/src/utils/preference-manager.js +622 -652
  266. package/dist/src/utils/timezone-utils.js +86 -105
  267. package/dist/src/validators/epic-config-schema.js +214 -0
  268. package/dist/src/validators/index.js +10 -0
  269. package/dist/src/validators/swarm-init-validator.js +259 -0
  270. package/dist/src/validators/todowrite-batching-validator.js +215 -0
  271. package/dist/src/validators/todowrite-integration.js +187 -0
  272. package/package.json +2 -2
@@ -0,0 +1,1135 @@
1
+ function _define_property(obj, key, value) {
2
+ if (key in obj) {
3
+ Object.defineProperty(obj, key, {
4
+ value: value,
5
+ enumerable: true,
6
+ configurable: true,
7
+ writable: true
8
+ });
9
+ } else {
10
+ obj[key] = value;
11
+ }
12
+ return obj;
13
+ }
14
+ import { EventEmitter } from "events";
15
+ import { writeFile, readFile, mkdir, readdir } from "node:fs/promises";
16
+ import { join } from "path";
17
+ import { Logger } from "../core/logger.js";
18
+ import { ConfigManager } from "../core/config.js";
19
+ export class AnalyticsManager extends EventEmitter {
20
+ async initialize() {
21
+ try {
22
+ await mkdir(this.analyticsPath, {
23
+ recursive: true
24
+ });
25
+ await mkdir(join(this.analyticsPath, 'metrics'), {
26
+ recursive: true
27
+ });
28
+ await mkdir(join(this.analyticsPath, 'dashboards'), {
29
+ recursive: true
30
+ });
31
+ await mkdir(join(this.analyticsPath, 'insights'), {
32
+ recursive: true
33
+ });
34
+ await mkdir(join(this.analyticsPath, 'models'), {
35
+ recursive: true
36
+ });
37
+ await mkdir(join(this.analyticsPath, 'reports'), {
38
+ recursive: true
39
+ });
40
+ await this.loadConfigurations();
41
+ await this.initializeDefaultDashboards();
42
+ await this.startMetricsCollection();
43
+ this.logger.info('Analytics Manager initialized successfully');
44
+ } catch (error) {
45
+ this.logger.error('Failed to initialize Analytics Manager', {
46
+ error
47
+ });
48
+ throw error;
49
+ }
50
+ }
51
+ async recordMetric(metric) {
52
+ const fullMetric = {
53
+ id: `metric-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
54
+ timestamp: new Date(),
55
+ ...metric
56
+ };
57
+ const key = `${metric.category}-${metric.name}`;
58
+ if (!this.metrics.has(key)) {
59
+ this.metrics.set(key, []);
60
+ }
61
+ const metricArray = this.metrics.get(key);
62
+ metricArray.push(fullMetric);
63
+ // Keep only recent metrics in memory (configurable retention)
64
+ const retentionPeriod = 24 * 60 * 60 * 1000; // 24 hours
65
+ const cutoff = Date.now() - retentionPeriod;
66
+ const filteredMetrics = metricArray.filter((m)=>m.timestamp.getTime() > cutoff);
67
+ this.metrics.set(key, filteredMetrics);
68
+ // Persist to disk for longer-term storage
69
+ await this.persistMetric(fullMetric);
70
+ this.emit('metric:recorded', fullMetric);
71
+ // Check for anomalies and generate insights
72
+ await this.checkForAnomalies(key, fullMetric);
73
+ }
74
+ async queryMetrics(query) {
75
+ const results = {};
76
+ for (const metricName of query.metrics){
77
+ const key = metricName.includes('-') ? metricName : `*-${metricName}`;
78
+ const matchingKeys = Array.from(this.metrics.keys()).filter((k)=>key === '*' || k.includes(key.replace('*-', '')) || k === key);
79
+ let allMetrics = [];
80
+ for (const k of matchingKeys){
81
+ const keyMetrics = this.metrics.get(k) || [];
82
+ allMetrics.push(...keyMetrics);
83
+ }
84
+ // Filter by time range
85
+ allMetrics = allMetrics.filter((m)=>m.timestamp >= query.timeRange.start && m.timestamp <= query.timeRange.end);
86
+ // Apply filters
87
+ if (query.filters) {
88
+ for (const [field, value] of Object.entries(query.filters)){
89
+ allMetrics = allMetrics.filter((m)=>{
90
+ if (field === 'tags') {
91
+ return Object.entries(value).every(([k, v])=>m.tags[k] === v);
92
+ }
93
+ return m[field] === value;
94
+ });
95
+ }
96
+ }
97
+ // Group by if specified
98
+ if (query.groupBy && query.groupBy.length > 0) {
99
+ const grouped = this.groupMetrics(allMetrics, query.groupBy);
100
+ for (const [group, metrics] of Object.entries(grouped)){
101
+ const aggregated = this.aggregateMetrics(metrics, query.aggregation || 'avg');
102
+ results[`${metricName}-${group}`] = aggregated;
103
+ }
104
+ } else {
105
+ const aggregated = this.aggregateMetrics(allMetrics, query.aggregation || 'avg');
106
+ results[metricName] = aggregated;
107
+ }
108
+ }
109
+ return results;
110
+ }
111
+ async createDashboard(dashboardData) {
112
+ const dashboard = {
113
+ id: `dashboard-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
114
+ name: dashboardData.name,
115
+ description: dashboardData.description,
116
+ type: dashboardData.type,
117
+ widgets: dashboardData.widgets.map((widget, index)=>({
118
+ id: `widget-${Date.now()}-${index}`,
119
+ ...widget
120
+ })),
121
+ layout: {
122
+ columns: 12,
123
+ rows: 8,
124
+ grid: true,
125
+ responsive: true
126
+ },
127
+ permissions: {
128
+ viewers: [],
129
+ editors: [],
130
+ public: false,
131
+ ...dashboardData.permissions
132
+ },
133
+ schedule: {
134
+ autoRefresh: true,
135
+ refreshInterval: 30
136
+ },
137
+ filters: [],
138
+ createdAt: new Date(),
139
+ updatedAt: new Date(),
140
+ createdBy: 'system'
141
+ };
142
+ this.dashboards.set(dashboard.id, dashboard);
143
+ await this.saveDashboard(dashboard);
144
+ this.emit('dashboard:created', dashboard);
145
+ this.logger.info(`Dashboard created: ${dashboard.name} (${dashboard.id})`);
146
+ return dashboard;
147
+ }
148
+ async generateInsights(scope = {}) {
149
+ const insights = [];
150
+ // Default time range: last 24 hours
151
+ const timeRange = scope.timeRange || {
152
+ start: new Date(Date.now() - 24 * 60 * 60 * 1000),
153
+ end: new Date()
154
+ };
155
+ // Anomaly detection
156
+ const anomalies = await this.detectAnomalies(timeRange, scope.metrics);
157
+ insights.push(...anomalies);
158
+ // Trend analysis
159
+ const trends = await this.analyzeTrends(timeRange, scope.metrics);
160
+ insights.push(...trends);
161
+ // Performance insights
162
+ const performance = await this.analyzePerformance(timeRange);
163
+ insights.push(...performance);
164
+ // Usage insights
165
+ const usage = await this.analyzeUsage(timeRange);
166
+ insights.push(...usage);
167
+ // Cost optimization insights
168
+ const costOptimizations = await this.analyzeCostOptimization(timeRange);
169
+ insights.push(...costOptimizations);
170
+ // Store insights
171
+ for (const insight of insights){
172
+ this.insights.set(insight.id, insight);
173
+ await this.saveInsight(insight);
174
+ }
175
+ this.emit('insights:generated', {
176
+ insights,
177
+ scope
178
+ });
179
+ this.logger.info(`Generated ${insights.length} insights`);
180
+ return insights;
181
+ }
182
+ async trainPredictiveModel(modelConfig) {
183
+ const model = {
184
+ id: `model-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
185
+ name: modelConfig.name,
186
+ description: modelConfig.description,
187
+ type: modelConfig.type,
188
+ algorithm: modelConfig.algorithm,
189
+ features: modelConfig.features,
190
+ target: modelConfig.target,
191
+ accuracy: 0,
192
+ confidence: 0,
193
+ trainedAt: new Date(),
194
+ trainingData: {
195
+ samples: 0,
196
+ features: modelConfig.features.length,
197
+ timeRange: modelConfig.trainingPeriod
198
+ },
199
+ performance: {
200
+ precision: 0,
201
+ recall: 0,
202
+ f1Score: 0
203
+ },
204
+ predictions: [],
205
+ status: 'training'
206
+ };
207
+ try {
208
+ // Collect training data
209
+ const trainingData = await this.collectTrainingData(model);
210
+ // Train the model (simplified implementation)
211
+ const trained = await this.executeModelTraining(model, trainingData);
212
+ Object.assign(model, trained);
213
+ model.status = 'ready';
214
+ this.models.set(model.id, model);
215
+ await this.saveModel(model);
216
+ this.emit('model:trained', model);
217
+ this.logger.info(`Predictive model trained: ${model.name} (${model.id}) - Accuracy: ${model.accuracy}%`);
218
+ } catch (error) {
219
+ model.status = 'error';
220
+ this.logger.error(`Model training failed: ${model.name}`, {
221
+ error
222
+ });
223
+ throw error;
224
+ }
225
+ return model;
226
+ }
227
+ async makePrediction(modelId, input) {
228
+ const model = this.models.get(modelId);
229
+ if (!model) {
230
+ throw new Error(`Model not found: ${modelId}`);
231
+ }
232
+ if (model.status !== 'ready') {
233
+ throw new Error(`Model is not ready for predictions: ${model.status}`);
234
+ }
235
+ // Simple prediction logic (would be replaced with actual ML inference)
236
+ const prediction = await this.executePrediction(model, input);
237
+ const result = {
238
+ id: `prediction-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
239
+ modelId,
240
+ input,
241
+ prediction: prediction.value,
242
+ confidence: prediction.confidence,
243
+ timestamp: new Date()
244
+ };
245
+ model.predictions.push(result);
246
+ model.lastPrediction = new Date();
247
+ await this.saveModel(model);
248
+ this.emit('prediction:made', {
249
+ model,
250
+ result
251
+ });
252
+ this.logger.debug(`Prediction made: ${modelId} - ${JSON.stringify(result.prediction)}`);
253
+ return result;
254
+ }
255
+ async getPerformanceMetrics(timeRange) {
256
+ const range = timeRange || {
257
+ start: new Date(Date.now() - 60 * 60 * 1000),
258
+ end: new Date()
259
+ };
260
+ const systemMetrics = await this.queryMetrics({
261
+ metrics: [
262
+ 'cpu-usage',
263
+ 'memory-usage',
264
+ 'disk-usage',
265
+ 'network-io'
266
+ ],
267
+ timeRange: range,
268
+ aggregation: 'avg'
269
+ });
270
+ const appMetrics = await this.queryMetrics({
271
+ metrics: [
272
+ 'response-time',
273
+ 'request-rate',
274
+ 'error-rate',
275
+ 'uptime'
276
+ ],
277
+ timeRange: range,
278
+ aggregation: 'avg'
279
+ });
280
+ const dbMetrics = await this.queryMetrics({
281
+ metrics: [
282
+ 'db-connections',
283
+ 'query-time',
284
+ 'db-size'
285
+ ],
286
+ timeRange: range,
287
+ aggregation: 'avg'
288
+ });
289
+ // Construct performance metrics (simplified)
290
+ return {
291
+ system: {
292
+ cpu: {
293
+ usage: this.getLatestValue(systemMetrics['cpu-usage']) || 0,
294
+ cores: 8,
295
+ loadAverage: [
296
+ 1.2,
297
+ 1.5,
298
+ 1.8
299
+ ]
300
+ },
301
+ memory: {
302
+ used: this.getLatestValue(systemMetrics['memory-usage']) || 0,
303
+ free: 4000000000,
304
+ total: 8000000000,
305
+ usage: 50
306
+ },
307
+ disk: {
308
+ used: this.getLatestValue(systemMetrics['disk-usage']) || 0,
309
+ free: 100000000000,
310
+ total: 500000000000,
311
+ usage: 20,
312
+ iops: 1000
313
+ },
314
+ network: {
315
+ bytesIn: 1000000,
316
+ bytesOut: 2000000,
317
+ packetsIn: 5000,
318
+ packetsOut: 6000,
319
+ errors: 5
320
+ }
321
+ },
322
+ application: {
323
+ responseTime: {
324
+ avg: this.getLatestValue(appMetrics['response-time']) || 0,
325
+ p50: 150,
326
+ p95: 500,
327
+ p99: 1000
328
+ },
329
+ throughput: {
330
+ requestsPerSecond: this.getLatestValue(appMetrics['request-rate']) || 0,
331
+ transactionsPerSecond: 50
332
+ },
333
+ errors: {
334
+ rate: this.getLatestValue(appMetrics['error-rate']) || 0,
335
+ count: 10,
336
+ types: {
337
+ '500': 5,
338
+ '404': 3,
339
+ '400': 2
340
+ }
341
+ },
342
+ availability: {
343
+ uptime: this.getLatestValue(appMetrics['uptime']) || 0,
344
+ sla: 99.9,
345
+ incidents: 2
346
+ }
347
+ },
348
+ database: {
349
+ connections: {
350
+ active: 25,
351
+ idle: 75,
352
+ max: 100
353
+ },
354
+ queries: {
355
+ avgExecutionTime: this.getLatestValue(dbMetrics['query-time']) || 0,
356
+ slowQueries: 5,
357
+ deadlocks: 0
358
+ },
359
+ storage: {
360
+ size: this.getLatestValue(dbMetrics['db-size']) || 0,
361
+ growth: 1000000,
362
+ fragmentation: 5
363
+ }
364
+ },
365
+ infrastructure: {
366
+ containers: {
367
+ running: 12,
368
+ stopped: 2,
369
+ restarts: 3
370
+ },
371
+ services: {
372
+ healthy: 15,
373
+ unhealthy: 1,
374
+ degraded: 0
375
+ }
376
+ }
377
+ };
378
+ }
379
+ async getUsageMetrics(timeRange) {
380
+ const range = timeRange || {
381
+ start: new Date(Date.now() - 24 * 60 * 60 * 1000),
382
+ end: new Date()
383
+ };
384
+ const usageData = await this.queryMetrics({
385
+ metrics: [
386
+ 'active-users',
387
+ 'sessions',
388
+ 'api-calls',
389
+ 'feature-usage'
390
+ ],
391
+ timeRange: range,
392
+ aggregation: 'sum'
393
+ });
394
+ return {
395
+ users: {
396
+ total: 10000,
397
+ active: this.getLatestValue(usageData['active-users']) || 0,
398
+ new: 50,
399
+ returning: 1500,
400
+ churn: 25
401
+ },
402
+ sessions: {
403
+ total: this.getLatestValue(usageData['sessions']) || 0,
404
+ duration: {
405
+ avg: 15 * 60,
406
+ median: 12 * 60
407
+ },
408
+ bounceRate: 25,
409
+ pagesPerSession: 4.5
410
+ },
411
+ features: {
412
+ adoption: {
413
+ dashboard: {
414
+ users: 800,
415
+ usage: 5000,
416
+ retention: 85
417
+ },
418
+ reports: {
419
+ users: 600,
420
+ usage: 2000,
421
+ retention: 70
422
+ },
423
+ analytics: {
424
+ users: 400,
425
+ usage: 1500,
426
+ retention: 60
427
+ }
428
+ },
429
+ mostUsed: [
430
+ 'dashboard',
431
+ 'reports',
432
+ 'search'
433
+ ],
434
+ leastUsed: [
435
+ 'advanced-filters',
436
+ 'export',
437
+ 'integrations'
438
+ ]
439
+ },
440
+ api: {
441
+ calls: this.getLatestValue(usageData['api-calls']) || 0,
442
+ uniqueConsumers: 150,
443
+ avgResponseTime: 250,
444
+ errorRate: 2.5,
445
+ rateLimits: {
446
+ hit: 5,
447
+ consumed: 75
448
+ }
449
+ },
450
+ content: {
451
+ created: 100,
452
+ modified: 250,
453
+ deleted: 25,
454
+ views: 5000
455
+ }
456
+ };
457
+ }
458
+ async getBusinessMetrics(timeRange) {
459
+ // This would integrate with business systems (CRM, billing, etc.)
460
+ return {
461
+ revenue: {
462
+ total: 1000000,
463
+ recurring: 800000,
464
+ growth: 15,
465
+ arpu: 100,
466
+ ltv: 2400
467
+ },
468
+ customers: {
469
+ total: 500,
470
+ new: 25,
471
+ retained: 450,
472
+ churned: 10,
473
+ satisfaction: 4.2
474
+ },
475
+ conversion: {
476
+ leads: 1000,
477
+ qualified: 400,
478
+ opportunities: 200,
479
+ closed: 50,
480
+ rate: 5
481
+ },
482
+ support: {
483
+ tickets: 150,
484
+ resolved: 140,
485
+ avgResolutionTime: 4 * 60 * 60,
486
+ satisfaction: 4.5
487
+ }
488
+ };
489
+ }
490
+ // Private helper methods
491
+ getDefaultConfiguration() {
492
+ return {
493
+ collection: {
494
+ enabled: true,
495
+ samplingRate: 1.0,
496
+ batchSize: 1000,
497
+ flushInterval: 60000
498
+ },
499
+ storage: {
500
+ retention: {
501
+ raw: '7d',
502
+ aggregated: '90d',
503
+ summary: '1y'
504
+ },
505
+ compression: true,
506
+ encryption: false
507
+ },
508
+ processing: {
509
+ realTime: true,
510
+ batchProcessing: true,
511
+ aggregationIntervals: [
512
+ '1m',
513
+ '5m',
514
+ '1h',
515
+ '1d'
516
+ ]
517
+ },
518
+ alerts: {
519
+ enabled: true,
520
+ channels: [
521
+ 'email',
522
+ 'slack'
523
+ ],
524
+ escalation: {
525
+ levels: 3,
526
+ intervals: [
527
+ 5,
528
+ 15,
529
+ 30
530
+ ]
531
+ }
532
+ },
533
+ privacy: {
534
+ anonymization: true,
535
+ gdprCompliant: true,
536
+ dataMinimization: true
537
+ },
538
+ integrations: {}
539
+ };
540
+ }
541
+ async loadConfigurations() {
542
+ try {
543
+ // Load dashboards
544
+ const dashboardFiles = await readdir(join(this.analyticsPath, 'dashboards'));
545
+ for (const file of dashboardFiles.filter((f)=>f.endsWith('.json'))){
546
+ const content = await readFile(join(this.analyticsPath, 'dashboards', file), 'utf-8');
547
+ const dashboard = JSON.parse(content);
548
+ this.dashboards.set(dashboard.id, dashboard);
549
+ }
550
+ // Load insights
551
+ const insightFiles = await readdir(join(this.analyticsPath, 'insights'));
552
+ for (const file of insightFiles.filter((f)=>f.endsWith('.json'))){
553
+ const content = await readFile(join(this.analyticsPath, 'insights', file), 'utf-8');
554
+ const insight = JSON.parse(content);
555
+ this.insights.set(insight.id, insight);
556
+ }
557
+ // Load models
558
+ const modelFiles = await readdir(join(this.analyticsPath, 'models'));
559
+ for (const file of modelFiles.filter((f)=>f.endsWith('.json'))){
560
+ const content = await readFile(join(this.analyticsPath, 'models', file), 'utf-8');
561
+ const model = JSON.parse(content);
562
+ this.models.set(model.id, model);
563
+ }
564
+ this.logger.info(`Loaded ${this.dashboards.size} dashboards, ${this.insights.size} insights, ${this.models.size} models`);
565
+ } catch (error) {
566
+ this.logger.warn('Failed to load some analytics configurations', {
567
+ error
568
+ });
569
+ }
570
+ }
571
+ async initializeDefaultDashboards() {
572
+ const defaultDashboards = [
573
+ {
574
+ name: 'System Performance',
575
+ description: 'Real-time system performance metrics',
576
+ type: 'operational',
577
+ widgets: [
578
+ {
579
+ title: 'CPU Usage',
580
+ type: 'gauge',
581
+ size: 'medium',
582
+ position: {
583
+ x: 0,
584
+ y: 0,
585
+ width: 6,
586
+ height: 3
587
+ },
588
+ dataSource: {
589
+ query: 'cpu-usage',
590
+ metrics: [
591
+ 'cpu-usage'
592
+ ],
593
+ aggregation: 'avg',
594
+ timeRange: '1h',
595
+ groupBy: []
596
+ },
597
+ visualization: {
598
+ chartType: 'gauge',
599
+ options: {
600
+ max: 100,
601
+ unit: '%'
602
+ },
603
+ thresholds: {
604
+ warning: 70,
605
+ critical: 90
606
+ }
607
+ },
608
+ alerts: {
609
+ enabled: true,
610
+ conditions: []
611
+ }
612
+ },
613
+ {
614
+ title: 'Memory Usage',
615
+ type: 'gauge',
616
+ size: 'medium',
617
+ position: {
618
+ x: 6,
619
+ y: 0,
620
+ width: 6,
621
+ height: 3
622
+ },
623
+ dataSource: {
624
+ query: 'memory-usage',
625
+ metrics: [
626
+ 'memory-usage'
627
+ ],
628
+ aggregation: 'avg',
629
+ timeRange: '1h',
630
+ groupBy: []
631
+ },
632
+ visualization: {
633
+ chartType: 'gauge',
634
+ options: {
635
+ max: 100,
636
+ unit: '%'
637
+ },
638
+ thresholds: {
639
+ warning: 80,
640
+ critical: 95
641
+ }
642
+ },
643
+ alerts: {
644
+ enabled: true,
645
+ conditions: []
646
+ }
647
+ },
648
+ {
649
+ title: 'Response Time',
650
+ type: 'chart',
651
+ size: 'large',
652
+ position: {
653
+ x: 0,
654
+ y: 3,
655
+ width: 12,
656
+ height: 4
657
+ },
658
+ dataSource: {
659
+ query: 'response-time',
660
+ metrics: [
661
+ 'response-time'
662
+ ],
663
+ aggregation: 'avg',
664
+ timeRange: '24h',
665
+ groupBy: [
666
+ 'service'
667
+ ]
668
+ },
669
+ visualization: {
670
+ chartType: 'line',
671
+ options: {
672
+ unit: 'ms'
673
+ }
674
+ },
675
+ alerts: {
676
+ enabled: false,
677
+ conditions: []
678
+ }
679
+ }
680
+ ]
681
+ },
682
+ {
683
+ name: 'Business KPIs',
684
+ description: 'Key business performance indicators',
685
+ type: 'executive',
686
+ widgets: [
687
+ {
688
+ title: 'Active Users',
689
+ type: 'metric',
690
+ size: 'small',
691
+ position: {
692
+ x: 0,
693
+ y: 0,
694
+ width: 3,
695
+ height: 2
696
+ },
697
+ dataSource: {
698
+ query: 'active-users',
699
+ metrics: [
700
+ 'active-users'
701
+ ],
702
+ aggregation: 'count',
703
+ timeRange: '24h',
704
+ groupBy: []
705
+ },
706
+ visualization: {
707
+ options: {
708
+ unit: 'users'
709
+ }
710
+ },
711
+ alerts: {
712
+ enabled: false,
713
+ conditions: []
714
+ }
715
+ }
716
+ ]
717
+ }
718
+ ];
719
+ for (const dashboardData of defaultDashboards){
720
+ if (!Array.from(this.dashboards.values()).some((d)=>d.name === dashboardData.name)) {
721
+ await this.createDashboard(dashboardData);
722
+ }
723
+ }
724
+ }
725
+ async startMetricsCollection() {
726
+ // Start collecting system metrics
727
+ setInterval(async ()=>{
728
+ await this.collectSystemMetrics();
729
+ }, 60000); // Every minute
730
+ // Start collecting application metrics
731
+ setInterval(async ()=>{
732
+ await this.collectApplicationMetrics();
733
+ }, 30000); // Every 30 seconds
734
+ this.logger.info('Started automatic metrics collection');
735
+ }
736
+ async collectSystemMetrics() {
737
+ try {
738
+ // Mock system metrics collection
739
+ await this.recordMetric({
740
+ name: 'cpu-usage',
741
+ description: 'CPU usage percentage',
742
+ type: 'gauge',
743
+ category: 'performance',
744
+ unit: 'percent',
745
+ value: Math.random() * 100,
746
+ tags: {
747
+ host: 'localhost',
748
+ service: 'system'
749
+ },
750
+ source: 'system-monitor',
751
+ metadata: {}
752
+ });
753
+ await this.recordMetric({
754
+ name: 'memory-usage',
755
+ description: 'Memory usage percentage',
756
+ type: 'gauge',
757
+ category: 'performance',
758
+ unit: 'percent',
759
+ value: Math.random() * 100,
760
+ tags: {
761
+ host: 'localhost',
762
+ service: 'system'
763
+ },
764
+ source: 'system-monitor',
765
+ metadata: {}
766
+ });
767
+ await this.recordMetric({
768
+ name: 'disk-usage',
769
+ description: 'Disk usage percentage',
770
+ type: 'gauge',
771
+ category: 'performance',
772
+ unit: 'percent',
773
+ value: Math.random() * 100,
774
+ tags: {
775
+ host: 'localhost',
776
+ service: 'system'
777
+ },
778
+ source: 'system-monitor',
779
+ metadata: {}
780
+ });
781
+ } catch (error) {
782
+ this.logger.error('Failed to collect system metrics', {
783
+ error
784
+ });
785
+ }
786
+ }
787
+ async collectApplicationMetrics() {
788
+ try {
789
+ // Mock application metrics collection
790
+ await this.recordMetric({
791
+ name: 'response-time',
792
+ description: 'Average response time',
793
+ type: 'gauge',
794
+ category: 'performance',
795
+ unit: 'milliseconds',
796
+ value: Math.random() * 1000 + 100,
797
+ tags: {
798
+ service: 'api',
799
+ endpoint: '/users'
800
+ },
801
+ source: 'application',
802
+ metadata: {}
803
+ });
804
+ await this.recordMetric({
805
+ name: 'request-rate',
806
+ description: 'Requests per second',
807
+ type: 'counter',
808
+ category: 'usage',
809
+ unit: 'requests/sec',
810
+ value: Math.random() * 100 + 10,
811
+ tags: {
812
+ service: 'api'
813
+ },
814
+ source: 'application',
815
+ metadata: {}
816
+ });
817
+ await this.recordMetric({
818
+ name: 'error-rate',
819
+ description: 'Error rate percentage',
820
+ type: 'gauge',
821
+ category: 'performance',
822
+ unit: 'percent',
823
+ value: Math.random() * 5,
824
+ tags: {
825
+ service: 'api'
826
+ },
827
+ source: 'application',
828
+ metadata: {}
829
+ });
830
+ } catch (error) {
831
+ this.logger.error('Failed to collect application metrics', {
832
+ error
833
+ });
834
+ }
835
+ }
836
+ async persistMetric(metric) {
837
+ const date = metric.timestamp.toISOString().split('T')[0];
838
+ const filePath = join(this.analyticsPath, 'metrics', `${date}.json`);
839
+ try {
840
+ let existingData = [];
841
+ try {
842
+ const content = await readFile(filePath, 'utf-8');
843
+ existingData = JSON.parse(content);
844
+ } catch {
845
+ // File doesn't exist yet
846
+ }
847
+ existingData.push(metric);
848
+ await writeFile(filePath, JSON.stringify(existingData, null, 2));
849
+ } catch (error) {
850
+ this.logger.error('Failed to persist metric', {
851
+ error,
852
+ metric: metric.id
853
+ });
854
+ }
855
+ }
856
+ async checkForAnomalies(metricKey, metric) {
857
+ const historical = this.metrics.get(metricKey) || [];
858
+ if (historical.length < 10) return; // Need enough data for baseline
859
+ const recent = historical.slice(-10);
860
+ const average = recent.reduce((sum, m)=>sum + m.value, 0) / recent.length;
861
+ const stdDev = Math.sqrt(recent.reduce((sum, m)=>sum + Math.pow(m.value - average, 2), 0) / recent.length);
862
+ const threshold = 2; // 2 standard deviations
863
+ const deviation = Math.abs(metric.value - average) / stdDev;
864
+ if (deviation > threshold) {
865
+ const insight = {
866
+ id: `insight-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
867
+ title: `Anomaly detected in ${metric.name}`,
868
+ description: `The metric ${metric.name} has deviated significantly from its normal pattern`,
869
+ type: 'anomaly',
870
+ category: metric.category,
871
+ confidence: Math.min(95, deviation * 20),
872
+ impact: deviation > 3 ? 'high' : 'medium',
873
+ priority: deviation > 3 ? 'high' : 'medium',
874
+ data: {
875
+ metrics: [
876
+ metric.name
877
+ ],
878
+ timeRange: {
879
+ start: recent[0].timestamp,
880
+ end: metric.timestamp
881
+ },
882
+ values: {
883
+ current: metric.value,
884
+ average,
885
+ stdDev
886
+ },
887
+ baseline: {
888
+ average,
889
+ stdDev
890
+ },
891
+ deviation
892
+ },
893
+ recommendations: [
894
+ {
895
+ action: 'Investigate the cause of the anomaly',
896
+ effort: 'medium',
897
+ impact: 'Identify potential issues before they become critical',
898
+ implementation: [
899
+ 'Check recent deployments or configuration changes',
900
+ 'Review system logs for errors or warnings',
901
+ 'Monitor related metrics for correlation'
902
+ ]
903
+ }
904
+ ],
905
+ status: 'new',
906
+ createdAt: new Date(),
907
+ updatedAt: new Date()
908
+ };
909
+ this.insights.set(insight.id, insight);
910
+ await this.saveInsight(insight);
911
+ this.emit('anomaly:detected', {
912
+ metric,
913
+ insight,
914
+ deviation
915
+ });
916
+ this.logger.warn(`Anomaly detected in ${metric.name}`, {
917
+ current: metric.value,
918
+ average,
919
+ deviation
920
+ });
921
+ }
922
+ }
923
+ async detectAnomalies(timeRange, metrics) {
924
+ // Simplified anomaly detection
925
+ return [];
926
+ }
927
+ async analyzeTrends(timeRange, metrics) {
928
+ // Simplified trend analysis
929
+ return [];
930
+ }
931
+ async analyzePerformance(timeRange) {
932
+ const insights = [];
933
+ // Check response time trends
934
+ const responseTimeData = await this.queryMetrics({
935
+ metrics: [
936
+ 'response-time'
937
+ ],
938
+ timeRange,
939
+ aggregation: 'avg'
940
+ });
941
+ if (responseTimeData['response-time']?.length > 0) {
942
+ const values = responseTimeData['response-time'].map((d)=>d.value);
943
+ const recent = values.slice(-5);
944
+ const earlier = values.slice(0, -5);
945
+ if (recent.length > 0 && earlier.length > 0) {
946
+ const recentAvg = recent.reduce((sum, v)=>sum + v, 0) / recent.length;
947
+ const earlierAvg = earlier.reduce((sum, v)=>sum + v, 0) / earlier.length;
948
+ const change = (recentAvg - earlierAvg) / earlierAvg * 100;
949
+ if (Math.abs(change) > 20) {
950
+ insights.push({
951
+ id: `perf-insight-${Date.now()}`,
952
+ title: `Response time ${change > 0 ? 'increased' : 'decreased'} by ${Math.abs(change).toFixed(1)}%`,
953
+ description: `Response time has changed significantly in the recent period`,
954
+ type: 'trend',
955
+ category: 'performance',
956
+ confidence: 80,
957
+ impact: Math.abs(change) > 50 ? 'high' : 'medium',
958
+ priority: Math.abs(change) > 50 ? 'high' : 'medium',
959
+ data: {
960
+ metrics: [
961
+ 'response-time'
962
+ ],
963
+ timeRange,
964
+ values: {
965
+ recent: recentAvg,
966
+ earlier: earlierAvg,
967
+ change
968
+ }
969
+ },
970
+ recommendations: change > 0 ? [
971
+ {
972
+ action: 'Investigate performance degradation',
973
+ effort: 'medium',
974
+ impact: 'Restore optimal response times',
975
+ implementation: [
976
+ 'Check for increased load or traffic',
977
+ 'Review recent code deployments',
978
+ 'Analyze database query performance',
979
+ 'Monitor resource utilization'
980
+ ]
981
+ }
982
+ ] : [
983
+ {
984
+ action: 'Document performance improvement',
985
+ effort: 'low',
986
+ impact: 'Understand what caused the improvement',
987
+ implementation: [
988
+ 'Identify recent optimizations',
989
+ 'Document best practices',
990
+ 'Monitor sustainability'
991
+ ]
992
+ }
993
+ ],
994
+ status: 'new',
995
+ createdAt: new Date(),
996
+ updatedAt: new Date()
997
+ });
998
+ }
999
+ }
1000
+ }
1001
+ return insights;
1002
+ }
1003
+ async analyzeUsage(timeRange) {
1004
+ // Simplified usage analysis
1005
+ return [];
1006
+ }
1007
+ async analyzeCostOptimization(timeRange) {
1008
+ // Simplified cost optimization analysis
1009
+ return [];
1010
+ }
1011
+ async collectTrainingData(model) {
1012
+ // Collect historical data for training
1013
+ const data = await this.queryMetrics({
1014
+ metrics: model.features,
1015
+ timeRange: model.trainingData.timeRange,
1016
+ aggregation: 'avg'
1017
+ });
1018
+ // Transform data for ML training (simplified)
1019
+ return Object.values(data).flat();
1020
+ }
1021
+ async executeModelTraining(model, data) {
1022
+ // Simplified model training
1023
+ return {
1024
+ accuracy: 85 + Math.random() * 10,
1025
+ confidence: 80 + Math.random() * 15,
1026
+ performance: {
1027
+ precision: 0.85,
1028
+ recall: 0.82,
1029
+ f1Score: 0.83
1030
+ },
1031
+ trainingData: {
1032
+ ...model.trainingData,
1033
+ samples: data.length
1034
+ }
1035
+ };
1036
+ }
1037
+ async executePrediction(model, input) {
1038
+ // Simplified prediction logic
1039
+ const value = Math.random() * 100;
1040
+ const confidence = 70 + Math.random() * 25;
1041
+ return {
1042
+ value,
1043
+ confidence
1044
+ };
1045
+ }
1046
+ groupMetrics(metrics, groupBy) {
1047
+ const groups = {};
1048
+ for (const metric of metrics){
1049
+ const key = groupBy.map((field)=>{
1050
+ if (field === 'tags') {
1051
+ return Object.entries(metric.tags).map(([k, v])=>`${k}:${v}`).join(',');
1052
+ }
1053
+ return metric[field] || 'unknown';
1054
+ }).join('-');
1055
+ if (!groups[key]) {
1056
+ groups[key] = [];
1057
+ }
1058
+ groups[key].push(metric);
1059
+ }
1060
+ return groups;
1061
+ }
1062
+ aggregateMetrics(metrics, aggregation) {
1063
+ if (metrics.length === 0) return [];
1064
+ // Group by time buckets for time series aggregation
1065
+ const buckets = {};
1066
+ for (const metric of metrics){
1067
+ const bucket = new Date(Math.floor(metric.timestamp.getTime() / 60000) * 60000).toISOString();
1068
+ if (!buckets[bucket]) {
1069
+ buckets[bucket] = [];
1070
+ }
1071
+ buckets[bucket].push(metric);
1072
+ }
1073
+ return Object.entries(buckets).map(([timestamp, bucketMetrics])=>{
1074
+ const values = bucketMetrics.map((m)=>m.value);
1075
+ let aggregatedValue;
1076
+ switch(aggregation){
1077
+ case 'sum':
1078
+ aggregatedValue = values.reduce((sum, v)=>sum + v, 0);
1079
+ break;
1080
+ case 'min':
1081
+ aggregatedValue = Math.min(...values);
1082
+ break;
1083
+ case 'max':
1084
+ aggregatedValue = Math.max(...values);
1085
+ break;
1086
+ case 'count':
1087
+ aggregatedValue = values.length;
1088
+ break;
1089
+ case 'p95':
1090
+ values.sort((a, b)=>a - b);
1091
+ aggregatedValue = values[Math.floor(values.length * 0.95)];
1092
+ break;
1093
+ case 'p99':
1094
+ values.sort((a, b)=>a - b);
1095
+ aggregatedValue = values[Math.floor(values.length * 0.99)];
1096
+ break;
1097
+ case 'avg':
1098
+ default:
1099
+ aggregatedValue = values.reduce((sum, v)=>sum + v, 0) / values.length;
1100
+ }
1101
+ return {
1102
+ timestamp: new Date(timestamp),
1103
+ value: aggregatedValue,
1104
+ count: values.length
1105
+ };
1106
+ }).sort((a, b)=>a.timestamp.getTime() - b.timestamp.getTime());
1107
+ }
1108
+ getLatestValue(dataPoints) {
1109
+ if (!dataPoints || dataPoints.length === 0) return 0;
1110
+ return dataPoints[dataPoints.length - 1]?.value || 0;
1111
+ }
1112
+ async saveDashboard(dashboard) {
1113
+ const filePath = join(this.analyticsPath, 'dashboards', `${dashboard.id}.json`);
1114
+ await writeFile(filePath, JSON.stringify(dashboard, null, 2));
1115
+ }
1116
+ async saveInsight(insight) {
1117
+ const filePath = join(this.analyticsPath, 'insights', `${insight.id}.json`);
1118
+ await writeFile(filePath, JSON.stringify(insight, null, 2));
1119
+ }
1120
+ async saveModel(model) {
1121
+ const filePath = join(this.analyticsPath, 'models', `${model.id}.json`);
1122
+ await writeFile(filePath, JSON.stringify(model, null, 2));
1123
+ }
1124
+ constructor(analyticsPath = './analytics', logger, config){
1125
+ super(), _define_property(this, "metrics", new Map()), _define_property(this, "dashboards", new Map()), _define_property(this, "insights", new Map()), _define_property(this, "models", new Map()), _define_property(this, "reports", new Map()), _define_property(this, "analyticsPath", void 0), _define_property(this, "logger", void 0), _define_property(this, "config", void 0), _define_property(this, "configuration", void 0);
1126
+ this.analyticsPath = analyticsPath;
1127
+ this.logger = logger || new Logger({
1128
+ level: 'info',
1129
+ format: 'text',
1130
+ destination: 'console'
1131
+ });
1132
+ this.config = config || ConfigManager.getInstance();
1133
+ this.configuration = this.getDefaultConfiguration();
1134
+ }
1135
+ }