claude-flow-novice 2.2.4 → 2.2.5

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 (288) hide show
  1. package/package.json +9 -8
  2. package/scripts/.claude-flow/metrics/agent-metrics.json +1 -0
  3. package/scripts/.claude-flow/metrics/performance.json +9 -0
  4. package/scripts/.claude-flow/metrics/task-metrics.json +10 -0
  5. package/scripts/CLEANUP_OPTIMIZATION_REPORT.json +312 -0
  6. package/scripts/CLEANUP_PERFORMANCE_OPTIMIZATION.md +387 -0
  7. package/scripts/CLEANUP_QUICK_START.md +268 -0
  8. package/scripts/CLEANUP_TEST_RESULTS.md +205 -0
  9. package/scripts/README.md +339 -0
  10. package/scripts/ace-query.sh +384 -0
  11. package/scripts/agent-token-analysis.js +430 -0
  12. package/scripts/auto-setup.js +332 -0
  13. package/scripts/build/README.md +167 -0
  14. package/scripts/build/build-config.js +27 -0
  15. package/scripts/build/build-prompt-copier.sh +30 -0
  16. package/scripts/build/performance-monitor.js +869 -0
  17. package/scripts/build/prepare-publish.js +150 -0
  18. package/scripts/build/typescript-fixer.js +621 -0
  19. package/scripts/build/unified-builder.sh +428 -0
  20. package/scripts/build/update-bin-version.js +32 -0
  21. package/scripts/build/validate-agents.js +238 -0
  22. package/scripts/build-index.js +43 -0
  23. package/scripts/build-orchestrator.js +320 -0
  24. package/scripts/check-routing-stats.cjs +122 -0
  25. package/scripts/ci-validation.js +375 -0
  26. package/scripts/cleanup-blocking-coordination.sh +420 -0
  27. package/scripts/cleanup-idle-sessions.sh +59 -0
  28. package/scripts/collect-build-metrics.js +65 -0
  29. package/scripts/demo/README.md +79 -0
  30. package/scripts/demo/autoscaling-demo-simplified.js +963 -0
  31. package/scripts/demo/comprehensive-dashboard-test.js +693 -0
  32. package/scripts/demo/confidence-log.js +87 -0
  33. package/scripts/demo/confidence-report.js +82 -0
  34. package/scripts/demo/demo-multi-swarm-coordination.js +325 -0
  35. package/scripts/demo/demo-production-deployment.js +399 -0
  36. package/scripts/demo/demo-visualization-system.js +149 -0
  37. package/scripts/demo/performance-analysis.cjs +71 -0
  38. package/scripts/demo/performance-analysis.js +71 -0
  39. package/scripts/demo/test-autoscaling-demo.js +314 -0
  40. package/scripts/dependency-optimizer.js +349 -0
  41. package/scripts/dependency-security-assessment.js +331 -0
  42. package/scripts/deploy-sdk.sh +176 -0
  43. package/scripts/deployment-readiness-report.json +179 -0
  44. package/scripts/dev/README.md +264 -0
  45. package/scripts/dev/claude-flow-wrapper.sh +35 -0
  46. package/scripts/dev/claude-monitor.py +419 -0
  47. package/scripts/dev/claude-sparc.sh +562 -0
  48. package/scripts/dev/claude-wrapper.sh +17 -0
  49. package/scripts/dev/demo-phase3-compliance.js +172 -0
  50. package/scripts/dev/demo-task-system.ts +224 -0
  51. package/scripts/dev/deployment-validator.js +315 -0
  52. package/scripts/dev/spawn-claude-terminal.sh +32 -0
  53. package/scripts/dev/start-portal.sh +506 -0
  54. package/scripts/dev/start-web-ui.js +15 -0
  55. package/scripts/dev/stop-portal.sh +311 -0
  56. package/scripts/dev/validate-examples.ts +288 -0
  57. package/scripts/dev/validate-phase2.cjs +451 -0
  58. package/scripts/dev/validate-phase2.js +785 -0
  59. package/scripts/dev/validate-phase3.cjs +208 -0
  60. package/scripts/dev/validate-security-remediation.js +1 -0
  61. package/scripts/ecosystem.config.cjs +90 -0
  62. package/scripts/fix-js-extensions.js +167 -0
  63. package/scripts/generate-basic-types.js +73 -0
  64. package/scripts/generate-changelog.js +318 -0
  65. package/scripts/git-hooks/pre-commit.sh +143 -0
  66. package/scripts/health-checks.js +634 -0
  67. package/scripts/hook-wrapper.sh +54 -0
  68. package/scripts/install/README.md +375 -0
  69. package/scripts/install/REDIS_SETUP_VALIDATION.json +245 -0
  70. package/scripts/install/check-prerequisites.js +303 -0
  71. package/scripts/install/config-wizard.js +606 -0
  72. package/scripts/install/dependency-checker.js +385 -0
  73. package/scripts/install/health-check.js +765 -0
  74. package/scripts/install/install.js +256 -0
  75. package/scripts/install/installation-benchmark.js +461 -0
  76. package/scripts/install/quick-install.js +720 -0
  77. package/scripts/install/quick-start-wizard.js +295 -0
  78. package/scripts/install/redis-cli.js +289 -0
  79. package/scripts/install/redis-install-guides.md +407 -0
  80. package/scripts/install/redis-setup.js +559 -0
  81. package/scripts/install/redis-test.js +278 -0
  82. package/scripts/install/service-manager.js +672 -0
  83. package/scripts/install/setup.js +832 -0
  84. package/scripts/install/uninstall.js +526 -0
  85. package/scripts/install/update.js +461 -0
  86. package/scripts/install-pre-commit-hook.sh +127 -0
  87. package/scripts/legacy/README.md +272 -0
  88. package/scripts/legacy/batch-fix-ts.sh +54 -0
  89. package/scripts/legacy/build-migration.sh +105 -0
  90. package/scripts/legacy/build-monitor.js +209 -0
  91. package/scripts/legacy/build-with-filter.sh +84 -0
  92. package/scripts/legacy/build-workaround.sh +71 -0
  93. package/scripts/legacy/fix-ts-advanced.js +358 -0
  94. package/scripts/legacy/fix-ts-final.sh +50 -0
  95. package/scripts/legacy/fix-ts-targeted.sh +49 -0
  96. package/scripts/legacy/fix-typescript-errors.js +305 -0
  97. package/scripts/legacy/force-build.sh +63 -0
  98. package/scripts/legacy/optimize-performance.js +400 -0
  99. package/scripts/legacy/performance-monitor.js +263 -0
  100. package/scripts/legacy/performance-monitoring.js +532 -0
  101. package/scripts/legacy/performance-test-runner.js +645 -0
  102. package/scripts/legacy/quick-fix-ts.js +281 -0
  103. package/scripts/legacy/safe-build.sh +63 -0
  104. package/scripts/memory-monitor-coordinator.js +322 -0
  105. package/scripts/migrate-to-sdk.sh +520 -0
  106. package/scripts/migration/QUICK-START.md +189 -0
  107. package/scripts/migration/QUICK-START.md.backup-1760135091363 +189 -0
  108. package/scripts/migration/README.md +464 -0
  109. package/scripts/migration/TASK-1.3.2-COMPLETION-REPORT.md +500 -0
  110. package/scripts/migration/TASK-1.3.2-COMPLETION-REPORT.md.backup-1760135091348 +500 -0
  111. package/scripts/migration/UPDATE-PATHS-README.md +464 -0
  112. package/scripts/migration/UPDATE-PATHS-README.md.backup-1760135091337 +464 -0
  113. package/scripts/migration/example-patterns.json +19 -0
  114. package/scripts/migration/install-arm64.js +78 -0
  115. package/scripts/migration/install.js +83 -0
  116. package/scripts/migration/migrate-hooks.js +173 -0
  117. package/scripts/migration/migration-examples.ts +318 -0
  118. package/scripts/migration/reorganize-workspace.js +504 -0
  119. package/scripts/migration/test-update-paths.js +359 -0
  120. package/scripts/migration/update-paths.js +664 -0
  121. package/scripts/migration/validate-migration.js +647 -0
  122. package/scripts/monitor-loop.sh +65 -0
  123. package/scripts/monitor-memory.sh +47 -0
  124. package/scripts/monitor-migration.js +339 -0
  125. package/scripts/monitor.py +43 -0
  126. package/scripts/monitoring/README.md +178 -0
  127. package/scripts/monitoring/alert-monitor.sh +220 -0
  128. package/scripts/monitoring/analyze-resources.sh +199 -0
  129. package/scripts/monitoring/dashboards/rate-limiting-dashboard.json +211 -0
  130. package/scripts/monitoring/dynamic-monitor.sh +85 -0
  131. package/scripts/monitoring/launch-stability-test.sh +184 -0
  132. package/scripts/monitoring/monitor-test.sh +93 -0
  133. package/scripts/monitoring/pre-test-validation.sh +208 -0
  134. package/scripts/monitoring/quick-test-alerting.sh +118 -0
  135. package/scripts/monitoring/quick-test-rate-limiting.sh +206 -0
  136. package/scripts/monitoring/rate-limiting-monitor.sh +380 -0
  137. package/scripts/monitoring/resource-monitor.sh +126 -0
  138. package/scripts/monitoring/stability-monitor.js +429 -0
  139. package/scripts/monitoring/test-monitor-quick.sh +54 -0
  140. package/scripts/monitoring/view-alerts.sh +307 -0
  141. package/scripts/npm-metrics-collector.js +482 -0
  142. package/scripts/npm-package-validation.cjs +299 -0
  143. package/scripts/optimization/build-optimizer.js +438 -0
  144. package/scripts/optimization/config-validator.js +761 -0
  145. package/scripts/optimization/test-optimization.js +432 -0
  146. package/scripts/optimization/unified-activation.js +839 -0
  147. package/scripts/optimize-package-swarm.js +54 -0
  148. package/scripts/performance/ACTIVATION_COMMANDS.md +292 -0
  149. package/scripts/performance/sqlite-enhanced-activation.sh +583 -0
  150. package/scripts/performance/test-enhanced-backend.sh +504 -0
  151. package/scripts/performance-monitor.js +644 -0
  152. package/scripts/performance-test-runner.js +698 -0
  153. package/scripts/post-deployment-monitoring.js +350 -0
  154. package/scripts/post-edit-pipeline.js +2091 -0
  155. package/scripts/post-install-claude-md.js +78 -0
  156. package/scripts/postinstall.js +79 -0
  157. package/scripts/pre-publish-validation.cjs +212 -0
  158. package/scripts/pre-publish-validation.js +429 -0
  159. package/scripts/redis-lua/cleanup-blocking-coordination.lua +198 -0
  160. package/scripts/release-announcement.js +425 -0
  161. package/scripts/release-notification.js +248 -0
  162. package/scripts/release-rollback.js +376 -0
  163. package/scripts/release-validation.js +460 -0
  164. package/scripts/rollback-sdk.sh +66 -0
  165. package/scripts/run-production-validation.ts +590 -0
  166. package/scripts/run-stability-validation.sh +687 -0
  167. package/scripts/security/README.md +339 -0
  168. package/scripts/security/deployment-validation.cjs +279 -0
  169. package/scripts/security/envelope-encryption-confidence-report.cjs +422 -0
  170. package/scripts/security/install-git-hooks.sh +132 -0
  171. package/scripts/security/install-git-secrets.sh +295 -0
  172. package/scripts/security/rotate-api-keys.js +469 -0
  173. package/scripts/security/ruv-swarm-safe.js +74 -0
  174. package/scripts/security/security-audit.cjs +538 -0
  175. package/scripts/security/setup-redis-auth.sh +397 -0
  176. package/scripts/security/validate-envelope-encryption.cjs +340 -0
  177. package/scripts/security-scan.js +492 -0
  178. package/scripts/src/web/frontend/.claude-flow/metrics/agent-metrics.json +1 -0
  179. package/scripts/src/web/frontend/.claude-flow/metrics/performance.json +9 -0
  180. package/scripts/src/web/frontend/.claude-flow/metrics/task-metrics.json +10 -0
  181. package/scripts/switch-api.sh +158 -0
  182. package/scripts/sync-agents.js +290 -0
  183. package/scripts/test/50-agent-test.js +625 -0
  184. package/scripts/test/NEW_STABILITY_TEST_GUIDE.md +407 -0
  185. package/scripts/test/README.md +236 -0
  186. package/scripts/test/STABILITY_TEST_EXAMPLE.md +347 -0
  187. package/scripts/test/STABILITY_TEST_README.md +480 -0
  188. package/scripts/test/agent-worker.js +309 -0
  189. package/scripts/test/ai-coordination-test.js +650 -0
  190. package/scripts/test/ai-mesh-coordination-test.js +416 -0
  191. package/scripts/test/check-links.ts +274 -0
  192. package/scripts/test/check-performance-regression.ts +168 -0
  193. package/scripts/test/cli-agent-coordination-test.js +313 -0
  194. package/scripts/test/coordinator-multilingual-test.js +396 -0
  195. package/scripts/test/coordinator-transparency-demo.js +585 -0
  196. package/scripts/test/coverage-report.ts +692 -0
  197. package/scripts/test/generate-swarm-tests.js +633 -0
  198. package/scripts/test/integration-test-validation.cjs +253 -0
  199. package/scripts/test/load-test-swarm.js +576 -0
  200. package/scripts/test/mesh-coordination-zero-overlap-test.js +740 -0
  201. package/scripts/test/multilingual-hello-world-test.js +390 -0
  202. package/scripts/test/quick-multilingual-demo.js +464 -0
  203. package/scripts/test/real-agent-test.js +312 -0
  204. package/scripts/test/run-phase3-compliance-tests.js +427 -0
  205. package/scripts/test/run-stability-test-examples.sh +292 -0
  206. package/scripts/test/stability-results/stability-metrics.jsonl +83 -0
  207. package/scripts/test/stability-results/stability-test-report.json +128 -0
  208. package/scripts/test/stability-results/stability-test.log +1827 -0
  209. package/scripts/test/stability-test-50-agents.js +734 -0
  210. package/scripts/test/test-batch-tasks.ts +29 -0
  211. package/scripts/test/test-byzantine-resolution.js +246 -0
  212. package/scripts/test/test-claude-spawn-options.sh +63 -0
  213. package/scripts/test/test-cli-wizard.js +331 -0
  214. package/scripts/test/test-comprehensive.js +401 -0
  215. package/scripts/test/test-coordination-features.ts +238 -0
  216. package/scripts/test/test-fallback-systems.js +276 -0
  217. package/scripts/test/test-init-command.ts +302 -0
  218. package/scripts/test/test-mcp.ts +251 -0
  219. package/scripts/test/test-runner.ts +568 -0
  220. package/scripts/test/test-swarm-integration.sh +92 -0
  221. package/scripts/test/test-swarm.ts +142 -0
  222. package/scripts/test/validation-summary.ts +408 -0
  223. package/scripts/test-cleanup-performance.sh +416 -0
  224. package/scripts/test-dashboard-auth.cjs +203 -0
  225. package/scripts/test-docker-deployment.sh +207 -0
  226. package/scripts/test-npm-package.cjs +167 -0
  227. package/scripts/test-provider-routing.cjs +226 -0
  228. package/scripts/test-routing-telemetry.cjs +147 -0
  229. package/scripts/test-runner.cjs +154 -0
  230. package/scripts/test-zai-10k.cjs +81 -0
  231. package/scripts/test-zai-api.cjs +191 -0
  232. package/scripts/test-zai-diagnostic.cjs +151 -0
  233. package/scripts/test-zai-final.cjs +128 -0
  234. package/scripts/test-zai-with-env.cjs +85 -0
  235. package/scripts/utils/README.md +261 -0
  236. package/scripts/utils/clean-build-artifacts.sh +94 -0
  237. package/scripts/utils/cleanup-root.sh +69 -0
  238. package/scripts/utils/fix-cliffy-imports.js +307 -0
  239. package/scripts/utils/fix-duplicate-imports.js +114 -0
  240. package/scripts/utils/fix-error-handling.cjs +70 -0
  241. package/scripts/utils/fix-import-paths.js +104 -0
  242. package/scripts/utils/fix-imports.js +116 -0
  243. package/scripts/utils/fix-shebang.js +78 -0
  244. package/scripts/utils/fix-test-modules.js +27 -0
  245. package/scripts/utils/fix-timezone-issue-246.js +200 -0
  246. package/scripts/utils/fix-ts-comprehensive.py +182 -0
  247. package/scripts/utils/fix-ts-targeted-batch.js +250 -0
  248. package/scripts/utils/remove-benchmark-conflicts.sh +140 -0
  249. package/scripts/utils/simple-test-fixer.js +190 -0
  250. package/scripts/utils/validate-metrics-structure.cjs +144 -0
  251. package/scripts/validate-agent-hooks.js +506 -0
  252. package/scripts/validate-changelog.js +241 -0
  253. package/scripts/validate-coordination-cli.js +69 -0
  254. package/scripts/validate-coordination-toggle-integration.cjs +501 -0
  255. package/scripts/validate-docker-infrastructure.sh +502 -0
  256. package/scripts/validate-entry-points.js +300 -0
  257. package/scripts/validate-stage3-performance.ts +377 -0
  258. package/scripts/validate-template-bundling.js +180 -0
  259. package/scripts/validation/README.md +33 -0
  260. package/scripts/validation/acl-security-validation.cjs +214 -0
  261. package/scripts/validation/acl-security-validation.js +402 -0
  262. package/scripts/validation/byzantine-verification.js +407 -0
  263. package/scripts/validation/final-phase-2-consensus.cjs +219 -0
  264. package/scripts/validation/final-security-validation.js +791 -0
  265. package/scripts/validation/final-wasm-validation.cjs +840 -0
  266. package/scripts/validation/integration-test-analysis.js +105 -0
  267. package/scripts/validation/phase-0-comprehensive-validation.js +474 -0
  268. package/scripts/validation/phase-0-consensus-report.js +139 -0
  269. package/scripts/validation/phase-0-final-report.js +112 -0
  270. package/scripts/validation/phase-0-redis-consensus-report.js +129 -0
  271. package/scripts/validation/phase-0-validation-improved.js +490 -0
  272. package/scripts/validation/phase-0-validation-test.js +65 -0
  273. package/scripts/validation/phase-1-consensus-report.cjs +342 -0
  274. package/scripts/validation/phase-1-consensus-validation.cjs +551 -0
  275. package/scripts/validation/phase-1-consensus-validation.js +551 -0
  276. package/scripts/validation/phase-2-consensus-report.cjs +186 -0
  277. package/scripts/validation/phase-2-validation.cjs +171 -0
  278. package/scripts/validation/phase-2-validation.js +171 -0
  279. package/scripts/validation/phase-4-consensus-report.js +181 -0
  280. package/scripts/validation/phase-4-final-validation.js +351 -0
  281. package/scripts/validation/phase-5-consensus-report.cjs +113 -0
  282. package/scripts/validation/phase-5-consensus-report.js +113 -0
  283. package/scripts/validation/security-analysis.js +49 -0
  284. package/scripts/validation/security-validation.js +492 -0
  285. package/scripts/validation/simple-security-validation.js +464 -0
  286. package/scripts/verify-installation.js +112 -0
  287. package/scripts/verify-mcp-server.js +86 -0
  288. package/scripts/verify-sdk-phase1.cjs +293 -0
