vibecodingmachine-core 2026.2.20-438 → 2026.2.26-1739

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 (202) hide show
  1. package/README.md +240 -0
  2. package/package.json +10 -2
  3. package/src/agents/Agent.js +300 -0
  4. package/src/agents/AgentAdditionService.js +311 -0
  5. package/src/agents/AgentCheckService.js +690 -0
  6. package/src/agents/AgentInstallationService.js +140 -0
  7. package/src/agents/AgentSetupService.js +467 -0
  8. package/src/agents/AgentStatus.js +183 -0
  9. package/src/agents/AgentVerificationService.js +634 -0
  10. package/src/agents/ConfigurationSchemaValidator.js +543 -0
  11. package/src/agents/EnvironmentConfigurationManager.js +602 -0
  12. package/src/agents/InstallationErrorHandler.js +372 -0
  13. package/src/agents/InstallationLog.js +363 -0
  14. package/src/agents/InstallationMethod.js +510 -0
  15. package/src/agents/InstallationOrchestrator.js +352 -0
  16. package/src/agents/InstallationProgressReporter.js +372 -0
  17. package/src/agents/InstallationRetryManager.js +322 -0
  18. package/src/agents/InstallationType.js +254 -0
  19. package/src/agents/OperationTypes.js +310 -0
  20. package/src/agents/PerformanceMetricsCollector.js +493 -0
  21. package/src/agents/SecurityValidationService.js +534 -0
  22. package/src/agents/VerificationTest.js +354 -0
  23. package/src/agents/VerificationType.js +226 -0
  24. package/src/agents/WindowsPermissionHandler.js +518 -0
  25. package/src/agents/config/AgentConfigManager.js +393 -0
  26. package/src/agents/config/AgentDefaultsRegistry.js +373 -0
  27. package/src/agents/config/ConfigValidator.js +281 -0
  28. package/src/agents/discovery/AgentDiscoveryService.js +707 -0
  29. package/src/agents/logging/AgentLogger.js +511 -0
  30. package/src/agents/status/AgentStatusManager.js +481 -0
  31. package/src/agents/storage/FileManager.js +454 -0
  32. package/src/agents/verification/AgentCommunicationTester.js +474 -0
  33. package/src/agents/verification/BaseVerifier.js +430 -0
  34. package/src/agents/verification/CommandVerifier.js +480 -0
  35. package/src/agents/verification/FileOperationVerifier.js +453 -0
  36. package/src/agents/verification/ResultAnalyzer.js +707 -0
  37. package/src/agents/verification/TestRequirementManager.js +495 -0
  38. package/src/agents/verification/VerificationRunner.js +433 -0
  39. package/src/agents/windows/BaseWindowsInstaller.js +441 -0
  40. package/src/agents/windows/ChocolateyInstaller.js +509 -0
  41. package/src/agents/windows/DirectInstaller.js +443 -0
  42. package/src/agents/windows/InstallerFactory.js +391 -0
  43. package/src/agents/windows/NpmInstaller.js +505 -0
  44. package/src/agents/windows/PowerShellInstaller.js +458 -0
  45. package/src/agents/windows/WinGetInstaller.js +390 -0
  46. package/src/analysis/analysis-reporter.js +132 -0
  47. package/src/analysis/boundary-detector.js +712 -0
  48. package/src/analysis/categorizer.js +340 -0
  49. package/src/analysis/codebase-scanner.js +384 -0
  50. package/src/analysis/line-counter.js +513 -0
  51. package/src/analysis/priority-calculator.js +679 -0
  52. package/src/analysis/report/analysis-report.js +250 -0
  53. package/src/analysis/report/package-analyzer.js +278 -0
  54. package/src/analysis/report/recommendation-generator.js +382 -0
  55. package/src/analysis/report/statistics-generator.js +515 -0
  56. package/src/analysis/reports/analysis-report-model.js +101 -0
  57. package/src/analysis/reports/recommendation-generator.js +283 -0
  58. package/src/analysis/reports/report-generators.js +191 -0
  59. package/src/analysis/reports/statistics-calculator.js +231 -0
  60. package/src/analysis/reports/trend-analyzer.js +219 -0
  61. package/src/analysis/strategy-generator.js +814 -0
  62. package/src/auto-mode/AutoModeBusinessLogic.js +836 -0
  63. package/src/config/refactoring-config.js +307 -0
  64. package/src/health-tracking/json-storage.js +38 -2
  65. package/src/ide-integration/applescript-manager-core.js +233 -0
  66. package/src/ide-integration/applescript-manager.cjs +357 -28
  67. package/src/ide-integration/applescript-manager.js +89 -3599
  68. package/src/ide-integration/cdp-manager.js +306 -0
  69. package/src/ide-integration/claude-code-cli-manager.cjs +1 -1
  70. package/src/ide-integration/continuation-handler.js +337 -0
  71. package/src/ide-integration/ide-status-checker.js +292 -0
  72. package/src/ide-integration/macos-ide-manager.js +627 -0
  73. package/src/ide-integration/macos-text-sender.js +528 -0
  74. package/src/ide-integration/response-reader.js +548 -0
  75. package/src/ide-integration/windows-automation-manager.js +121 -0
  76. package/src/ide-integration/windows-ide-manager.js +373 -0
  77. package/src/index.cjs +25 -3
  78. package/src/index.js +15 -1
  79. package/src/llm/direct-llm-manager.cjs +90 -2
  80. package/src/models/compliance-report.js +538 -0
  81. package/src/models/file-analysis.js +681 -0
  82. package/src/models/refactoring-plan.js +770 -0
  83. package/src/monitoring/alert-system.js +834 -0
  84. package/src/monitoring/compliance-progress-tracker.js +437 -0
  85. package/src/monitoring/continuous-scan-notifications.js +661 -0
  86. package/src/monitoring/continuous-scanner.js +279 -0
  87. package/src/monitoring/file-monitor/file-analyzer.js +262 -0
  88. package/src/monitoring/file-monitor/file-monitor.js +237 -0
  89. package/src/monitoring/file-monitor/watcher.js +194 -0
  90. package/src/monitoring/file-monitor.js +17 -0
  91. package/src/monitoring/notification-manager.js +437 -0
  92. package/src/monitoring/scanner-core.js +368 -0
  93. package/src/monitoring/scanner-events.js +214 -0
  94. package/src/monitoring/violation-notification-system.js +515 -0
  95. package/src/refactoring/boundaries/cohesion-analyzer.js +316 -0
  96. package/src/refactoring/boundaries/extraction-result.js +285 -0
  97. package/src/refactoring/boundaries/extraction-strategies.js +392 -0
  98. package/src/refactoring/boundaries/module-boundary.js +209 -0
  99. package/src/refactoring/boundary/boundary-detector.js +741 -0
  100. package/src/refactoring/boundary/boundary-types.js +405 -0
  101. package/src/refactoring/boundary/extraction-strategies.js +554 -0
  102. package/src/refactoring/boundary-extraction-result.js +77 -0
  103. package/src/refactoring/boundary-extraction-strategies.js +330 -0
  104. package/src/refactoring/boundary-extractor.js +384 -0
  105. package/src/refactoring/boundary-types.js +46 -0
  106. package/src/refactoring/circular/circular-dependency.js +88 -0
  107. package/src/refactoring/circular/cycle-detection.js +147 -0
  108. package/src/refactoring/circular/dependency-node.js +82 -0
  109. package/src/refactoring/circular/dependency-result.js +107 -0
  110. package/src/refactoring/circular/dependency-types.js +58 -0
  111. package/src/refactoring/circular/graph-builder.js +213 -0
  112. package/src/refactoring/circular/resolution-strategy.js +72 -0
  113. package/src/refactoring/circular/strategy-generator.js +229 -0
  114. package/src/refactoring/circular-dependency-resolver-original.js +809 -0
  115. package/src/refactoring/circular-dependency-resolver.js +200 -0
  116. package/src/refactoring/code-mover.js +761 -0
  117. package/src/refactoring/file-splitter.js +696 -0
  118. package/src/refactoring/functionality-validator.js +816 -0
  119. package/src/refactoring/import-manager.js +774 -0
  120. package/src/refactoring/module-boundary.js +107 -0
  121. package/src/refactoring/refactoring-executor.js +672 -0
  122. package/src/refactoring/refactoring-rollback.js +614 -0
  123. package/src/refactoring/test-validator.js +631 -0
  124. package/src/requirement-management/default-requirement-manager.js +321 -0
  125. package/src/requirement-management/requirement-file-parser.js +159 -0
  126. package/src/requirement-management/requirement-sequencer.js +221 -0
  127. package/src/rui/commands/AgentCommandParser.js +600 -0
  128. package/src/rui/commands/AgentCommands.js +487 -0
  129. package/src/rui/commands/AgentResponseFormatter.js +832 -0
  130. package/src/scripts/verify-full-compliance.js +269 -0
  131. package/src/sync/sync-engine-core.js +1 -0
  132. package/src/sync/sync-engine-remote-handlers.js +135 -0
  133. package/src/task-generation/automated-task-generator.js +351 -0
  134. package/src/task-generation/prioritizer.js +287 -0
  135. package/src/task-generation/task-list-updater.js +215 -0
  136. package/src/task-generation/task-management-integration.js +480 -0
  137. package/src/task-generation/task-manager-integration.js +270 -0
  138. package/src/task-generation/violation-task-generator.js +474 -0
  139. package/src/task-management/continuous-scan-integration.js +342 -0
  140. package/src/timeout-management/index.js +12 -3
  141. package/src/timeout-management/response-time-tracker.js +167 -0
  142. package/src/timeout-management/timeout-calculator.js +159 -0
  143. package/src/timeout-management/timeout-config-manager.js +172 -0
  144. package/src/utils/ast-analyzer.js +417 -0
  145. package/src/utils/current-requirement-manager.js +276 -0
  146. package/src/utils/current-requirement-operations.js +472 -0
  147. package/src/utils/dependency-mapper.js +456 -0
  148. package/src/utils/download-with-progress.js +4 -2
  149. package/src/utils/electron-update-checker.js +4 -1
  150. package/src/utils/file-size-analyzer.js +272 -0
  151. package/src/utils/import-updater.js +280 -0
  152. package/src/utils/refactoring-tools.js +512 -0
  153. package/src/utils/report-generator.js +569 -0
  154. package/src/utils/reports/report-analysis.js +218 -0
  155. package/src/utils/reports/report-types.js +55 -0
  156. package/src/utils/reports/summary-generators.js +102 -0
  157. package/src/utils/requirement-file-management.js +157 -0
  158. package/src/utils/requirement-helpers/requirement-file-ops.js +392 -0
  159. package/src/utils/requirement-helpers/requirement-mover.js +414 -0
  160. package/src/utils/requirement-helpers/requirement-parser.js +326 -0
  161. package/src/utils/requirement-helpers/requirement-status.js +320 -0
  162. package/src/utils/requirement-helpers-new.js +55 -0
  163. package/src/utils/requirement-helpers-refactored.js +367 -0
  164. package/src/utils/requirement-helpers.js +291 -1191
  165. package/src/utils/requirement-movement-operations.js +450 -0
  166. package/src/utils/requirement-movement.js +312 -0
  167. package/src/utils/requirement-parsing-helpers.js +56 -0
  168. package/src/utils/requirement-statistics.js +200 -0
  169. package/src/utils/requirement-text-utils.js +58 -0
  170. package/src/utils/rollback/rollback-handlers.js +125 -0
  171. package/src/utils/rollback/rollback-operation.js +63 -0
  172. package/src/utils/rollback/rollback-recorder.js +166 -0
  173. package/src/utils/rollback/rollback-state-manager.js +175 -0
  174. package/src/utils/rollback/rollback-types.js +33 -0
  175. package/src/utils/rollback/rollback-utils.js +110 -0
  176. package/src/utils/rollback-manager-original.js +569 -0
  177. package/src/utils/rollback-manager.js +202 -0
  178. package/src/utils/smoke-test-cli.js +362 -0
  179. package/src/utils/smoke-test-gui.js +351 -0
  180. package/src/utils/smoke-test-orchestrator.js +321 -0
  181. package/src/utils/smoke-test-runner.js +60 -0
  182. package/src/utils/smoke-test-web.js +347 -0
  183. package/src/utils/specification-helpers.js +39 -13
  184. package/src/utils/specification-migration.js +97 -0
  185. package/src/utils/test-runner.js +579 -0
  186. package/src/utils/validation-framework.js +518 -0
  187. package/src/validation/compliance-analyzer.js +197 -0
  188. package/src/validation/compliance-report-generator.js +343 -0
  189. package/src/validation/compliance-reporter.js +711 -0
  190. package/src/validation/compliance-rules.js +127 -0
  191. package/src/validation/constitution-validator-new.js +196 -0
  192. package/src/validation/constitution-validator.js +17 -0
  193. package/src/validation/file-validators.js +170 -0
  194. package/src/validation/line-limit/file-analyzer.js +201 -0
  195. package/src/validation/line-limit/line-limit-validator.js +208 -0
  196. package/src/validation/line-limit/validation-result.js +144 -0
  197. package/src/validation/line-limit-core.js +225 -0
  198. package/src/validation/line-limit-reporter.js +134 -0
  199. package/src/validation/line-limit-result.js +125 -0
  200. package/src/validation/line-limit-validator.js +41 -0
  201. package/src/validation/metrics-calculator.js +660 -0
  202. package/src/sync/sync-engine-backup.js +0 -559
