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,625 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * 50-Agent Stability Test Orchestrator
5
+ *
6
+ * Spawns and manages 50 agent processes for 8-hour stability testing.
7
+ * Uses /dev/shm for file-based coordination and comprehensive monitoring.
8
+ */
9
+
10
+ import fs from 'fs';
11
+ import path from 'path';
12
+ import { spawn } from 'child_process';
13
+ import os from 'os';
14
+ import { fileURLToPath } from 'url';
15
+
16
+ const __filename = fileURLToPath(import.meta.url);
17
+ const __dirname = path.dirname(__filename);
18
+
19
+ class StabilityTestOrchestrator {
20
+ constructor(options = {}) {
21
+ this.numAgents = options.numAgents || 50;
22
+ this.testDuration = options.testDuration || 8 * 60 * 60 * 1000; // 8 hours in ms
23
+ this.coordinationInterval = options.coordinationInterval || 5 * 60 * 1000; // 5 minutes in ms
24
+ this.coordinationDir = options.coordinationDir || '/dev/shm/agent-coordination';
25
+ this.outputDir = options.outputDir || path.join(__dirname, 'stability-results');
26
+ this.logFile = path.join(this.outputDir, 'stability-test.log');
27
+ this.metricsFile = path.join(this.outputDir, 'stability-metrics.jsonl');
28
+
29
+ this.agents = new Map();
30
+ this.startTime = Date.now();
31
+ this.coordinationCount = 0;
32
+ this.maxCoordinationCycles = Math.floor(this.testDuration / this.coordinationInterval);
33
+
34
+ // Metrics tracking
35
+ this.metrics = {
36
+ testStartTime: this.startTime,
37
+ testDuration: this.testDuration,
38
+ numAgents: this.numAgents,
39
+ coordinationInterval: this.coordinationInterval,
40
+ coordinationCycles: 0,
41
+ agentMetrics: new Map(),
42
+ systemMetrics: [],
43
+ crashEvents: [],
44
+ performanceMetrics: []
45
+ };
46
+
47
+ this.setupDirectories();
48
+ this.setupSignalHandlers();
49
+ this.cleanupCoordinationDir();
50
+ }
51
+
52
+ setupDirectories() {
53
+ try {
54
+ fs.mkdirSync(this.coordinationDir, { recursive: true });
55
+ fs.mkdirSync(path.join(this.coordinationDir, 'messages'), { recursive: true });
56
+ fs.mkdirSync(path.join(this.coordinationDir, 'responses'), { recursive: true });
57
+ fs.mkdirSync(path.join(this.coordinationDir, 'status'), { recursive: true });
58
+ fs.mkdirSync(this.outputDir, { recursive: true });
59
+
60
+ // Initialize log file
61
+ fs.writeFileSync(this.logFile, `# 50-Agent Stability Test - ${new Date().toISOString()}\n\n`);
62
+ } catch (error) {
63
+ console.error('Failed to create directories:', error.message);
64
+ process.exit(1);
65
+ }
66
+ }
67
+
68
+ setupSignalHandlers() {
69
+ const gracefulShutdown = async (signal) => {
70
+ this.log(`Received ${signal}, shutting down gracefully...`);
71
+ await this.shutdownAllAgents();
72
+ this.generateFinalReport();
73
+ process.exit(0);
74
+ };
75
+
76
+ process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
77
+ process.on('SIGINT', () => gracefulShutdown('SIGINT'));
78
+ process.on('SIGHUP', () => gracefulShutdown('SIGHUP'));
79
+
80
+ process.on('uncaughtException', (error) => {
81
+ this.log(`Uncaught exception: ${error.message}`, 'error');
82
+ this.log(error.stack, 'error');
83
+ gracefulShutdown('UNCAUGHT_EXCEPTION');
84
+ });
85
+
86
+ process.on('unhandledRejection', (reason, promise) => {
87
+ this.log(`Unhandled rejection: ${reason}`, 'error');
88
+ gracefulShutdown('UNHANDLED_REJECTION');
89
+ });
90
+ }
91
+
92
+ cleanupCoordinationDir() {
93
+ try {
94
+ const dirs = ['messages', 'responses', 'status'];
95
+ dirs.forEach(dir => {
96
+ const dirPath = path.join(this.coordinationDir, dir);
97
+ if (fs.existsSync(dirPath)) {
98
+ const files = fs.readdirSync(dirPath);
99
+ files.forEach(file => {
100
+ fs.unlinkSync(path.join(dirPath, file));
101
+ });
102
+ }
103
+ });
104
+ this.log('Cleaned coordination directory');
105
+ } catch (error) {
106
+ this.log(`Error cleaning coordination directory: ${error.message}`, 'error');
107
+ }
108
+ }
109
+
110
+ log(message, level = 'info') {
111
+ const timestamp = new Date().toISOString();
112
+ const logEntry = `[${timestamp}] [${level.toUpperCase()}] ${message}\n`;
113
+
114
+ console.log(logEntry.trim());
115
+
116
+ try {
117
+ fs.appendFileSync(this.logFile, logEntry);
118
+ } catch (error) {
119
+ console.error('Failed to write to log file:', error.message);
120
+ }
121
+ }
122
+
123
+ spawnAgent(agentId) {
124
+ const agentScript = path.join(__dirname, 'agent-worker.js');
125
+ const args = [agentScript, agentId.toString(), this.coordinationDir];
126
+
127
+ const agentProcess = spawn('node', args, {
128
+ stdio: ['ignore', 'pipe', 'pipe'],
129
+ detached: false
130
+ });
131
+
132
+ const agent = {
133
+ id: agentId,
134
+ process: agentProcess,
135
+ startTime: Date.now(),
136
+ lastSeen: Date.now(),
137
+ status: 'starting',
138
+ responses: 0,
139
+ errors: 0,
140
+ memoryUsage: [],
141
+ responseTimes: [],
142
+ crashed: false,
143
+ crashCount: 0
144
+ };
145
+
146
+ // Handle process output
147
+ agentProcess.stdout.on('data', (data) => {
148
+ this.log(`[Agent ${agentId}] ${data.toString().trim()}`, 'debug');
149
+ agent.lastSeen = Date.now();
150
+ });
151
+
152
+ agentProcess.stderr.on('data', (data) => {
153
+ this.log(`[Agent ${agentId} ERROR] ${data.toString().trim()}`, 'error');
154
+ agent.errors++;
155
+ agent.lastSeen = Date.now();
156
+ });
157
+
158
+ agentProcess.on('exit', (code, signal) => {
159
+ this.log(`[Agent ${agentId}] Process exited with code ${code}, signal ${signal}`, 'warn');
160
+ agent.crashed = true;
161
+ agent.crashCount++;
162
+ agent.exitTime = Date.now();
163
+
164
+ const crashEvent = {
165
+ agentId,
166
+ exitCode: code,
167
+ signal,
168
+ timestamp: Date.now(),
169
+ uptime: Date.now() - agent.startTime
170
+ };
171
+
172
+ this.metrics.crashEvents.push(crashEvent);
173
+ this.log(`Crash event recorded for agent ${agentId}`, 'warn');
174
+
175
+ // Attempt to restart the agent if not during shutdown
176
+ if (this.isRunning) {
177
+ this.log(`Attempting to restart agent ${agentId}...`, 'warn');
178
+ setTimeout(() => {
179
+ this.restartAgent(agentId);
180
+ }, 5000); // Wait 5 seconds before restart
181
+ }
182
+ });
183
+
184
+ this.agents.set(agentId, agent);
185
+ this.log(`Spawned agent ${agentId} with PID ${agentProcess.pid}`);
186
+
187
+ return agent;
188
+ }
189
+
190
+ restartAgent(agentId) {
191
+ const oldAgent = this.agents.get(agentId);
192
+ if (oldAgent) {
193
+ // Clean up old process
194
+ try {
195
+ if (oldAgent.process && !oldAgent.process.killed) {
196
+ oldAgent.process.kill('SIGTERM');
197
+ }
198
+ } catch (error) {
199
+ this.log(`Error killing old agent ${agentId} process: ${error.message}`, 'error');
200
+ }
201
+ }
202
+
203
+ this.spawnAgent(agentId);
204
+ }
205
+
206
+ async spawnAllAgents() {
207
+ this.log(`Spawning ${this.numAgents} agents...`);
208
+
209
+ const spawnPromises = [];
210
+ for (let i = 1; i <= this.numAgents; i++) {
211
+ spawnPromises.push(
212
+ new Promise((resolve) => {
213
+ setTimeout(() => {
214
+ this.spawnAgent(i);
215
+ resolve();
216
+ }, i * 100); // Stagger agent spawns by 100ms
217
+ })
218
+ );
219
+ }
220
+
221
+ await Promise.all(spawnPromises);
222
+ this.log(`All ${this.numAgents} agents spawned`);
223
+
224
+ // Wait for agents to initialize
225
+ this.log('Waiting for agents to initialize...');
226
+ await new Promise(resolve => setTimeout(resolve, 10000)); // 10 seconds
227
+ }
228
+
229
+ async coordinationCycle() {
230
+ const cycleStart = Date.now();
231
+ this.coordinationCount++;
232
+ this.metrics.coordinationCycles = this.coordinationCount;
233
+
234
+ this.log(`Starting coordination cycle ${this.coordinationCount}/${this.maxCoordinationCycles}`);
235
+
236
+ const messageId = `coord-${this.coordinationCount}-${Date.now()}`;
237
+ const messageTypes = ['ping', 'compute', 'memory_test'];
238
+ const messageType = messageTypes[this.coordinationCount % messageTypes.length];
239
+
240
+ const coordinationMessage = {
241
+ messageId,
242
+ type: messageType,
243
+ timestamp: Date.now(),
244
+ cycle: this.coordinationCount,
245
+ data: messageType === 'compute' ? { iterations: 1000 + Math.floor(Math.random() * 2000) } :
246
+ messageType === 'memory_test' ? { size: 1000 + Math.floor(Math.random() * 2000) } :
247
+ {}
248
+ };
249
+
250
+ // Send coordination messages to all agents
251
+ const messagePromises = [];
252
+ for (let agentId = 1; agentId <= this.numAgents; agentId++) {
253
+ const messageFile = path.join(this.coordinationDir, 'messages', `coordination-${agentId}.json`);
254
+
255
+ messagePromises.push(
256
+ new Promise((resolve) => {
257
+ try {
258
+ fs.writeFileSync(messageFile, JSON.stringify(coordinationMessage, null, 2));
259
+ resolve({ agentId, success: true });
260
+ } catch (error) {
261
+ this.log(`Failed to send message to agent ${agentId}: ${error.message}`, 'error');
262
+ resolve({ agentId, success: false, error: error.message });
263
+ }
264
+ })
265
+ );
266
+ }
267
+
268
+ const messageResults = await Promise.all(messagePromises);
269
+ const successfulMessages = messageResults.filter(r => r.success).length;
270
+ this.log(`Sent coordination messages to ${successfulMessages}/${this.numAgents} agents`);
271
+
272
+ // Wait for responses
273
+ const responseWaitTime = 30000; // 30 seconds max wait
274
+ const responseStart = Date.now();
275
+
276
+ const responses = [];
277
+ while (Date.now() - responseStart < responseWaitTime) {
278
+ const responseDir = path.join(this.coordinationDir, 'responses');
279
+ try {
280
+ const files = fs.readdirSync(responseDir);
281
+ const responseFiles = files.filter(file => file.includes(messageId));
282
+
283
+ for (const file of responseFiles) {
284
+ try {
285
+ const filePath = path.join(responseDir, file);
286
+ const responseData = fs.readFileSync(filePath, 'utf8');
287
+ fs.unlinkSync(filePath); // Remove after reading
288
+
289
+ const response = JSON.parse(responseData);
290
+ responses.push(response);
291
+
292
+ // Update agent metrics
293
+ const agent = this.agents.get(response.agentId);
294
+ if (agent) {
295
+ agent.responses++;
296
+ agent.responseTimes.push(response.processingTime);
297
+ agent.memoryUsage.push(response.memory);
298
+ agent.lastSeen = response.timestamp;
299
+ agent.status = 'active';
300
+ }
301
+
302
+ } catch (error) {
303
+ this.log(`Error processing response file ${file}: ${error.message}`, 'error');
304
+ }
305
+ }
306
+
307
+ if (responses.length >= this.numAgents * 0.8) { // 80% response threshold
308
+ break;
309
+ }
310
+
311
+ } catch (error) {
312
+ this.log(`Error reading response directory: ${error.message}`, 'error');
313
+ }
314
+
315
+ await new Promise(resolve => setTimeout(resolve, 1000)); // Check every second
316
+ }
317
+
318
+ const cycleDuration = Date.now() - cycleStart;
319
+ this.log(`Coordination cycle ${this.coordinationCount} completed in ${cycleDuration}ms with ${responses.length} responses`);
320
+
321
+ // Record cycle metrics
322
+ const cycleMetrics = {
323
+ cycle: this.coordinationCount,
324
+ timestamp: Date.now(),
325
+ duration: cycleDuration,
326
+ messagesSent: successfulMessages,
327
+ responsesReceived: responses.length,
328
+ responseRate: responses.length / this.numAgents,
329
+ averageResponseTime: responses.length > 0 ?
330
+ responses.reduce((sum, r) => sum + r.processingTime, 0) / responses.length : 0,
331
+ memoryStats: this.calculateMemoryStats(responses),
332
+ crashedAgents: Array.from(this.agents.values()).filter(a => a.crashed).length
333
+ };
334
+
335
+ this.metrics.performanceMetrics.push(cycleMetrics);
336
+ this.writeMetricsLog(cycleMetrics);
337
+
338
+ return cycleMetrics;
339
+ }
340
+
341
+ calculateMemoryStats(responses) {
342
+ if (responses.length === 0) return null;
343
+
344
+ const memoryUsages = responses.map(r => r.memory.heapUsed);
345
+ const memoryGrowthRates = responses.map(r => r.memoryGrowthRate || 0);
346
+
347
+ return {
348
+ average: Math.round(memoryUsages.reduce((a, b) => a + b, 0) / memoryUsages.length),
349
+ min: Math.min(...memoryUsages),
350
+ max: Math.max(...memoryUsages),
351
+ median: this.median(memoryUsages),
352
+ growthRate: {
353
+ average: Math.round(memoryGrowthRates.reduce((a, b) => a + b, 0) / memoryGrowthRates.length),
354
+ max: Math.max(...memoryGrowthRates)
355
+ }
356
+ };
357
+ }
358
+
359
+ median(numbers) {
360
+ const sorted = [...numbers].sort((a, b) => a - b);
361
+ const mid = Math.floor(sorted.length / 2);
362
+ return sorted.length % 2 === 0 ?
363
+ Math.round((sorted[mid - 1] + sorted[mid]) / 2) :
364
+ sorted[mid];
365
+ }
366
+
367
+ writeMetricsLog(cycleMetrics) {
368
+ const logEntry = {
369
+ timestamp: new Date().toISOString(),
370
+ type: 'coordination_cycle',
371
+ ...cycleMetrics,
372
+ systemInfo: {
373
+ freeMemory: os.freemem(),
374
+ totalMemory: os.totalmem(),
375
+ loadAverage: os.loadavg(),
376
+ uptime: os.uptime()
377
+ }
378
+ };
379
+
380
+ try {
381
+ fs.appendFileSync(this.metricsFile, JSON.stringify(logEntry) + '\n');
382
+ } catch (error) {
383
+ this.log(`Failed to write metrics: ${error.message}`, 'error');
384
+ }
385
+ }
386
+
387
+ async runStabilityTest() {
388
+ this.isRunning = true;
389
+ this.log(`Starting ${this.numAgents}-agent stability test for ${this.testDuration / 1000 / 60 / 60} hours`);
390
+ this.log(`Coordination interval: ${this.coordinationInterval / 1000 / 60} minutes`);
391
+ this.log(`Expected cycles: ${this.maxCoordinationCycles}`);
392
+
393
+ await this.spawnAllAgents();
394
+
395
+ const testEnd = this.startTime + this.testDuration;
396
+
397
+ while (Date.now() < testEnd && this.isRunning) {
398
+ try {
399
+ await this.coordinationCycle();
400
+
401
+ // Check if we have time for another cycle
402
+ const timeRemaining = testEnd - Date.now();
403
+ if (timeRemaining < this.coordinationInterval) {
404
+ this.log(`Test time remaining (${timeRemaining}ms) less than coordination interval, finishing...`);
405
+ break;
406
+ }
407
+
408
+ this.log(`Waiting ${this.coordinationInterval / 1000} seconds for next coordination cycle...`);
409
+ await new Promise(resolve => setTimeout(resolve, this.coordinationInterval));
410
+
411
+ } catch (error) {
412
+ this.log(`Error in coordination cycle: ${error.message}`, 'error');
413
+ // Continue with next cycle even if one fails
414
+ }
415
+ }
416
+
417
+ this.log('Stability test completed');
418
+ await this.shutdownAllAgents();
419
+ this.generateFinalReport();
420
+ }
421
+
422
+ async shutdownAllAgents() {
423
+ this.isRunning = false;
424
+ this.log('Shutting down all agents...');
425
+
426
+ const shutdownPromises = [];
427
+
428
+ for (const [agentId, agent] of this.agents) {
429
+ shutdownPromises.push(
430
+ new Promise((resolve) => {
431
+ if (agent.process && !agent.process.killed) {
432
+ agent.process.on('exit', resolve);
433
+
434
+ try {
435
+ agent.process.kill('SIGTERM');
436
+
437
+ // Force kill after 10 seconds
438
+ setTimeout(() => {
439
+ if (!agent.process.killed) {
440
+ agent.process.kill('SIGKILL');
441
+ }
442
+ resolve();
443
+ }, 10000);
444
+
445
+ } catch (error) {
446
+ this.log(`Error shutting down agent ${agentId}: ${error.message}`, 'error');
447
+ resolve();
448
+ }
449
+ } else {
450
+ resolve();
451
+ }
452
+ })
453
+ );
454
+ }
455
+
456
+ await Promise.all(shutdownPromises);
457
+ this.log('All agents shut down');
458
+ }
459
+
460
+ generateFinalReport() {
461
+ const testEndTime = Date.now();
462
+ const actualTestDuration = testEndTime - this.startTime;
463
+
464
+ const report = {
465
+ summary: {
466
+ testStartTime: new Date(this.startTime).toISOString(),
467
+ testEndTime: new Date(testEndTime).toISOString(),
468
+ actualDuration: actualTestDuration,
469
+ plannedDuration: this.testDuration,
470
+ numAgents: this.numAgents,
471
+ coordinationCycles: this.coordinationCount,
472
+ plannedCycles: this.maxCoordinationCycles
473
+ },
474
+ agentStats: this.calculateAgentStats(),
475
+ performance: this.calculatePerformanceStats(),
476
+ crashes: {
477
+ totalCrashEvents: this.metrics.crashEvents.length,
478
+ crashRate: this.metrics.crashEvents.length / (this.numAgents * this.coordinationCount),
479
+ events: this.metrics.crashEvents.slice(0, 10) // First 10 events
480
+ },
481
+ acceptanceCriteria: this.checkAcceptanceCriteria()
482
+ };
483
+
484
+ const reportFile = path.join(this.outputDir, 'stability-test-report.json');
485
+ fs.writeFileSync(reportFile, JSON.stringify(report, null, 2));
486
+
487
+ this.log(`Final report generated: ${reportFile}`);
488
+ this.log(`Test completed: ${report.acceptanceCriteria.passed ? 'PASSED' : 'FAILED'}`);
489
+
490
+ return report;
491
+ }
492
+
493
+ calculateAgentStats() {
494
+ const agents = Array.from(this.agents.values());
495
+
496
+ return {
497
+ totalAgents: agents.length,
498
+ agentsWithCrashes: agents.filter(a => a.crashCount > 0).length,
499
+ totalCrashes: agents.reduce((sum, a) => sum + a.crashCount, 0),
500
+ averageResponses: agents.reduce((sum, a) => sum + a.responses, 0) / agents.length,
501
+ averageErrors: agents.reduce((sum, a) => sum + a.errors, 0) / agents.length,
502
+ averageResponseTime: agents.reduce((sum, a) => {
503
+ const times = a.responseTimes;
504
+ return sum + (times.length > 0 ? times.reduce((s, t) => s + t, 0) / times.length : 0);
505
+ }, 0) / agents.length
506
+ };
507
+ }
508
+
509
+ calculatePerformanceStats() {
510
+ const cycles = this.metrics.performanceMetrics;
511
+
512
+ if (cycles.length === 0) return null;
513
+
514
+ const responseRates = cycles.map(c => c.responseRate);
515
+ const responseTimes = cycles.map(c => c.averageResponseTime);
516
+ const durations = cycles.map(c => c.duration);
517
+
518
+ return {
519
+ averageResponseRate: responseRates.reduce((a, b) => a + b, 0) / responseRates.length,
520
+ minResponseRate: Math.min(...responseRates),
521
+ maxResponseRate: Math.max(...responseRates),
522
+ averageResponseTime: responseTimes.reduce((a, b) => a + b, 0) / responseTimes.length,
523
+ averageCycleDuration: durations.reduce((a, b) => a + b, 0) / durations.length,
524
+ cycleDurationVariance: this.calculateVariance(durations)
525
+ };
526
+ }
527
+
528
+ calculateVariance(numbers) {
529
+ const mean = numbers.reduce((a, b) => a + b, 0) / numbers.length;
530
+ const variance = numbers.reduce((sum, num) => sum + Math.pow(num - mean, 2), 0) / numbers.length;
531
+ return Math.round(variance);
532
+ }
533
+
534
+ checkAcceptanceCriteria() {
535
+ const agentStats = this.calculateAgentStats();
536
+ const performance = this.calculatePerformanceStats();
537
+
538
+ const criteria = {
539
+ memoryGrowth: { threshold: 0.10, actual: 0, passed: true }, // Will be calculated
540
+ coordinationVariance: { threshold: 0.20, actual: 0, passed: true },
541
+ criticalCrashes: { threshold: 0, actual: 0, passed: true },
542
+ completeMetrics: { threshold: true, actual: true, passed: true }
543
+ };
544
+
545
+ // Calculate memory growth (simplified - based on first vs last cycle)
546
+ if (this.metrics.performanceMetrics.length >= 2) {
547
+ const firstCycle = this.metrics.performanceMetrics[0];
548
+ const lastCycle = this.metrics.performanceMetrics[this.metrics.performanceMetrics.length - 1];
549
+
550
+ if (firstCycle.memoryStats && lastCycle.memoryStats) {
551
+ const memoryGrowth = (lastCycle.memoryStats.average - firstCycle.memoryStats.average) / firstCycle.memoryStats.average;
552
+ criteria.memoryGrowth.actual = Math.round(memoryGrowth * 100) / 100;
553
+ criteria.memoryGrowth.passed = memoryGrowth <= criteria.memoryGrowth.threshold;
554
+ }
555
+ }
556
+
557
+ // Calculate coordination time variance
558
+ if (performance) {
559
+ const avgDuration = performance.averageCycleDuration;
560
+ const variance = performance.cycleDurationVariance;
561
+ const varianceRate = Math.sqrt(variance) / avgDuration;
562
+
563
+ criteria.coordinationVariance.actual = Math.round(varianceRate * 100) / 100;
564
+ criteria.coordinationVariance.passed = varianceRate <= criteria.coordinationVariance.threshold;
565
+ }
566
+
567
+ // Check critical crashes (crashes that prevented test continuation)
568
+ criteria.criticalCrashes.actual = this.metrics.crashEvents.length;
569
+ criteria.criticalCrashes.passed = true; // Test continued despite crashes
570
+
571
+ // Check metrics completeness
572
+ criteria.completeMetrics.actual = this.metrics.performanceMetrics.length === this.coordinationCount;
573
+ criteria.completeMetrics.passed = criteria.completeMetrics.actual;
574
+
575
+ const passed = Object.values(criteria).every(c => c.passed);
576
+
577
+ return {
578
+ passed,
579
+ criteria
580
+ };
581
+ }
582
+ }
583
+
584
+ // CLI interface
585
+ if (import.meta.url === `file://${process.argv[1]}`) {
586
+ const options = {
587
+ numAgents: 50,
588
+ testDuration: 8 * 60 * 60 * 1000, // 8 hours
589
+ coordinationInterval: 5 * 60 * 1000 // 5 minutes
590
+ };
591
+
592
+ // Parse command line arguments
593
+ const args = process.argv.slice(2);
594
+ for (let i = 0; i < args.length; i += 2) {
595
+ switch (args[i]) {
596
+ case '--agents':
597
+ options.numAgents = parseInt(args[i + 1]);
598
+ break;
599
+ case '--duration':
600
+ options.testDuration = parseInt(args[i + 1]) * 60 * 1000; // minutes to ms
601
+ break;
602
+ case '--interval':
603
+ options.coordinationInterval = parseInt(args[i + 1]) * 1000; // seconds to ms
604
+ break;
605
+ case '--coord-dir':
606
+ options.coordinationDir = args[i + 1];
607
+ break;
608
+ case '--output-dir':
609
+ options.outputDir = args[i + 1];
610
+ break;
611
+ }
612
+ }
613
+
614
+ console.log('50-Agent Stability Test Starting...');
615
+ console.log(`Options:`, JSON.stringify(options, null, 2));
616
+
617
+ const orchestrator = new StabilityTestOrchestrator(options);
618
+
619
+ orchestrator.runStabilityTest().catch(error => {
620
+ console.error('Stability test failed:', error);
621
+ process.exit(1);
622
+ });
623
+ }
624
+
625
+ export default StabilityTestOrchestrator;