@@ -0,0 +1,869 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Unified Performance Monitor - Consolidates 4+ performance scripts
5
+ * Phase 12: Script Consolidation - Performance Testing & Monitoring
6
+ *
7
+ * Consolidates:
8
+ * - performance-test-runner.js
9
+ * - performance-monitor.js
10
+ * - performance-monitoring.js
11
+ * - build-monitor.js
12
+ * - optimize-performance.js
13
+ */
14
+
15
+ import { promises as fs } from 'fs';
16
+ import { exec } from 'child_process';
17
+ import { promisify } from 'util';
18
+ import path from 'path';
19
+ import { EventEmitter } from 'events';
20
+
21
+ const execAsync = promisify(exec);
22
+
23
+ class UnifiedPerformanceMonitor extends EventEmitter {
24
+ constructor() {
25
+ super();
26
+ this.version = '1.0.0';
27
+ this.monitoring = false;
28
+ this.startTime = Date.now();
29
+ this.metrics = {
30
+ build: { attempts: 0, successes: 0, failures: 0, avgTime: 0 },
31
+ performance: { tests: 0, passed: 0, failed: 0, avgDuration: 0 },
32
+ system: { cpu: [], memory: [], load: [] },
33
+ errors: { total: 0, byType: {}, recent: [] }
34
+ };
35
+ this.thresholds = {
36
+ buildTime: 300000, // 5 minutes
37
+ memoryUsage: 1024, // MB
38
+ cpuUsage: 80, // percentage
39
+ errorRate: 0.1 // 10%
40
+ };
41
+ this.reportFile = null;
42
+ this.logFile = null;
43
+ this.setupLogging();
44
+ }
45
+
46
+ setupLogging() {
47
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
48
+ this.reportFile = `reports/performance-${timestamp}.json`;
49
+ this.logFile = `logs/performance-${timestamp}.log`;
50
+
51
+ // Ensure directories exist
52
+ this.ensureDirectories();
53
+ }
54
+
55
+ async ensureDirectories() {
56
+ await fs.mkdir('reports', { recursive: true });
57
+ await fs.mkdir('logs', { recursive: true });
58
+ await fs.mkdir('.tmp-performance', { recursive: true });
59
+ }
60
+
61
+ log(message, level = 'info') {
62
+ const timestamp = new Date().toISOString();
63
+ const logEntry = `[${timestamp}] [${level.toUpperCase()}] ${message}`;
64
+
65
+ console.log(logEntry);
66
+
67
+ if (this.logFile) {
68
+ fs.appendFile(this.logFile, logEntry + '\n').catch(() => {});
69
+ }
70
+ }
71
+
72
+ // Performance Test Runner (from performance-test-runner.js)
73
+ async runPerformanceTests(type = 'basic', options = {}) {
74
+ this.log(`🚀 Starting performance tests: ${type}`);
75
+
76
+ const testConfigs = {
77
+ basic: {
78
+ name: 'basic-cli-operations',
79
+ description: 'Basic CLI command performance',
80
+ duration: 30000,
81
+ concurrency: 5,
82
+ targetThroughput: 10,
83
+ maxLatency: 1000
84
+ },
85
+ load: {
86
+ name: 'load-test-swarm',
87
+ description: 'Load test for swarm operations',
88
+ duration: 300000,
89
+ concurrency: parseInt(process.env.LOAD_TEST_CONCURRENCY || '50'),
90
+ targetThroughput: 100,
91
+ maxLatency: 2000
92
+ },
93
+ stress: {
94
+ name: 'stress-test-agents',
95
+ description: 'Stress test for agent spawning',
96
+ duration: 600000,
97
+ concurrency: parseInt(process.env.STRESS_TEST_MAX_CONCURRENCY || '200'),
98
+ targetThroughput: 50,
99
+ maxLatency: 5000
100
+ },
101
+ endurance: {
102
+ name: 'endurance-test-memory',
103
+ description: 'Endurance test for memory stability',
104
+ duration: parseInt(process.env.ENDURANCE_TEST_DURATION || '3600000'),
105
+ concurrency: parseInt(process.env.ENDURANCE_TEST_CONCURRENCY || '25'),
106
+ targetThroughput: 20,
107
+ maxLatency: 3000
108
+ }
109
+ };
110
+
111
+ const config = testConfigs[type];
112
+ if (!config) {
113
+ throw new Error(`Unknown test type: ${type}`);
114
+ }
115
+
116
+ const startTime = Date.now();
117
+ const results = {
118
+ config,
119
+ startTime,
120
+ endTime: null,
121
+ duration: null,
122
+ metrics: {
123
+ operations: 0,
124
+ successful: 0,
125
+ failed: 0,
126
+ avgLatency: 0,
127
+ maxLatency: 0,
128
+ throughput: 0,
129
+ errors: []
130
+ },
131
+ systemMetrics: {
132
+ cpu: { avg: 0, max: 0, samples: [] },
133
+ memory: { avg: 0, max: 0, samples: [] },
134
+ network: { in: 0, out: 0 }
135
+ }
136
+ };
137
+
138
+ try {
139
+ // Warmup phase
140
+ this.log('🔥 Warmup phase...');
141
+ await this.runWarmup(config);
142
+
143
+ // Main test phase
144
+ this.log(`🏃 Running ${type} performance test...`);
145
+ const testResult = await this.executePerformanceTest(config);
146
+
147
+ results.endTime = Date.now();
148
+ results.duration = results.endTime - startTime;
149
+ results.metrics = testResult;
150
+
151
+ // Collect system metrics
152
+ const systemMetrics = await this.collectSystemMetrics();
153
+ results.systemMetrics = systemMetrics;
154
+
155
+ // Validate against thresholds
156
+ const validation = this.validateResults(results);
157
+ results.validation = validation;
158
+
159
+ this.log(`✅ Performance test completed: ${type}`);
160
+ this.log(`📊 Operations: ${results.metrics.operations}`);
161
+ this.log(`📊 Success rate: ${((results.metrics.successful / results.metrics.operations) * 100).toFixed(2)}%`);
162
+ this.log(`📊 Avg latency: ${results.metrics.avgLatency.toFixed(2)}ms`);
163
+
164
+ // Update internal metrics
165
+ this.metrics.performance.tests++;
166
+ if (validation.passed) {
167
+ this.metrics.performance.passed++;
168
+ } else {
169
+ this.metrics.performance.failed++;
170
+ }
171
+
172
+ // Save results
173
+ await this.saveResults(results);
174
+
175
+ return results;
176
+
177
+ } catch (error) {
178
+ this.log(`❌ Performance test failed: ${error.message}`, 'error');
179
+ this.metrics.performance.failed++;
180
+ throw error;
181
+ }
182
+ }
183
+
184
+ async runWarmup(config) {
185
+ const warmupDuration = Math.min(config.duration * 0.1, 30000); // 10% of test duration, max 30s
186
+ const warmupOps = Math.ceil(config.concurrency * 2);
187
+
188
+ for (let i = 0; i < warmupOps; i++) {
189
+ try {
190
+ await this.simulateOperation('warmup');
191
+ } catch (err) {
192
+ // Ignore warmup errors
193
+ }
194
+ }
195
+
196
+ await new Promise(resolve => setTimeout(resolve, 1000));
197
+ }
198
+
199
+ async executePerformanceTest(config) {
200
+ const operations = [];
201
+ const startTime = Date.now();
202
+ const endTime = startTime + config.duration;
203
+ let operationCount = 0;
204
+
205
+ const metrics = {
206
+ operations: 0,
207
+ successful: 0,
208
+ failed: 0,
209
+ latencies: [],
210
+ errors: []
211
+ };
212
+
213
+ // Start monitoring
214
+ const monitorInterval = setInterval(async () => {
215
+ const sysMetrics = await this.getSystemSnapshot();
216
+ this.metrics.system.cpu.push(sysMetrics.cpu);
217
+ this.metrics.system.memory.push(sysMetrics.memory);
218
+ }, 5000);
219
+
220
+ try {
221
+ while (Date.now() < endTime) {
222
+ const batchPromises = [];
223
+
224
+ // Create batch of concurrent operations
225
+ for (let i = 0; i < config.concurrency && Date.now() < endTime; i++) {
226
+ batchPromises.push(this.executeOperation(operationCount++));
227
+ }
228
+
229
+ // Wait for batch completion
230
+ const batchResults = await Promise.allSettled(batchPromises);
231
+
232
+ // Process results
233
+ for (const result of batchResults) {
234
+ metrics.operations++;
235
+
236
+ if (result.status === 'fulfilled') {
237
+ metrics.successful++;
238
+ metrics.latencies.push(result.value.latency);
239
+ } else {
240
+ metrics.failed++;
241
+ metrics.errors.push(result.reason.message);
242
+ }
243
+ }
244
+
245
+ // Throttle based on target throughput
246
+ const expectedOperations = ((Date.now() - startTime) / 1000) * config.targetThroughput;
247
+ if (metrics.operations > expectedOperations) {
248
+ await new Promise(resolve => setTimeout(resolve, 100));
249
+ }
250
+ }
251
+
252
+ } finally {
253
+ clearInterval(monitorInterval);
254
+ }
255
+
256
+ // Calculate final metrics
257
+ metrics.avgLatency = metrics.latencies.length > 0 ?
258
+ metrics.latencies.reduce((a, b) => a + b, 0) / metrics.latencies.length : 0;
259
+
260
+ metrics.maxLatency = metrics.latencies.length > 0 ?
261
+ Math.max(...metrics.latencies) : 0;
262
+
263
+ metrics.throughput = metrics.operations / ((Date.now() - startTime) / 1000);
264
+
265
+ return metrics;
266
+ }
267
+
268
+ async executeOperation(operationId) {
269
+ const startTime = Date.now();
270
+
271
+ try {
272
+ // Simulate different types of operations
273
+ const operationType = this.selectOperationType();
274
+ await this.simulateOperation(operationType);
275
+
276
+ const latency = Date.now() - startTime;
277
+ return { operationId, latency, success: true };
278
+
279
+ } catch (error) {
280
+ const latency = Date.now() - startTime;
281
+ throw { operationId, latency, success: false, error: error.message };
282
+ }
283
+ }
284
+
285
+ selectOperationType() {
286
+ const operations = ['cli-command', 'swarm-spawn', 'agent-task', 'file-operation', 'memory-operation'];
287
+ return operations[Math.floor(Math.random() * operations.length)];
288
+ }
289
+
290
+ async simulateOperation(type) {
291
+ switch (type) {
292
+ case 'cli-command':
293
+ return this.simulateCLICommand();
294
+ case 'swarm-spawn':
295
+ return this.simulateSwarmSpawn();
296
+ case 'agent-task':
297
+ return this.simulateAgentTask();
298
+ case 'file-operation':
299
+ return this.simulateFileOperation();
300
+ case 'memory-operation':
301
+ return this.simulateMemoryOperation();
302
+ case 'warmup':
303
+ return new Promise(resolve => setTimeout(resolve, Math.random() * 100));
304
+ default:
305
+ throw new Error(`Unknown operation type: ${type}`);
306
+ }
307
+ }
308
+
309
+ async simulateCLICommand() {
310
+ // Simulate CLI command execution
311
+ const delay = 50 + Math.random() * 200; // 50-250ms
312
+ await new Promise(resolve => setTimeout(resolve, delay));
313
+
314
+ if (Math.random() < 0.05) { // 5% failure rate
315
+ throw new Error('CLI command failed');
316
+ }
317
+
318
+ return { type: 'cli-command', duration: delay };
319
+ }
320
+
321
+ async simulateSwarmSpawn() {
322
+ // Simulate swarm spawning operation
323
+ const delay = 100 + Math.random() * 500; // 100-600ms
324
+ await new Promise(resolve => setTimeout(resolve, delay));
325
+
326
+ if (Math.random() < 0.02) { // 2% failure rate
327
+ throw new Error('Swarm spawn failed');
328
+ }
329
+
330
+ return { type: 'swarm-spawn', duration: delay };
331
+ }
332
+
333
+ async simulateAgentTask() {
334
+ // Simulate agent task execution
335
+ const delay = 200 + Math.random() * 800; // 200-1000ms
336
+ await new Promise(resolve => setTimeout(resolve, delay));
337
+
338
+ if (Math.random() < 0.03) { // 3% failure rate
339
+ throw new Error('Agent task failed');
340
+ }
341
+
342
+ return { type: 'agent-task', duration: delay };
343
+ }
344
+
345
+ async simulateFileOperation() {
346
+ // Simulate file I/O operation
347
+ try {
348
+ const tempFile = `.tmp-performance/test-${Date.now()}-${Math.random().toString(36).substr(2, 9)}.tmp`;
349
+ const data = 'x'.repeat(1000 + Math.random() * 10000); // 1-11KB
350
+
351
+ await fs.writeFile(tempFile, data);
352
+ await fs.readFile(tempFile);
353
+ await fs.unlink(tempFile);
354
+
355
+ return { type: 'file-operation', size: data.length };
356
+
357
+ } catch (error) {
358
+ throw new Error(`File operation failed: ${error.message}`);
359
+ }
360
+ }
361
+
362
+ async simulateMemoryOperation() {
363
+ // Simulate memory-intensive operation
364
+ const arraySize = 1000 + Math.random() * 10000;
365
+ const data = new Array(arraySize).fill(0).map(() => Math.random());
366
+
367
+ // Perform some operations
368
+ data.sort();
369
+ const sum = data.reduce((a, b) => a + b, 0);
370
+
371
+ return { type: 'memory-operation', arraySize, sum };
372
+ }
373
+
374
+ // Build Monitor (from build-monitor.js)
375
+ async startBuildMonitoring(options = {}) {
376
+ this.log('🐝 Starting build monitoring...');
377
+
378
+ const { interval = 30000, continuous = false } = options;
379
+ this.monitoring = true;
380
+
381
+ while (this.monitoring) {
382
+ try {
383
+ const buildResult = await this.checkBuildStatus();
384
+ this.processBuildResult(buildResult);
385
+
386
+ if (!continuous) {
387
+ break;
388
+ }
389
+
390
+ await new Promise(resolve => setTimeout(resolve, interval));
391
+
392
+ } catch (error) {
393
+ this.log(`❌ Build monitoring error: ${error.message}`, 'error');
394
+ this.metrics.errors.total++;
395
+ }
396
+ }
397
+ }
398
+
399
+ async checkBuildStatus() {
400
+ const startTime = Date.now();
401
+
402
+ try {
403
+ const { stdout, stderr } = await execAsync('npm run build 2>&1');
404
+ const buildOutput = stderr || stdout;
405
+ const errors = this.parseBuildErrors(buildOutput);
406
+
407
+ const buildTime = Date.now() - startTime;
408
+
409
+ this.metrics.build.attempts++;
410
+
411
+ const result = {
412
+ timestamp: new Date().toISOString(),
413
+ buildTime,
414
+ errorCount: errors.length,
415
+ errors,
416
+ success: errors.length === 0,
417
+ output: buildOutput
418
+ };
419
+
420
+ if (result.success) {
421
+ this.metrics.build.successes++;
422
+ } else {
423
+ this.metrics.build.failures++;
424
+ }
425
+
426
+ this.metrics.build.avgTime =
427
+ ((this.metrics.build.avgTime * (this.metrics.build.attempts - 1)) + buildTime) /
428
+ this.metrics.build.attempts;
429
+
430
+ return result;
431
+
432
+ } catch (error) {
433
+ this.metrics.build.failures++;
434
+ throw error;
435
+ }
436
+ }
437
+
438
+ parseBuildErrors(output) {
439
+ if (!output) return [];
440
+
441
+ const errorLines = output.split('\n').filter(line =>
442
+ line.includes('error TS') ||
443
+ line.includes('Error:') ||
444
+ line.includes('✘ [ERROR]')
445
+ );
446
+
447
+ return errorLines.map(line => {
448
+ const tsMatch = line.match(/([^:]+):\s*error\s+TS(\d+):\s*(.+)/);
449
+ if (tsMatch) {
450
+ return {
451
+ type: 'typescript',
452
+ file: tsMatch[1],
453
+ code: tsMatch[2],
454
+ message: tsMatch[3]
455
+ };
456
+ }
457
+
458
+ return {
459
+ type: 'general',
460
+ message: line.trim()
461
+ };
462
+ });
463
+ }
464
+
465
+ processBuildResult(result) {
466
+ if (result.success) {
467
+ this.log(`✅ Build successful (${result.buildTime}ms)`);
468
+ } else {
469
+ this.log(`❌ Build failed with ${result.errorCount} errors`, 'error');
470
+
471
+ // Track error types
472
+ for (const error of result.errors) {
473
+ const errorType = error.code || error.type || 'unknown';
474
+ this.metrics.errors.byType[errorType] =
475
+ (this.metrics.errors.byType[errorType] || 0) + 1;
476
+ }
477
+
478
+ this.metrics.errors.recent = result.errors.slice(-10); // Keep last 10 errors
479
+ }
480
+
481
+ // Emit events for external handlers
482
+ this.emit('buildResult', result);
483
+
484
+ if (result.buildTime > this.thresholds.buildTime) {
485
+ this.emit('buildSlow', result);
486
+ }
487
+ }
488
+
489
+ // System Metrics Collection
490
+ async collectSystemMetrics() {
491
+ try {
492
+ const metrics = {
493
+ timestamp: Date.now(),
494
+ cpu: await this.getCPUUsage(),
495
+ memory: await this.getMemoryUsage(),
496
+ disk: await this.getDiskUsage(),
497
+ network: await this.getNetworkUsage(),
498
+ processes: await this.getProcessInfo()
499
+ };
500
+
501
+ return metrics;
502
+
503
+ } catch (error) {
504
+ this.log(`Warning: Could not collect system metrics: ${error.message}`, 'warn');
505
+ return null;
506
+ }
507
+ }
508
+
509
+ async getSystemSnapshot() {
510
+ try {
511
+ return {
512
+ cpu: await this.getCPUUsage(),
513
+ memory: await this.getMemoryUsage(),
514
+ timestamp: Date.now()
515
+ };
516
+ } catch (error) {
517
+ return { cpu: 0, memory: 0, timestamp: Date.now() };
518
+ }
519
+ }
520
+
521
+ async getCPUUsage() {
522
+ try {
523
+ if (process.platform === 'linux') {
524
+ const { stdout } = await execAsync("top -bn1 | grep 'Cpu(s)' | awk '{print $2}' | cut -d'%' -f1");
525
+ return parseFloat(stdout.trim()) || 0;
526
+ } else if (process.platform === 'darwin') {
527
+ const { stdout } = await execAsync("top -l 1 -n 0 | grep 'CPU usage' | awk '{print $3}' | cut -d'%' -f1");
528
+ return parseFloat(stdout.trim()) || 0;
529
+ } else {
530
+ // Windows or fallback
531
+ return 0;
532
+ }
533
+ } catch (error) {
534
+ return 0;
535
+ }
536
+ }
537
+
538
+ async getMemoryUsage() {
539
+ try {
540
+ const usage = process.memoryUsage();
541
+ return {
542
+ rss: Math.round(usage.rss / 1024 / 1024), // MB
543
+ heapTotal: Math.round(usage.heapTotal / 1024 / 1024),
544
+ heapUsed: Math.round(usage.heapUsed / 1024 / 1024),
545
+ external: Math.round(usage.external / 1024 / 1024)
546
+ };
547
+ } catch (error) {
548
+ return { rss: 0, heapTotal: 0, heapUsed: 0, external: 0 };
549
+ }
550
+ }
551
+
552
+ async getDiskUsage() {
553
+ try {
554
+ if (process.platform !== 'win32') {
555
+ const { stdout } = await execAsync("df -h . | tail -1 | awk '{print $5}' | cut -d'%' -f1");
556
+ return parseInt(stdout.trim()) || 0;
557
+ }
558
+ return 0;
559
+ } catch (error) {
560
+ return 0;
561
+ }
562
+ }
563
+
564
+ async getNetworkUsage() {
565
+ // Simplified network usage - would need more complex implementation for real metrics
566
+ return { in: 0, out: 0 };
567
+ }
568
+
569
+ async getProcessInfo() {
570
+ try {
571
+ const { stdout } = await execAsync('ps aux | grep node | grep -v grep | wc -l');
572
+ return {
573
+ nodeProcesses: parseInt(stdout.trim()) || 0
574
+ };
575
+ } catch (error) {
576
+ return { nodeProcesses: 0 };
577
+ }
578
+ }
579
+
580
+ // Results validation
581
+ validateResults(results) {
582
+ const validation = {
583
+ passed: true,
584
+ issues: [],
585
+ score: 100
586
+ };
587
+
588
+ // Check latency
589
+ if (results.metrics.avgLatency > results.config.maxLatency) {
590
+ validation.passed = false;
591
+ validation.issues.push(`Average latency ${results.metrics.avgLatency.toFixed(2)}ms exceeds threshold ${results.config.maxLatency}ms`);
592
+ validation.score -= 20;
593
+ }
594
+
595
+ // Check throughput
596
+ const actualThroughput = results.metrics.operations / (results.duration / 1000);
597
+ if (actualThroughput < results.config.targetThroughput * 0.8) {
598
+ validation.passed = false;
599
+ validation.issues.push(`Throughput ${actualThroughput.toFixed(2)} ops/s below 80% of target ${results.config.targetThroughput} ops/s`);
600
+ validation.score -= 15;
601
+ }
602
+
603
+ // Check success rate
604
+ const successRate = results.metrics.successful / results.metrics.operations;
605
+ if (successRate < 0.95) {
606
+ validation.passed = false;
607
+ validation.issues.push(`Success rate ${(successRate * 100).toFixed(2)}% below 95%`);
608
+ validation.score -= 25;
609
+ }
610
+
611
+ // Check system metrics
612
+ if (results.systemMetrics && results.systemMetrics.memory.max > this.thresholds.memoryUsage) {
613
+ validation.issues.push(`Peak memory usage ${results.systemMetrics.memory.max}MB exceeds threshold`);
614
+ validation.score -= 10;
615
+ }
616
+
617
+ validation.score = Math.max(0, validation.score);
618
+ return validation;
619
+ }
620
+
621
+ // Results management
622
+ async saveResults(results) {
623
+ try {
624
+ // Save detailed results
625
+ await fs.writeFile(this.reportFile, JSON.stringify(results, null, 2));
626
+
627
+ // Save summary
628
+ const summary = {
629
+ timestamp: results.startTime,
630
+ test: results.config.name,
631
+ duration: results.duration,
632
+ operations: results.metrics.operations,
633
+ successRate: (results.metrics.successful / results.metrics.operations * 100).toFixed(2),
634
+ avgLatency: results.metrics.avgLatency.toFixed(2),
635
+ throughput: results.metrics.throughput.toFixed(2),
636
+ passed: results.validation.passed,
637
+ score: results.validation.score
638
+ };
639
+
640
+ const summaryFile = 'reports/performance-summary.json';
641
+ let summaries = [];
642
+
643
+ try {
644
+ const existing = await fs.readFile(summaryFile, 'utf8');
645
+ summaries = JSON.parse(existing);
646
+ } catch (err) {
647
+ // File doesn't exist, start fresh
648
+ }
649
+
650
+ summaries.push(summary);
651
+
652
+ // Keep only last 100 results
653
+ if (summaries.length > 100) {
654
+ summaries = summaries.slice(-100);
655
+ }
656
+
657
+ await fs.writeFile(summaryFile, JSON.stringify(summaries, null, 2));
658
+
659
+ this.log(`📊 Results saved to ${this.reportFile}`);
660
+
661
+ } catch (error) {
662
+ this.log(`❌ Failed to save results: ${error.message}`, 'error');
663
+ }
664
+ }
665
+
666
+ // Report generation
667
+ async generateReport(options = {}) {
668
+ const { format = 'summary', timeframe = '24h' } = options;
669
+
670
+ this.log(`📋 Generating ${format} report for ${timeframe}...`);
671
+
672
+ try {
673
+ const summaryFile = 'reports/performance-summary.json';
674
+ const summaries = JSON.parse(await fs.readFile(summaryFile, 'utf8'));
675
+
676
+ // Filter by timeframe
677
+ const cutoff = Date.now() - this.parseTimeframe(timeframe);
678
+ const filtered = summaries.filter(s => s.timestamp > cutoff);
679
+
680
+ if (format === 'summary') {
681
+ return this.generateSummaryReport(filtered);
682
+ } else if (format === 'detailed') {
683
+ return this.generateDetailedReport(filtered);
684
+ } else if (format === 'json') {
685
+ return filtered;
686
+ }
687
+
688
+ } catch (error) {
689
+ this.log(`❌ Failed to generate report: ${error.message}`, 'error');
690
+ return null;
691
+ }
692
+ }
693
+
694
+ generateSummaryReport(data) {
695
+ if (data.length === 0) {
696
+ return 'No performance data found for the specified timeframe.';
697
+ }
698
+
699
+ const avgScore = data.reduce((sum, d) => sum + d.score, 0) / data.length;
700
+ const passed = data.filter(d => d.passed).length;
701
+ const failed = data.length - passed;
702
+
703
+ let report = '\n📊 Performance Summary Report\n';
704
+ report += '================================\n\n';
705
+ report += `Total Tests: ${data.length}\n`;
706
+ report += `Passed: ${passed} (${(passed/data.length*100).toFixed(1)}%)\n`;
707
+ report += `Failed: ${failed} (${(failed/data.length*100).toFixed(1)}%)\n`;
708
+ report += `Average Score: ${avgScore.toFixed(1)}/100\n\n`;
709
+
710
+ // Test type breakdown
711
+ const byType = {};
712
+ data.forEach(d => {
713
+ byType[d.test] = (byType[d.test] || 0) + 1;
714
+ });
715
+
716
+ report += 'Test Distribution:\n';
717
+ Object.entries(byType).forEach(([test, count]) => {
718
+ report += ` ${test}: ${count}\n`;
719
+ });
720
+
721
+ // Recent performance
722
+ const recent = data.slice(-5);
723
+ report += '\nRecent Performance:\n';
724
+ recent.forEach(d => {
725
+ const status = d.passed ? '✅' : '❌';
726
+ report += ` ${status} ${d.test}: ${d.score}/100 (${d.successRate}% success)\n`;
727
+ });
728
+
729
+ return report;
730
+ }
731
+
732
+ generateDetailedReport(data) {
733
+ // More detailed analysis would go here
734
+ return this.generateSummaryReport(data) + '\n\nDetailed metrics available in JSON format.';
735
+ }
736
+
737
+ parseTimeframe(timeframe) {
738
+ const unit = timeframe.slice(-1);
739
+ const value = parseInt(timeframe.slice(0, -1));
740
+
741
+ switch (unit) {
742
+ case 'h': return value * 60 * 60 * 1000;
743
+ case 'd': return value * 24 * 60 * 60 * 1000;
744
+ case 'w': return value * 7 * 24 * 60 * 60 * 1000;
745
+ default: return 24 * 60 * 60 * 1000; // Default 24h
746
+ }
747
+ }
748
+
749
+ // Control methods
750
+ stopMonitoring() {
751
+ this.monitoring = false;
752
+ this.log('🛑 Monitoring stopped');
753
+ }
754
+
755
+ getMetrics() {
756
+ return {
757
+ ...this.metrics,
758
+ uptime: Date.now() - this.startTime,
759
+ monitoring: this.monitoring
760
+ };
761
+ }
762
+
763
+ printUsage() {
764
+ console.log('Unified Performance Monitor v' + this.version);
765
+ console.log('Comprehensive performance testing and monitoring utility');
766
+ console.log('');
767
+ console.log('Usage: node performance-monitor.js [command] [options]');
768
+ console.log('');
769
+ console.log('Commands:');
770
+ console.log(' test [type] Run performance tests (basic|load|stress|endurance)');
771
+ console.log(' monitor Start build monitoring');
772
+ console.log(' report [format] Generate performance report (summary|detailed|json)');
773
+ console.log(' metrics Show current metrics');
774
+ console.log(' help Show this help');
775
+ console.log('');
776
+ console.log('Options:');
777
+ console.log(' --continuous Run monitoring continuously');
778
+ console.log(' --interval N Monitoring interval in ms (default: 30000)');
779
+ console.log(' --timeframe T Report timeframe (24h|7d|30d, default: 24h)');
780
+ console.log(' --format F Report format (summary|detailed|json)');
781
+ console.log(' --dry-run Show what would be done');
782
+ console.log('');
783
+ console.log('Examples:');
784
+ console.log(' node performance-monitor.js test basic');
785
+ console.log(' node performance-monitor.js monitor --continuous');
786
+ console.log(' node performance-monitor.js report --format detailed --timeframe 7d');
787
+ console.log(' node performance-monitor.js metrics');
788
+ }
789
+ }
790
+
791
+ // Main execution
792
+ async function main() {
793
+ const args = process.argv.slice(2);
794
+ const monitor = new UnifiedPerformanceMonitor();
795
+
796
+ if (args.length === 0 || args[0] === 'help' || args[0] === '--help') {
797
+ monitor.printUsage();
798
+ process.exit(0);
799
+ }
800
+
801
+ const command = args[0];
802
+ const options = {};
803
+
804
+ // Parse options
805
+ for (let i = 1; i < args.length; i++) {
806
+ const arg = args[i];
807
+ if (arg === '--continuous') {
808
+ options.continuous = true;
809
+ } else if (arg === '--interval') {
810
+ options.interval = parseInt(args[++i]) || 30000;
811
+ } else if (arg === '--timeframe') {
812
+ options.timeframe = args[++i] || '24h';
813
+ } else if (arg === '--format') {
814
+ options.format = args[++i] || 'summary';
815
+ } else if (arg === '--dry-run') {
816
+ options.dryRun = true;
817
+ } else if (!arg.startsWith('--') && command === 'test') {
818
+ options.testType = arg;
819
+ }
820
+ }
821
+
822
+ try {
823
+ switch (command) {
824
+ case 'test':
825
+ const testType = options.testType || 'basic';
826
+ const result = await monitor.runPerformanceTests(testType, options);
827
+ console.log(`\n🎯 Test Result: ${result.validation.passed ? 'PASSED' : 'FAILED'}`);
828
+ console.log(`📊 Score: ${result.validation.score}/100`);
829
+ break;
830
+
831
+ case 'monitor':
832
+ await monitor.startBuildMonitoring(options);
833
+ break;
834
+
835
+ case 'report':
836
+ const report = await monitor.generateReport(options);
837
+ console.log(report);
838
+ break;
839
+
840
+ case 'metrics':
841
+ const metrics = monitor.getMetrics();
842
+ console.log(JSON.stringify(metrics, null, 2));
843
+ break;
844
+
845
+ default:
846
+ console.error(`Unknown command: ${command}`);
847
+ monitor.printUsage();
848
+ process.exit(1);
849
+ }
850
+
851
+ // Coordination hook
852
+ try {
853
+ await execAsync('npx claude-flow@alpha hooks post-edit --file "performance-monitor" --memory-key "swarm/phase12/performance"');
854
+ } catch (err) {
855
+ // Ignore hook errors
856
+ }
857
+
858
+ } catch (error) {
859
+ console.error('❌ Error:', error.message);
860
+ process.exit(1);
861
+ }
862
+ }
863
+
864
+ // Execute if run directly
865
+ if (import.meta.url === `file://${process.argv[1]}`) {
866
+ main();
867
+ }
868
+
869
+ export { UnifiedPerformanceMonitor };