@@ -0,0 +1,493 @@
1
+ /**
2
+ * Performance Metrics Collector
3
+ *
4
+ * Collects and manages performance metrics for agent operations.
5
+ * Follows constitutional requirements: <555 lines, test-first approach.
6
+ */
7
+
8
+ /**
9
+ * Performance Metrics Collector class
10
+ */
11
+ class PerformanceMetricsCollector {
12
+ /**
13
+ * Create metrics collector instance
14
+ * @param {Object} options - Collector options
15
+ */
16
+ constructor(options = {}) {
17
+ this.logger = options.logger || null;
18
+ this.enabled = options.enabled !== false; // Default to enabled
19
+ this.maxHistorySize = options.maxHistorySize || 1000;
20
+ this.flushInterval = options.flushInterval || 60000; // 1 minute
21
+
22
+ // Metrics storage
23
+ this.metrics = {
24
+ operations: new Map(),
25
+ system: new Map(),
26
+ performance: new Map()
27
+ };
28
+
29
+ // Active operations tracking
30
+ this.activeOperations = new Map();
31
+
32
+ // Start periodic flush if enabled
33
+ if (this.enabled) {
34
+ this.startPeriodicFlush();
35
+ }
36
+ }
37
+
38
+ /**
39
+ * Start tracking an operation
40
+ * @param {string} operationId - Unique operation identifier
41
+ * @param {Object} context - Operation context
42
+ * @returns {Object} - Operation tracker
43
+ */
44
+ startOperation(operationId, context = {}) {
45
+ if (!this.enabled) return this.createNoOpTracker();
46
+
47
+ const startTime = process.hrtime.bigint();
48
+ const startMemory = this.getMemoryUsage();
49
+
50
+ const operation = {
51
+ id: operationId,
52
+ type: context.type || 'UNKNOWN',
53
+ agentId: context.agentId,
54
+ installerType: context.installerType,
55
+ startTime: Number(startTime / 1000000n), // Convert to milliseconds
56
+ startMemory,
57
+ status: 'RUNNING',
58
+ phases: [],
59
+ checkpoints: []
60
+ };
61
+
62
+ this.activeOperations.set(operationId, operation);
63
+
64
+ // Record initial system metrics
65
+ this.recordSystemMetrics('operation_start', {
66
+ operationId,
67
+ type: operation.type,
68
+ agentId: operation.agentId
69
+ });
70
+
71
+ if (this.logger) {
72
+ this.logger.debug('Started operation tracking', {
73
+ operationId,
74
+ type: operation.type,
75
+ agentId: operation.agentId
76
+ });
77
+ }
78
+
79
+ return {
80
+ addPhase: (phaseName, details = {}) => this.addOperationPhase(operationId, phaseName, details),
81
+ addCheckpoint: (checkpointName, details = {}) => this.addOperationCheckpoint(operationId, checkpointName, details),
82
+ complete: (result = {}) => this.completeOperation(operationId, result),
83
+ fail: (error) => this.failOperation(operationId, error),
84
+ getMetrics: () => this.getOperationMetrics(operationId)
85
+ };
86
+ }
87
+
88
+ /**
89
+ * Add phase to operation
90
+ * @param {string} operationId - Operation identifier
91
+ * @param {string} phaseName - Name of phase
92
+ * @param {Object} details - Phase details
93
+ */
94
+ addOperationPhase(operationId, phaseName, details = {}) {
95
+ if (!this.enabled) return;
96
+
97
+ const operation = this.activeOperations.get(operationId);
98
+ if (!operation) return;
99
+
100
+ const phase = {
101
+ name: phaseName,
102
+ startTime: Date.now(),
103
+ startMemory: this.getMemoryUsage(),
104
+ details
105
+ };
106
+
107
+ operation.phases.push(phase);
108
+
109
+ if (this.logger) {
110
+ this.logger.debug(`Added operation phase: ${phaseName}`, {
111
+ operationId,
112
+ phaseName,
113
+ details
114
+ });
115
+ }
116
+ }
117
+
118
+ /**
119
+ * Add checkpoint to operation
120
+ * @param {string} operationId - Operation identifier
121
+ * @param {string} checkpointName - Name of checkpoint
122
+ * @param {Object} details - Checkpoint details
123
+ */
124
+ addOperationCheckpoint(operationId, checkpointName, details = {}) {
125
+ if (!this.enabled) return;
126
+
127
+ const operation = this.activeOperations.get(operationId);
128
+ if (!operation) return;
129
+
130
+ const checkpoint = {
131
+ name: checkpointName,
132
+ timestamp: Date.now(),
133
+ memory: this.getMemoryUsage(),
134
+ details
135
+ };
136
+
137
+ operation.checkpoints.push(checkpoint);
138
+
139
+ if (this.logger) {
140
+ this.logger.debug(`Added operation checkpoint: ${checkpointName}`, {
141
+ operationId,
142
+ checkpointName,
143
+ details
144
+ });
145
+ }
146
+ }
147
+
148
+ /**
149
+ * Complete operation tracking
150
+ * @param {string} operationId - Operation identifier
151
+ * @param {Object} result - Operation result
152
+ */
153
+ completeOperation(operationId, result = {}) {
154
+ if (!this.enabled) return;
155
+
156
+ const operation = this.activeOperations.get(operationId);
157
+ if (!operation) return;
158
+
159
+ const endTime = process.hrtime.bigint();
160
+ const endMemory = this.getMemoryUsage();
161
+
162
+ operation.endTime = Number(endTime / 1000000n);
163
+ operation.endMemory = endMemory;
164
+ operation.duration = operation.endTime - operation.startTime;
165
+ operation.memoryDelta = endMemory - operation.startMemory;
166
+ operation.status = 'COMPLETED';
167
+ operation.result = result;
168
+
169
+ // Complete final phase
170
+ if (operation.phases.length > 0) {
171
+ const lastPhase = operation.phases[operation.phases.length - 1];
172
+ if (!lastPhase.endTime) {
173
+ lastPhase.endTime = operation.endTime;
174
+ lastPhase.duration = lastPhase.endTime - lastPhase.startTime;
175
+ lastPhase.memoryDelta = endMemory - lastPhase.startMemory;
176
+ }
177
+ }
178
+
179
+ // Store in metrics
180
+ this.storeOperationMetrics(operation);
181
+
182
+ // Remove from active operations
183
+ this.activeOperations.delete(operationId);
184
+
185
+ // Record completion metrics
186
+ this.recordSystemMetrics('operation_complete', {
187
+ operationId,
188
+ type: operation.type,
189
+ duration: operation.duration,
190
+ memoryDelta: operation.memoryDelta,
191
+ success: true
192
+ });
193
+
194
+ if (this.logger) {
195
+ this.logger.info('Completed operation tracking', {
196
+ operationId,
197
+ type: operation.type,
198
+ duration: operation.duration,
199
+ memoryDelta: operation.memoryDelta
200
+ });
201
+ }
202
+ }
203
+
204
+ /**
205
+ * Fail operation tracking
206
+ * @param {string} operationId - Operation identifier
207
+ * @param {Error} error - Error that caused failure
208
+ */
209
+ failOperation(operationId, error) {
210
+ if (!this.enabled) return;
211
+
212
+ const operation = this.activeOperations.get(operationId);
213
+ if (!operation) return;
214
+
215
+ const endTime = process.hrtime.bigint();
216
+ const endMemory = this.getMemoryUsage();
217
+
218
+ operation.endTime = Number(endTime / 1000000n);
219
+ operation.endMemory = endMemory;
220
+ operation.duration = operation.endTime - operation.startTime;
221
+ operation.memoryDelta = endMemory - operation.startMemory;
222
+ operation.status = 'FAILED';
223
+ operation.error = error.message;
224
+
225
+ // Store in metrics
226
+ this.storeOperationMetrics(operation);
227
+
228
+ // Remove from active operations
229
+ this.activeOperations.delete(operationId);
230
+
231
+ // Record failure metrics
232
+ this.recordSystemMetrics('operation_fail', {
233
+ operationId,
234
+ type: operation.type,
235
+ duration: operation.duration,
236
+ error: error.message,
237
+ success: false
238
+ });
239
+
240
+ if (this.logger) {
241
+ this.logger.warn('Failed operation tracking', {
242
+ operationId,
243
+ type: operation.type,
244
+ duration: operation.duration,
245
+ error: error.message
246
+ });
247
+ }
248
+ }
249
+
250
+ /**
251
+ * Store operation metrics
252
+ * @param {Object} operation - Operation to store
253
+ */
254
+ storeOperationMetrics(operation) {
255
+ const typeMetrics = this.metrics.operations.get(operation.type) || [];
256
+ typeMetrics.push(operation);
257
+
258
+ // Limit history size
259
+ if (typeMetrics.length > this.maxHistorySize) {
260
+ typeMetrics.shift();
261
+ }
262
+
263
+ this.metrics.operations.set(operation.type, typeMetrics);
264
+ }
265
+
266
+ /**
267
+ * Record system metrics
268
+ * @param {string} event - Event type
269
+ * @param {Object} data - Event data
270
+ */
271
+ recordSystemMetrics(event, data = {}) {
272
+ if (!this.enabled) return;
273
+
274
+ const timestamp = Date.now();
275
+ const memory = this.getMemoryUsage();
276
+ const cpu = this.getCpuUsage();
277
+
278
+ const metric = {
279
+ timestamp,
280
+ event,
281
+ memory,
282
+ cpu,
283
+ data
284
+ };
285
+
286
+ const systemMetrics = this.metrics.system.get(event) || [];
287
+ systemMetrics.push(metric);
288
+
289
+ // Limit history size
290
+ if (systemMetrics.length > this.maxHistorySize) {
291
+ systemMetrics.shift();
292
+ }
293
+
294
+ this.metrics.system.set(event, systemMetrics);
295
+ }
296
+
297
+ /**
298
+ * Get operation metrics
299
+ * @param {string} operationId - Operation identifier
300
+ * @returns {Object|null} - Operation metrics or null
301
+ */
302
+ getOperationMetrics(operationId) {
303
+ const operation = this.activeOperations.get(operationId);
304
+ if (!operation) return null;
305
+
306
+ const currentMemory = this.getMemoryUsage();
307
+ const currentTime = Date.now();
308
+
309
+ return {
310
+ id: operation.id,
311
+ type: operation.type,
312
+ agentId: operation.agentId,
313
+ status: operation.status,
314
+ startTime: operation.startTime,
315
+ currentDuration: currentTime - operation.startTime,
316
+ currentMemoryDelta: currentMemory - operation.startMemory,
317
+ phases: operation.phases,
318
+ checkpoints: operation.checkpoints
319
+ };
320
+ }
321
+
322
+ /**
323
+ * Get aggregated metrics
324
+ * @param {Object} filters - Filters to apply
325
+ * @returns {Object} - Aggregated metrics
326
+ */
327
+ getAggregatedMetrics(filters = {}) {
328
+ if (!this.enabled) return {};
329
+
330
+ const { operationType, timeRange, agentId } = filters;
331
+ const now = Date.now();
332
+ const timeLimit = timeRange ? now - timeRange : 0;
333
+
334
+ const result = {
335
+ summary: {},
336
+ operations: {},
337
+ performance: {},
338
+ system: {}
339
+ };
340
+
341
+ // Aggregate operation metrics
342
+ for (const [type, operations] of this.metrics.operations) {
343
+ if (operationType && type !== operationType) continue;
344
+
345
+ const filteredOps = operations.filter(op =>
346
+ op.endTime >= timeLimit &&
347
+ (!agentId || op.agentId === agentId)
348
+ );
349
+
350
+ if (filteredOps.length === 0) continue;
351
+
352
+ const completed = filteredOps.filter(op => op.status === 'COMPLETED');
353
+ const failed = filteredOps.filter(op => op.status === 'FAILED');
354
+
355
+ const durations = completed.map(op => op.duration);
356
+ const memoryDeltas = completed.map(op => op.memoryDelta);
357
+
358
+ result.operations[type] = {
359
+ total: filteredOps.length,
360
+ completed: completed.length,
361
+ failed: failed.length,
362
+ successRate: filteredOps.length > 0 ? (completed.length / filteredOps.length) * 100 : 0,
363
+ avgDuration: durations.length > 0 ? durations.reduce((a, b) => a + b, 0) / durations.length : 0,
364
+ minDuration: durations.length > 0 ? Math.min(...durations) : 0,
365
+ maxDuration: durations.length > 0 ? Math.max(...durations) : 0,
366
+ avgMemoryDelta: memoryDeltas.length > 0 ? memoryDeltas.reduce((a, b) => a + b, 0) / memoryDeltas.length : 0
367
+ };
368
+ }
369
+
370
+ // System metrics summary
371
+ for (const [event, metrics] of this.metrics.system) {
372
+ const recentMetrics = metrics.filter(m => m.timestamp >= timeLimit);
373
+ result.system[event] = {
374
+ count: recentMetrics.length,
375
+ avgMemory: recentMetrics.length > 0 ? recentMetrics.reduce((sum, m) => sum + m.memory, 0) / recentMetrics.length : 0,
376
+ avgCpu: recentMetrics.length > 0 ? recentMetrics.reduce((sum, m) => sum + (m.cpu || 0), 0) / recentMetrics.length : 0
377
+ };
378
+ }
379
+
380
+ return result;
381
+ }
382
+
383
+ /**
384
+ * Get memory usage
385
+ * @returns {number} - Memory usage in MB
386
+ */
387
+ getMemoryUsage() {
388
+ const usage = process.memoryUsage();
389
+ return Math.round(usage.heapUsed / 1024 / 1024); // MB
390
+ }
391
+
392
+ /**
393
+ * Get CPU usage
394
+ * @returns {number} - CPU usage percentage
395
+ */
396
+ getCpuUsage() {
397
+ const usage = process.cpuUsage();
398
+ return Math.round((usage.user + usage.system) / 1000000); // Convert to milliseconds
399
+ }
400
+
401
+ /**
402
+ * Start periodic flush
403
+ */
404
+ startPeriodicFlush() {
405
+ if (this.flushTimer) return;
406
+
407
+ this.flushTimer = setInterval(() => {
408
+ this.flushMetrics();
409
+ }, this.flushInterval);
410
+ }
411
+
412
+ /**
413
+ * Stop periodic flush
414
+ */
415
+ stopPeriodicFlush() {
416
+ if (this.flushTimer) {
417
+ clearInterval(this.flushTimer);
418
+ this.flushTimer = null;
419
+ }
420
+ }
421
+
422
+ /**
423
+ * Flush metrics to storage/log
424
+ */
425
+ flushMetrics() {
426
+ if (!this.enabled) return;
427
+
428
+ const metrics = this.getAggregatedMetrics();
429
+
430
+ if (this.logger) {
431
+ this.logger.debug('Flushing performance metrics', {
432
+ operationsCount: Object.keys(metrics.operations).length,
433
+ systemEventsCount: Object.keys(metrics.system).length
434
+ });
435
+ }
436
+
437
+ // Could integrate with external metrics systems here
438
+ // For now, just log summary
439
+ }
440
+
441
+ /**
442
+ * Create no-op tracker for when metrics are disabled
443
+ * @returns {Object} - No-op tracker
444
+ */
445
+ createNoOpTracker() {
446
+ return {
447
+ addPhase: () => {},
448
+ addCheckpoint: () => {},
449
+ complete: () => {},
450
+ fail: () => {},
451
+ getMetrics: () => null
452
+ };
453
+ }
454
+
455
+ /**
456
+ * Reset all metrics
457
+ */
458
+ reset() {
459
+ this.metrics.operations.clear();
460
+ this.metrics.system.clear();
461
+ this.metrics.performance.clear();
462
+ this.activeOperations.clear();
463
+
464
+ if (this.logger) {
465
+ this.logger.info('Reset all performance metrics');
466
+ }
467
+ }
468
+
469
+ /**
470
+ * Get current configuration
471
+ * @returns {Object} - Current configuration
472
+ */
473
+ getConfiguration() {
474
+ return {
475
+ enabled: this.enabled,
476
+ maxHistorySize: this.maxHistorySize,
477
+ flushInterval: this.flushInterval,
478
+ activeOperations: this.activeOperations.size,
479
+ operationTypes: Array.from(this.metrics.operations.keys()),
480
+ systemEvents: Array.from(this.metrics.system.keys())
481
+ };
482
+ }
483
+
484
+ /**
485
+ * Cleanup resources
486
+ */
487
+ cleanup() {
488
+ this.stopPeriodicFlush();
489
+ this.reset();
490
+ }
491
+ }
492
+
493
+ module.exports = PerformanceMetricsCollector;