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,963 @@
1
+ /**
2
+ * Simplified Auto-Scaling Engine Demo (No Redis Required)
3
+ * Demonstrates the Phase 2 Auto-Scaling Engine algorithms and logic
4
+ */
5
+
6
+ // Mock Redis for demonstration
7
+ class MockRedis {
8
+ constructor() {
9
+ this.data = new Map();
10
+ this.subscribers = new Map();
11
+ }
12
+
13
+ async get(key) {
14
+ return this.data.get(key);
15
+ }
16
+
17
+ async set(key, value) {
18
+ this.data.set(key, value);
19
+ }
20
+
21
+ async hget(hash, field) {
22
+ const hashData = this.data.get(hash) || {};
23
+ return hashData[field];
24
+ }
25
+
26
+ async hset(hash, field, value) {
27
+ const hashData = this.data.get(hash) || {};
28
+ hashData[field] = value;
29
+ this.data.set(hash, hashData);
30
+ }
31
+
32
+ async hgetall(hash) {
33
+ return this.data.get(hash) || {};
34
+ }
35
+
36
+ async llen(key) {
37
+ const list = this.data.get(key) || [];
38
+ return list.length;
39
+ }
40
+
41
+ async lpush(key, ...items) {
42
+ const list = this.data.get(key) || [];
43
+ list.unshift(...items);
44
+ this.data.set(key, list);
45
+ return list.length;
46
+ }
47
+
48
+ async lpop(key) {
49
+ const list = this.data.get(key) || [];
50
+ return list.shift();
51
+ }
52
+
53
+ async subscribe(channel) {
54
+ return Promise.resolve();
55
+ }
56
+
57
+ async publish(channel, message) {
58
+ const subscribers = this.subscribers.get(channel) || [];
59
+ subscribers.forEach(callback => {
60
+ try {
61
+ callback(channel, message);
62
+ } catch (error) {
63
+ console.error('Subscriber error:', error);
64
+ }
65
+ });
66
+ return Promise.resolve();
67
+ }
68
+
69
+ on(event, callback) {
70
+ if (event === 'message') {
71
+ // Store callback for later use
72
+ this.messageCallback = callback;
73
+ }
74
+ }
75
+
76
+ async quit() {
77
+ return Promise.resolve();
78
+ }
79
+ }
80
+
81
+ // Simplified Scaling Algorithm implementation
82
+ class ScalingAlgorithm {
83
+ constructor(type, config = {}) {
84
+ this.type = type;
85
+ this.config = {
86
+ predictive: {
87
+ lookbackWindow: 300,
88
+ forecastWindow: 60,
89
+ minConfidence: 0.7
90
+ },
91
+ reactive: {
92
+ thresholds: {
93
+ scaleUp: 0.8,
94
+ scaleDown: 0.3
95
+ },
96
+ cooldown: {
97
+ scaleUp: 30000,
98
+ scaleDown: 120000
99
+ }
100
+ },
101
+ hybrid: {
102
+ predictiveWeight: 0.6,
103
+ reactiveWeight: 0.4
104
+ },
105
+ ...config
106
+ };
107
+ this.metrics = new Map();
108
+ this.lastDecision = null;
109
+ this.lastScaleTime = { up: 0, down: 0 };
110
+ }
111
+
112
+ async analyze(metrics) {
113
+ this.updateMetrics(metrics);
114
+
115
+ switch (this.type) {
116
+ case 'predictive':
117
+ return this.predictiveScaling();
118
+ case 'reactive':
119
+ return this.reactiveScaling();
120
+ case 'hybrid':
121
+ return this.hybridScaling();
122
+ default:
123
+ throw new Error(`Unknown scaling algorithm type: ${this.type}`);
124
+ }
125
+ }
126
+
127
+ predictiveScaling() {
128
+ const currentMetrics = this.getCurrentMetrics();
129
+
130
+ if (!currentMetrics || currentMetrics.length < 5) {
131
+ return this.createDecision('no_action', 0.5, 'Insufficient data for prediction');
132
+ }
133
+
134
+ // Simple trend calculation
135
+ const recentMetrics = currentMetrics.slice(-5);
136
+ const avgUtilization = recentMetrics.reduce((sum, m) => sum + m.utilization, 0) / recentMetrics.length;
137
+ const trend = recentMetrics[recentMetrics.length - 1].utilization - recentMetrics[0].utilization;
138
+
139
+ const forecastedUtilization = Math.max(0, Math.min(1, avgUtilization + trend * 0.5));
140
+ const confidence = 0.7 + Math.random() * 0.2; // Simulated confidence
141
+
142
+ if (forecastedUtilization > 0.8) {
143
+ return this.createDecision('scale_up', confidence,
144
+ `Predicted high utilization: ${(forecastedUtilization * 100).toFixed(1)}%`);
145
+ } else if (forecastedUtilization < 0.3) {
146
+ return this.createDecision('scale_down', confidence,
147
+ `Predicted low utilization: ${(forecastedUtilization * 100).toFixed(1)}%`);
148
+ }
149
+
150
+ return this.createDecision('no_action', confidence, 'Predicted optimal utilization');
151
+ }
152
+
153
+ reactiveScaling() {
154
+ const config = this.config.reactive;
155
+ const currentMetrics = this.getCurrentMetrics();
156
+ const now = Date.now();
157
+
158
+ if (!currentMetrics || currentMetrics.length === 0) {
159
+ return this.createDecision('no_action', 0.5, 'No metrics available');
160
+ }
161
+
162
+ const latestMetric = currentMetrics[currentMetrics.length - 1];
163
+ const utilization = latestMetric.utilization;
164
+
165
+ if (utilization > config.thresholds.scaleUp) {
166
+ if (now - this.lastScaleTime.up < config.cooldown.scaleUp) {
167
+ return this.createDecision('no_action', 0.8, 'Scale up cooldown active');
168
+ }
169
+
170
+ this.lastScaleTime.up = now;
171
+ return this.createDecision('scale_up', 0.9,
172
+ `High utilization: ${(utilization * 100).toFixed(1)}%`);
173
+ } else if (utilization < config.thresholds.scaleDown) {
174
+ if (now - this.lastScaleTime.down < config.cooldown.scaleDown) {
175
+ return this.createDecision('no_action', 0.8, 'Scale down cooldown active');
176
+ }
177
+
178
+ this.lastScaleTime.down = now;
179
+ return this.createDecision('scale_down', 0.9,
180
+ `Low utilization: ${(utilization * 100).toFixed(1)}%`);
181
+ }
182
+
183
+ return this.createDecision('no_action', 0.7, 'Utilization within optimal range');
184
+ }
185
+
186
+ hybridScaling() {
187
+ const predictiveResult = this.predictiveScaling();
188
+ const reactiveResult = this.reactiveScaling();
189
+
190
+ const weightedConfidence =
191
+ (predictiveResult.confidence * this.config.hybrid.predictiveWeight) +
192
+ (reactiveResult.confidence * this.config.hybrid.reactiveWeight);
193
+
194
+ if (predictiveResult.action === reactiveResult.action) {
195
+ return {
196
+ ...predictiveResult,
197
+ confidence: Math.min(0.95, weightedConfidence + 0.1),
198
+ reasoning: `Consensus: ${predictiveResult.reasoning} | ${reactiveResult.reasoning}`
199
+ };
200
+ }
201
+
202
+ if (reactiveResult.action !== 'no_action') {
203
+ return {
204
+ ...reactiveResult,
205
+ confidence: weightedConfidence,
206
+ reasoning: `Reactive priority: ${reactiveResult.reasoning}`
207
+ };
208
+ }
209
+
210
+ return {
211
+ ...predictiveResult,
212
+ confidence: weightedConfidence * 0.8,
213
+ reasoning: `Predictive preference: ${predictiveResult.reasoning}`
214
+ };
215
+ }
216
+
217
+ updateMetrics(metrics) {
218
+ const timestamp = Date.now();
219
+ this.metrics.set(timestamp, {
220
+ timestamp,
221
+ ...metrics,
222
+ utilization: this.calculateUtilization(metrics)
223
+ });
224
+
225
+ // Keep only recent metrics
226
+ const cutoffTime = timestamp - (this.config.predictive.lookbackWindow * 1000);
227
+ for (const [key] of this.metrics) {
228
+ if (key < cutoffTime) {
229
+ this.metrics.delete(key);
230
+ }
231
+ }
232
+ }
233
+
234
+ calculateUtilization(metrics) {
235
+ if (!metrics) return 0;
236
+
237
+ const weights = { cpu: 0.3, memory: 0.2, taskQueue: 0.3, responseTime: 0.2 };
238
+
239
+ const utilization = {
240
+ cpu: Math.min(1, metrics.cpu || 0),
241
+ memory: Math.min(1, metrics.memory || 0),
242
+ taskQueue: Math.min(1, metrics.taskQueue / 10 || 0),
243
+ responseTime: Math.min(1, metrics.responseTime / 1000 || 0)
244
+ };
245
+
246
+ return Object.keys(weights).reduce((total, key) =>
247
+ total + (utilization[key] * weights[key]), 0);
248
+ }
249
+
250
+ getCurrentMetrics() {
251
+ return Array.from(this.metrics.values())
252
+ .sort((a, b) => a.timestamp - b.timestamp);
253
+ }
254
+
255
+ createDecision(action, confidence, reasoning) {
256
+ this.lastDecision = {
257
+ action,
258
+ confidence,
259
+ reasoning,
260
+ timestamp: Date.now(),
261
+ algorithm: this.type
262
+ };
263
+ return this.lastDecision;
264
+ }
265
+ }
266
+
267
+ // Simplified Pool Manager
268
+ class DynamicPoolManager {
269
+ constructor(config = {}) {
270
+ this.config = {
271
+ pool: {
272
+ minSize: 5,
273
+ maxSize: 200,
274
+ initialSize: 10
275
+ },
276
+ scaling: {
277
+ algorithm: 'hybrid',
278
+ scaleUpCooldown: 30000,
279
+ scaleDownCooldown: 120000,
280
+ checkInterval: 5000
281
+ }
282
+ };
283
+
284
+ this.agents = new Map();
285
+ this.metrics = new Map();
286
+ this.lastScaleTime = { up: 0, down: 0 };
287
+ this.isRunning = false;
288
+ this.stats = {
289
+ scaleUps: 0,
290
+ scaleDowns: 0,
291
+ totalAgents: 0,
292
+ avgUtilization: 0
293
+ };
294
+
295
+ this.scalingAlgorithm = new ScalingAlgorithm(
296
+ this.config.scaling.algorithm,
297
+ this.config.scaling.config
298
+ );
299
+
300
+ this.initializePool();
301
+ }
302
+
303
+ initializePool() {
304
+ const initialSize = this.config.pool.initialSize;
305
+ console.log(`Initializing agent pool with ${initialSize} agents...`);
306
+
307
+ for (let i = 0; i < initialSize; i++) {
308
+ this.addAgent();
309
+ }
310
+
311
+ console.log(`Agent pool initialized with ${this.agents.size} agents`);
312
+ }
313
+
314
+ async start() {
315
+ if (this.isRunning) {
316
+ console.log('Dynamic Pool Manager is already running');
317
+ return;
318
+ }
319
+
320
+ this.isRunning = true;
321
+ console.log('Starting Dynamic Pool Manager...');
322
+
323
+ this.monitoringInterval = setInterval(async () => {
324
+ await this.checkScaling();
325
+ }, this.config.scaling.checkInterval);
326
+ }
327
+
328
+ async stop() {
329
+ if (!this.isRunning) {
330
+ return;
331
+ }
332
+
333
+ this.isRunning = false;
334
+ console.log('Stopping Dynamic Pool Manager...');
335
+
336
+ if (this.monitoringInterval) {
337
+ clearInterval(this.monitoringInterval);
338
+ }
339
+ }
340
+
341
+ async checkScaling() {
342
+ try {
343
+ const currentMetrics = await this.collectMetrics();
344
+ const scalingDecision = await this.scalingAlgorithm.analyze(currentMetrics);
345
+
346
+ console.log(`Scaling decision: ${scalingDecision.action} (${scalingDecision.reasoning})`);
347
+
348
+ if (scalingDecision.action === 'scale_up') {
349
+ await this.scaleUp(scalingDecision);
350
+ } else if (scalingDecision.action === 'scale_down') {
351
+ await this.scaleDown(scalingDecision);
352
+ }
353
+
354
+ await this.updateStats(currentMetrics);
355
+
356
+ } catch (error) {
357
+ console.error('Error during scaling check:', error);
358
+ }
359
+ }
360
+
361
+ async scaleUp(decision) {
362
+ const now = Date.now();
363
+ const cooldown = this.config.scaling.scaleUpCooldown;
364
+
365
+ if (now - this.lastScaleTime.up < cooldown) {
366
+ console.log('Scale up cooldown active, skipping');
367
+ return;
368
+ }
369
+
370
+ if (this.agents.size >= this.config.pool.maxSize) {
371
+ console.log('Pool at maximum size, cannot scale up');
372
+ return;
373
+ }
374
+
375
+ const agentsToAdd = Math.min(
376
+ Math.ceil(this.agents.size * 0.2),
377
+ this.config.pool.maxSize - this.agents.size
378
+ );
379
+
380
+ console.log(`โฌ†๏ธ Scaling up by ${agentsToAdd} agents: ${decision.reasoning}`);
381
+
382
+ for (let i = 0; i < agentsToAdd; i++) {
383
+ this.addAgent();
384
+ }
385
+
386
+ this.lastScaleTime.up = now;
387
+ this.stats.scaleUps++;
388
+ }
389
+
390
+ async scaleDown(decision) {
391
+ const now = Date.now();
392
+ const cooldown = this.config.scaling.scaleDownCooldown;
393
+
394
+ if (now - this.lastScaleTime.down < cooldown) {
395
+ console.log('Scale down cooldown active, skipping');
396
+ return;
397
+ }
398
+
399
+ if (this.agents.size <= this.config.pool.minSize) {
400
+ console.log('Pool at minimum size, cannot scale down');
401
+ return;
402
+ }
403
+
404
+ const agentsToRemove = Math.min(
405
+ Math.ceil(this.agents.size * 0.15),
406
+ this.agents.size - this.config.pool.minSize
407
+ );
408
+
409
+ console.log(`โฌ‡๏ธ Scaling down by ${agentsToRemove} agents: ${decision.reasoning}`);
410
+
411
+ for (let i = 0; i < agentsToRemove; i++) {
412
+ const agentId = this.getIdleAgents(1)[0];
413
+ if (agentId) {
414
+ this.removeAgent(agentId);
415
+ }
416
+ }
417
+
418
+ this.lastScaleTime.down = now;
419
+ this.stats.scaleDowns++;
420
+ }
421
+
422
+ addAgent() {
423
+ const agentId = `agent_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
424
+ const agent = {
425
+ id: agentId,
426
+ status: 'idle',
427
+ createdAt: Date.now(),
428
+ lastActivity: Date.now(),
429
+ tasksCompleted: 0,
430
+ utilization: 0
431
+ };
432
+
433
+ this.agents.set(agentId, agent);
434
+ return agentId;
435
+ }
436
+
437
+ removeAgent(agentId) {
438
+ const agent = this.agents.get(agentId);
439
+ if (!agent) {
440
+ console.warn(`Agent ${agentId} not found in pool`);
441
+ return;
442
+ }
443
+
444
+ agent.status = 'terminating';
445
+ this.agents.delete(agentId);
446
+ console.log(`Agent ${agentId} removed from pool`);
447
+ }
448
+
449
+ getIdleAgents(count) {
450
+ const agents = Array.from(this.agents.values())
451
+ .filter(agent => agent.status === 'idle')
452
+ .sort((a, b) => b.lastActivity - a.lastActivity)
453
+ .slice(0, count)
454
+ .map(agent => agent.id);
455
+
456
+ return agents;
457
+ }
458
+
459
+ async collectMetrics() {
460
+ const now = Date.now();
461
+ const activeAgents = Array.from(this.agents.values())
462
+ .filter(agent => agent.status === 'active');
463
+
464
+ const avgAgentUtilization = activeAgents.length > 0
465
+ ? activeAgents.reduce((sum, agent) => sum + agent.utilization, 0) / activeAgents.length
466
+ : 0;
467
+
468
+ // Simulate system metrics
469
+ const systemMetrics = {
470
+ cpu: 0.3 + Math.random() * 0.5,
471
+ memory: 0.4 + Math.random() * 0.4,
472
+ responseTime: 50 + Math.random() * 150
473
+ };
474
+
475
+ const metrics = {
476
+ timestamp: now,
477
+ poolSize: this.agents.size,
478
+ activeAgents: activeAgents.length,
479
+ idleAgents: this.agents.size - activeAgents.length,
480
+ agentUtilization: avgAgentUtilization,
481
+ taskQueue: Math.floor(Math.random() * 20),
482
+ responseTime: systemMetrics.responseTime,
483
+ cpu: systemMetrics.cpu,
484
+ memory: systemMetrics.memory
485
+ };
486
+
487
+ this.metrics.set(now, metrics);
488
+
489
+ // Keep only recent metrics
490
+ const cutoffTime = now - (60 * 60 * 1000);
491
+ for (const [timestamp] of this.metrics) {
492
+ if (timestamp < cutoffTime) {
493
+ this.metrics.delete(timestamp);
494
+ }
495
+ }
496
+
497
+ return metrics;
498
+ }
499
+
500
+ async updateStats(currentMetrics) {
501
+ this.stats.totalAgents = this.agents.size;
502
+ this.stats.avgUtilization = currentMetrics.agentUtilization;
503
+ }
504
+
505
+ getPoolStatus() {
506
+ const agents = Array.from(this.agents.values());
507
+ const activeAgents = agents.filter(a => a.status === 'active');
508
+ const idleAgents = agents.filter(a => a.status === 'idle');
509
+
510
+ return {
511
+ poolSize: agents.length,
512
+ activeAgents: activeAgents.length,
513
+ idleAgents: idleAgents.length,
514
+ utilization: activeAgents.length > 0
515
+ ? activeAgents.reduce((sum, a) => sum + a.utilization, 0) / activeAgents.length
516
+ : 0,
517
+ stats: this.stats,
518
+ config: this.config
519
+ };
520
+ }
521
+ }
522
+
523
+ // Performance Benchmarking
524
+ class PerformanceBenchmark {
525
+ constructor(config = {}) {
526
+ this.config = {
527
+ benchmarks: {
528
+ efficiency: {
529
+ target: 0.40,
530
+ measurementInterval: 60000,
531
+ baselineWindow: 300000
532
+ },
533
+ utilization: {
534
+ target: 0.85,
535
+ minThreshold: 0.7,
536
+ maxThreshold: 0.95
537
+ },
538
+ responseTime: {
539
+ target: 100,
540
+ maxAcceptable: 500
541
+ }
542
+ }
543
+ };
544
+
545
+ this.isRunning = false;
546
+ this.metrics = new Map();
547
+ this.baseline = null;
548
+ this.results = {
549
+ efficiency: 0,
550
+ utilization: 0,
551
+ responseTime: 0,
552
+ overall: 0
553
+ };
554
+
555
+ this.counters = {
556
+ tasksProcessed: 0,
557
+ scaleUpEvents: 0,
558
+ scaleDownEvents: 0,
559
+ totalResponseTime: 0,
560
+ responseTimeSamples: 0
561
+ };
562
+ }
563
+
564
+ async start() {
565
+ if (this.isRunning) {
566
+ console.log('Performance Benchmark is already running');
567
+ return;
568
+ }
569
+
570
+ this.isRunning = true;
571
+ console.log('Starting Performance Benchmark...');
572
+
573
+ await this.establishBaseline();
574
+
575
+ this.measurementInterval = setInterval(async () => {
576
+ await this.runBenchmarkCycle();
577
+ }, this.config.benchmarks.efficiency.measurementInterval);
578
+ }
579
+
580
+ async stop() {
581
+ if (!this.isRunning) {
582
+ return;
583
+ }
584
+
585
+ this.isRunning = false;
586
+ console.log('Stopping Performance Benchmark...');
587
+
588
+ if (this.measurementInterval) {
589
+ clearInterval(this.measurementInterval);
590
+ }
591
+ }
592
+
593
+ async establishBaseline() {
594
+ console.log('Establishing performance baseline...');
595
+
596
+ const baselineStart = Date.now();
597
+ const baselineMetrics = [];
598
+
599
+ const baselineInterval = setInterval(async () => {
600
+ const metrics = await this.collectCurrentMetrics();
601
+ baselineMetrics.push(metrics);
602
+
603
+ if (Date.now() - baselineStart >= 10000) { // 10 seconds for demo
604
+ clearInterval(baselineInterval);
605
+
606
+ this.baseline = this.calculateBaseline(baselineMetrics);
607
+ console.log('Baseline established:', this.baseline);
608
+ }
609
+ }, 2000);
610
+ }
611
+
612
+ calculateBaseline(metrics) {
613
+ if (metrics.length === 0) {
614
+ return { utilization: 0.5, responseTime: 200, throughput: 10 };
615
+ }
616
+
617
+ const avgUtilization = metrics.reduce((sum, m) => sum + m.utilization, 0) / metrics.length;
618
+ const avgResponseTime = metrics.reduce((sum, m) => sum + m.responseTime, 0) / metrics.length;
619
+ const avgThroughput = metrics.reduce((sum, m) => sum + m.throughput, 0) / metrics.length;
620
+
621
+ return {
622
+ utilization: avgUtilization,
623
+ responseTime: avgResponseTime,
624
+ throughput: avgThroughput,
625
+ timestamp: Date.now(),
626
+ sampleSize: metrics.length
627
+ };
628
+ }
629
+
630
+ async runBenchmarkCycle() {
631
+ try {
632
+ const cycleStart = Date.now();
633
+ const currentMetrics = await this.collectCurrentMetrics();
634
+
635
+ const efficiency = await this.calculateEfficiency(currentMetrics);
636
+ const utilization = await this.calculateUtilization(currentMetrics);
637
+ const responseTime = await this.calculateResponseTime(currentMetrics);
638
+
639
+ this.results = {
640
+ efficiency,
641
+ utilization,
642
+ responseTime,
643
+ overall: this.calculateOverallScore(efficiency, utilization, responseTime)
644
+ };
645
+
646
+ this.metrics.set(Date.now(), {
647
+ ...currentMetrics,
648
+ ...this.results
649
+ });
650
+
651
+ console.log(`๐Ÿ“Š Performance: Efficiency ${(efficiency * 100).toFixed(1)}%, ` +
652
+ `Utilization ${(utilization * 100).toFixed(1)}%, ` +
653
+ `Response Score ${(responseTime * 100).toFixed(1)}%`);
654
+
655
+ } catch (error) {
656
+ console.error('Error during benchmark cycle:', error);
657
+ }
658
+ }
659
+
660
+ async collectCurrentMetrics() {
661
+ // Simulate current metrics
662
+ return {
663
+ timestamp: Date.now(),
664
+ poolSize: 10 + Math.floor(Math.random() * 20),
665
+ activeAgents: 5 + Math.floor(Math.random() * 15),
666
+ taskQueueSize: Math.floor(Math.random() * 10),
667
+ utilization: 0.6 + Math.random() * 0.3,
668
+ responseTime: 80 + Math.random() * 120,
669
+ throughput: 8 + Math.random() * 12
670
+ };
671
+ }
672
+
673
+ async calculateEfficiency(currentMetrics) {
674
+ if (!this.baseline) {
675
+ return 0;
676
+ }
677
+
678
+ const baselineThroughput = this.baseline.throughput;
679
+ const currentThroughput = currentMetrics.throughput;
680
+
681
+ if (baselineThroughput === 0) return 0;
682
+
683
+ const efficiencyGain = (currentThroughput - baselineThroughput) / baselineThroughput;
684
+ return Math.max(0, efficiencyGain);
685
+ }
686
+
687
+ async calculateUtilization(currentMetrics) {
688
+ const target = this.config.benchmarks.utilization.target;
689
+ const currentUtilization = currentMetrics.utilization;
690
+
691
+ const distance = Math.abs(currentUtilization - target);
692
+ const maxDistance = Math.max(target, 1 - target);
693
+ const score = 1 - (distance / maxDistance);
694
+
695
+ if (currentUtilization < this.config.benchmarks.utilization.minThreshold ||
696
+ currentUtilization > this.config.benchmarks.utilization.maxThreshold) {
697
+ return score * 0.5;
698
+ }
699
+
700
+ return score;
701
+ }
702
+
703
+ async calculateResponseTime(currentMetrics) {
704
+ const target = this.config.benchmarks.responseTime.target;
705
+ const maxAcceptable = this.config.benchmarks.responseTime.maxAcceptable;
706
+ const currentResponseTime = currentMetrics.responseTime;
707
+
708
+ if (currentResponseTime <= target) {
709
+ return 1.0;
710
+ }
711
+
712
+ if (currentResponseTime >= maxAcceptable) {
713
+ return 0.0;
714
+ }
715
+
716
+ const ratio = (currentResponseTime - target) / (maxAcceptable - target);
717
+ return 1 - ratio;
718
+ }
719
+
720
+ calculateOverallScore(efficiency, utilization, responseTime) {
721
+ const weights = {
722
+ efficiency: 0.4,
723
+ utilization: 0.4,
724
+ responseTime: 0.2
725
+ };
726
+
727
+ return (
728
+ efficiency * weights.efficiency +
729
+ utilization * weights.utilization +
730
+ responseTime * weights.responseTime
731
+ );
732
+ }
733
+
734
+ getResults() {
735
+ return {
736
+ ...this.results,
737
+ counters: this.counters,
738
+ baseline: this.baseline,
739
+ timestamp: Date.now()
740
+ };
741
+ }
742
+ }
743
+
744
+ // Demo class
745
+ class AutoScalingDemo {
746
+ constructor() {
747
+ this.poolManager = null;
748
+ this.benchmark = null;
749
+ this.demoMetrics = {
750
+ startTime: Date.now(),
751
+ tasksSubmitted: 0,
752
+ scaleEvents: 0,
753
+ efficiencyMeasurements: []
754
+ };
755
+ }
756
+
757
+ async runDemo() {
758
+ console.log('๐Ÿš€ Phase 2 Auto-Scaling Engine Demo (Simplified)');
759
+ console.log('===============================================');
760
+
761
+ try {
762
+ await this.initializeComponents();
763
+ await this.demonstrateScalingAlgorithms();
764
+ await this.demonstratePerformanceTargets();
765
+ await this.generateDemoReport();
766
+
767
+ } catch (error) {
768
+ console.error('Demo failed:', error);
769
+ } finally {
770
+ await this.cleanup();
771
+ }
772
+ }
773
+
774
+ async initializeComponents() {
775
+ console.log('\n๐Ÿ“‹ Initializing Auto-Scaling Components...');
776
+
777
+ this.poolManager = new DynamicPoolManager({
778
+ pool: {
779
+ minSize: 3,
780
+ maxSize: 20,
781
+ initialSize: 5
782
+ }
783
+ });
784
+
785
+ this.benchmark = new PerformanceBenchmark();
786
+
787
+ // Set up event listeners
788
+ this.poolManager.on = (event, callback) => {
789
+ if (event === 'scaleUp') {
790
+ setInterval(() => {
791
+ if (Math.random() < 0.3) {
792
+ this.demoMetrics.scaleEvents++;
793
+ callback({ agentsAdded: 1, newPoolSize: this.poolManager.agents.size });
794
+ }
795
+ }, 8000);
796
+ }
797
+ };
798
+
799
+ await this.poolManager.start();
800
+ await this.benchmark.start();
801
+
802
+ console.log('โœ… Components initialized successfully');
803
+ }
804
+
805
+ async demonstrateScalingAlgorithms() {
806
+ console.log('\n๐Ÿ”ง Demonstrating Scaling Algorithms...');
807
+ console.log('------------------------------------');
808
+
809
+ const algorithms = ['reactive', 'predictive', 'hybrid'];
810
+
811
+ for (const algorithmType of algorithms) {
812
+ console.log(`\nTesting ${algorithmType} algorithm:`);
813
+
814
+ const algorithm = new ScalingAlgorithm(algorithmType);
815
+
816
+ // Simulate increasing load
817
+ for (let i = 0; i < 5; i++) {
818
+ const metrics = {
819
+ cpu: 0.3 + (i * 0.15),
820
+ memory: 0.4 + (i * 0.12),
821
+ taskQueue: i * 2,
822
+ responseTime: 50 + (i * 30)
823
+ };
824
+
825
+ const decision = await algorithm.analyze(metrics);
826
+ console.log(` Load ${i + 1}: ${decision.action} (confidence: ${(decision.confidence * 100).toFixed(1)}%)`);
827
+
828
+ await this.sleep(1000);
829
+ }
830
+ }
831
+ }
832
+
833
+ async demonstratePerformanceTargets() {
834
+ console.log('\n๐Ÿ“ˆ Demonstrating Performance Targets...');
835
+ console.log('-------------------------------------');
836
+
837
+ const targets = {
838
+ efficiency: 0.40,
839
+ utilization: 0.85,
840
+ responseTime: 100
841
+ };
842
+
843
+ console.log('Performance Targets:');
844
+ console.log(` โ€ข Efficiency: โ‰ฅ${(targets.efficiency * 100).toFixed(0)}% improvement`);
845
+ console.log(` โ€ข Utilization: โ‰ฅ${(targets.utilization * 100).toFixed(0)}% resource usage`);
846
+ console.log(` โ€ข Response Time: โ‰ค${targets.responseTime}ms average`);
847
+
848
+ // Simulate performance measurements
849
+ for (let i = 0; i < 5; i++) {
850
+ await this.sleep(2000);
851
+
852
+ const simulatedResults = {
853
+ efficiency: 0.35 + Math.random() * 0.20,
854
+ utilization: 0.75 + Math.random() * 0.20,
855
+ responseTime: 80 + Math.random() * 60
856
+ };
857
+
858
+ this.demoMetrics.efficiencyMeasurements.push({
859
+ timestamp: Date.now(),
860
+ ...simulatedResults
861
+ });
862
+
863
+ console.log(`\nMeasurement ${i + 1}:`);
864
+ console.log(` Efficiency: ${(simulatedResults.efficiency * 100).toFixed(1)}% ` +
865
+ `(${simulatedResults.efficiency >= targets.efficiency ? 'โœ…' : 'โŒ'})`);
866
+ console.log(` Utilization: ${(simulatedResults.utilization * 100).toFixed(1)}% ` +
867
+ `(${simulatedResults.utilization >= targets.utilization ? 'โœ…' : 'โŒ'})`);
868
+ console.log(` Response Time: ${simulatedResults.responseTime.toFixed(0)}ms ` +
869
+ `(${simulatedResults.responseTime <= targets.responseTime ? 'โœ…' : 'โŒ'})`);
870
+ }
871
+ }
872
+
873
+ async generateDemoReport() {
874
+ console.log('\n๐Ÿ“Š Demo Performance Report');
875
+ console.log('===========================');
876
+
877
+ const runtime = Date.now() - this.demoMetrics.startTime;
878
+ const minutes = Math.floor(runtime / 60000);
879
+ const seconds = Math.floor((runtime % 60000) / 1000);
880
+
881
+ console.log(`Runtime: ${minutes}m ${seconds}s`);
882
+ console.log(`Scale Events: ${this.demoMetrics.scaleEvents}`);
883
+
884
+ if (this.demoMetrics.efficiencyMeasurements.length > 0) {
885
+ const avgEfficiency = this.demoMetrics.efficiencyMeasurements
886
+ .reduce((sum, m) => sum + m.efficiency, 0) / this.demoMetrics.efficiencyMeasurements.length;
887
+ const avgUtilization = this.demoMetrics.efficiencyMeasurements
888
+ .reduce((sum, m) => sum + m.utilization, 0) / this.demoMetrics.efficiencyMeasurements.length;
889
+ const avgResponseTime = this.demoMetrics.efficiencyMeasurements
890
+ .reduce((sum, m) => sum + m.responseTime, 0) / this.demoMetrics.efficiencyMeasurements.length;
891
+
892
+ console.log(`Average Efficiency: ${(avgEfficiency * 100).toFixed(1)}%`);
893
+ console.log(`Average Utilization: ${(avgUtilization * 100).toFixed(1)}%`);
894
+ console.log(`Average Response Time: ${avgResponseTime.toFixed(0)}ms`);
895
+
896
+ const targets = { efficiency: 0.40, utilization: 0.85, responseTime: 100 };
897
+ const efficiencyTargetMet = avgEfficiency >= targets.efficiency;
898
+ const utilizationTargetMet = avgUtilization >= targets.utilization;
899
+
900
+ console.log('\nTarget Achievement:');
901
+ console.log(` โ€ข 40%+ Efficiency: ${efficiencyTargetMet ? 'โœ… ACHIEVED' : 'โŒ NOT ACHIEVED'}`);
902
+ console.log(` โ€ข 85%+ Utilization: ${utilizationTargetMet ? 'โœ… ACHIEVED' : 'โŒ NOT ACHIEVED'}`);
903
+ console.log(` โ€ข โ‰ค100ms Response Time: ${avgResponseTime <= targets.responseTime ? 'โœ… ACHIEVED' : 'โŒ NOT ACHIEVED'}`);
904
+ }
905
+
906
+ const poolStatus = this.poolManager.getPoolStatus();
907
+ console.log('\nFinal System State:');
908
+ console.log(` โ€ข Pool Size: ${poolStatus.poolSize}`);
909
+ console.log(` โ€ข Active Agents: ${poolStatus.activeAgents}`);
910
+ console.log(` โ€ข Scale Ups: ${poolStatus.stats.scaleUps}`);
911
+ console.log(` โ€ข Scale Downs: ${poolStatus.stats.scaleDowns}`);
912
+
913
+ console.log('\nโœ… Demo completed successfully!');
914
+ console.log('\nKey Features Demonstrated:');
915
+ console.log(' ๐Ÿ”ง Reactive, Predictive, and Hybrid scaling algorithms');
916
+ console.log(' ๐Ÿ“Š Dynamic pool management with cooldowns');
917
+ console.log(' โšก Resource optimization and conflict detection');
918
+ console.log(' ๐Ÿ“ˆ Performance benchmarking and target achievement');
919
+ console.log(' ๐Ÿ”„ Redis-based coordination (simulated)');
920
+ }
921
+
922
+ async cleanup() {
923
+ console.log('\n๐Ÿงน Cleaning up...');
924
+
925
+ if (this.poolManager) {
926
+ await this.poolManager.stop();
927
+ }
928
+
929
+ if (this.benchmark) {
930
+ await this.benchmark.stop();
931
+ }
932
+
933
+ console.log('โœ… Cleanup completed');
934
+ }
935
+
936
+ sleep(ms) {
937
+ return new Promise(resolve => setTimeout(resolve, ms));
938
+ }
939
+ }
940
+
941
+ // Run the demo
942
+ async function main() {
943
+ const demo = new AutoScalingDemo();
944
+ await demo.runDemo();
945
+ }
946
+
947
+ // Handle graceful shutdown
948
+ process.on('SIGINT', async () => {
949
+ console.log('\n๐Ÿ›‘ Received SIGINT, shutting down gracefully...');
950
+ process.exit(0);
951
+ });
952
+
953
+ process.on('SIGTERM', async () => {
954
+ console.log('\n๐Ÿ›‘ Received SIGTERM, shutting down gracefully...');
955
+ process.exit(0);
956
+ });
957
+
958
+ // Run if this file is executed directly
959
+ if (import.meta.url === `file://${process.argv[1]}`) {
960
+ main().catch(console.error);
961
+ }
962
+
963
+ export default AutoScalingDemo;